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
;
33 use LanguageConverter
;
34 use MediaWiki\Auth\AuthManager
;
35 use MediaWiki\Auth\PasswordAuthenticationRequest
;
36 use MediaWiki\Config\ServiceOptions
;
37 use MediaWiki\Linker\LinkRenderer
;
38 use MediaWiki\MediaWikiServices
;
39 use MediaWiki\Permissions\PermissionManager
;
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 */
80 /** @var PermissionManager */
81 protected $permissionManager;
87 public const CONSTRUCTOR_OPTIONS
= [
88 'AllowRequiringEmailForResets',
93 'DisableLangConversion',
94 'EmailAuthentication',
98 'EnableUserEmailBlacklist',
100 'EnotifRevealEditorAddress',
109 'RCShowWatchingUsers',
110 'RCWatchCategoryMembership',
116 * Do not call this directly. Get it from MediaWikiServices.
118 * @param ServiceOptions $options
119 * @param Language $contLang
120 * @param AuthManager $authManager
121 * @param LinkRenderer $linkRenderer
122 * @param NamespaceInfo $nsInfo
123 * @param PermissionManager $permissionManager
125 public function __construct(
126 ServiceOptions
$options,
128 AuthManager
$authManager,
129 LinkRenderer
$linkRenderer,
130 NamespaceInfo
$nsInfo,
131 PermissionManager
$permissionManager
133 $options->assertRequiredOptions( self
::CONSTRUCTOR_OPTIONS
);
135 $this->options
= $options;
136 $this->contLang
= $contLang;
137 $this->authManager
= $authManager;
138 $this->linkRenderer
= $linkRenderer;
139 $this->nsInfo
= $nsInfo;
140 $this->permissionManager
= $permissionManager;
141 $this->logger
= new NullLogger();
147 public function getSaveBlacklist() {
155 * @throws MWException
157 * @param IContextSource $context
160 public function getFormDescriptor( User
$user, IContextSource
$context ) {
163 OutputPage
::setupOOUI(
164 strtolower( $context->getSkin()->getSkinName() ),
165 $context->getLanguage()->getDir()
168 $canIPUseHTTPS = wfCanIPUseHTTPS( $context->getRequest()->getIP() );
169 $this->profilePreferences( $user, $context, $preferences, $canIPUseHTTPS );
170 $this->skinPreferences( $user, $context, $preferences );
171 $this->datetimePreferences( $user, $context, $preferences );
172 $this->filesPreferences( $context, $preferences );
173 $this->renderingPreferences( $user, $context, $preferences );
174 $this->editingPreferences( $user, $context, $preferences );
175 $this->rcPreferences( $user, $context, $preferences );
176 $this->watchlistPreferences( $user, $context, $preferences );
177 $this->searchPreferences( $preferences );
179 Hooks
::run( 'GetPreferences', [ $user, &$preferences ] );
181 $this->loadPreferenceValues( $user, $context, $preferences );
182 $this->logger
->debug( "Created form descriptor for user '{$user->getName()}'" );
187 * Loads existing values for a given array of preferences
188 * @throws MWException
190 * @param IContextSource $context
191 * @param array &$defaultPreferences Array to load values for
194 private function loadPreferenceValues(
195 User
$user, IContextSource
$context, &$defaultPreferences
197 # # Remove preferences that wikis don't want to use
198 foreach ( $this->options
->get( 'HiddenPrefs' ) as $pref ) {
199 if ( isset( $defaultPreferences[$pref] ) ) {
200 unset( $defaultPreferences[$pref] );
204 # # Make sure that form fields have their parent set. See T43337.
205 $dummyForm = new HTMLForm( [], $context );
207 $disable = !$this->permissionManager
->userHasRight( $user, 'editmyoptions' );
209 $defaultOptions = User
::getDefaultOptions();
210 $userOptions = $user->getOptions();
211 $this->applyFilters( $userOptions, $defaultPreferences, 'filterForForm' );
212 # # Prod in defaults from the user
213 foreach ( $defaultPreferences as $name => &$info ) {
214 $prefFromUser = $this->getOptionFromUser( $name, $info, $userOptions );
215 if ( $disable && !in_array( $name, $this->getSaveBlacklist() ) ) {
216 $info['disabled'] = 'disabled';
218 $field = HTMLForm
::loadInputFromParameters( $name, $info, $dummyForm ); // For validation
219 $globalDefault = $defaultOptions[$name] ??
null;
221 // If it validates, set it as the default
222 if ( isset( $info['default'] ) ) {
223 // Already set, no problem
225 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
226 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
227 $info['default'] = $prefFromUser;
228 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
229 $info['default'] = $globalDefault;
231 $globalDefault = json_encode( $globalDefault );
232 throw new MWException(
233 "Default '$globalDefault' is invalid for preference $name of user $user"
238 return $defaultPreferences;
242 * Pull option from a user account. Handles stuff like array-type preferences.
244 * @param string $name
246 * @param array $userOptions
247 * @return array|string
249 protected function getOptionFromUser( $name, $info, array $userOptions ) {
250 $val = $userOptions[$name] ??
null;
252 // Handling for multiselect preferences
253 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
254 ( isset( $info['class'] ) && $info['class'] == \HTMLMultiSelectField
::class ) ) {
255 $options = HTMLFormField
::flattenOptions( $info['options'] );
256 $prefix = $info['prefix'] ??
$name;
259 foreach ( $options as $value ) {
260 if ( $userOptions["$prefix$value"] ??
false ) {
266 // Handling for checkmatrix preferences
267 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
268 ( isset( $info['class'] ) && $info['class'] == \HTMLCheckMatrix
::class ) ) {
269 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
270 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
271 $prefix = $info['prefix'] ??
$name;
274 foreach ( $columns as $column ) {
275 foreach ( $rows as $row ) {
276 if ( $userOptions["$prefix$column-$row"] ??
false ) {
277 $val[] = "$column-$row";
287 * @todo Inject user Language instead of using context.
289 * @param IContextSource $context
290 * @param array &$defaultPreferences
291 * @param bool $canIPUseHTTPS Whether the user's IP is likely to be able to access the wiki
295 protected function profilePreferences(
296 User
$user, IContextSource
$context, &$defaultPreferences, $canIPUseHTTPS
298 // retrieving user name for GENDER and misc.
299 $userName = $user->getName();
301 # # User info #####################################
303 $defaultPreferences['username'] = [
305 'label-message' => [ 'username', $userName ],
306 'default' => $userName,
307 'section' => 'personal/info',
310 $lang = $context->getLanguage();
312 # Get groups to which the user belongs
313 $userEffectiveGroups = $user->getEffectiveGroups();
314 $userGroupMemberships = $user->getGroupMemberships();
315 $userGroups = $userMembers = $userTempGroups = $userTempMembers = [];
316 foreach ( $userEffectiveGroups as $ueg ) {
318 // Skip the default * group, seems useless here
322 $groupStringOrObject = $userGroupMemberships[$ueg] ??
$ueg;
324 $userG = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html' );
325 $userM = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html',
328 // Store expiring groups separately, so we can place them before non-expiring
329 // groups in the list. This is to avoid the ambiguity of something like
330 // "administrator, bureaucrat (until X date)" -- users might wonder whether the
331 // expiry date applies to both groups, or just the last one
332 if ( $groupStringOrObject instanceof UserGroupMembership
&&
333 $groupStringOrObject->getExpiry()
335 $userTempGroups[] = $userG;
336 $userTempMembers[] = $userM;
338 $userGroups[] = $userG;
339 $userMembers[] = $userM;
343 sort( $userMembers );
344 sort( $userTempGroups );
345 sort( $userTempMembers );
346 $userGroups = array_merge( $userTempGroups, $userGroups );
347 $userMembers = array_merge( $userTempMembers, $userMembers );
349 $defaultPreferences['usergroups'] = [
351 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
352 count( $userGroups ) )->params( $userName )->parse(),
353 'default' => $context->msg( 'prefs-memberingroups-type' )
354 ->rawParams( $lang->commaList( $userGroups ), $lang->commaList( $userMembers ) )
357 'section' => 'personal/info',
360 $contribTitle = SpecialPage
::getTitleFor( "Contributions", $userName );
361 $formattedEditCount = $lang->formatNum( $user->getEditCount() );
362 $editCount = $this->linkRenderer
->makeLink( $contribTitle, $formattedEditCount );
364 $defaultPreferences['editcount'] = [
367 'label-message' => 'prefs-edits',
368 'default' => $editCount,
369 'section' => 'personal/info',
372 if ( $user->getRegistration() ) {
373 $displayUser = $context->getUser();
374 $userRegistration = $user->getRegistration();
375 $defaultPreferences['registrationdate'] = [
377 'label-message' => 'prefs-registration',
378 'default' => $context->msg(
379 'prefs-registration-date-time',
380 $lang->userTimeAndDate( $userRegistration, $displayUser ),
381 $lang->userDate( $userRegistration, $displayUser ),
382 $lang->userTime( $userRegistration, $displayUser )
384 'section' => 'personal/info',
388 $canViewPrivateInfo = $this->permissionManager
->userHasRight( $user, 'viewmyprivateinfo' );
389 $canEditPrivateInfo = $this->permissionManager
->userHasRight( $user, 'editmyprivateinfo' );
391 // Actually changeable stuff
392 $defaultPreferences['realname'] = [
393 // (not really "private", but still shouldn't be edited without permission)
394 'type' => $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'realname' )
396 'default' => $user->getRealName(),
397 'section' => 'personal/info',
398 'label-message' => 'yourrealname',
399 'help-message' => 'prefs-help-realname',
402 if ( $canEditPrivateInfo && $this->authManager
->allowsAuthenticationDataChange(
403 new PasswordAuthenticationRequest(), false )->isGood()
405 $defaultPreferences['password'] = [
408 'default' => (string)new \OOUI\
ButtonWidget( [
409 'href' => SpecialPage
::getTitleFor( 'ChangePassword' )->getLinkURL( [
410 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
412 'label' => $context->msg( 'prefs-resetpass' )->text(),
414 'label-message' => 'yourpassword',
415 'section' => 'personal/info',
418 // Only show prefershttps if secure login is turned on
419 if ( $this->options
->get( 'SecureLogin' ) && $canIPUseHTTPS ) {
420 $defaultPreferences['prefershttps'] = [
422 'label-message' => 'tog-prefershttps',
423 'help-message' => 'prefs-help-prefershttps',
424 'section' => 'personal/info'
428 $languages = Language
::fetchLanguageNames( null, 'mwfile' );
429 $languageCode = $this->options
->get( 'LanguageCode' );
430 if ( !array_key_exists( $languageCode, $languages ) ) {
431 $languages[$languageCode] = $languageCode;
432 // Sort the array again
437 foreach ( $languages as $code => $name ) {
438 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
439 $options[$display] = $code;
441 $defaultPreferences['language'] = [
443 'section' => 'personal/i18n',
444 'options' => $options,
445 'label-message' => 'yourlanguage',
448 $defaultPreferences['gender'] = [
450 'section' => 'personal/i18n',
452 $context->msg( 'parentheses' )
453 ->params( $context->msg( 'gender-unknown' )->plain() )
454 ->escaped() => 'unknown',
455 $context->msg( 'gender-female' )->escaped() => 'female',
456 $context->msg( 'gender-male' )->escaped() => 'male',
458 'label-message' => 'yourgender',
459 'help-message' => 'prefs-help-gender',
462 // see if there are multiple language variants to choose from
463 if ( !$this->options
->get( 'DisableLangConversion' ) ) {
464 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
465 if ( $langCode == $this->contLang
->getCode() ) {
466 if ( !$this->contLang
->hasVariants() ) {
470 $variants = $this->contLang
->getVariants();
472 foreach ( $variants as $v ) {
473 $v = str_replace( '_', '-', strtolower( $v ) );
474 $variantArray[$v] = $lang->getVariantname( $v, false );
478 foreach ( $variantArray as $code => $name ) {
479 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
480 $options[$display] = $code;
483 $defaultPreferences['variant'] = [
484 'label-message' => 'yourvariant',
486 'options' => $options,
487 'section' => 'personal/i18n',
488 'help-message' => 'prefs-help-variant',
491 $defaultPreferences["variant-$langCode"] = [
498 // show a preview of the old signature first
499 $oldsigWikiText = MediaWikiServices
::getInstance()->getParser()->preSaveTransform(
501 $context->getTitle(),
503 ParserOptions
::newFromContext( $context )
505 $oldsigHTML = Parser
::stripOuterParagraph(
506 $context->getOutput()->parseAsContent( $oldsigWikiText )
508 $defaultPreferences['oldsig'] = [
511 'label-message' => 'tog-oldsig',
512 'default' => $oldsigHTML,
513 'section' => 'personal/signature',
515 $defaultPreferences['nickname'] = [
516 'type' => $this->authManager
->allowsPropertyChange( 'nickname' ) ?
'text' : 'info',
517 'maxlength' => $this->options
->get( 'MaxSigChars' ),
518 'label-message' => 'yournick',
519 'validation-callback' => function ( $signature, $alldata, HTMLForm
$form ) {
520 return $this->validateSignature( $signature, $alldata, $form );
522 'section' => 'personal/signature',
523 'filter-callback' => function ( $signature, array $alldata, HTMLForm
$form ) {
524 return $this->cleanSignature( $signature, $alldata, $form );
527 $defaultPreferences['fancysig'] = [
529 'label-message' => 'tog-fancysig',
530 // show general help about signature at the bottom of the section
531 'help-message' => 'prefs-help-signature',
532 'section' => 'personal/signature'
537 if ( $this->options
->get( 'EnableEmail' ) ) {
538 if ( $canViewPrivateInfo ) {
540 $helpMessages[] = $this->options
->get( 'EmailConfirmToEdit' )
541 ?
'prefs-help-email-required'
542 : 'prefs-help-email';
544 if ( $this->options
->get( 'EnableUserEmail' ) ) {
545 // additional messages when users can send email to each other
546 $helpMessages[] = 'prefs-help-email-others';
549 $emailAddress = $user->getEmail() ?
htmlspecialchars( $user->getEmail() ) : '';
550 if ( $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'emailaddress' ) ) {
551 $button = new \OOUI\
ButtonWidget( [
552 'href' => SpecialPage
::getTitleFor( 'ChangeEmail' )->getLinkURL( [
553 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
556 $context->msg( $user->getEmail() ?
'prefs-changeemail' : 'prefs-setemail' )->text(),
559 $emailAddress .= $emailAddress == '' ?
$button : ( '<br />' . $button );
562 $defaultPreferences['emailaddress'] = [
565 'default' => $emailAddress,
566 'label-message' => 'youremail',
567 'section' => 'personal/email',
568 'help-messages' => $helpMessages,
569 # 'cssclass' chosen below
573 $disableEmailPrefs = false;
575 if ( $this->options
->get( 'EmailAuthentication' ) ) {
576 $emailauthenticationclass = 'mw-email-not-authenticated';
577 if ( $user->getEmail() ) {
578 if ( $user->getEmailAuthenticationTimestamp() ) {
579 // date and time are separate parameters to facilitate localisation.
580 // $time is kept for backward compat reasons.
581 // 'emailauthenticated' is also used in SpecialConfirmemail.php
582 $displayUser = $context->getUser();
583 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
584 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
585 $d = $lang->userDate( $emailTimestamp, $displayUser );
586 $t = $lang->userTime( $emailTimestamp, $displayUser );
587 $emailauthenticated = $context->msg( 'emailauthenticated',
588 $time, $d, $t )->parse() . '<br />';
589 $disableEmailPrefs = false;
590 $emailauthenticationclass = 'mw-email-authenticated';
592 $disableEmailPrefs = true;
593 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
594 new \OOUI\
ButtonWidget( [
595 'href' => SpecialPage
::getTitleFor( 'Confirmemail' )->getLinkURL(),
596 'label' => $context->msg( 'emailconfirmlink' )->text(),
598 $emailauthenticationclass = "mw-email-not-authenticated";
601 $disableEmailPrefs = true;
602 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
603 $emailauthenticationclass = 'mw-email-none';
606 if ( $canViewPrivateInfo ) {
607 $defaultPreferences['emailauthentication'] = [
610 'section' => 'personal/email',
611 'label-message' => 'prefs-emailconfirm-label',
612 'default' => $emailauthenticated,
613 # Apply the same CSS class used on the input to the message:
614 'cssclass' => $emailauthenticationclass,
619 if ( $this->options
->get( 'AllowRequiringEmailForResets' ) ) {
620 $defaultPreferences['requireemail'] = [
622 'label-message' => 'tog-requireemail',
623 'help-message' => 'prefs-help-requireemail',
624 'section' => 'personal/email',
625 'disabled' => $disableEmailPrefs,
629 if ( $this->options
->get( 'EnableUserEmail' ) &&
630 $this->permissionManager
->userHasRight( $user, 'sendemail' )
632 $defaultPreferences['disablemail'] = [
633 'id' => 'wpAllowEmail',
636 'section' => 'personal/email',
637 'label-message' => 'allowemail',
638 'disabled' => $disableEmailPrefs,
641 $defaultPreferences['email-allow-new-users'] = [
642 'id' => 'wpAllowEmailFromNewUsers',
644 'section' => 'personal/email',
645 'label-message' => 'email-allow-new-users-label',
646 'disabled' => $disableEmailPrefs,
649 $defaultPreferences['ccmeonemails'] = [
651 'section' => 'personal/email',
652 'label-message' => 'tog-ccmeonemails',
653 'disabled' => $disableEmailPrefs,
656 if ( $this->options
->get( 'EnableUserEmailBlacklist' ) ) {
657 $defaultPreferences['email-blacklist'] = [
658 'type' => 'usersmultiselect',
659 'label-message' => 'email-blacklist-label',
660 'section' => 'personal/email',
661 'disabled' => $disableEmailPrefs,
662 'filter' => MultiUsernameFilter
::class,
667 if ( $this->options
->get( 'EnotifWatchlist' ) ) {
668 $defaultPreferences['enotifwatchlistpages'] = [
670 'section' => 'personal/email',
671 'label-message' => 'tog-enotifwatchlistpages',
672 'disabled' => $disableEmailPrefs,
675 if ( $this->options
->get( 'EnotifUserTalk' ) ) {
676 $defaultPreferences['enotifusertalkpages'] = [
678 'section' => 'personal/email',
679 'label-message' => 'tog-enotifusertalkpages',
680 'disabled' => $disableEmailPrefs,
683 if ( $this->options
->get( 'EnotifUserTalk' ) ||
684 $this->options
->get( 'EnotifWatchlist' ) ) {
685 if ( $this->options
->get( 'EnotifMinorEdits' ) ) {
686 $defaultPreferences['enotifminoredits'] = [
688 'section' => 'personal/email',
689 'label-message' => 'tog-enotifminoredits',
690 'disabled' => $disableEmailPrefs,
694 if ( $this->options
->get( 'EnotifRevealEditorAddress' ) ) {
695 $defaultPreferences['enotifrevealaddr'] = [
697 'section' => 'personal/email',
698 'label-message' => 'tog-enotifrevealaddr',
699 'disabled' => $disableEmailPrefs,
708 * @param IContextSource $context
709 * @param array &$defaultPreferences
712 protected function skinPreferences( User
$user, IContextSource
$context, &$defaultPreferences ) {
713 # # Skin #####################################
715 // Skin selector, if there is at least one valid skin
716 $skinOptions = $this->generateSkinOptions( $user, $context );
717 if ( $skinOptions ) {
718 $defaultPreferences['skin'] = [
720 'options' => $skinOptions,
721 'section' => 'rendering/skin',
725 $allowUserCss = $this->options
->get( 'AllowUserCss' );
726 $allowUserJs = $this->options
->get( 'AllowUserJs' );
727 # Create links to user CSS/JS pages for all skins
728 # This code is basically copied from generateSkinOptions(). It'd
729 # be nice to somehow merge this back in there to avoid redundancy.
730 if ( $allowUserCss ||
$allowUserJs ) {
732 $userName = $user->getName();
734 if ( $allowUserCss ) {
735 $cssPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.css' );
736 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
737 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
740 if ( $allowUserJs ) {
741 $jsPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.js' );
742 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
743 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
746 $defaultPreferences['commoncssjs'] = [
749 'default' => $context->getLanguage()->pipeList( $linkTools ),
750 'label-message' => 'prefs-common-config',
751 'section' => 'rendering/skin',
757 * @param IContextSource $context
758 * @param array &$defaultPreferences
760 protected function filesPreferences( IContextSource
$context, &$defaultPreferences ) {
761 # # Files #####################################
762 $defaultPreferences['imagesize'] = [
764 'options' => $this->getImageSizes( $context ),
765 'label-message' => 'imagemaxsize',
766 'section' => 'rendering/files',
768 $defaultPreferences['thumbsize'] = [
770 'options' => $this->getThumbSizes( $context ),
771 'label-message' => 'thumbsize',
772 'section' => 'rendering/files',
778 * @param IContextSource $context
779 * @param array &$defaultPreferences
782 protected function datetimePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
783 # # Date and time #####################################
784 $dateOptions = $this->getDateOptions( $context );
785 if ( $dateOptions ) {
786 $defaultPreferences['date'] = [
788 'options' => $dateOptions,
789 'section' => 'rendering/dateformat',
794 $now = wfTimestampNow();
795 $lang = $context->getLanguage();
796 $nowlocal = Xml
::element( 'span', [ 'id' => 'wpLocalTime' ],
797 $lang->userTime( $now, $user ) );
798 $nowserver = $lang->userTime( $now, $user,
799 [ 'format' => false, 'timecorrection' => false ] ) .
800 Html
::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 +
(int)substr( $now, 10, 2 ) );
802 $defaultPreferences['nowserver'] = [
805 'label-message' => 'servertime',
806 'default' => $nowserver,
807 'section' => 'rendering/timeoffset',
810 $defaultPreferences['nowlocal'] = [
813 'label-message' => 'localtime',
814 'default' => $nowlocal,
815 'section' => 'rendering/timeoffset',
818 // Grab existing pref.
819 $tzOffset = $user->getOption( 'timecorrection' );
820 $tz = explode( '|', $tzOffset, 3 );
822 $tzOptions = $this->getTimezoneOptions( $context );
824 $tzSetting = $tzOffset;
825 if ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
826 !in_array( $tzOffset, HTMLFormField
::flattenOptions( $tzOptions ) )
828 // Timezone offset can vary with DST
830 $userTZ = new DateTimeZone( $tz[2] );
831 $minDiff = floor( $userTZ->getOffset( new DateTime( 'now' ) ) / 60 );
832 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
833 } catch ( Exception
$e ) {
834 // User has an invalid time zone set. Fall back to just using the offset
838 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
840 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) %
60 );
843 $defaultPreferences['timecorrection'] = [
844 'class' => \HTMLSelectOrOtherField
::class,
845 'label-message' => 'timezonelegend',
846 'options' => $tzOptions,
847 'default' => $tzSetting,
849 'section' => 'rendering/timeoffset',
850 'id' => 'wpTimeCorrection',
851 'filter' => TimezoneFilter
::class,
852 'placeholder-message' => 'timezone-useoffset-placeholder',
858 * @param MessageLocalizer $l10n
859 * @param array &$defaultPreferences
861 protected function renderingPreferences(
863 MessageLocalizer
$l10n,
866 # # Diffs ####################################
867 $defaultPreferences['diffonly'] = [
869 'section' => 'rendering/diffs',
870 'label-message' => 'tog-diffonly',
872 $defaultPreferences['norollbackdiff'] = [
874 'section' => 'rendering/diffs',
875 'label-message' => 'tog-norollbackdiff',
878 # # Page Rendering ##############################
879 if ( $this->options
->get( 'AllowUserCssPrefs' ) ) {
880 $defaultPreferences['underline'] = [
883 $l10n->msg( 'underline-never' )->text() => 0,
884 $l10n->msg( 'underline-always' )->text() => 1,
885 $l10n->msg( 'underline-default' )->text() => 2,
887 'label-message' => 'tog-underline',
888 'section' => 'rendering/advancedrendering',
892 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
893 $stubThresholdOptions = [ $l10n->msg( 'stub-threshold-disabled' )->text() => 0 ];
894 foreach ( $stubThresholdValues as $value ) {
895 $stubThresholdOptions[$l10n->msg( 'size-bytes', $value )->text()] = $value;
898 $defaultPreferences['stubthreshold'] = [
900 'section' => 'rendering/advancedrendering',
901 'options' => $stubThresholdOptions,
902 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
903 'label-raw' => $l10n->msg( 'stub-threshold' )->rawParams(
905 $l10n->msg( 'stub-threshold-sample-link' )->parse() .
909 $defaultPreferences['showhiddencats'] = [
911 'section' => 'rendering/advancedrendering',
912 'label-message' => 'tog-showhiddencats'
915 $defaultPreferences['numberheadings'] = [
917 'section' => 'rendering/advancedrendering',
918 'label-message' => 'tog-numberheadings',
921 if ( $this->permissionManager
->userHasRight( $user, 'rollback' ) ) {
922 $defaultPreferences['showrollbackconfirmation'] = [
924 'section' => 'rendering/advancedrendering',
925 'label-message' => 'tog-showrollbackconfirmation',
932 * @param MessageLocalizer $l10n
933 * @param array &$defaultPreferences
935 protected function editingPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
936 # # Editing #####################################
937 $defaultPreferences['editsectiononrightclick'] = [
939 'section' => 'editing/advancedediting',
940 'label-message' => 'tog-editsectiononrightclick',
942 $defaultPreferences['editondblclick'] = [
944 'section' => 'editing/advancedediting',
945 'label-message' => 'tog-editondblclick',
948 if ( $this->options
->get( 'AllowUserCssPrefs' ) ) {
949 $defaultPreferences['editfont'] = [
951 'section' => 'editing/editor',
952 'label-message' => 'editfont-style',
954 $l10n->msg( 'editfont-monospace' )->text() => 'monospace',
955 $l10n->msg( 'editfont-sansserif' )->text() => 'sans-serif',
956 $l10n->msg( 'editfont-serif' )->text() => 'serif',
961 if ( $this->permissionManager
->userHasRight( $user, 'minoredit' ) ) {
962 $defaultPreferences['minordefault'] = [
964 'section' => 'editing/editor',
965 'label-message' => 'tog-minordefault',
969 $defaultPreferences['forceeditsummary'] = [
971 'section' => 'editing/editor',
972 'label-message' => 'tog-forceeditsummary',
974 $defaultPreferences['useeditwarning'] = [
976 'section' => 'editing/editor',
977 'label-message' => 'tog-useeditwarning',
980 $defaultPreferences['previewonfirst'] = [
982 'section' => 'editing/preview',
983 'label-message' => 'tog-previewonfirst',
985 $defaultPreferences['previewontop'] = [
987 'section' => 'editing/preview',
988 'label-message' => 'tog-previewontop',
990 $defaultPreferences['uselivepreview'] = [
992 'section' => 'editing/preview',
993 'label-message' => 'tog-uselivepreview',
999 * @param MessageLocalizer $l10n
1000 * @param array &$defaultPreferences
1002 protected function rcPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
1003 $rcMaxAge = $this->options
->get( 'RCMaxAge' );
1004 # # RecentChanges #####################################
1005 $defaultPreferences['rcdays'] = [
1007 'label-message' => 'recentchangesdays',
1008 'section' => 'rc/displayrc',
1010 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
1011 'help' => $l10n->msg( 'recentchangesdays-max' )->numParams(
1012 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
1014 $defaultPreferences['rclimit'] = [
1018 'label-message' => 'recentchangescount',
1019 'help-message' => 'prefs-help-recentchangescount',
1020 'section' => 'rc/displayrc',
1021 'filter' => IntvalFilter
::class,
1023 $defaultPreferences['usenewrc'] = [
1025 'label-message' => 'tog-usenewrc',
1026 'section' => 'rc/advancedrc',
1028 $defaultPreferences['hideminor'] = [
1030 'label-message' => 'tog-hideminor',
1031 'section' => 'rc/changesrc',
1033 $defaultPreferences['rcfilters-rc-collapsed'] = [
1036 $defaultPreferences['rcfilters-wl-collapsed'] = [
1039 $defaultPreferences['rcfilters-saved-queries'] = [
1042 $defaultPreferences['rcfilters-wl-saved-queries'] = [
1045 // Override RCFilters preferences for RecentChanges 'limit'
1046 $defaultPreferences['rcfilters-limit'] = [
1049 $defaultPreferences['rcfilters-saved-queries-versionbackup'] = [
1052 $defaultPreferences['rcfilters-wl-saved-queries-versionbackup'] = [
1056 if ( $this->options
->get( 'RCWatchCategoryMembership' ) ) {
1057 $defaultPreferences['hidecategorization'] = [
1059 'label-message' => 'tog-hidecategorization',
1060 'section' => 'rc/changesrc',
1064 if ( $user->useRCPatrol() ) {
1065 $defaultPreferences['hidepatrolled'] = [
1067 'section' => 'rc/changesrc',
1068 'label-message' => 'tog-hidepatrolled',
1072 if ( $user->useNPPatrol() ) {
1073 $defaultPreferences['newpageshidepatrolled'] = [
1075 'section' => 'rc/changesrc',
1076 'label-message' => 'tog-newpageshidepatrolled',
1080 if ( $this->options
->get( 'RCShowWatchingUsers' ) ) {
1081 $defaultPreferences['shownumberswatching'] = [
1083 'section' => 'rc/advancedrc',
1084 'label-message' => 'tog-shownumberswatching',
1088 $defaultPreferences['rcenhancedfilters-disable'] = [
1090 'section' => 'rc/advancedrc',
1091 'label-message' => 'rcfilters-preference-label',
1092 'help-message' => 'rcfilters-preference-help',
1098 * @param IContextSource $context
1099 * @param array &$defaultPreferences
1101 protected function watchlistPreferences(
1102 User
$user, IContextSource
$context, &$defaultPreferences
1104 $watchlistdaysMax = ceil( $this->options
->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1106 # # Watchlist #####################################
1107 if ( $this->permissionManager
->userHasRight( $user, 'editmywatchlist' ) ) {
1108 $editWatchlistLinks = '';
1109 $editWatchlistModes = [
1110 'edit' => [ 'subpage' => false, 'flags' => [] ],
1111 'raw' => [ 'subpage' => 'raw', 'flags' => [] ],
1112 'clear' => [ 'subpage' => 'clear', 'flags' => [ 'destructive' ] ],
1114 foreach ( $editWatchlistModes as $mode => $options ) {
1115 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1116 $editWatchlistLinks .=
1117 new \OOUI\
ButtonWidget( [
1118 'href' => SpecialPage
::getTitleFor( 'EditWatchlist', $options['subpage'] )->getLinkURL(),
1119 'flags' => $options[ 'flags' ],
1120 'label' => new \OOUI\
HtmlSnippet(
1121 $context->msg( "prefs-editwatchlist-{$mode}" )->parse()
1126 $defaultPreferences['editwatchlist'] = [
1129 'default' => $editWatchlistLinks,
1130 'label-message' => 'prefs-editwatchlist-label',
1131 'section' => 'watchlist/editwatchlist',
1135 $defaultPreferences['watchlistdays'] = [
1138 'max' => $watchlistdaysMax,
1139 'section' => 'watchlist/displaywatchlist',
1140 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1141 $watchlistdaysMax )->escaped(),
1142 'label-message' => 'prefs-watchlist-days',
1144 $defaultPreferences['wllimit'] = [
1148 'label-message' => 'prefs-watchlist-edits',
1149 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1150 'section' => 'watchlist/displaywatchlist',
1151 'filter' => IntvalFilter
::class,
1153 $defaultPreferences['extendwatchlist'] = [
1155 'section' => 'watchlist/advancedwatchlist',
1156 'label-message' => 'tog-extendwatchlist',
1158 $defaultPreferences['watchlisthideminor'] = [
1160 'section' => 'watchlist/changeswatchlist',
1161 'label-message' => 'tog-watchlisthideminor',
1163 $defaultPreferences['watchlisthidebots'] = [
1165 'section' => 'watchlist/changeswatchlist',
1166 'label-message' => 'tog-watchlisthidebots',
1168 $defaultPreferences['watchlisthideown'] = [
1170 'section' => 'watchlist/changeswatchlist',
1171 'label-message' => 'tog-watchlisthideown',
1173 $defaultPreferences['watchlisthideanons'] = [
1175 'section' => 'watchlist/changeswatchlist',
1176 'label-message' => 'tog-watchlisthideanons',
1178 $defaultPreferences['watchlisthideliu'] = [
1180 'section' => 'watchlist/changeswatchlist',
1181 'label-message' => 'tog-watchlisthideliu',
1184 if ( !\SpecialWatchlist
::checkStructuredFilterUiEnabled( $user ) ) {
1185 $defaultPreferences['watchlistreloadautomatically'] = [
1187 'section' => 'watchlist/advancedwatchlist',
1188 'label-message' => 'tog-watchlistreloadautomatically',
1192 $defaultPreferences['watchlistunwatchlinks'] = [
1194 'section' => 'watchlist/advancedwatchlist',
1195 'label-message' => 'tog-watchlistunwatchlinks',
1198 if ( $this->options
->get( 'RCWatchCategoryMembership' ) ) {
1199 $defaultPreferences['watchlisthidecategorization'] = [
1201 'section' => 'watchlist/changeswatchlist',
1202 'label-message' => 'tog-watchlisthidecategorization',
1206 if ( $user->useRCPatrol() ) {
1207 $defaultPreferences['watchlisthidepatrolled'] = [
1209 'section' => 'watchlist/changeswatchlist',
1210 'label-message' => 'tog-watchlisthidepatrolled',
1215 'edit' => 'watchdefault',
1216 'move' => 'watchmoves',
1217 'delete' => 'watchdeletion'
1221 if ( $this->permissionManager
->userHasAnyRight( $user, 'createpage', 'createtalk' ) ) {
1222 $watchTypes['read'] = 'watchcreations';
1225 if ( $this->permissionManager
->userHasRight( $user, 'rollback' ) ) {
1226 $watchTypes['rollback'] = 'watchrollback';
1229 if ( $this->permissionManager
->userHasRight( $user, 'upload' ) ) {
1230 $watchTypes['upload'] = 'watchuploads';
1233 foreach ( $watchTypes as $action => $pref ) {
1234 if ( $this->permissionManager
->userHasRight( $user, $action ) ) {
1236 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1237 // tog-watchrollback
1238 $defaultPreferences[$pref] = [
1240 'section' => 'watchlist/pageswatchlist',
1241 'label-message' => "tog-$pref",
1246 $defaultPreferences['watchlisttoken'] = [
1250 $tokenButton = new \OOUI\
ButtonWidget( [
1251 'href' => SpecialPage
::getTitleFor( 'ResetTokens' )->getLinkURL( [
1252 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
1254 'label' => $context->msg( 'prefs-watchlist-managetokens' )->text(),
1256 $defaultPreferences['watchlisttoken-info'] = [
1258 'section' => 'watchlist/tokenwatchlist',
1259 'label-message' => 'prefs-watchlist-token',
1260 'help-message' => 'prefs-help-tokenmanagement',
1262 'default' => (string)$tokenButton,
1265 $defaultPreferences['wlenhancedfilters-disable'] = [
1267 'section' => 'watchlist/advancedwatchlist',
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 ( $this->nsInfo
->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();
1297 $allInstalledSkins = Skin
::getSkinNames();
1299 // Display the installed skin the user has specifically requested via useskin=….
1300 $useSkin = $context->getRequest()->getRawVal( 'useskin' );
1301 if ( isset( $allInstalledSkins[$useSkin] )
1302 && $context->msg( "skinname-$useSkin" )->exists()
1304 $validSkinNames[$useSkin] = $useSkin;
1307 // Display the skin if the user has set it as a preference already before it was hidden.
1308 $currentUserSkin = $user->getOption( 'skin' );
1309 if ( isset( $allInstalledSkins[$currentUserSkin] )
1310 && $context->msg( "skinname-$currentUserSkin" )->exists()
1312 $validSkinNames[$currentUserSkin] = $currentUserSkin;
1315 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1316 $msg = $context->msg( "skinname-{$skinkey}" );
1317 if ( $msg->exists() ) {
1318 $skinname = htmlspecialchars( $msg->text() );
1322 $defaultSkin = $this->options
->get( 'DefaultSkin' );
1323 $allowUserCss = $this->options
->get( 'AllowUserCss' );
1324 $allowUserJs = $this->options
->get( 'AllowUserJs' );
1326 # Sort by the internal name, so that the ordering is the same for each display language,
1327 # especially if some skin names are translated to use a different alphabet and some are not.
1328 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1329 # Display the default first in the list by comparing it as lesser than any other.
1330 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1333 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1336 return strcasecmp( $a, $b );
1339 $foundDefault = false;
1340 foreach ( $validSkinNames as $skinkey => $sn ) {
1343 # Mark the default skin
1344 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1345 $linkTools[] = $context->msg( 'default' )->escaped();
1346 $foundDefault = true;
1349 # Create preview link
1350 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1351 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1353 # Create links to user CSS/JS pages
1354 if ( $allowUserCss ) {
1355 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1356 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
1357 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
1360 if ( $allowUserJs ) {
1361 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1362 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
1363 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
1366 $display = $sn . ' ' . $context->msg( 'parentheses' )
1367 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1369 $ret[$display] = $skinkey;
1372 if ( !$foundDefault ) {
1373 // If the default skin is not available, things are going to break horribly because the
1374 // default value for skin selector will not be a valid value. Let's just not show it then.
1382 * @param IContextSource $context
1385 protected function getDateOptions( IContextSource
$context ) {
1386 $lang = $context->getLanguage();
1387 $dateopts = $lang->getDatePreferences();
1392 if ( !in_array( 'default', $dateopts ) ) {
1393 $dateopts[] = 'default'; // Make sure default is always valid T21237
1396 // FIXME KLUGE: site default might not be valid for user language
1397 global $wgDefaultUserOptions;
1398 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1399 $wgDefaultUserOptions['date'] = 'default';
1402 $epoch = wfTimestampNow();
1403 foreach ( $dateopts as $key ) {
1404 if ( $key == 'default' ) {
1405 $formatted = $context->msg( 'datedefault' )->escaped();
1407 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1409 $ret[$formatted] = $key;
1416 * @param MessageLocalizer $l10n
1419 protected function getImageSizes( MessageLocalizer
$l10n ) {
1421 $pixels = $l10n->msg( 'unit-pixel' )->text();
1423 foreach ( $this->options
->get( 'ImageLimits' ) as $index => $limits ) {
1424 // Note: A left-to-right marker (U+200E) is inserted, see T144386
1425 $display = "{$limits[0]}\u{200E}×{$limits[1]}$pixels";
1426 $ret[$display] = $index;
1433 * @param MessageLocalizer $l10n
1436 protected function getThumbSizes( MessageLocalizer
$l10n ) {
1438 $pixels = $l10n->msg( 'unit-pixel' )->text();
1440 foreach ( $this->options
->get( 'ThumbLimits' ) as $index => $size ) {
1441 $display = $size . $pixels;
1442 $ret[$display] = $index;
1449 * @param string $signature
1450 * @param array $alldata
1451 * @param HTMLForm $form
1452 * @return bool|string
1454 protected function validateSignature( $signature, $alldata, HTMLForm
$form ) {
1455 $maxSigChars = $this->options
->get( 'MaxSigChars' );
1456 if ( mb_strlen( $signature ) > $maxSigChars ) {
1457 return Xml
::element( 'span', [ 'class' => 'error' ],
1458 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1459 } elseif ( isset( $alldata['fancysig'] ) &&
1460 $alldata['fancysig'] &&
1461 MediaWikiServices
::getInstance()->getParser()->validateSig( $signature ) === false
1463 return Xml
::element(
1465 [ 'class' => 'error' ],
1466 $form->msg( 'badsig' )->text()
1474 * @param string $signature
1475 * @param array $alldata
1476 * @param HTMLForm $form
1479 protected function cleanSignature( $signature, $alldata, HTMLForm
$form ) {
1480 $parser = MediaWikiServices
::getInstance()->getParser();
1481 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1482 $signature = $parser->cleanSig( $signature );
1484 // When no fancy sig used, make sure ~{3,5} get removed.
1485 $signature = Parser
::cleanSigInSig( $signature );
1493 * @param IContextSource $context
1494 * @param string $formClass
1495 * @param array $remove Array of items to remove
1498 public function getForm(
1500 IContextSource
$context,
1501 $formClass = PreferencesFormOOUI
::class,
1504 // We use ButtonWidgets in some of the getPreferences() functions
1505 $context->getOutput()->enableOOUI();
1507 $formDescriptor = $this->getFormDescriptor( $user, $context );
1508 if ( count( $remove ) ) {
1509 $removeKeys = array_flip( $remove );
1510 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1513 // Remove type=api preferences. They are not intended for rendering in the form.
1514 foreach ( $formDescriptor as $name => $info ) {
1515 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1516 unset( $formDescriptor[$name] );
1521 * @var PreferencesFormOOUI $htmlForm
1523 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1525 // This allows users to opt-in to hidden skins. While this should be discouraged and is not
1526 // discoverable, this allows users to still use hidden skins while preventing new users from
1527 // adopting unsupported skins. If no useskin=… parameter was provided, it will not show up
1528 // in the resulting URL.
1529 $htmlForm->setAction( $context->getTitle()->getLocalURL( [
1530 'useskin' => $context->getRequest()->getRawVal( 'useskin' )
1533 $htmlForm->setModifiedUser( $user );
1534 $htmlForm->setOptionsEditable( $this->permissionManager
1535 ->userHasRight( $user, 'editmyoptions' ) );
1536 $htmlForm->setPrivateInfoEditable( $this->permissionManager
1537 ->userHasRight( $user, 'editmyprivateinfo' ) );
1538 $htmlForm->setId( 'mw-prefs-form' );
1539 $htmlForm->setAutocomplete( 'off' );
1540 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1541 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1542 $htmlForm->setSubmitTooltip( 'preferences-save' );
1543 $htmlForm->setSubmitID( 'prefcontrol' );
1544 $htmlForm->setSubmitCallback(
1545 function ( array $formData, PreferencesFormOOUI
$form ) use ( $formDescriptor ) {
1546 return $this->submitForm( $formData, $form, $formDescriptor );
1554 * @param IContextSource $context
1557 protected function getTimezoneOptions( IContextSource
$context ) {
1560 $localTZoffset = $this->options
->get( 'LocalTZoffset' );
1561 $timeZoneList = $this->getTimeZoneList( $context->getLanguage() );
1563 $timestamp = MWTimestamp
::getLocalInstance();
1564 // Check that the LocalTZoffset is the same as the local time zone offset
1565 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1566 $timezoneName = $timestamp->getTimezone()->getName();
1567 // Localize timezone
1568 if ( isset( $timeZoneList[$timezoneName] ) ) {
1569 $timezoneName = $timeZoneList[$timezoneName]['name'];
1571 $server_tz_msg = $context->msg(
1572 'timezoneuseserverdefault',
1576 $tzstring = sprintf(
1578 floor( $localTZoffset / 60 ),
1579 abs( $localTZoffset ) %
60
1581 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1583 $opt[$server_tz_msg] = "System|$localTZoffset";
1584 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1585 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1587 foreach ( $timeZoneList as $timeZoneInfo ) {
1588 $region = $timeZoneInfo['region'];
1589 if ( !isset( $opt[$region] ) ) {
1592 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1598 * Handle the form submission if everything validated properly
1600 * @param array $formData
1601 * @param PreferencesFormOOUI $form
1602 * @param array[] $formDescriptor
1603 * @return bool|Status|string
1605 protected function saveFormData( $formData, PreferencesFormOOUI
$form, array $formDescriptor ) {
1606 $user = $form->getModifiedUser();
1607 $hiddenPrefs = $this->options
->get( 'HiddenPrefs' );
1610 if ( !$this->permissionManager
1611 ->userHasAnyRight( $user, 'editmyprivateinfo', 'editmyoptions' )
1613 return Status
::newFatal( 'mypreferencesprotected' );
1617 $this->applyFilters( $formData, $formDescriptor, 'filterFromForm' );
1619 // Fortunately, the realname field is MUCH simpler
1620 // (not really "private", but still shouldn't be edited without permission)
1622 if ( !in_array( 'realname', $hiddenPrefs )
1623 && $this->permissionManager
->userHasRight( $user, 'editmyprivateinfo' )
1624 && array_key_exists( 'realname', $formData )
1626 $realName = $formData['realname'];
1627 $user->setRealName( $realName );
1630 if ( $this->permissionManager
->userHasRight( $user, 'editmyoptions' ) ) {
1631 $oldUserOptions = $user->getOptions();
1633 foreach ( $this->getSaveBlacklist() as $b ) {
1634 unset( $formData[$b] );
1637 # If users have saved a value for a preference which has subsequently been disabled
1638 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1639 # is subsequently re-enabled
1640 foreach ( $hiddenPrefs as $pref ) {
1641 # If the user has not set a non-default value here, the default will be returned
1642 # and subsequently discarded
1643 $formData[$pref] = $user->getOption( $pref, null, true );
1646 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1648 isset( $formData['rclimit'] ) &&
1649 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1651 $formData['rcfilters-limit'] = $formData['rclimit'];
1654 // Keep old preferences from interfering due to back-compat code, etc.
1655 $user->resetOptions( 'unused', $form->getContext() );
1657 foreach ( $formData as $key => $value ) {
1658 $user->setOption( $key, $value );
1662 'PreferencesFormPreSave',
1663 [ $formData, $form, $user, &$result, $oldUserOptions ]
1667 $user->saveSettings();
1673 * Applies filters to preferences either before or after form usage
1675 * @param array &$preferences
1676 * @param array $formDescriptor
1677 * @param string $verb Name of the filter method to call, either 'filterFromForm' or
1680 protected function applyFilters( array &$preferences, array $formDescriptor, $verb ) {
1681 foreach ( $formDescriptor as $preference => $desc ) {
1682 if ( !isset( $desc['filter'] ) ||
!isset( $preferences[$preference] ) ) {
1685 $filterDesc = $desc['filter'];
1686 if ( $filterDesc instanceof Filter
) {
1687 $filter = $filterDesc;
1688 } elseif ( class_exists( $filterDesc ) ) {
1689 $filter = new $filterDesc();
1690 } elseif ( is_callable( $filterDesc ) ) {
1691 $filter = $filterDesc();
1693 throw new UnexpectedValueException(
1694 "Unrecognized filter type for preference '$preference'"
1697 $preferences[$preference] = $filter->$verb( $preferences[$preference] );
1702 * Save the form data and reload the page
1704 * @param array $formData
1705 * @param PreferencesFormOOUI $form
1706 * @param array $formDescriptor
1709 protected function submitForm(
1711 PreferencesFormOOUI
$form,
1712 array $formDescriptor
1714 $res = $this->saveFormData( $formData, $form, $formDescriptor );
1716 if ( $res === true ) {
1717 $context = $form->getContext();
1720 if ( $res === 'eauth' ) {
1721 $urlOptions['eauth'] = 1;
1724 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1726 $url = $form->getTitle()->getFullURL( $urlOptions );
1728 // Set session data for the success message
1729 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1731 $context->getOutput()->redirect( $url );
1734 return ( $res === true ? Status
::newGood() : $res );
1738 * Get a list of all time zones
1739 * @param Language $language Language used for the localized names
1740 * @return array A list of all time zones. The system name of the time zone is used as key and
1741 * the value is an array which contains localized name, the timecorrection value used for
1742 * preferences and the region
1745 protected function getTimeZoneList( Language
$language ) {
1746 $identifiers = DateTimeZone
::listIdentifiers();
1747 // @phan-suppress-next-line PhanTypeComparisonFromArray See phan issue #3162
1748 if ( $identifiers === false ) {
1751 sort( $identifiers );
1754 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1755 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1756 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1757 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1758 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1759 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1760 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1761 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1762 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1763 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1765 asort( $tzRegions );
1769 $now = new DateTime();
1771 foreach ( $identifiers as $identifier ) {
1772 $parts = explode( '/', $identifier, 2 );
1774 // DateTimeZone::listIdentifiers() returns a number of
1775 // backwards-compatibility entries. This filters them out of the
1776 // list presented to the user.
1777 if ( count( $parts ) !== 2 ||
!array_key_exists( $parts[0], $tzRegions ) ) {
1782 $parts[0] = $tzRegions[$parts[0]];
1784 $dateTimeZone = new DateTimeZone( $identifier );
1785 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1787 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1788 $value = "ZoneInfo|$minDiff|$identifier";
1790 $timeZoneList[$identifier] = [
1792 'timecorrection' => $value,
1793 'region' => $parts[0],
1797 return $timeZoneList;