3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 namespace MediaWiki\Preferences
;
34 use LanguageConverter
;
35 use MediaWiki\Auth\AuthManager
;
36 use MediaWiki\Auth\PasswordAuthenticationRequest
;
37 use MediaWiki\Config\ServiceOptions
;
38 use MediaWiki\Linker\LinkRenderer
;
39 use MediaWiki\MediaWikiServices
;
47 use PreferencesFormOOUI
;
48 use Psr\Log\LoggerAwareTrait
;
49 use Psr\Log\NullLogger
;
54 use UnexpectedValueException
;
56 use UserGroupMembership
;
60 * This is the default implementation of PreferencesFactory.
62 class DefaultPreferencesFactory
implements PreferencesFactory
{
65 /** @var ServiceOptions */
68 /** @var Language The wiki's content language. */
71 /** @var AuthManager */
72 protected $authManager;
74 /** @var LinkRenderer */
75 protected $linkRenderer;
77 /** @var NamespaceInfo */
81 * TODO Make this a const when we drop HHVM support (T192166)
86 public static $constructorOptions = [
87 'AllowRequiringEmailForResets',
92 'DisableLangConversion',
93 'EmailAuthentication',
97 'EnableUserEmailBlacklist',
99 'EnotifRevealEditorAddress',
108 'RCShowWatchingUsers',
109 'RCWatchCategoryMembership',
115 * Do not call this directly. Get it from MediaWikiServices.
117 * @param ServiceOptions|Config $options Config accepted for backwards compatibility
118 * @param Language $contLang
119 * @param AuthManager $authManager
120 * @param LinkRenderer $linkRenderer
121 * @param NamespaceInfo|null $nsInfo
123 public function __construct(
126 AuthManager
$authManager,
127 LinkRenderer
$linkRenderer,
128 NamespaceInfo
$nsInfo = null
130 if ( $options instanceof Config
) {
131 wfDeprecated( __METHOD__
. ' with Config parameter', '1.34' );
132 $options = new ServiceOptions( self
::$constructorOptions, $options );
135 $options->assertRequiredOptions( self
::$constructorOptions );
138 wfDeprecated( __METHOD__
. ' with no NamespaceInfo argument', '1.34' );
139 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
141 $this->options
= $options;
142 $this->contLang
= $contLang;
143 $this->authManager
= $authManager;
144 $this->linkRenderer
= $linkRenderer;
145 $this->nsInfo
= $nsInfo;
146 $this->logger
= new NullLogger();
152 public function getSaveBlacklist() {
160 * @throws MWException
162 * @param IContextSource $context
165 public function getFormDescriptor( User
$user, IContextSource
$context ) {
168 OutputPage
::setupOOUI(
169 strtolower( $context->getSkin()->getSkinName() ),
170 $context->getLanguage()->getDir()
173 $canIPUseHTTPS = wfCanIPUseHTTPS( $context->getRequest()->getIP() );
174 $this->profilePreferences( $user, $context, $preferences, $canIPUseHTTPS );
175 $this->skinPreferences( $user, $context, $preferences );
176 $this->datetimePreferences( $user, $context, $preferences );
177 $this->filesPreferences( $context, $preferences );
178 $this->renderingPreferences( $user, $context, $preferences );
179 $this->editingPreferences( $user, $context, $preferences );
180 $this->rcPreferences( $user, $context, $preferences );
181 $this->watchlistPreferences( $user, $context, $preferences );
182 $this->searchPreferences( $preferences );
184 Hooks
::run( 'GetPreferences', [ $user, &$preferences ] );
186 $this->loadPreferenceValues( $user, $context, $preferences );
187 $this->logger
->debug( "Created form descriptor for user '{$user->getName()}'" );
192 * Loads existing values for a given array of preferences
193 * @throws MWException
195 * @param IContextSource $context
196 * @param array &$defaultPreferences Array to load values for
199 private function loadPreferenceValues(
200 User
$user, IContextSource
$context, &$defaultPreferences
202 # # Remove preferences that wikis don't want to use
203 foreach ( $this->options
->get( 'HiddenPrefs' ) as $pref ) {
204 if ( isset( $defaultPreferences[$pref] ) ) {
205 unset( $defaultPreferences[$pref] );
209 # # Make sure that form fields have their parent set. See T43337.
210 $dummyForm = new HTMLForm( [], $context );
212 $disable = !$user->isAllowed( 'editmyoptions' );
214 $defaultOptions = User
::getDefaultOptions();
215 $userOptions = $user->getOptions();
216 $this->applyFilters( $userOptions, $defaultPreferences, 'filterForForm' );
217 # # Prod in defaults from the user
218 foreach ( $defaultPreferences as $name => &$info ) {
219 $prefFromUser = $this->getOptionFromUser( $name, $info, $userOptions );
220 if ( $disable && !in_array( $name, $this->getSaveBlacklist() ) ) {
221 $info['disabled'] = 'disabled';
223 $field = HTMLForm
::loadInputFromParameters( $name, $info, $dummyForm ); // For validation
224 $globalDefault = $defaultOptions[$name] ??
null;
226 // If it validates, set it as the default
227 if ( isset( $info['default'] ) ) {
228 // Already set, no problem
230 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
231 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
232 $info['default'] = $prefFromUser;
233 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
234 $info['default'] = $globalDefault;
236 $globalDefault = json_encode( $globalDefault );
237 throw new MWException(
238 "Default '$globalDefault' is invalid for preference $name of user $user"
243 return $defaultPreferences;
247 * Pull option from a user account. Handles stuff like array-type preferences.
249 * @param string $name
251 * @param array $userOptions
252 * @return array|string
254 protected function getOptionFromUser( $name, $info, array $userOptions ) {
255 $val = $userOptions[$name] ??
null;
257 // Handling for multiselect preferences
258 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
259 ( isset( $info['class'] ) && $info['class'] == \HTMLMultiSelectField
::class ) ) {
260 $options = HTMLFormField
::flattenOptions( $info['options'] );
261 $prefix = $info['prefix'] ??
$name;
264 foreach ( $options as $value ) {
265 if ( $userOptions["$prefix$value"] ??
false ) {
271 // Handling for checkmatrix preferences
272 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
273 ( isset( $info['class'] ) && $info['class'] == \HTMLCheckMatrix
::class ) ) {
274 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
275 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
276 $prefix = $info['prefix'] ??
$name;
279 foreach ( $columns as $column ) {
280 foreach ( $rows as $row ) {
281 if ( $userOptions["$prefix$column-$row"] ??
false ) {
282 $val[] = "$column-$row";
292 * @todo Inject user Language instead of using context.
294 * @param IContextSource $context
295 * @param array &$defaultPreferences
296 * @param bool $canIPUseHTTPS Whether the user's IP is likely to be able to access the wiki
300 protected function profilePreferences(
301 User
$user, IContextSource
$context, &$defaultPreferences, $canIPUseHTTPS
303 // retrieving user name for GENDER and misc.
304 $userName = $user->getName();
306 # # User info #####################################
308 $defaultPreferences['username'] = [
310 'label-message' => [ 'username', $userName ],
311 'default' => $userName,
312 'section' => 'personal/info',
315 $lang = $context->getLanguage();
317 # Get groups to which the user belongs
318 $userEffectiveGroups = $user->getEffectiveGroups();
319 $userGroupMemberships = $user->getGroupMemberships();
320 $userGroups = $userMembers = $userTempGroups = $userTempMembers = [];
321 foreach ( $userEffectiveGroups as $ueg ) {
323 // Skip the default * group, seems useless here
327 $groupStringOrObject = $userGroupMemberships[$ueg] ??
$ueg;
329 $userG = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html' );
330 $userM = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html',
333 // Store expiring groups separately, so we can place them before non-expiring
334 // groups in the list. This is to avoid the ambiguity of something like
335 // "administrator, bureaucrat (until X date)" -- users might wonder whether the
336 // expiry date applies to both groups, or just the last one
337 if ( $groupStringOrObject instanceof UserGroupMembership
&&
338 $groupStringOrObject->getExpiry()
340 $userTempGroups[] = $userG;
341 $userTempMembers[] = $userM;
343 $userGroups[] = $userG;
344 $userMembers[] = $userM;
348 sort( $userMembers );
349 sort( $userTempGroups );
350 sort( $userTempMembers );
351 $userGroups = array_merge( $userTempGroups, $userGroups );
352 $userMembers = array_merge( $userTempMembers, $userMembers );
354 $defaultPreferences['usergroups'] = [
356 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
357 count( $userGroups ) )->params( $userName )->parse(),
358 'default' => $context->msg( 'prefs-memberingroups-type' )
359 ->rawParams( $lang->commaList( $userGroups ), $lang->commaList( $userMembers ) )
362 'section' => 'personal/info',
365 $contribTitle = SpecialPage
::getTitleFor( "Contributions", $userName );
366 $formattedEditCount = $lang->formatNum( $user->getEditCount() );
367 $editCount = $this->linkRenderer
->makeLink( $contribTitle, $formattedEditCount );
369 $defaultPreferences['editcount'] = [
372 'label-message' => 'prefs-edits',
373 'default' => $editCount,
374 'section' => 'personal/info',
377 if ( $user->getRegistration() ) {
378 $displayUser = $context->getUser();
379 $userRegistration = $user->getRegistration();
380 $defaultPreferences['registrationdate'] = [
382 'label-message' => 'prefs-registration',
383 'default' => $context->msg(
384 'prefs-registration-date-time',
385 $lang->userTimeAndDate( $userRegistration, $displayUser ),
386 $lang->userDate( $userRegistration, $displayUser ),
387 $lang->userTime( $userRegistration, $displayUser )
389 'section' => 'personal/info',
393 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
394 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
396 // Actually changeable stuff
397 $defaultPreferences['realname'] = [
398 // (not really "private", but still shouldn't be edited without permission)
399 'type' => $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'realname' )
401 'default' => $user->getRealName(),
402 'section' => 'personal/info',
403 'label-message' => 'yourrealname',
404 'help-message' => 'prefs-help-realname',
407 if ( $canEditPrivateInfo && $this->authManager
->allowsAuthenticationDataChange(
408 new PasswordAuthenticationRequest(), false )->isGood()
410 $defaultPreferences['password'] = [
413 'default' => (string)new \OOUI\
ButtonWidget( [
414 'href' => SpecialPage
::getTitleFor( 'ChangePassword' )->getLinkURL( [
415 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
417 'label' => $context->msg( 'prefs-resetpass' )->text(),
419 'label-message' => 'yourpassword',
420 'section' => 'personal/info',
423 // Only show prefershttps if secure login is turned on
424 if ( $this->options
->get( 'SecureLogin' ) && $canIPUseHTTPS ) {
425 $defaultPreferences['prefershttps'] = [
427 'label-message' => 'tog-prefershttps',
428 'help-message' => 'prefs-help-prefershttps',
429 'section' => 'personal/info'
433 $languages = Language
::fetchLanguageNames( null, 'mwfile' );
434 $languageCode = $this->options
->get( 'LanguageCode' );
435 if ( !array_key_exists( $languageCode, $languages ) ) {
436 $languages[$languageCode] = $languageCode;
437 // Sort the array again
442 foreach ( $languages as $code => $name ) {
443 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
444 $options[$display] = $code;
446 $defaultPreferences['language'] = [
448 'section' => 'personal/i18n',
449 'options' => $options,
450 'label-message' => 'yourlanguage',
453 $defaultPreferences['gender'] = [
455 'section' => 'personal/i18n',
457 $context->msg( 'parentheses' )
458 ->params( $context->msg( 'gender-unknown' )->plain() )
459 ->escaped() => 'unknown',
460 $context->msg( 'gender-female' )->escaped() => 'female',
461 $context->msg( 'gender-male' )->escaped() => 'male',
463 'label-message' => 'yourgender',
464 'help-message' => 'prefs-help-gender',
467 // see if there are multiple language variants to choose from
468 if ( !$this->options
->get( 'DisableLangConversion' ) ) {
469 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
470 if ( $langCode == $this->contLang
->getCode() ) {
471 if ( !$this->contLang
->hasVariants() ) {
475 $variants = $this->contLang
->getVariants();
477 foreach ( $variants as $v ) {
478 $v = str_replace( '_', '-', strtolower( $v ) );
479 $variantArray[$v] = $lang->getVariantname( $v, false );
483 foreach ( $variantArray as $code => $name ) {
484 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
485 $options[$display] = $code;
488 $defaultPreferences['variant'] = [
489 'label-message' => 'yourvariant',
491 'options' => $options,
492 'section' => 'personal/i18n',
493 'help-message' => 'prefs-help-variant',
496 $defaultPreferences["variant-$langCode"] = [
503 // show a preview of the old signature first
504 $oldsigWikiText = MediaWikiServices
::getInstance()->getParser()->preSaveTransform(
506 $context->getTitle(),
508 ParserOptions
::newFromContext( $context )
510 $oldsigHTML = Parser
::stripOuterParagraph(
511 $context->getOutput()->parseAsContent( $oldsigWikiText )
513 $defaultPreferences['oldsig'] = [
516 'label-message' => 'tog-oldsig',
517 'default' => $oldsigHTML,
518 'section' => 'personal/signature',
520 $defaultPreferences['nickname'] = [
521 'type' => $this->authManager
->allowsPropertyChange( 'nickname' ) ?
'text' : 'info',
522 'maxlength' => $this->options
->get( 'MaxSigChars' ),
523 'label-message' => 'yournick',
524 'validation-callback' => function ( $signature, $alldata, HTMLForm
$form ) {
525 return $this->validateSignature( $signature, $alldata, $form );
527 'section' => 'personal/signature',
528 'filter-callback' => function ( $signature, array $alldata, HTMLForm
$form ) {
529 return $this->cleanSignature( $signature, $alldata, $form );
532 $defaultPreferences['fancysig'] = [
534 'label-message' => 'tog-fancysig',
535 // show general help about signature at the bottom of the section
536 'help-message' => 'prefs-help-signature',
537 'section' => 'personal/signature'
542 if ( $this->options
->get( 'EnableEmail' ) ) {
543 if ( $canViewPrivateInfo ) {
545 $helpMessages[] = $this->options
->get( 'EmailConfirmToEdit' )
546 ?
'prefs-help-email-required'
547 : 'prefs-help-email';
549 if ( $this->options
->get( 'EnableUserEmail' ) ) {
550 // additional messages when users can send email to each other
551 $helpMessages[] = 'prefs-help-email-others';
554 $emailAddress = $user->getEmail() ?
htmlspecialchars( $user->getEmail() ) : '';
555 if ( $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'emailaddress' ) ) {
556 $button = new \OOUI\
ButtonWidget( [
557 'href' => SpecialPage
::getTitleFor( 'ChangeEmail' )->getLinkURL( [
558 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
561 $context->msg( $user->getEmail() ?
'prefs-changeemail' : 'prefs-setemail' )->text(),
564 $emailAddress .= $emailAddress == '' ?
$button : ( '<br />' . $button );
567 $defaultPreferences['emailaddress'] = [
570 'default' => $emailAddress,
571 'label-message' => 'youremail',
572 'section' => 'personal/email',
573 'help-messages' => $helpMessages,
574 # 'cssclass' chosen below
578 $disableEmailPrefs = false;
580 if ( $this->options
->get( 'EmailAuthentication' ) ) {
581 $emailauthenticationclass = 'mw-email-not-authenticated';
582 if ( $user->getEmail() ) {
583 if ( $user->getEmailAuthenticationTimestamp() ) {
584 // date and time are separate parameters to facilitate localisation.
585 // $time is kept for backward compat reasons.
586 // 'emailauthenticated' is also used in SpecialConfirmemail.php
587 $displayUser = $context->getUser();
588 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
589 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
590 $d = $lang->userDate( $emailTimestamp, $displayUser );
591 $t = $lang->userTime( $emailTimestamp, $displayUser );
592 $emailauthenticated = $context->msg( 'emailauthenticated',
593 $time, $d, $t )->parse() . '<br />';
594 $disableEmailPrefs = false;
595 $emailauthenticationclass = 'mw-email-authenticated';
597 $disableEmailPrefs = true;
598 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
599 new \OOUI\
ButtonWidget( [
600 'href' => SpecialPage
::getTitleFor( 'Confirmemail' )->getLinkURL(),
601 'label' => $context->msg( 'emailconfirmlink' )->text(),
603 $emailauthenticationclass = "mw-email-not-authenticated";
606 $disableEmailPrefs = true;
607 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
608 $emailauthenticationclass = 'mw-email-none';
611 if ( $canViewPrivateInfo ) {
612 $defaultPreferences['emailauthentication'] = [
615 'section' => 'personal/email',
616 'label-message' => 'prefs-emailconfirm-label',
617 'default' => $emailauthenticated,
618 # Apply the same CSS class used on the input to the message:
619 'cssclass' => $emailauthenticationclass,
624 if ( $this->options
->get( 'AllowRequiringEmailForResets' ) ) {
625 $defaultPreferences['requireemail'] = [
627 'label-message' => 'tog-requireemail',
628 'help-message' => 'prefs-help-requireemail',
629 'section' => 'personal/email',
630 'disabled' => $disableEmailPrefs,
634 if ( $this->options
->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
635 $defaultPreferences['disablemail'] = [
636 'id' => 'wpAllowEmail',
639 'section' => 'personal/email',
640 'label-message' => 'allowemail',
641 'disabled' => $disableEmailPrefs,
644 $defaultPreferences['email-allow-new-users'] = [
645 'id' => 'wpAllowEmailFromNewUsers',
647 'section' => 'personal/email',
648 'label-message' => 'email-allow-new-users-label',
649 'disabled' => $disableEmailPrefs,
652 $defaultPreferences['ccmeonemails'] = [
654 'section' => 'personal/email',
655 'label-message' => 'tog-ccmeonemails',
656 'disabled' => $disableEmailPrefs,
659 if ( $this->options
->get( 'EnableUserEmailBlacklist' ) ) {
660 $defaultPreferences['email-blacklist'] = [
661 'type' => 'usersmultiselect',
662 'label-message' => 'email-blacklist-label',
663 'section' => 'personal/email',
664 'disabled' => $disableEmailPrefs,
665 'filter' => MultiUsernameFilter
::class,
670 if ( $this->options
->get( 'EnotifWatchlist' ) ) {
671 $defaultPreferences['enotifwatchlistpages'] = [
673 'section' => 'personal/email',
674 'label-message' => 'tog-enotifwatchlistpages',
675 'disabled' => $disableEmailPrefs,
678 if ( $this->options
->get( 'EnotifUserTalk' ) ) {
679 $defaultPreferences['enotifusertalkpages'] = [
681 'section' => 'personal/email',
682 'label-message' => 'tog-enotifusertalkpages',
683 'disabled' => $disableEmailPrefs,
686 if ( $this->options
->get( 'EnotifUserTalk' ) ||
687 $this->options
->get( 'EnotifWatchlist' ) ) {
688 if ( $this->options
->get( 'EnotifMinorEdits' ) ) {
689 $defaultPreferences['enotifminoredits'] = [
691 'section' => 'personal/email',
692 'label-message' => 'tog-enotifminoredits',
693 'disabled' => $disableEmailPrefs,
697 if ( $this->options
->get( 'EnotifRevealEditorAddress' ) ) {
698 $defaultPreferences['enotifrevealaddr'] = [
700 'section' => 'personal/email',
701 'label-message' => 'tog-enotifrevealaddr',
702 'disabled' => $disableEmailPrefs,
711 * @param IContextSource $context
712 * @param array &$defaultPreferences
715 protected function skinPreferences( User
$user, IContextSource
$context, &$defaultPreferences ) {
716 # # Skin #####################################
718 // Skin selector, if there is at least one valid skin
719 $skinOptions = $this->generateSkinOptions( $user, $context );
720 if ( $skinOptions ) {
721 $defaultPreferences['skin'] = [
723 'options' => $skinOptions,
724 'section' => 'rendering/skin',
728 $allowUserCss = $this->options
->get( 'AllowUserCss' );
729 $allowUserJs = $this->options
->get( 'AllowUserJs' );
730 # Create links to user CSS/JS pages for all skins
731 # This code is basically copied from generateSkinOptions(). It'd
732 # be nice to somehow merge this back in there to avoid redundancy.
733 if ( $allowUserCss ||
$allowUserJs ) {
735 $userName = $user->getName();
737 if ( $allowUserCss ) {
738 $cssPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.css' );
739 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
740 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
743 if ( $allowUserJs ) {
744 $jsPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.js' );
745 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
746 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
749 $defaultPreferences['commoncssjs'] = [
752 'default' => $context->getLanguage()->pipeList( $linkTools ),
753 'label-message' => 'prefs-common-config',
754 'section' => 'rendering/skin',
760 * @param IContextSource $context
761 * @param array &$defaultPreferences
763 protected function filesPreferences( IContextSource
$context, &$defaultPreferences ) {
764 # # Files #####################################
765 $defaultPreferences['imagesize'] = [
767 'options' => $this->getImageSizes( $context ),
768 'label-message' => 'imagemaxsize',
769 'section' => 'rendering/files',
771 $defaultPreferences['thumbsize'] = [
773 'options' => $this->getThumbSizes( $context ),
774 'label-message' => 'thumbsize',
775 'section' => 'rendering/files',
781 * @param IContextSource $context
782 * @param array &$defaultPreferences
785 protected function datetimePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
786 # # Date and time #####################################
787 $dateOptions = $this->getDateOptions( $context );
788 if ( $dateOptions ) {
789 $defaultPreferences['date'] = [
791 'options' => $dateOptions,
792 'section' => 'rendering/dateformat',
797 $now = wfTimestampNow();
798 $lang = $context->getLanguage();
799 $nowlocal = Xml
::element( 'span', [ 'id' => 'wpLocalTime' ],
800 $lang->userTime( $now, $user ) );
801 $nowserver = $lang->userTime( $now, $user,
802 [ 'format' => false, 'timecorrection' => false ] ) .
803 Html
::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 +
(int)substr( $now, 10, 2 ) );
805 $defaultPreferences['nowserver'] = [
808 'label-message' => 'servertime',
809 'default' => $nowserver,
810 'section' => 'rendering/timeoffset',
813 $defaultPreferences['nowlocal'] = [
816 'label-message' => 'localtime',
817 'default' => $nowlocal,
818 'section' => 'rendering/timeoffset',
821 // Grab existing pref.
822 $tzOffset = $user->getOption( 'timecorrection' );
823 $tz = explode( '|', $tzOffset, 3 );
825 $tzOptions = $this->getTimezoneOptions( $context );
827 $tzSetting = $tzOffset;
828 if ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
829 !in_array( $tzOffset, HTMLFormField
::flattenOptions( $tzOptions ) )
831 // Timezone offset can vary with DST
833 $userTZ = new DateTimeZone( $tz[2] );
834 $minDiff = floor( $userTZ->getOffset( new DateTime( 'now' ) ) / 60 );
835 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
836 } catch ( Exception
$e ) {
837 // User has an invalid time zone set. Fall back to just using the offset
841 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
843 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) %
60 );
846 $defaultPreferences['timecorrection'] = [
847 'class' => \HTMLSelectOrOtherField
::class,
848 'label-message' => 'timezonelegend',
849 'options' => $tzOptions,
850 'default' => $tzSetting,
852 'section' => 'rendering/timeoffset',
853 'id' => 'wpTimeCorrection',
854 'filter' => TimezoneFilter
::class,
855 'placeholder-message' => 'timezone-useoffset-placeholder',
861 * @param MessageLocalizer $l10n
862 * @param array &$defaultPreferences
864 protected function renderingPreferences(
866 MessageLocalizer
$l10n,
869 # # Diffs ####################################
870 $defaultPreferences['diffonly'] = [
872 'section' => 'rendering/diffs',
873 'label-message' => 'tog-diffonly',
875 $defaultPreferences['norollbackdiff'] = [
877 'section' => 'rendering/diffs',
878 'label-message' => 'tog-norollbackdiff',
881 # # Page Rendering ##############################
882 if ( $this->options
->get( 'AllowUserCssPrefs' ) ) {
883 $defaultPreferences['underline'] = [
886 $l10n->msg( 'underline-never' )->text() => 0,
887 $l10n->msg( 'underline-always' )->text() => 1,
888 $l10n->msg( 'underline-default' )->text() => 2,
890 'label-message' => 'tog-underline',
891 'section' => 'rendering/advancedrendering',
895 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
896 $stubThresholdOptions = [ $l10n->msg( 'stub-threshold-disabled' )->text() => 0 ];
897 foreach ( $stubThresholdValues as $value ) {
898 $stubThresholdOptions[$l10n->msg( 'size-bytes', $value )->text()] = $value;
901 $defaultPreferences['stubthreshold'] = [
903 'section' => 'rendering/advancedrendering',
904 'options' => $stubThresholdOptions,
905 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
906 'label-raw' => $l10n->msg( 'stub-threshold' )->rawParams(
908 $l10n->msg( 'stub-threshold-sample-link' )->parse() .
912 $defaultPreferences['showhiddencats'] = [
914 'section' => 'rendering/advancedrendering',
915 'label-message' => 'tog-showhiddencats'
918 $defaultPreferences['numberheadings'] = [
920 'section' => 'rendering/advancedrendering',
921 'label-message' => 'tog-numberheadings',
924 if ( $user->isAllowed( 'rollback' ) ) {
925 $defaultPreferences['showrollbackconfirmation'] = [
927 'section' => 'rendering/advancedrendering',
928 'label-message' => 'tog-showrollbackconfirmation',
935 * @param MessageLocalizer $l10n
936 * @param array &$defaultPreferences
938 protected function editingPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
939 # # Editing #####################################
940 $defaultPreferences['editsectiononrightclick'] = [
942 'section' => 'editing/advancedediting',
943 'label-message' => 'tog-editsectiononrightclick',
945 $defaultPreferences['editondblclick'] = [
947 'section' => 'editing/advancedediting',
948 'label-message' => 'tog-editondblclick',
951 if ( $this->options
->get( 'AllowUserCssPrefs' ) ) {
952 $defaultPreferences['editfont'] = [
954 'section' => 'editing/editor',
955 'label-message' => 'editfont-style',
957 $l10n->msg( 'editfont-monospace' )->text() => 'monospace',
958 $l10n->msg( 'editfont-sansserif' )->text() => 'sans-serif',
959 $l10n->msg( 'editfont-serif' )->text() => 'serif',
964 if ( $user->isAllowed( 'minoredit' ) ) {
965 $defaultPreferences['minordefault'] = [
967 'section' => 'editing/editor',
968 'label-message' => 'tog-minordefault',
972 $defaultPreferences['forceeditsummary'] = [
974 'section' => 'editing/editor',
975 'label-message' => 'tog-forceeditsummary',
977 $defaultPreferences['useeditwarning'] = [
979 'section' => 'editing/editor',
980 'label-message' => 'tog-useeditwarning',
983 $defaultPreferences['previewonfirst'] = [
985 'section' => 'editing/preview',
986 'label-message' => 'tog-previewonfirst',
988 $defaultPreferences['previewontop'] = [
990 'section' => 'editing/preview',
991 'label-message' => 'tog-previewontop',
993 $defaultPreferences['uselivepreview'] = [
995 'section' => 'editing/preview',
996 'label-message' => 'tog-uselivepreview',
1002 * @param MessageLocalizer $l10n
1003 * @param array &$defaultPreferences
1005 protected function rcPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
1006 $rcMaxAge = $this->options
->get( 'RCMaxAge' );
1007 # # RecentChanges #####################################
1008 $defaultPreferences['rcdays'] = [
1010 'label-message' => 'recentchangesdays',
1011 'section' => 'rc/displayrc',
1013 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
1014 'help' => $l10n->msg( 'recentchangesdays-max' )->numParams(
1015 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
1017 $defaultPreferences['rclimit'] = [
1021 'label-message' => 'recentchangescount',
1022 'help-message' => 'prefs-help-recentchangescount',
1023 'section' => 'rc/displayrc',
1024 'filter' => IntvalFilter
::class,
1026 $defaultPreferences['usenewrc'] = [
1028 'label-message' => 'tog-usenewrc',
1029 'section' => 'rc/advancedrc',
1031 $defaultPreferences['hideminor'] = [
1033 'label-message' => 'tog-hideminor',
1034 'section' => 'rc/changesrc',
1036 $defaultPreferences['rcfilters-rc-collapsed'] = [
1039 $defaultPreferences['rcfilters-wl-collapsed'] = [
1042 $defaultPreferences['rcfilters-saved-queries'] = [
1045 $defaultPreferences['rcfilters-wl-saved-queries'] = [
1048 // Override RCFilters preferences for RecentChanges 'limit'
1049 $defaultPreferences['rcfilters-limit'] = [
1052 $defaultPreferences['rcfilters-saved-queries-versionbackup'] = [
1055 $defaultPreferences['rcfilters-wl-saved-queries-versionbackup'] = [
1059 if ( $this->options
->get( 'RCWatchCategoryMembership' ) ) {
1060 $defaultPreferences['hidecategorization'] = [
1062 'label-message' => 'tog-hidecategorization',
1063 'section' => 'rc/changesrc',
1067 if ( $user->useRCPatrol() ) {
1068 $defaultPreferences['hidepatrolled'] = [
1070 'section' => 'rc/changesrc',
1071 'label-message' => 'tog-hidepatrolled',
1075 if ( $user->useNPPatrol() ) {
1076 $defaultPreferences['newpageshidepatrolled'] = [
1078 'section' => 'rc/changesrc',
1079 'label-message' => 'tog-newpageshidepatrolled',
1083 if ( $this->options
->get( 'RCShowWatchingUsers' ) ) {
1084 $defaultPreferences['shownumberswatching'] = [
1086 'section' => 'rc/advancedrc',
1087 'label-message' => 'tog-shownumberswatching',
1091 $defaultPreferences['rcenhancedfilters-disable'] = [
1093 'section' => 'rc/advancedrc',
1094 'label-message' => 'rcfilters-preference-label',
1095 'help-message' => 'rcfilters-preference-help',
1101 * @param IContextSource $context
1102 * @param array &$defaultPreferences
1104 protected function watchlistPreferences(
1105 User
$user, IContextSource
$context, &$defaultPreferences
1107 $watchlistdaysMax = ceil( $this->options
->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1109 # # Watchlist #####################################
1110 if ( $user->isAllowed( 'editmywatchlist' ) ) {
1111 $editWatchlistLinks = '';
1112 $editWatchlistModes = [
1113 'edit' => [ 'subpage' => false, 'flags' => [] ],
1114 'raw' => [ 'subpage' => 'raw', 'flags' => [] ],
1115 'clear' => [ 'subpage' => 'clear', 'flags' => [ 'destructive' ] ],
1117 foreach ( $editWatchlistModes as $mode => $options ) {
1118 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1119 $editWatchlistLinks .=
1120 new \OOUI\
ButtonWidget( [
1121 'href' => SpecialPage
::getTitleFor( 'EditWatchlist', $options['subpage'] )->getLinkURL(),
1122 'flags' => $options[ 'flags' ],
1123 'label' => new \OOUI\
HtmlSnippet(
1124 $context->msg( "prefs-editwatchlist-{$mode}" )->parse()
1129 $defaultPreferences['editwatchlist'] = [
1132 'default' => $editWatchlistLinks,
1133 'label-message' => 'prefs-editwatchlist-label',
1134 'section' => 'watchlist/editwatchlist',
1138 $defaultPreferences['watchlistdays'] = [
1141 'max' => $watchlistdaysMax,
1142 'section' => 'watchlist/displaywatchlist',
1143 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1144 $watchlistdaysMax )->escaped(),
1145 'label-message' => 'prefs-watchlist-days',
1147 $defaultPreferences['wllimit'] = [
1151 'label-message' => 'prefs-watchlist-edits',
1152 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1153 'section' => 'watchlist/displaywatchlist',
1154 'filter' => IntvalFilter
::class,
1156 $defaultPreferences['extendwatchlist'] = [
1158 'section' => 'watchlist/advancedwatchlist',
1159 'label-message' => 'tog-extendwatchlist',
1161 $defaultPreferences['watchlisthideminor'] = [
1163 'section' => 'watchlist/changeswatchlist',
1164 'label-message' => 'tog-watchlisthideminor',
1166 $defaultPreferences['watchlisthidebots'] = [
1168 'section' => 'watchlist/changeswatchlist',
1169 'label-message' => 'tog-watchlisthidebots',
1171 $defaultPreferences['watchlisthideown'] = [
1173 'section' => 'watchlist/changeswatchlist',
1174 'label-message' => 'tog-watchlisthideown',
1176 $defaultPreferences['watchlisthideanons'] = [
1178 'section' => 'watchlist/changeswatchlist',
1179 'label-message' => 'tog-watchlisthideanons',
1181 $defaultPreferences['watchlisthideliu'] = [
1183 'section' => 'watchlist/changeswatchlist',
1184 'label-message' => 'tog-watchlisthideliu',
1187 if ( !\SpecialWatchlist
::checkStructuredFilterUiEnabled( $user ) ) {
1188 $defaultPreferences['watchlistreloadautomatically'] = [
1190 'section' => 'watchlist/advancedwatchlist',
1191 'label-message' => 'tog-watchlistreloadautomatically',
1195 $defaultPreferences['watchlistunwatchlinks'] = [
1197 'section' => 'watchlist/advancedwatchlist',
1198 'label-message' => 'tog-watchlistunwatchlinks',
1201 if ( $this->options
->get( 'RCWatchCategoryMembership' ) ) {
1202 $defaultPreferences['watchlisthidecategorization'] = [
1204 'section' => 'watchlist/changeswatchlist',
1205 'label-message' => 'tog-watchlisthidecategorization',
1209 if ( $user->useRCPatrol() ) {
1210 $defaultPreferences['watchlisthidepatrolled'] = [
1212 'section' => 'watchlist/changeswatchlist',
1213 'label-message' => 'tog-watchlisthidepatrolled',
1218 'edit' => 'watchdefault',
1219 'move' => 'watchmoves',
1220 'delete' => 'watchdeletion'
1224 if ( $user->isAllowed( 'createpage' ) ||
$user->isAllowed( 'createtalk' ) ) {
1225 $watchTypes['read'] = 'watchcreations';
1228 if ( $user->isAllowed( 'rollback' ) ) {
1229 $watchTypes['rollback'] = 'watchrollback';
1232 if ( $user->isAllowed( 'upload' ) ) {
1233 $watchTypes['upload'] = 'watchuploads';
1236 foreach ( $watchTypes as $action => $pref ) {
1237 if ( $user->isAllowed( $action ) ) {
1239 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1240 // tog-watchrollback
1241 $defaultPreferences[$pref] = [
1243 'section' => 'watchlist/pageswatchlist',
1244 'label-message' => "tog-$pref",
1249 $defaultPreferences['watchlisttoken'] = [
1253 $tokenButton = new \OOUI\
ButtonWidget( [
1254 'href' => SpecialPage
::getTitleFor( 'ResetTokens' )->getLinkURL( [
1255 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
1257 'label' => $context->msg( 'prefs-watchlist-managetokens' )->text(),
1259 $defaultPreferences['watchlisttoken-info'] = [
1261 'section' => 'watchlist/tokenwatchlist',
1262 'label-message' => 'prefs-watchlist-token',
1263 'help-message' => 'prefs-help-tokenmanagement',
1265 'default' => (string)$tokenButton,
1268 $defaultPreferences['wlenhancedfilters-disable'] = [
1270 'section' => 'watchlist/advancedwatchlist',
1271 'label-message' => 'rcfilters-watchlist-preference-label',
1272 'help-message' => 'rcfilters-watchlist-preference-help',
1277 * @param array &$defaultPreferences
1279 protected function searchPreferences( &$defaultPreferences ) {
1280 foreach ( $this->nsInfo
->getValidNamespaces() as $n ) {
1281 $defaultPreferences['searchNs' . $n] = [
1288 * @param User $user The User object
1289 * @param IContextSource $context
1290 * @return array Text/links to display as key; $skinkey as value
1292 protected function generateSkinOptions( User
$user, IContextSource
$context ) {
1295 $mptitle = Title
::newMainPage();
1296 $previewtext = $context->msg( 'skin-preview' )->escaped();
1298 # Only show skins that aren't disabled in $wgSkipSkins
1299 $validSkinNames = Skin
::getAllowedSkins();
1300 $allInstalledSkins = Skin
::getSkinNames();
1302 // Display the installed skin the user has specifically requested via useskin=….
1303 $useSkin = $context->getRequest()->getRawVal( 'useskin' );
1304 if ( isset( $allInstalledSkins[$useSkin] )
1305 && $context->msg( "skinname-$useSkin" )->exists()
1307 $validSkinNames[$useSkin] = $useSkin;
1310 // Display the skin if the user has set it as a preference already before it was hidden.
1311 $currentUserSkin = $user->getOption( 'skin' );
1312 if ( isset( $allInstalledSkins[$currentUserSkin] )
1313 && $context->msg( "skinname-$currentUserSkin" )->exists()
1315 $validSkinNames[$currentUserSkin] = $currentUserSkin;
1318 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1319 $msg = $context->msg( "skinname-{$skinkey}" );
1320 if ( $msg->exists() ) {
1321 $skinname = htmlspecialchars( $msg->text() );
1325 $defaultSkin = $this->options
->get( 'DefaultSkin' );
1326 $allowUserCss = $this->options
->get( 'AllowUserCss' );
1327 $allowUserJs = $this->options
->get( 'AllowUserJs' );
1329 # Sort by the internal name, so that the ordering is the same for each display language,
1330 # especially if some skin names are translated to use a different alphabet and some are not.
1331 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1332 # Display the default first in the list by comparing it as lesser than any other.
1333 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1336 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1339 return strcasecmp( $a, $b );
1342 $foundDefault = false;
1343 foreach ( $validSkinNames as $skinkey => $sn ) {
1346 # Mark the default skin
1347 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1348 $linkTools[] = $context->msg( 'default' )->escaped();
1349 $foundDefault = true;
1352 # Create preview link
1353 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1354 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1356 # Create links to user CSS/JS pages
1357 if ( $allowUserCss ) {
1358 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1359 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
1360 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
1363 if ( $allowUserJs ) {
1364 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1365 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
1366 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
1369 $display = $sn . ' ' . $context->msg( 'parentheses' )
1370 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1372 $ret[$display] = $skinkey;
1375 if ( !$foundDefault ) {
1376 // If the default skin is not available, things are going to break horribly because the
1377 // default value for skin selector will not be a valid value. Let's just not show it then.
1385 * @param IContextSource $context
1388 protected function getDateOptions( IContextSource
$context ) {
1389 $lang = $context->getLanguage();
1390 $dateopts = $lang->getDatePreferences();
1395 if ( !in_array( 'default', $dateopts ) ) {
1396 $dateopts[] = 'default'; // Make sure default is always valid T21237
1399 // FIXME KLUGE: site default might not be valid for user language
1400 global $wgDefaultUserOptions;
1401 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1402 $wgDefaultUserOptions['date'] = 'default';
1405 $epoch = wfTimestampNow();
1406 foreach ( $dateopts as $key ) {
1407 if ( $key == 'default' ) {
1408 $formatted = $context->msg( 'datedefault' )->escaped();
1410 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1412 $ret[$formatted] = $key;
1419 * @param MessageLocalizer $l10n
1422 protected function getImageSizes( MessageLocalizer
$l10n ) {
1424 $pixels = $l10n->msg( 'unit-pixel' )->text();
1426 foreach ( $this->options
->get( 'ImageLimits' ) as $index => $limits ) {
1427 // Note: A left-to-right marker (U+200E) is inserted, see T144386
1428 $display = "{$limits[0]}\u{200E}×{$limits[1]}$pixels";
1429 $ret[$display] = $index;
1436 * @param MessageLocalizer $l10n
1439 protected function getThumbSizes( MessageLocalizer
$l10n ) {
1441 $pixels = $l10n->msg( 'unit-pixel' )->text();
1443 foreach ( $this->options
->get( 'ThumbLimits' ) as $index => $size ) {
1444 $display = $size . $pixels;
1445 $ret[$display] = $index;
1452 * @param string $signature
1453 * @param array $alldata
1454 * @param HTMLForm $form
1455 * @return bool|string
1457 protected function validateSignature( $signature, $alldata, HTMLForm
$form ) {
1458 $maxSigChars = $this->options
->get( 'MaxSigChars' );
1459 if ( mb_strlen( $signature ) > $maxSigChars ) {
1460 return Xml
::element( 'span', [ 'class' => 'error' ],
1461 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1462 } elseif ( isset( $alldata['fancysig'] ) &&
1463 $alldata['fancysig'] &&
1464 MediaWikiServices
::getInstance()->getParser()->validateSig( $signature ) === false
1466 return Xml
::element(
1468 [ 'class' => 'error' ],
1469 $form->msg( 'badsig' )->text()
1477 * @param string $signature
1478 * @param array $alldata
1479 * @param HTMLForm $form
1482 protected function cleanSignature( $signature, $alldata, HTMLForm
$form ) {
1483 $parser = MediaWikiServices
::getInstance()->getParser();
1484 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1485 $signature = $parser->cleanSig( $signature );
1487 // When no fancy sig used, make sure ~{3,5} get removed.
1488 $signature = Parser
::cleanSigInSig( $signature );
1496 * @param IContextSource $context
1497 * @param string $formClass
1498 * @param array $remove Array of items to remove
1501 public function getForm(
1503 IContextSource
$context,
1504 $formClass = PreferencesFormOOUI
::class,
1507 // We use ButtonWidgets in some of the getPreferences() functions
1508 $context->getOutput()->enableOOUI();
1510 $formDescriptor = $this->getFormDescriptor( $user, $context );
1511 if ( count( $remove ) ) {
1512 $removeKeys = array_flip( $remove );
1513 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1516 // Remove type=api preferences. They are not intended for rendering in the form.
1517 foreach ( $formDescriptor as $name => $info ) {
1518 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1519 unset( $formDescriptor[$name] );
1524 * @var HTMLForm $htmlForm
1526 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1528 // This allows users to opt-in to hidden skins. While this should be discouraged and is not
1529 // discoverable, this allows users to still use hidden skins while preventing new users from
1530 // adopting unsupported skins. If no useskin=… parameter was provided, it will not show up
1531 // in the resulting URL.
1532 $htmlForm->setAction( $context->getTitle()->getLocalURL( [
1533 'useskin' => $context->getRequest()->getRawVal( 'useskin' )
1536 $htmlForm->setModifiedUser( $user );
1537 $htmlForm->setId( 'mw-prefs-form' );
1538 $htmlForm->setAutocomplete( 'off' );
1539 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1540 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1541 $htmlForm->setSubmitTooltip( 'preferences-save' );
1542 $htmlForm->setSubmitID( 'prefcontrol' );
1543 $htmlForm->setSubmitCallback(
1544 function ( array $formData, HTMLForm
$form ) use ( $formDescriptor ) {
1545 return $this->submitForm( $formData, $form, $formDescriptor );
1553 * @param IContextSource $context
1556 protected function getTimezoneOptions( IContextSource
$context ) {
1559 $localTZoffset = $this->options
->get( 'LocalTZoffset' );
1560 $timeZoneList = $this->getTimeZoneList( $context->getLanguage() );
1562 $timestamp = MWTimestamp
::getLocalInstance();
1563 // Check that the LocalTZoffset is the same as the local time zone offset
1564 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1565 $timezoneName = $timestamp->getTimezone()->getName();
1566 // Localize timezone
1567 if ( isset( $timeZoneList[$timezoneName] ) ) {
1568 $timezoneName = $timeZoneList[$timezoneName]['name'];
1570 $server_tz_msg = $context->msg(
1571 'timezoneuseserverdefault',
1575 $tzstring = sprintf(
1577 floor( $localTZoffset / 60 ),
1578 abs( $localTZoffset ) %
60
1580 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1582 $opt[$server_tz_msg] = "System|$localTZoffset";
1583 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1584 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1586 foreach ( $timeZoneList as $timeZoneInfo ) {
1587 $region = $timeZoneInfo['region'];
1588 if ( !isset( $opt[$region] ) ) {
1591 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1597 * Handle the form submission if everything validated properly
1599 * @param array $formData
1600 * @param PreferencesFormOOUI $form
1601 * @param array[] $formDescriptor
1602 * @return bool|Status|string
1604 protected function saveFormData( $formData, PreferencesFormOOUI
$form, array $formDescriptor ) {
1605 $user = $form->getModifiedUser();
1606 $hiddenPrefs = $this->options
->get( 'HiddenPrefs' );
1609 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1610 return Status
::newFatal( 'mypreferencesprotected' );
1614 $this->applyFilters( $formData, $formDescriptor, 'filterFromForm' );
1616 // Fortunately, the realname field is MUCH simpler
1617 // (not really "private", but still shouldn't be edited without permission)
1619 if ( !in_array( 'realname', $hiddenPrefs )
1620 && $user->isAllowed( 'editmyprivateinfo' )
1621 && array_key_exists( 'realname', $formData )
1623 $realName = $formData['realname'];
1624 $user->setRealName( $realName );
1627 if ( $user->isAllowed( 'editmyoptions' ) ) {
1628 $oldUserOptions = $user->getOptions();
1630 foreach ( $this->getSaveBlacklist() as $b ) {
1631 unset( $formData[$b] );
1634 # If users have saved a value for a preference which has subsequently been disabled
1635 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1636 # is subsequently re-enabled
1637 foreach ( $hiddenPrefs as $pref ) {
1638 # If the user has not set a non-default value here, the default will be returned
1639 # and subsequently discarded
1640 $formData[$pref] = $user->getOption( $pref, null, true );
1643 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1645 isset( $formData['rclimit'] ) &&
1646 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1648 $formData['rcfilters-limit'] = $formData['rclimit'];
1651 // Keep old preferences from interfering due to back-compat code, etc.
1652 $user->resetOptions( 'unused', $form->getContext() );
1654 foreach ( $formData as $key => $value ) {
1655 $user->setOption( $key, $value );
1659 'PreferencesFormPreSave',
1660 [ $formData, $form, $user, &$result, $oldUserOptions ]
1664 $user->saveSettings();
1670 * Applies filters to preferences either before or after form usage
1672 * @param array &$preferences
1673 * @param array $formDescriptor
1674 * @param string $verb Name of the filter method to call, either 'filterFromForm' or
1677 protected function applyFilters( array &$preferences, array $formDescriptor, $verb ) {
1678 foreach ( $formDescriptor as $preference => $desc ) {
1679 if ( !isset( $desc['filter'] ) ||
!isset( $preferences[$preference] ) ) {
1682 $filterDesc = $desc['filter'];
1683 if ( $filterDesc instanceof Filter
) {
1684 $filter = $filterDesc;
1685 } elseif ( class_exists( $filterDesc ) ) {
1686 $filter = new $filterDesc();
1687 } elseif ( is_callable( $filterDesc ) ) {
1688 $filter = $filterDesc();
1690 throw new UnexpectedValueException(
1691 "Unrecognized filter type for preference '$preference'"
1694 $preferences[$preference] = $filter->$verb( $preferences[$preference] );
1699 * Save the form data and reload the page
1701 * @param array $formData
1702 * @param PreferencesFormOOUI $form
1703 * @param array $formDescriptor
1706 protected function submitForm(
1708 PreferencesFormOOUI
$form,
1709 array $formDescriptor
1711 $res = $this->saveFormData( $formData, $form, $formDescriptor );
1713 if ( $res === true ) {
1714 $context = $form->getContext();
1717 if ( $res === 'eauth' ) {
1718 $urlOptions['eauth'] = 1;
1721 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1723 $url = $form->getTitle()->getFullURL( $urlOptions );
1725 // Set session data for the success message
1726 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1728 $context->getOutput()->redirect( $url );
1731 return ( $res === true ? Status
::newGood() : $res );
1735 * Get a list of all time zones
1736 * @param Language $language Language used for the localized names
1737 * @return array A list of all time zones. The system name of the time zone is used as key and
1738 * the value is an array which contains localized name, the timecorrection value used for
1739 * preferences and the region
1742 protected function getTimeZoneList( Language
$language ) {
1743 $identifiers = DateTimeZone
::listIdentifiers();
1744 // @phan-suppress-next-line PhanTypeComparisonFromArray See phan issue #3162
1745 if ( $identifiers === false ) {
1748 sort( $identifiers );
1751 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1752 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1753 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1754 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1755 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1756 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1757 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1758 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1759 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1760 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1762 asort( $tzRegions );
1766 $now = new DateTime();
1768 foreach ( $identifiers as $identifier ) {
1769 $parts = explode( '/', $identifier, 2 );
1771 // DateTimeZone::listIdentifiers() returns a number of
1772 // backwards-compatibility entries. This filters them out of the
1773 // list presented to the user.
1774 if ( count( $parts ) !== 2 ||
!array_key_exists( $parts[0], $tzRegions ) ) {
1779 $parts[0] = $tzRegions[$parts[0]];
1781 $dateTimeZone = new DateTimeZone( $identifier );
1782 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1784 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1785 $value = "ZoneInfo|$minDiff|$identifier";
1787 $timeZoneList[$identifier] = [
1789 'timecorrection' => $value,
1790 'region' => $parts[0],
1794 return $timeZoneList;