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 $defaultPreferences['rcenhancedfilters-disable'] = [
1065 'section' => 'rc/optoutrc',
1066 'label-message' => 'rcfilters-preference-label',
1067 'help-message' => 'rcfilters-preference-help',
1073 * @param IContextSource $context
1074 * @param array &$defaultPreferences
1076 protected function watchlistPreferences(
1077 User
$user, IContextSource
$context, &$defaultPreferences
1079 $oouiEnabled = SpecialPreferences
::isOouiEnabled( $context );
1081 $watchlistdaysMax = ceil( $this->config
->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1083 # # Watchlist #####################################
1084 if ( $user->isAllowed( 'editmywatchlist' ) ) {
1085 $editWatchlistLinks = '';
1086 $editWatchlistLinksOld = [];
1087 $editWatchlistModes = [
1088 'edit' => [ 'subpage' => false, 'flags' => [] ],
1089 'raw' => [ 'subpage' => 'raw', 'flags' => [] ],
1090 'clear' => [ 'subpage' => 'clear', 'flags' => [ 'destructive' ] ],
1092 foreach ( $editWatchlistModes as $mode => $options ) {
1093 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1094 if ( $oouiEnabled ) {
1095 $editWatchlistLinks .=
1096 new \OOUI\
ButtonWidget( [
1097 'href' => SpecialPage
::getTitleFor( 'EditWatchlist', $options['subpage'] )->getLinkURL(),
1098 'flags' => $options[ 'flags' ],
1099 'label' => new \OOUI\
HtmlSnippet(
1100 $context->msg( "prefs-editwatchlist-{$mode}" )->parse()
1104 $editWatchlistLinksOld[] = $this->linkRenderer
->makeKnownLink(
1105 SpecialPage
::getTitleFor( 'EditWatchlist', $options['subpage'] ),
1106 new HtmlArmor( $context->msg( "prefs-editwatchlist-{$mode}" )->parse() )
1111 $defaultPreferences['editwatchlist'] = [
1114 'default' => $oouiEnabled ?
1115 $editWatchlistLinks :
1116 $context->getLanguage()->pipeList( $editWatchlistLinksOld ),
1117 'label-message' => 'prefs-editwatchlist-label',
1118 'section' => 'watchlist/editwatchlist',
1122 $defaultPreferences['watchlistdays'] = [
1125 'max' => $watchlistdaysMax,
1126 'section' => 'watchlist/displaywatchlist',
1127 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1128 $watchlistdaysMax )->escaped(),
1129 'label-message' => 'prefs-watchlist-days',
1131 $defaultPreferences['wllimit'] = [
1135 'label-message' => 'prefs-watchlist-edits',
1136 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1137 'section' => 'watchlist/displaywatchlist',
1138 'filter' => IntvalFilter
::class,
1140 $defaultPreferences['extendwatchlist'] = [
1142 'section' => 'watchlist/advancedwatchlist',
1143 'label-message' => 'tog-extendwatchlist',
1145 $defaultPreferences['watchlisthideminor'] = [
1147 'section' => 'watchlist/advancedwatchlist',
1148 'label-message' => 'tog-watchlisthideminor',
1150 $defaultPreferences['watchlisthidebots'] = [
1152 'section' => 'watchlist/advancedwatchlist',
1153 'label-message' => 'tog-watchlisthidebots',
1155 $defaultPreferences['watchlisthideown'] = [
1157 'section' => 'watchlist/advancedwatchlist',
1158 'label-message' => 'tog-watchlisthideown',
1160 $defaultPreferences['watchlisthideanons'] = [
1162 'section' => 'watchlist/advancedwatchlist',
1163 'label-message' => 'tog-watchlisthideanons',
1165 $defaultPreferences['watchlisthideliu'] = [
1167 'section' => 'watchlist/advancedwatchlist',
1168 'label-message' => 'tog-watchlisthideliu',
1171 if ( !\SpecialWatchlist
::checkStructuredFilterUiEnabled(
1175 $defaultPreferences['watchlistreloadautomatically'] = [
1177 'section' => 'watchlist/advancedwatchlist',
1178 'label-message' => 'tog-watchlistreloadautomatically',
1182 $defaultPreferences['watchlistunwatchlinks'] = [
1184 'section' => 'watchlist/advancedwatchlist',
1185 'label-message' => 'tog-watchlistunwatchlinks',
1188 if ( $this->config
->get( 'RCWatchCategoryMembership' ) ) {
1189 $defaultPreferences['watchlisthidecategorization'] = [
1191 'section' => 'watchlist/advancedwatchlist',
1192 'label-message' => 'tog-watchlisthidecategorization',
1196 if ( $user->useRCPatrol() ) {
1197 $defaultPreferences['watchlisthidepatrolled'] = [
1199 'section' => 'watchlist/advancedwatchlist',
1200 'label-message' => 'tog-watchlisthidepatrolled',
1205 'edit' => 'watchdefault',
1206 'move' => 'watchmoves',
1207 'delete' => 'watchdeletion'
1211 if ( $user->isAllowed( 'createpage' ) ||
$user->isAllowed( 'createtalk' ) ) {
1212 $watchTypes['read'] = 'watchcreations';
1215 if ( $user->isAllowed( 'rollback' ) ) {
1216 $watchTypes['rollback'] = 'watchrollback';
1219 if ( $user->isAllowed( 'upload' ) ) {
1220 $watchTypes['upload'] = 'watchuploads';
1223 foreach ( $watchTypes as $action => $pref ) {
1224 if ( $user->isAllowed( $action ) ) {
1226 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1227 // tog-watchrollback
1228 $defaultPreferences[$pref] = [
1230 'section' => 'watchlist/advancedwatchlist',
1231 'label-message' => "tog-$pref",
1236 $defaultPreferences['watchlisttoken'] = [
1240 if ( $oouiEnabled ) {
1241 $tokenButton = new \OOUI\
ButtonWidget( [
1242 'href' => SpecialPage
::getTitleFor( 'ResetTokens' )->getLinkURL( [
1243 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
1245 'label' => $context->msg( 'prefs-watchlist-managetokens' )->text(),
1247 $defaultPreferences['watchlisttoken-info'] = [
1249 'section' => 'watchlist/tokenwatchlist',
1250 'label-message' => 'prefs-watchlist-token',
1251 'help-message' => 'prefs-help-tokenmanagement',
1253 'default' => (string)$tokenButton,
1256 $defaultPreferences['watchlisttoken-info'] = [
1258 'section' => 'watchlist/tokenwatchlist',
1259 'label-message' => 'prefs-watchlist-token',
1260 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1261 'help-message' => 'prefs-help-watchlist-token2',
1265 $defaultPreferences['wlenhancedfilters-disable'] = [
1267 'section' => 'watchlist/optoutwatchlist',
1268 'label-message' => 'rcfilters-watchlist-preference-label',
1269 'help-message' => 'rcfilters-watchlist-preference-help',
1274 * @param array &$defaultPreferences
1276 protected function searchPreferences( &$defaultPreferences ) {
1277 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
1278 $defaultPreferences['searchNs' . $n] = [
1285 * @param User $user The User object
1286 * @param IContextSource $context
1287 * @return array Text/links to display as key; $skinkey as value
1289 protected function generateSkinOptions( User
$user, IContextSource
$context ) {
1292 $mptitle = Title
::newMainPage();
1293 $previewtext = $context->msg( 'skin-preview' )->escaped();
1295 # Only show skins that aren't disabled in $wgSkipSkins
1296 $validSkinNames = Skin
::getAllowedSkins();
1298 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1299 $msg = $context->msg( "skinname-{$skinkey}" );
1300 if ( $msg->exists() ) {
1301 $skinname = htmlspecialchars( $msg->text() );
1305 $defaultSkin = $this->config
->get( 'DefaultSkin' );
1306 $allowUserCss = $this->config
->get( 'AllowUserCss' );
1307 $allowUserJs = $this->config
->get( 'AllowUserJs' );
1309 # Sort by the internal name, so that the ordering is the same for each display language,
1310 # especially if some skin names are translated to use a different alphabet and some are not.
1311 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1312 # Display the default first in the list by comparing it as lesser than any other.
1313 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1316 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1319 return strcasecmp( $a, $b );
1322 $foundDefault = false;
1323 foreach ( $validSkinNames as $skinkey => $sn ) {
1326 # Mark the default skin
1327 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1328 $linkTools[] = $context->msg( 'default' )->escaped();
1329 $foundDefault = true;
1332 # Create preview link
1333 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1334 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1336 # Create links to user CSS/JS pages
1337 if ( $allowUserCss ) {
1338 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1339 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
1340 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
1343 if ( $allowUserJs ) {
1344 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1345 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
1346 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
1349 $display = $sn . ' ' . $context->msg( 'parentheses' )
1350 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1352 $ret[$display] = $skinkey;
1355 if ( !$foundDefault ) {
1356 // If the default skin is not available, things are going to break horribly because the
1357 // default value for skin selector will not be a valid value. Let's just not show it then.
1365 * @param IContextSource $context
1368 protected function getDateOptions( IContextSource
$context ) {
1369 $lang = $context->getLanguage();
1370 $dateopts = $lang->getDatePreferences();
1375 if ( !in_array( 'default', $dateopts ) ) {
1376 $dateopts[] = 'default'; // Make sure default is always valid T21237
1379 // FIXME KLUGE: site default might not be valid for user language
1380 global $wgDefaultUserOptions;
1381 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1382 $wgDefaultUserOptions['date'] = 'default';
1385 $epoch = wfTimestampNow();
1386 foreach ( $dateopts as $key ) {
1387 if ( $key == 'default' ) {
1388 $formatted = $context->msg( 'datedefault' )->escaped();
1390 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1392 $ret[$formatted] = $key;
1399 * @param MessageLocalizer $l10n
1402 protected function getImageSizes( MessageLocalizer
$l10n ) {
1404 $pixels = $l10n->msg( 'unit-pixel' )->text();
1406 foreach ( $this->config
->get( 'ImageLimits' ) as $index => $limits ) {
1407 // Note: A left-to-right marker (U+200E) is inserted, see T144386
1408 $display = "{$limits[0]}\u{200E}×{$limits[1]}$pixels";
1409 $ret[$display] = $index;
1416 * @param MessageLocalizer $l10n
1419 protected function getThumbSizes( MessageLocalizer
$l10n ) {
1421 $pixels = $l10n->msg( 'unit-pixel' )->text();
1423 foreach ( $this->config
->get( 'ThumbLimits' ) as $index => $size ) {
1424 $display = $size . $pixels;
1425 $ret[$display] = $index;
1432 * @param string $signature
1433 * @param array $alldata
1434 * @param HTMLForm $form
1435 * @return bool|string
1437 protected function validateSignature( $signature, $alldata, HTMLForm
$form ) {
1438 $maxSigChars = $this->config
->get( 'MaxSigChars' );
1439 if ( mb_strlen( $signature ) > $maxSigChars ) {
1440 return Xml
::element( 'span', [ 'class' => 'error' ],
1441 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1442 } elseif ( isset( $alldata['fancysig'] ) &&
1443 $alldata['fancysig'] &&
1444 MediaWikiServices
::getInstance()->getParser()->validateSig( $signature ) === false
1446 return Xml
::element(
1448 [ 'class' => 'error' ],
1449 $form->msg( 'badsig' )->text()
1457 * @param string $signature
1458 * @param array $alldata
1459 * @param HTMLForm $form
1462 protected function cleanSignature( $signature, $alldata, HTMLForm
$form ) {
1463 $parser = MediaWikiServices
::getInstance()->getParser();
1464 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1465 $signature = $parser->cleanSig( $signature );
1467 // When no fancy sig used, make sure ~{3,5} get removed.
1468 $signature = Parser
::cleanSigInSig( $signature );
1476 * @param IContextSource $context
1477 * @param string $formClass
1478 * @param array $remove Array of items to remove
1481 public function getForm(
1483 IContextSource
$context,
1484 $formClass = PreferencesFormLegacy
::class,
1487 if ( SpecialPreferences
::isOouiEnabled( $context ) ) {
1488 // We use ButtonWidgets in some of the getPreferences() functions
1489 $context->getOutput()->enableOOUI();
1492 $formDescriptor = $this->getFormDescriptor( $user, $context );
1493 if ( count( $remove ) ) {
1494 $removeKeys = array_flip( $remove );
1495 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1498 // Remove type=api preferences. They are not intended for rendering in the form.
1499 foreach ( $formDescriptor as $name => $info ) {
1500 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1501 unset( $formDescriptor[$name] );
1506 * @var $htmlForm HTMLForm
1508 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1510 $htmlForm->setModifiedUser( $user );
1511 $htmlForm->setId( 'mw-prefs-form' );
1512 $htmlForm->setAutocomplete( 'off' );
1513 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1514 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1515 $htmlForm->setSubmitTooltip( 'preferences-save' );
1516 $htmlForm->setSubmitID( 'prefcontrol' );
1517 $htmlForm->setSubmitCallback(
1518 function ( array $formData, HTMLForm
$form ) use ( $formDescriptor ) {
1519 return $this->submitForm( $formData, $form, $formDescriptor );
1527 * @param IContextSource $context
1530 protected function getTimezoneOptions( IContextSource
$context ) {
1533 $localTZoffset = $this->config
->get( 'LocalTZoffset' );
1534 $timeZoneList = $this->getTimeZoneList( $context->getLanguage() );
1536 $timestamp = MWTimestamp
::getLocalInstance();
1537 // Check that the LocalTZoffset is the same as the local time zone offset
1538 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1539 $timezoneName = $timestamp->getTimezone()->getName();
1540 // Localize timezone
1541 if ( isset( $timeZoneList[$timezoneName] ) ) {
1542 $timezoneName = $timeZoneList[$timezoneName]['name'];
1544 $server_tz_msg = $context->msg(
1545 'timezoneuseserverdefault',
1549 $tzstring = sprintf(
1551 floor( $localTZoffset / 60 ),
1552 abs( $localTZoffset ) %
60
1554 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1556 $opt[$server_tz_msg] = "System|$localTZoffset";
1557 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1558 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1560 foreach ( $timeZoneList as $timeZoneInfo ) {
1561 $region = $timeZoneInfo['region'];
1562 if ( !isset( $opt[$region] ) ) {
1565 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1571 * Handle the form submission if everything validated properly
1573 * @param array $formData
1574 * @param HTMLForm $form
1575 * @param array[] $formDescriptor
1576 * @return bool|Status|string
1578 protected function saveFormData( $formData, HTMLForm
$form, array $formDescriptor ) {
1579 /** @var \User $user */
1580 $user = $form->getModifiedUser();
1581 $hiddenPrefs = $this->config
->get( 'HiddenPrefs' );
1584 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1585 return Status
::newFatal( 'mypreferencesprotected' );
1589 $this->applyFilters( $formData, $formDescriptor, 'filterFromForm' );
1591 // Fortunately, the realname field is MUCH simpler
1592 // (not really "private", but still shouldn't be edited without permission)
1594 if ( !in_array( 'realname', $hiddenPrefs )
1595 && $user->isAllowed( 'editmyprivateinfo' )
1596 && array_key_exists( 'realname', $formData )
1598 $realName = $formData['realname'];
1599 $user->setRealName( $realName );
1602 if ( $user->isAllowed( 'editmyoptions' ) ) {
1603 $oldUserOptions = $user->getOptions();
1605 foreach ( $this->getSaveBlacklist() as $b ) {
1606 unset( $formData[$b] );
1609 # If users have saved a value for a preference which has subsequently been disabled
1610 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1611 # is subsequently re-enabled
1612 foreach ( $hiddenPrefs as $pref ) {
1613 # If the user has not set a non-default value here, the default will be returned
1614 # and subsequently discarded
1615 $formData[$pref] = $user->getOption( $pref, null, true );
1618 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1620 isset( $formData['rclimit'] ) &&
1621 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1623 $formData['rcfilters-limit'] = $formData['rclimit'];
1626 // Keep old preferences from interfering due to back-compat code, etc.
1627 $user->resetOptions( 'unused', $form->getContext() );
1629 foreach ( $formData as $key => $value ) {
1630 $user->setOption( $key, $value );
1634 'PreferencesFormPreSave',
1635 [ $formData, $form, $user, &$result, $oldUserOptions ]
1639 AuthManager
::callLegacyAuthPlugin( 'updateExternalDB', [ $user ] );
1640 $user->saveSettings();
1646 * Applies filters to preferences either before or after form usage
1648 * @param array &$preferences
1649 * @param array $formDescriptor
1650 * @param string $verb Name of the filter method to call, either 'filterFromForm' or
1653 protected function applyFilters( array &$preferences, array $formDescriptor, $verb ) {
1654 foreach ( $formDescriptor as $preference => $desc ) {
1655 if ( !isset( $desc['filter'] ) ||
!isset( $preferences[$preference] ) ) {
1658 $filterDesc = $desc['filter'];
1659 if ( $filterDesc instanceof Filter
) {
1660 $filter = $filterDesc;
1661 } elseif ( class_exists( $filterDesc ) ) {
1662 $filter = new $filterDesc();
1663 } elseif ( is_callable( $filterDesc ) ) {
1664 $filter = $filterDesc();
1666 throw new UnexpectedValueException(
1667 "Unrecognized filter type for preference '$preference'"
1670 $preferences[$preference] = $filter->$verb( $preferences[$preference] );
1675 * Save the form data and reload the page
1677 * @param array $formData
1678 * @param HTMLForm $form
1679 * @param array $formDescriptor
1682 protected function submitForm( array $formData, HTMLForm
$form, array $formDescriptor ) {
1683 $res = $this->saveFormData( $formData, $form, $formDescriptor );
1685 if ( $res === true ) {
1686 $context = $form->getContext();
1689 if ( $res === 'eauth' ) {
1690 $urlOptions['eauth'] = 1;
1694 $context->getRequest()->getFuzzyBool( 'ooui' ) !==
1695 $context->getConfig()->get( 'OOUIPreferences' )
1697 $urlOptions[ 'ooui' ] = $context->getRequest()->getFuzzyBool( 'ooui' ) ?
1 : 0;
1700 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1702 $url = $form->getTitle()->getFullURL( $urlOptions );
1704 // Set session data for the success message
1705 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1707 $context->getOutput()->redirect( $url );
1710 return ( $res === true ? Status
::newGood() : $res );
1714 * Get a list of all time zones
1715 * @param Language $language Language used for the localized names
1716 * @return array A list of all time zones. The system name of the time zone is used as key and
1717 * the value is an array which contains localized name, the timecorrection value used for
1718 * preferences and the region
1721 protected function getTimeZoneList( Language
$language ) {
1722 $identifiers = DateTimeZone
::listIdentifiers();
1723 if ( $identifiers === false ) {
1726 sort( $identifiers );
1729 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1730 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1731 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1732 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1733 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1734 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1735 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1736 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1737 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1738 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1740 asort( $tzRegions );
1744 $now = new DateTime();
1746 foreach ( $identifiers as $identifier ) {
1747 $parts = explode( '/', $identifier, 2 );
1749 // DateTimeZone::listIdentifiers() returns a number of
1750 // backwards-compatibility entries. This filters them out of the
1751 // list presented to the user.
1752 if ( count( $parts ) !== 2 ||
!array_key_exists( $parts[0], $tzRegions ) ) {
1757 $parts[0] = $tzRegions[$parts[0]];
1759 $dateTimeZone = new DateTimeZone( $identifier );
1760 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1762 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1763 $value = "ZoneInfo|$minDiff|$identifier";
1765 $timeZoneList[$identifier] = [
1767 'timecorrection' => $value,
1768 'region' => $parts[0],
1772 return $timeZoneList;