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
;
35 use LanguageConverter
;
36 use MediaWiki\Auth\AuthManager
;
37 use MediaWiki\Auth\PasswordAuthenticationRequest
;
38 use MediaWiki\Linker\LinkRenderer
;
39 use MediaWiki\MediaWikiServices
;
47 use PreferencesFormLegacy
;
48 use Psr\Log\LoggerAwareTrait
;
49 use Psr\Log\NullLogger
;
52 use SpecialPreferences
;
55 use UnexpectedValueException
;
57 use UserGroupMembership
;
61 * This is the default implementation of PreferencesFactory.
63 class DefaultPreferencesFactory
implements PreferencesFactory
{
69 /** @var Language The wiki's content language. */
72 /** @var AuthManager */
73 protected $authManager;
75 /** @var LinkRenderer */
76 protected $linkRenderer;
79 * @param Config $config
80 * @param Language $contLang
81 * @param AuthManager $authManager
82 * @param LinkRenderer $linkRenderer
84 public function __construct(
87 AuthManager
$authManager,
88 LinkRenderer
$linkRenderer
90 $this->config
= $config;
91 $this->contLang
= $contLang;
92 $this->authManager
= $authManager;
93 $this->linkRenderer
= $linkRenderer;
94 $this->logger
= new NullLogger();
100 public function getSaveBlacklist() {
108 * @throws MWException
110 * @param IContextSource $context
113 public function getFormDescriptor( User
$user, IContextSource
$context ) {
116 if ( SpecialPreferences
::isOouiEnabled( $context ) ) {
117 OutputPage
::setupOOUI(
118 strtolower( $context->getSkin()->getSkinName() ),
119 $context->getLanguage()->getDir()
123 $canIPUseHTTPS = wfCanIPUseHTTPS( $context->getRequest()->getIP() );
124 $this->profilePreferences( $user, $context, $preferences, $canIPUseHTTPS );
125 $this->skinPreferences( $user, $context, $preferences );
126 $this->datetimePreferences( $user, $context, $preferences );
127 $this->filesPreferences( $context, $preferences );
128 $this->renderingPreferences( $context, $preferences );
129 $this->editingPreferences( $user, $context, $preferences );
130 $this->rcPreferences( $user, $context, $preferences );
131 $this->watchlistPreferences( $user, $context, $preferences );
132 $this->searchPreferences( $preferences );
134 Hooks
::run( 'GetPreferences', [ $user, &$preferences ] );
136 $this->loadPreferenceValues( $user, $context, $preferences );
137 $this->logger
->debug( "Created form descriptor for user '{$user->getName()}'" );
142 * Loads existing values for a given array of preferences
143 * @throws MWException
145 * @param IContextSource $context
146 * @param array &$defaultPreferences Array to load values for
149 private function loadPreferenceValues(
150 User
$user, IContextSource
$context, &$defaultPreferences
152 # # Remove preferences that wikis don't want to use
153 foreach ( $this->config
->get( 'HiddenPrefs' ) as $pref ) {
154 if ( isset( $defaultPreferences[$pref] ) ) {
155 unset( $defaultPreferences[$pref] );
159 # # Make sure that form fields have their parent set. See T43337.
160 $dummyForm = new HTMLForm( [], $context );
162 $disable = !$user->isAllowed( 'editmyoptions' );
164 $defaultOptions = User
::getDefaultOptions();
165 $userOptions = $user->getOptions();
166 $this->applyFilters( $userOptions, $defaultPreferences, 'filterForForm' );
167 # # Prod in defaults from the user
168 foreach ( $defaultPreferences as $name => &$info ) {
169 $prefFromUser = $this->getOptionFromUser( $name, $info, $userOptions );
170 if ( $disable && !in_array( $name, $this->getSaveBlacklist() ) ) {
171 $info['disabled'] = 'disabled';
173 $field = HTMLForm
::loadInputFromParameters( $name, $info, $dummyForm ); // For validation
174 $globalDefault = $defaultOptions[$name] ??
null;
176 // If it validates, set it as the default
177 if ( isset( $info['default'] ) ) {
178 // Already set, no problem
180 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
181 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
182 $info['default'] = $prefFromUser;
183 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
184 $info['default'] = $globalDefault;
186 throw new MWException( "Global default '$globalDefault' is invalid for field $name" );
190 return $defaultPreferences;
194 * Pull option from a user account. Handles stuff like array-type preferences.
196 * @param string $name
198 * @param array $userOptions
199 * @return array|string
201 protected function getOptionFromUser( $name, $info, array $userOptions ) {
202 $val = $userOptions[$name] ??
null;
204 // Handling for multiselect preferences
205 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
206 ( isset( $info['class'] ) && $info['class'] == \HTMLMultiSelectField
::class ) ) {
207 $options = HTMLFormField
::flattenOptions( $info['options'] );
208 $prefix = $info['prefix'] ??
$name;
211 foreach ( $options as $value ) {
212 if ( $userOptions["$prefix$value"] ??
false ) {
218 // Handling for checkmatrix preferences
219 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
220 ( isset( $info['class'] ) && $info['class'] == \HTMLCheckMatrix
::class ) ) {
221 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
222 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
223 $prefix = $info['prefix'] ??
$name;
226 foreach ( $columns as $column ) {
227 foreach ( $rows as $row ) {
228 if ( $userOptions["$prefix$column-$row"] ??
false ) {
229 $val[] = "$column-$row";
239 * @todo Inject user Language instead of using context.
241 * @param IContextSource $context
242 * @param array &$defaultPreferences
243 * @param bool $canIPUseHTTPS Whether the user's IP is likely to be able to access the wiki
247 protected function profilePreferences(
248 User
$user, IContextSource
$context, &$defaultPreferences, $canIPUseHTTPS
250 $oouiEnabled = SpecialPreferences
::isOouiEnabled( $context );
252 // retrieving user name for GENDER and misc.
253 $userName = $user->getName();
255 # # User info #####################################
257 $defaultPreferences['username'] = [
259 'label-message' => [ 'username', $userName ],
260 'default' => $userName,
261 'section' => 'personal/info',
264 $lang = $context->getLanguage();
266 # Get groups to which the user belongs
267 $userEffectiveGroups = $user->getEffectiveGroups();
268 $userGroupMemberships = $user->getGroupMemberships();
269 $userGroups = $userMembers = $userTempGroups = $userTempMembers = [];
270 foreach ( $userEffectiveGroups as $ueg ) {
272 // Skip the default * group, seems useless here
276 if ( isset( $userGroupMemberships[$ueg] ) ) {
277 $groupStringOrObject = $userGroupMemberships[$ueg];
279 $groupStringOrObject = $ueg;
282 $userG = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html' );
283 $userM = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html',
286 // Store expiring groups separately, so we can place them before non-expiring
287 // groups in the list. This is to avoid the ambiguity of something like
288 // "administrator, bureaucrat (until X date)" -- users might wonder whether the
289 // expiry date applies to both groups, or just the last one
290 if ( $groupStringOrObject instanceof UserGroupMembership
&&
291 $groupStringOrObject->getExpiry()
293 $userTempGroups[] = $userG;
294 $userTempMembers[] = $userM;
296 $userGroups[] = $userG;
297 $userMembers[] = $userM;
301 sort( $userMembers );
302 sort( $userTempGroups );
303 sort( $userTempMembers );
304 $userGroups = array_merge( $userTempGroups, $userGroups );
305 $userMembers = array_merge( $userTempMembers, $userMembers );
307 $defaultPreferences['usergroups'] = [
309 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
310 count( $userGroups ) )->params( $userName )->parse(),
311 'default' => $context->msg( 'prefs-memberingroups-type' )
312 ->rawParams( $lang->commaList( $userGroups ), $lang->commaList( $userMembers ) )
315 'section' => 'personal/info',
318 $contribTitle = SpecialPage
::getTitleFor( "Contributions", $userName );
319 $formattedEditCount = $lang->formatNum( $user->getEditCount() );
320 $editCount = $this->linkRenderer
->makeLink( $contribTitle, $formattedEditCount );
322 $defaultPreferences['editcount'] = [
325 'label-message' => 'prefs-edits',
326 'default' => $editCount,
327 'section' => 'personal/info',
330 if ( $user->getRegistration() ) {
331 $displayUser = $context->getUser();
332 $userRegistration = $user->getRegistration();
333 $defaultPreferences['registrationdate'] = [
335 'label-message' => 'prefs-registration',
336 'default' => $context->msg(
337 'prefs-registration-date-time',
338 $lang->userTimeAndDate( $userRegistration, $displayUser ),
339 $lang->userDate( $userRegistration, $displayUser ),
340 $lang->userTime( $userRegistration, $displayUser )
342 'section' => 'personal/info',
346 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
347 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
349 // Actually changeable stuff
350 $defaultPreferences['realname'] = [
351 // (not really "private", but still shouldn't be edited without permission)
352 'type' => $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'realname' )
354 'default' => $user->getRealName(),
355 'section' => 'personal/info',
356 'label-message' => 'yourrealname',
357 'help-message' => 'prefs-help-realname',
360 if ( $canEditPrivateInfo && $this->authManager
->allowsAuthenticationDataChange(
361 new PasswordAuthenticationRequest(), false )->isGood()
363 if ( $oouiEnabled ) {
364 $link = new \OOUI\
ButtonWidget( [
365 'href' => SpecialPage
::getTitleFor( 'ChangePassword' )->getLinkURL( [
366 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
368 'label' => $context->msg( 'prefs-resetpass' )->text(),
371 $link = $this->linkRenderer
->makeLink( SpecialPage
::getTitleFor( 'ChangePassword' ),
372 $context->msg( 'prefs-resetpass' )->text(), [],
373 [ 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText() ] );
376 $defaultPreferences['password'] = [
379 'default' => (string)$link,
380 'label-message' => 'yourpassword',
381 'section' => 'personal/info',
384 // Only show prefershttps if secure login is turned on
385 if ( $this->config
->get( 'SecureLogin' ) && $canIPUseHTTPS ) {
386 $defaultPreferences['prefershttps'] = [
388 'label-message' => 'tog-prefershttps',
389 'help-message' => 'prefs-help-prefershttps',
390 'section' => 'personal/info'
395 $languages = Language
::fetchLanguageNames( null, 'mwfile' );
396 $languageCode = $this->config
->get( 'LanguageCode' );
397 if ( !array_key_exists( $languageCode, $languages ) ) {
398 $languages[$languageCode] = $languageCode;
399 // Sort the array again
404 foreach ( $languages as $code => $name ) {
405 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
406 $options[$display] = $code;
408 $defaultPreferences['language'] = [
410 'section' => 'personal/i18n',
411 'options' => $options,
412 'label-message' => 'yourlanguage',
415 $defaultPreferences['gender'] = [
417 'section' => 'personal/i18n',
419 $context->msg( 'parentheses' )
420 ->params( $context->msg( 'gender-unknown' )->plain() )
421 ->escaped() => 'unknown',
422 $context->msg( 'gender-female' )->escaped() => 'female',
423 $context->msg( 'gender-male' )->escaped() => 'male',
425 'label-message' => 'yourgender',
426 'help-message' => 'prefs-help-gender',
429 // see if there are multiple language variants to choose from
430 if ( !$this->config
->get( 'DisableLangConversion' ) ) {
431 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
432 if ( $langCode == $this->contLang
->getCode() ) {
433 if ( !$this->contLang
->hasVariants() ) {
437 $variants = $this->contLang
->getVariants();
439 foreach ( $variants as $v ) {
440 $v = str_replace( '_', '-', strtolower( $v ) );
441 $variantArray[$v] = $lang->getVariantname( $v, false );
445 foreach ( $variantArray as $code => $name ) {
446 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
447 $options[$display] = $code;
450 $defaultPreferences['variant'] = [
451 'label-message' => 'yourvariant',
453 'options' => $options,
454 'section' => 'personal/i18n',
455 'help-message' => 'prefs-help-variant',
458 $defaultPreferences["variant-$langCode"] = [
465 // Stuff from Language::getExtraUserToggles()
466 // FIXME is this dead code? $extraUserToggles doesn't seem to be defined for any language
467 $toggles = $this->contLang
->getExtraUserToggles();
469 foreach ( $toggles as $toggle ) {
470 $defaultPreferences[$toggle] = [
472 'section' => 'personal/i18n',
473 'label-message' => "tog-$toggle",
477 // show a preview of the old signature first
478 $oldsigWikiText = MediaWikiServices
::getInstance()->getParser()->preSaveTransform(
480 $context->getTitle(),
482 ParserOptions
::newFromContext( $context )
484 $oldsigHTML = $context->getOutput()->parseInline( $oldsigWikiText, true, true );
485 $defaultPreferences['oldsig'] = [
488 'label-message' => 'tog-oldsig',
489 'default' => $oldsigHTML,
490 'section' => 'personal/signature',
492 $defaultPreferences['nickname'] = [
493 'type' => $this->authManager
->allowsPropertyChange( 'nickname' ) ?
'text' : 'info',
494 'maxlength' => $this->config
->get( 'MaxSigChars' ),
495 'label-message' => 'yournick',
496 'validation-callback' => function ( $signature, $alldata, HTMLForm
$form ) {
497 return $this->validateSignature( $signature, $alldata, $form );
499 'section' => 'personal/signature',
500 'filter-callback' => function ( $signature, array $alldata, HTMLForm
$form ) {
501 return $this->cleanSignature( $signature, $alldata, $form );
504 $defaultPreferences['fancysig'] = [
506 'label-message' => 'tog-fancysig',
507 // show general help about signature at the bottom of the section
508 'help-message' => 'prefs-help-signature',
509 'section' => 'personal/signature'
514 if ( $this->config
->get( 'EnableEmail' ) ) {
515 if ( $canViewPrivateInfo ) {
516 $helpMessages[] = $this->config
->get( 'EmailConfirmToEdit' )
517 ?
'prefs-help-email-required'
518 : 'prefs-help-email';
520 if ( $this->config
->get( 'EnableUserEmail' ) ) {
521 // additional messages when users can send email to each other
522 $helpMessages[] = 'prefs-help-email-others';
525 $emailAddress = $user->getEmail() ?
htmlspecialchars( $user->getEmail() ) : '';
526 if ( $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'emailaddress' ) ) {
527 if ( $oouiEnabled ) {
528 $link = new \OOUI\
ButtonWidget( [
529 'href' => SpecialPage
::getTitleFor( 'ChangeEmail' )->getLinkURL( [
530 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
533 $context->msg( $user->getEmail() ?
'prefs-changeemail' : 'prefs-setemail' )->text(),
536 $emailAddress .= $emailAddress == '' ?
$link : ( '<br />' . $link );
538 $link = $this->linkRenderer
->makeLink(
539 SpecialPage
::getTitleFor( 'ChangeEmail' ),
540 $context->msg( $user->getEmail() ?
'prefs-changeemail' : 'prefs-setemail' )->text(),
542 [ 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText() ] );
544 $emailAddress .= $emailAddress == '' ?
$link : (
545 $context->msg( 'word-separator' )->escaped()
546 . $context->msg( 'parentheses' )->rawParams( $link )->escaped()
551 $defaultPreferences['emailaddress'] = [
554 'default' => $emailAddress,
555 'label-message' => 'youremail',
556 'section' => 'personal/email',
557 'help-messages' => $helpMessages,
558 # 'cssclass' chosen below
562 $disableEmailPrefs = false;
564 if ( $this->config
->get( 'EmailAuthentication' ) ) {
565 $emailauthenticationclass = 'mw-email-not-authenticated';
566 if ( $user->getEmail() ) {
567 if ( $user->getEmailAuthenticationTimestamp() ) {
568 // date and time are separate parameters to facilitate localisation.
569 // $time is kept for backward compat reasons.
570 // 'emailauthenticated' is also used in SpecialConfirmemail.php
571 $displayUser = $context->getUser();
572 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
573 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
574 $d = $lang->userDate( $emailTimestamp, $displayUser );
575 $t = $lang->userTime( $emailTimestamp, $displayUser );
576 $emailauthenticated = $context->msg( 'emailauthenticated',
577 $time, $d, $t )->parse() . '<br />';
578 $disableEmailPrefs = false;
579 $emailauthenticationclass = 'mw-email-authenticated';
581 $disableEmailPrefs = true;
582 if ( $oouiEnabled ) {
583 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
584 new \OOUI\
ButtonWidget( [
585 'href' => SpecialPage
::getTitleFor( 'Confirmemail' )->getLinkURL(),
586 'label' => $context->msg( 'emailconfirmlink' )->text(),
589 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
590 $this->linkRenderer
->makeKnownLink(
591 SpecialPage
::getTitleFor( 'Confirmemail' ),
592 $context->msg( 'emailconfirmlink' )->text()
595 $emailauthenticationclass = "mw-email-not-authenticated";
598 $disableEmailPrefs = true;
599 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
600 $emailauthenticationclass = 'mw-email-none';
603 if ( $canViewPrivateInfo ) {
604 $defaultPreferences['emailauthentication'] = [
607 'section' => 'personal/email',
608 'label-message' => 'prefs-emailconfirm-label',
609 'default' => $emailauthenticated,
610 # Apply the same CSS class used on the input to the message:
611 'cssclass' => $emailauthenticationclass,
616 if ( $this->config
->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
617 $defaultPreferences['disablemail'] = [
618 'id' => 'wpAllowEmail',
621 'section' => 'personal/email',
622 'label-message' => 'allowemail',
623 'disabled' => $disableEmailPrefs,
626 $defaultPreferences['email-allow-new-users'] = [
627 'id' => 'wpAllowEmailFromNewUsers',
629 'section' => 'personal/email',
630 'label-message' => 'email-allow-new-users-label',
631 'disabled' => $disableEmailPrefs,
634 $defaultPreferences['ccmeonemails'] = [
636 'section' => 'personal/email',
637 'label-message' => 'tog-ccmeonemails',
638 'disabled' => $disableEmailPrefs,
641 if ( $this->config
->get( 'EnableUserEmailBlacklist' ) ) {
642 $defaultPreferences['email-blacklist'] = [
643 'type' => 'usersmultiselect',
644 'label-message' => 'email-blacklist-label',
645 'section' => 'personal/email',
646 'disabled' => $disableEmailPrefs,
647 'filter' => MultiUsernameFilter
::class,
652 if ( $this->config
->get( 'EnotifWatchlist' ) ) {
653 $defaultPreferences['enotifwatchlistpages'] = [
655 'section' => 'personal/email',
656 'label-message' => 'tog-enotifwatchlistpages',
657 'disabled' => $disableEmailPrefs,
660 if ( $this->config
->get( 'EnotifUserTalk' ) ) {
661 $defaultPreferences['enotifusertalkpages'] = [
663 'section' => 'personal/email',
664 'label-message' => 'tog-enotifusertalkpages',
665 'disabled' => $disableEmailPrefs,
668 if ( $this->config
->get( 'EnotifUserTalk' ) ||
$this->config
->get( 'EnotifWatchlist' ) ) {
669 if ( $this->config
->get( 'EnotifMinorEdits' ) ) {
670 $defaultPreferences['enotifminoredits'] = [
672 'section' => 'personal/email',
673 'label-message' => 'tog-enotifminoredits',
674 'disabled' => $disableEmailPrefs,
678 if ( $this->config
->get( 'EnotifRevealEditorAddress' ) ) {
679 $defaultPreferences['enotifrevealaddr'] = [
681 'section' => 'personal/email',
682 'label-message' => 'tog-enotifrevealaddr',
683 'disabled' => $disableEmailPrefs,
692 * @param IContextSource $context
693 * @param array &$defaultPreferences
696 protected function skinPreferences( User
$user, IContextSource
$context, &$defaultPreferences ) {
697 # # Skin #####################################
699 // Skin selector, if there is at least one valid skin
700 $skinOptions = $this->generateSkinOptions( $user, $context );
701 if ( $skinOptions ) {
702 $defaultPreferences['skin'] = [
704 'options' => $skinOptions,
705 'section' => 'rendering/skin',
709 $allowUserCss = $this->config
->get( 'AllowUserCss' );
710 $allowUserJs = $this->config
->get( 'AllowUserJs' );
711 # Create links to user CSS/JS pages for all skins
712 # This code is basically copied from generateSkinOptions(). It'd
713 # be nice to somehow merge this back in there to avoid redundancy.
714 if ( $allowUserCss ||
$allowUserJs ) {
716 $userName = $user->getName();
718 if ( $allowUserCss ) {
719 $cssPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.css' );
720 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
721 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
724 if ( $allowUserJs ) {
725 $jsPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.js' );
726 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
727 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
730 $defaultPreferences['commoncssjs'] = [
733 'default' => $context->getLanguage()->pipeList( $linkTools ),
734 'label-message' => 'prefs-common-config',
735 'section' => 'rendering/skin',
741 * @param IContextSource $context
742 * @param array &$defaultPreferences
744 protected function filesPreferences( IContextSource
$context, &$defaultPreferences ) {
745 # # Files #####################################
746 $defaultPreferences['imagesize'] = [
748 'options' => $this->getImageSizes( $context ),
749 'label-message' => 'imagemaxsize',
750 'section' => 'rendering/files',
752 $defaultPreferences['thumbsize'] = [
754 'options' => $this->getThumbSizes( $context ),
755 'label-message' => 'thumbsize',
756 'section' => 'rendering/files',
762 * @param IContextSource $context
763 * @param array &$defaultPreferences
766 protected function datetimePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
767 # # Date and time #####################################
768 $dateOptions = $this->getDateOptions( $context );
769 if ( $dateOptions ) {
770 $defaultPreferences['date'] = [
772 'options' => $dateOptions,
773 'section' => 'rendering/dateformat',
778 $now = wfTimestampNow();
779 $lang = $context->getLanguage();
780 $nowlocal = Xml
::element( 'span', [ 'id' => 'wpLocalTime' ],
781 $lang->userTime( $now, $user ) );
782 $nowserver = $lang->userTime( $now, $user,
783 [ 'format' => false, 'timecorrection' => false ] ) .
784 Html
::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 +
(int)substr( $now, 10, 2 ) );
786 $defaultPreferences['nowserver'] = [
789 'label-message' => 'servertime',
790 'default' => $nowserver,
791 'section' => 'rendering/timeoffset',
794 $defaultPreferences['nowlocal'] = [
797 'label-message' => 'localtime',
798 'default' => $nowlocal,
799 'section' => 'rendering/timeoffset',
802 // Grab existing pref.
803 $tzOffset = $user->getOption( 'timecorrection' );
804 $tz = explode( '|', $tzOffset, 3 );
806 $tzOptions = $this->getTimezoneOptions( $context );
808 $tzSetting = $tzOffset;
809 if ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
810 !in_array( $tzOffset, HTMLFormField
::flattenOptions( $tzOptions ) )
812 // Timezone offset can vary with DST
814 $userTZ = new DateTimeZone( $tz[2] );
815 $minDiff = floor( $userTZ->getOffset( new DateTime( 'now' ) ) / 60 );
816 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
817 } catch ( Exception
$e ) {
818 // User has an invalid time zone set. Fall back to just using the offset
822 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
824 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) %
60 );
827 $defaultPreferences['timecorrection'] = [
828 'class' => \HTMLSelectOrOtherField
::class,
829 'label-message' => 'timezonelegend',
830 'options' => $tzOptions,
831 'default' => $tzSetting,
833 'section' => 'rendering/timeoffset',
834 'id' => 'wpTimeCorrection',
835 'filter' => TimezoneFilter
::class,
840 * @param MessageLocalizer $l10n
841 * @param array &$defaultPreferences
843 protected function renderingPreferences( MessageLocalizer
$l10n, &$defaultPreferences ) {
844 # # Diffs ####################################
845 $defaultPreferences['diffonly'] = [
847 'section' => 'rendering/diffs',
848 'label-message' => 'tog-diffonly',
850 $defaultPreferences['norollbackdiff'] = [
852 'section' => 'rendering/diffs',
853 'label-message' => 'tog-norollbackdiff',
856 # # Page Rendering ##############################
857 if ( $this->config
->get( 'AllowUserCssPrefs' ) ) {
858 $defaultPreferences['underline'] = [
861 $l10n->msg( 'underline-never' )->text() => 0,
862 $l10n->msg( 'underline-always' )->text() => 1,
863 $l10n->msg( 'underline-default' )->text() => 2,
865 'label-message' => 'tog-underline',
866 'section' => 'rendering/advancedrendering',
870 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
871 $stubThresholdOptions = [ $l10n->msg( 'stub-threshold-disabled' )->text() => 0 ];
872 foreach ( $stubThresholdValues as $value ) {
873 $stubThresholdOptions[$l10n->msg( 'size-bytes', $value )->text()] = $value;
876 $defaultPreferences['stubthreshold'] = [
878 'section' => 'rendering/advancedrendering',
879 'options' => $stubThresholdOptions,
880 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
881 'label-raw' => $l10n->msg( 'stub-threshold' )->rawParams(
882 '<a href="#" class="stub">' .
883 $l10n->msg( 'stub-threshold-sample-link' )->parse() .
887 $defaultPreferences['showhiddencats'] = [
889 'section' => 'rendering/advancedrendering',
890 'label-message' => 'tog-showhiddencats'
893 $defaultPreferences['numberheadings'] = [
895 'section' => 'rendering/advancedrendering',
896 'label-message' => 'tog-numberheadings',
902 * @param MessageLocalizer $l10n
903 * @param array &$defaultPreferences
905 protected function editingPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
906 # # Editing #####################################
907 $defaultPreferences['editsectiononrightclick'] = [
909 'section' => 'editing/advancedediting',
910 'label-message' => 'tog-editsectiononrightclick',
912 $defaultPreferences['editondblclick'] = [
914 'section' => 'editing/advancedediting',
915 'label-message' => 'tog-editondblclick',
918 if ( $this->config
->get( 'AllowUserCssPrefs' ) ) {
919 $defaultPreferences['editfont'] = [
921 'section' => 'editing/editor',
922 'label-message' => 'editfont-style',
924 $l10n->msg( 'editfont-monospace' )->text() => 'monospace',
925 $l10n->msg( 'editfont-sansserif' )->text() => 'sans-serif',
926 $l10n->msg( 'editfont-serif' )->text() => 'serif',
931 if ( $user->isAllowed( 'minoredit' ) ) {
932 $defaultPreferences['minordefault'] = [
934 'section' => 'editing/editor',
935 'label-message' => 'tog-minordefault',
939 $defaultPreferences['forceeditsummary'] = [
941 'section' => 'editing/editor',
942 'label-message' => 'tog-forceeditsummary',
944 $defaultPreferences['useeditwarning'] = [
946 'section' => 'editing/editor',
947 'label-message' => 'tog-useeditwarning',
949 $defaultPreferences['showtoolbar'] = [
951 'section' => 'editing/editor',
952 'label-message' => 'tog-showtoolbar',
955 $defaultPreferences['previewonfirst'] = [
957 'section' => 'editing/preview',
958 'label-message' => 'tog-previewonfirst',
960 $defaultPreferences['previewontop'] = [
962 'section' => 'editing/preview',
963 'label-message' => 'tog-previewontop',
965 $defaultPreferences['uselivepreview'] = [
967 'section' => 'editing/preview',
968 'label-message' => 'tog-uselivepreview',
974 * @param MessageLocalizer $l10n
975 * @param array &$defaultPreferences
977 protected function rcPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
978 $rcMaxAge = $this->config
->get( 'RCMaxAge' );
979 # # RecentChanges #####################################
980 $defaultPreferences['rcdays'] = [
982 'label-message' => 'recentchangesdays',
983 'section' => 'rc/displayrc',
985 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
986 'help' => $l10n->msg( 'recentchangesdays-max' )->numParams(
987 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
989 $defaultPreferences['rclimit'] = [
993 'label-message' => 'recentchangescount',
994 'help-message' => 'prefs-help-recentchangescount',
995 'section' => 'rc/displayrc',
996 'filter' => IntvalFilter
::class,
998 $defaultPreferences['usenewrc'] = [
1000 'label-message' => 'tog-usenewrc',
1001 'section' => 'rc/advancedrc',
1003 $defaultPreferences['hideminor'] = [
1005 'label-message' => 'tog-hideminor',
1006 'section' => 'rc/advancedrc',
1008 $defaultPreferences['rcfilters-rc-collapsed'] = [
1011 $defaultPreferences['rcfilters-wl-collapsed'] = [
1014 $defaultPreferences['rcfilters-saved-queries'] = [
1017 $defaultPreferences['rcfilters-wl-saved-queries'] = [
1020 // Override RCFilters preferences for RecentChanges 'limit'
1021 $defaultPreferences['rcfilters-limit'] = [
1024 $defaultPreferences['rcfilters-saved-queries-versionbackup'] = [
1027 $defaultPreferences['rcfilters-wl-saved-queries-versionbackup'] = [
1031 if ( $this->config
->get( 'RCWatchCategoryMembership' ) ) {
1032 $defaultPreferences['hidecategorization'] = [
1034 'label-message' => 'tog-hidecategorization',
1035 'section' => 'rc/advancedrc',
1039 if ( $user->useRCPatrol() ) {
1040 $defaultPreferences['hidepatrolled'] = [
1042 'section' => 'rc/advancedrc',
1043 'label-message' => 'tog-hidepatrolled',
1047 if ( $user->useNPPatrol() ) {
1048 $defaultPreferences['newpageshidepatrolled'] = [
1050 'section' => 'rc/advancedrc',
1051 'label-message' => 'tog-newpageshidepatrolled',
1055 if ( $this->config
->get( 'RCShowWatchingUsers' ) ) {
1056 $defaultPreferences['shownumberswatching'] = [
1058 'section' => 'rc/advancedrc',
1059 'label-message' => 'tog-shownumberswatching',
1063 if ( $this->config
->get( 'StructuredChangeFiltersShowPreference' ) ) {
1064 $defaultPreferences['rcenhancedfilters-disable'] = [
1066 'section' => 'rc/optoutrc',
1067 'label-message' => 'rcfilters-preference-label',
1068 'help-message' => 'rcfilters-preference-help',
1075 * @param IContextSource $context
1076 * @param array &$defaultPreferences
1078 protected function watchlistPreferences(
1079 User
$user, IContextSource
$context, &$defaultPreferences
1081 $oouiEnabled = SpecialPreferences
::isOouiEnabled( $context );
1083 $watchlistdaysMax = ceil( $this->config
->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1085 # # Watchlist #####################################
1086 if ( $user->isAllowed( 'editmywatchlist' ) ) {
1087 $editWatchlistLinks = '';
1088 $editWatchlistLinksOld = [];
1089 $editWatchlistModes = [
1090 'edit' => [ 'subpage' => false, 'flags' => [] ],
1091 'raw' => [ 'subpage' => 'raw', 'flags' => [] ],
1092 'clear' => [ 'subpage' => 'clear', 'flags' => [ 'destructive' ] ],
1094 foreach ( $editWatchlistModes as $mode => $options ) {
1095 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1096 if ( $oouiEnabled ) {
1097 $editWatchlistLinks .=
1098 new \OOUI\
ButtonWidget( [
1099 'href' => SpecialPage
::getTitleFor( 'EditWatchlist', $options['subpage'] )->getLinkURL(),
1100 'flags' => $options[ 'flags' ],
1101 'label' => new \OOUI\
HtmlSnippet(
1102 $context->msg( "prefs-editwatchlist-{$mode}" )->parse()
1106 $editWatchlistLinksOld[] = $this->linkRenderer
->makeKnownLink(
1107 SpecialPage
::getTitleFor( 'EditWatchlist', $options['subpage'] ),
1108 new HtmlArmor( $context->msg( "prefs-editwatchlist-{$mode}" )->parse() )
1113 $defaultPreferences['editwatchlist'] = [
1116 'default' => $oouiEnabled ?
1117 $editWatchlistLinks :
1118 $context->getLanguage()->pipeList( $editWatchlistLinksOld ),
1119 'label-message' => 'prefs-editwatchlist-label',
1120 'section' => 'watchlist/editwatchlist',
1124 $defaultPreferences['watchlistdays'] = [
1127 'max' => $watchlistdaysMax,
1128 'section' => 'watchlist/displaywatchlist',
1129 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1130 $watchlistdaysMax )->escaped(),
1131 'label-message' => 'prefs-watchlist-days',
1133 $defaultPreferences['wllimit'] = [
1137 'label-message' => 'prefs-watchlist-edits',
1138 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1139 'section' => 'watchlist/displaywatchlist',
1140 'filter' => IntvalFilter
::class,
1142 $defaultPreferences['extendwatchlist'] = [
1144 'section' => 'watchlist/advancedwatchlist',
1145 'label-message' => 'tog-extendwatchlist',
1147 $defaultPreferences['watchlisthideminor'] = [
1149 'section' => 'watchlist/advancedwatchlist',
1150 'label-message' => 'tog-watchlisthideminor',
1152 $defaultPreferences['watchlisthidebots'] = [
1154 'section' => 'watchlist/advancedwatchlist',
1155 'label-message' => 'tog-watchlisthidebots',
1157 $defaultPreferences['watchlisthideown'] = [
1159 'section' => 'watchlist/advancedwatchlist',
1160 'label-message' => 'tog-watchlisthideown',
1162 $defaultPreferences['watchlisthideanons'] = [
1164 'section' => 'watchlist/advancedwatchlist',
1165 'label-message' => 'tog-watchlisthideanons',
1167 $defaultPreferences['watchlisthideliu'] = [
1169 'section' => 'watchlist/advancedwatchlist',
1170 'label-message' => 'tog-watchlisthideliu',
1173 if ( !\SpecialWatchlist
::checkStructuredFilterUiEnabled(
1177 $defaultPreferences['watchlistreloadautomatically'] = [
1179 'section' => 'watchlist/advancedwatchlist',
1180 'label-message' => 'tog-watchlistreloadautomatically',
1184 $defaultPreferences['watchlistunwatchlinks'] = [
1186 'section' => 'watchlist/advancedwatchlist',
1187 'label-message' => 'tog-watchlistunwatchlinks',
1190 if ( $this->config
->get( 'RCWatchCategoryMembership' ) ) {
1191 $defaultPreferences['watchlisthidecategorization'] = [
1193 'section' => 'watchlist/advancedwatchlist',
1194 'label-message' => 'tog-watchlisthidecategorization',
1198 if ( $user->useRCPatrol() ) {
1199 $defaultPreferences['watchlisthidepatrolled'] = [
1201 'section' => 'watchlist/advancedwatchlist',
1202 'label-message' => 'tog-watchlisthidepatrolled',
1207 'edit' => 'watchdefault',
1208 'move' => 'watchmoves',
1209 'delete' => 'watchdeletion'
1213 if ( $user->isAllowed( 'createpage' ) ||
$user->isAllowed( 'createtalk' ) ) {
1214 $watchTypes['read'] = 'watchcreations';
1217 if ( $user->isAllowed( 'rollback' ) ) {
1218 $watchTypes['rollback'] = 'watchrollback';
1221 if ( $user->isAllowed( 'upload' ) ) {
1222 $watchTypes['upload'] = 'watchuploads';
1225 foreach ( $watchTypes as $action => $pref ) {
1226 if ( $user->isAllowed( $action ) ) {
1228 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1229 // tog-watchrollback
1230 $defaultPreferences[$pref] = [
1232 'section' => 'watchlist/advancedwatchlist',
1233 'label-message' => "tog-$pref",
1238 $defaultPreferences['watchlisttoken'] = [
1242 if ( $oouiEnabled ) {
1243 $tokenButton = new \OOUI\
ButtonWidget( [
1244 'href' => SpecialPage
::getTitleFor( 'ResetTokens' )->getLinkURL( [
1245 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
1247 'label' => $context->msg( 'prefs-watchlist-managetokens' )->text(),
1249 $defaultPreferences['watchlisttoken-info'] = [
1251 'section' => 'watchlist/tokenwatchlist',
1252 'label-message' => 'prefs-watchlist-token',
1253 'help-message' => 'prefs-help-tokenmanagement',
1255 'default' => (string)$tokenButton,
1258 $defaultPreferences['watchlisttoken-info'] = [
1260 'section' => 'watchlist/tokenwatchlist',
1261 'label-message' => 'prefs-watchlist-token',
1262 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1263 'help-message' => 'prefs-help-watchlist-token2',
1267 if ( $this->config
->get( 'StructuredChangeFiltersShowWatchlistPreference' ) ) {
1268 $defaultPreferences['wlenhancedfilters-disable'] = [
1270 'section' => 'watchlist/optoutwatchlist',
1271 'label-message' => 'rcfilters-watchlist-preference-label',
1272 'help-message' => 'rcfilters-watchlist-preference-help',
1278 * @param array &$defaultPreferences
1280 protected function searchPreferences( &$defaultPreferences ) {
1281 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
1282 $defaultPreferences['searchNs' . $n] = [
1289 * @param User $user The User object
1290 * @param IContextSource $context
1291 * @return array Text/links to display as key; $skinkey as value
1293 protected function generateSkinOptions( User
$user, IContextSource
$context ) {
1296 $mptitle = Title
::newMainPage();
1297 $previewtext = $context->msg( 'skin-preview' )->escaped();
1299 # Only show skins that aren't disabled in $wgSkipSkins
1300 $validSkinNames = Skin
::getAllowedSkins();
1302 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1303 $msg = $context->msg( "skinname-{$skinkey}" );
1304 if ( $msg->exists() ) {
1305 $skinname = htmlspecialchars( $msg->text() );
1309 $defaultSkin = $this->config
->get( 'DefaultSkin' );
1310 $allowUserCss = $this->config
->get( 'AllowUserCss' );
1311 $allowUserJs = $this->config
->get( 'AllowUserJs' );
1313 # Sort by the internal name, so that the ordering is the same for each display language,
1314 # especially if some skin names are translated to use a different alphabet and some are not.
1315 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1316 # Display the default first in the list by comparing it as lesser than any other.
1317 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1320 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1323 return strcasecmp( $a, $b );
1326 $foundDefault = false;
1327 foreach ( $validSkinNames as $skinkey => $sn ) {
1330 # Mark the default skin
1331 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1332 $linkTools[] = $context->msg( 'default' )->escaped();
1333 $foundDefault = true;
1336 # Create preview link
1337 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1338 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1340 # Create links to user CSS/JS pages
1341 if ( $allowUserCss ) {
1342 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1343 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
1344 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
1347 if ( $allowUserJs ) {
1348 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1349 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
1350 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
1353 $display = $sn . ' ' . $context->msg( 'parentheses' )
1354 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1356 $ret[$display] = $skinkey;
1359 if ( !$foundDefault ) {
1360 // If the default skin is not available, things are going to break horribly because the
1361 // default value for skin selector will not be a valid value. Let's just not show it then.
1369 * @param IContextSource $context
1372 protected function getDateOptions( IContextSource
$context ) {
1373 $lang = $context->getLanguage();
1374 $dateopts = $lang->getDatePreferences();
1379 if ( !in_array( 'default', $dateopts ) ) {
1380 $dateopts[] = 'default'; // Make sure default is always valid T21237
1383 // FIXME KLUGE: site default might not be valid for user language
1384 global $wgDefaultUserOptions;
1385 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1386 $wgDefaultUserOptions['date'] = 'default';
1389 $epoch = wfTimestampNow();
1390 foreach ( $dateopts as $key ) {
1391 if ( $key == 'default' ) {
1392 $formatted = $context->msg( 'datedefault' )->escaped();
1394 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1396 $ret[$formatted] = $key;
1403 * @param MessageLocalizer $l10n
1406 protected function getImageSizes( MessageLocalizer
$l10n ) {
1408 $pixels = $l10n->msg( 'unit-pixel' )->text();
1410 foreach ( $this->config
->get( 'ImageLimits' ) as $index => $limits ) {
1411 // Note: A left-to-right marker (U+200E) is inserted, see T144386
1412 $display = "{$limits[0]}\u{200E}×{$limits[1]}$pixels";
1413 $ret[$display] = $index;
1420 * @param MessageLocalizer $l10n
1423 protected function getThumbSizes( MessageLocalizer
$l10n ) {
1425 $pixels = $l10n->msg( 'unit-pixel' )->text();
1427 foreach ( $this->config
->get( 'ThumbLimits' ) as $index => $size ) {
1428 $display = $size . $pixels;
1429 $ret[$display] = $index;
1436 * @param string $signature
1437 * @param array $alldata
1438 * @param HTMLForm $form
1439 * @return bool|string
1441 protected function validateSignature( $signature, $alldata, HTMLForm
$form ) {
1442 $maxSigChars = $this->config
->get( 'MaxSigChars' );
1443 if ( mb_strlen( $signature ) > $maxSigChars ) {
1444 return Xml
::element( 'span', [ 'class' => 'error' ],
1445 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1446 } elseif ( isset( $alldata['fancysig'] ) &&
1447 $alldata['fancysig'] &&
1448 MediaWikiServices
::getInstance()->getParser()->validateSig( $signature ) === false
1450 return Xml
::element(
1452 [ 'class' => 'error' ],
1453 $form->msg( 'badsig' )->text()
1461 * @param string $signature
1462 * @param array $alldata
1463 * @param HTMLForm $form
1466 protected function cleanSignature( $signature, $alldata, HTMLForm
$form ) {
1467 $parser = MediaWikiServices
::getInstance()->getParser();
1468 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1469 $signature = $parser->cleanSig( $signature );
1471 // When no fancy sig used, make sure ~{3,5} get removed.
1472 $signature = Parser
::cleanSigInSig( $signature );
1480 * @param IContextSource $context
1481 * @param string $formClass
1482 * @param array $remove Array of items to remove
1485 public function getForm(
1487 IContextSource
$context,
1488 $formClass = PreferencesFormLegacy
::class,
1491 if ( SpecialPreferences
::isOouiEnabled( $context ) ) {
1492 // We use ButtonWidgets in some of the getPreferences() functions
1493 $context->getOutput()->enableOOUI();
1496 $formDescriptor = $this->getFormDescriptor( $user, $context );
1497 if ( count( $remove ) ) {
1498 $removeKeys = array_flip( $remove );
1499 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1502 // Remove type=api preferences. They are not intended for rendering in the form.
1503 foreach ( $formDescriptor as $name => $info ) {
1504 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1505 unset( $formDescriptor[$name] );
1510 * @var $htmlForm HTMLForm
1512 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1514 $htmlForm->setModifiedUser( $user );
1515 $htmlForm->setId( 'mw-prefs-form' );
1516 $htmlForm->setAutocomplete( 'off' );
1517 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1518 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1519 $htmlForm->setSubmitTooltip( 'preferences-save' );
1520 $htmlForm->setSubmitID( 'prefcontrol' );
1521 $htmlForm->setSubmitCallback(
1522 function ( array $formData, HTMLForm
$form ) use ( $formDescriptor ) {
1523 return $this->submitForm( $formData, $form, $formDescriptor );
1531 * @param IContextSource $context
1534 protected function getTimezoneOptions( IContextSource
$context ) {
1537 $localTZoffset = $this->config
->get( 'LocalTZoffset' );
1538 $timeZoneList = $this->getTimeZoneList( $context->getLanguage() );
1540 $timestamp = MWTimestamp
::getLocalInstance();
1541 // Check that the LocalTZoffset is the same as the local time zone offset
1542 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1543 $timezoneName = $timestamp->getTimezone()->getName();
1544 // Localize timezone
1545 if ( isset( $timeZoneList[$timezoneName] ) ) {
1546 $timezoneName = $timeZoneList[$timezoneName]['name'];
1548 $server_tz_msg = $context->msg(
1549 'timezoneuseserverdefault',
1553 $tzstring = sprintf(
1555 floor( $localTZoffset / 60 ),
1556 abs( $localTZoffset ) %
60
1558 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1560 $opt[$server_tz_msg] = "System|$localTZoffset";
1561 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1562 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1564 foreach ( $timeZoneList as $timeZoneInfo ) {
1565 $region = $timeZoneInfo['region'];
1566 if ( !isset( $opt[$region] ) ) {
1569 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1575 * Handle the form submission if everything validated properly
1577 * @param array $formData
1578 * @param HTMLForm $form
1579 * @param array[] $formDescriptor
1580 * @return bool|Status|string
1582 protected function saveFormData( $formData, HTMLForm
$form, array $formDescriptor ) {
1583 /** @var \User $user */
1584 $user = $form->getModifiedUser();
1585 $hiddenPrefs = $this->config
->get( 'HiddenPrefs' );
1588 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1589 return Status
::newFatal( 'mypreferencesprotected' );
1593 $this->applyFilters( $formData, $formDescriptor, 'filterFromForm' );
1595 // Fortunately, the realname field is MUCH simpler
1596 // (not really "private", but still shouldn't be edited without permission)
1598 if ( !in_array( 'realname', $hiddenPrefs )
1599 && $user->isAllowed( 'editmyprivateinfo' )
1600 && array_key_exists( 'realname', $formData )
1602 $realName = $formData['realname'];
1603 $user->setRealName( $realName );
1606 if ( $user->isAllowed( 'editmyoptions' ) ) {
1607 $oldUserOptions = $user->getOptions();
1609 foreach ( $this->getSaveBlacklist() as $b ) {
1610 unset( $formData[$b] );
1613 # If users have saved a value for a preference which has subsequently been disabled
1614 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1615 # is subsequently re-enabled
1616 foreach ( $hiddenPrefs as $pref ) {
1617 # If the user has not set a non-default value here, the default will be returned
1618 # and subsequently discarded
1619 $formData[$pref] = $user->getOption( $pref, null, true );
1622 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1624 isset( $formData['rclimit'] ) &&
1625 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1627 $formData['rcfilters-limit'] = $formData['rclimit'];
1630 // Keep old preferences from interfering due to back-compat code, etc.
1631 $user->resetOptions( 'unused', $form->getContext() );
1633 foreach ( $formData as $key => $value ) {
1634 $user->setOption( $key, $value );
1638 'PreferencesFormPreSave',
1639 [ $formData, $form, $user, &$result, $oldUserOptions ]
1643 AuthManager
::callLegacyAuthPlugin( 'updateExternalDB', [ $user ] );
1644 $user->saveSettings();
1650 * Applies filters to preferences either before or after form usage
1652 * @param array &$preferences
1653 * @param array $formDescriptor
1654 * @param string $verb Name of the filter method to call, either 'filterFromForm' or
1657 protected function applyFilters( array &$preferences, array $formDescriptor, $verb ) {
1658 foreach ( $formDescriptor as $preference => $desc ) {
1659 if ( !isset( $desc['filter'] ) ||
!isset( $preferences[$preference] ) ) {
1662 $filterDesc = $desc['filter'];
1663 if ( $filterDesc instanceof Filter
) {
1664 $filter = $filterDesc;
1665 } elseif ( class_exists( $filterDesc ) ) {
1666 $filter = new $filterDesc();
1667 } elseif ( is_callable( $filterDesc ) ) {
1668 $filter = $filterDesc();
1670 throw new UnexpectedValueException(
1671 "Unrecognized filter type for preference '$preference'"
1674 $preferences[$preference] = $filter->$verb( $preferences[$preference] );
1679 * Save the form data and reload the page
1681 * @param array $formData
1682 * @param HTMLForm $form
1683 * @param array $formDescriptor
1686 protected function submitForm( array $formData, HTMLForm
$form, array $formDescriptor ) {
1687 $res = $this->saveFormData( $formData, $form, $formDescriptor );
1689 if ( $res === true ) {
1690 $context = $form->getContext();
1693 if ( $res === 'eauth' ) {
1694 $urlOptions['eauth'] = 1;
1698 $context->getRequest()->getFuzzyBool( 'ooui' ) !==
1699 $context->getConfig()->get( 'OOUIPreferences' )
1701 $urlOptions[ 'ooui' ] = $context->getRequest()->getFuzzyBool( 'ooui' ) ?
1 : 0;
1704 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1706 $url = $form->getTitle()->getFullURL( $urlOptions );
1708 // Set session data for the success message
1709 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1711 $context->getOutput()->redirect( $url );
1714 return ( $res === true ? Status
::newGood() : $res );
1718 * Get a list of all time zones
1719 * @param Language $language Language used for the localized names
1720 * @return array A list of all time zones. The system name of the time zone is used as key and
1721 * the value is an array which contains localized name, the timecorrection value used for
1722 * preferences and the region
1725 protected function getTimeZoneList( Language
$language ) {
1726 $identifiers = DateTimeZone
::listIdentifiers();
1727 if ( $identifiers === false ) {
1730 sort( $identifiers );
1733 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1734 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1735 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1736 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1737 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1738 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1739 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1740 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1741 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1742 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1744 asort( $tzRegions );
1748 $now = new DateTime();
1750 foreach ( $identifiers as $identifier ) {
1751 $parts = explode( '/', $identifier, 2 );
1753 // DateTimeZone::listIdentifiers() returns a number of
1754 // backwards-compatibility entries. This filters them out of the
1755 // list presented to the user.
1756 if ( count( $parts ) !== 2 ||
!array_key_exists( $parts[0], $tzRegions ) ) {
1761 $parts[0] = $tzRegions[$parts[0]];
1763 $dateTimeZone = new DateTimeZone( $identifier );
1764 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1766 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1767 $value = "ZoneInfo|$minDiff|$identifier";
1769 $timeZoneList[$identifier] = [
1771 'timecorrection' => $value,
1772 'region' => $parts[0],
1776 return $timeZoneList;