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 = [
91 'DisableLangConversion',
92 'EmailAuthentication',
96 'EnableUserEmailBlacklist',
98 'EnotifRevealEditorAddress',
107 'RCShowWatchingUsers',
108 'RCWatchCategoryMembership',
114 * Do not call this directly. Get it from MediaWikiServices.
116 * @param ServiceOptions|Config $options Config accepted for backwards compatibility
117 * @param Language $contLang
118 * @param AuthManager $authManager
119 * @param LinkRenderer $linkRenderer
120 * @param NamespaceInfo|null $nsInfo
122 public function __construct(
125 AuthManager
$authManager,
126 LinkRenderer
$linkRenderer,
127 NamespaceInfo
$nsInfo = null
129 if ( $options instanceof Config
) {
130 wfDeprecated( __METHOD__
. ' with Config parameter', '1.34' );
131 $options = new ServiceOptions( self
::$constructorOptions, $options );
134 $options->assertRequiredOptions( self
::$constructorOptions );
137 wfDeprecated( __METHOD__
. ' with no NamespaceInfo argument', '1.34' );
138 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
140 $this->options
= $options;
141 $this->contLang
= $contLang;
142 $this->authManager
= $authManager;
143 $this->linkRenderer
= $linkRenderer;
144 $this->nsInfo
= $nsInfo;
145 $this->logger
= new NullLogger();
151 public function getSaveBlacklist() {
159 * @throws MWException
161 * @param IContextSource $context
164 public function getFormDescriptor( User
$user, IContextSource
$context ) {
167 OutputPage
::setupOOUI(
168 strtolower( $context->getSkin()->getSkinName() ),
169 $context->getLanguage()->getDir()
172 $canIPUseHTTPS = wfCanIPUseHTTPS( $context->getRequest()->getIP() );
173 $this->profilePreferences( $user, $context, $preferences, $canIPUseHTTPS );
174 $this->skinPreferences( $user, $context, $preferences );
175 $this->datetimePreferences( $user, $context, $preferences );
176 $this->filesPreferences( $context, $preferences );
177 $this->renderingPreferences( $user, $context, $preferences );
178 $this->editingPreferences( $user, $context, $preferences );
179 $this->rcPreferences( $user, $context, $preferences );
180 $this->watchlistPreferences( $user, $context, $preferences );
181 $this->searchPreferences( $preferences );
183 Hooks
::run( 'GetPreferences', [ $user, &$preferences ] );
185 $this->loadPreferenceValues( $user, $context, $preferences );
186 $this->logger
->debug( "Created form descriptor for user '{$user->getName()}'" );
191 * Loads existing values for a given array of preferences
192 * @throws MWException
194 * @param IContextSource $context
195 * @param array &$defaultPreferences Array to load values for
198 private function loadPreferenceValues(
199 User
$user, IContextSource
$context, &$defaultPreferences
201 # # Remove preferences that wikis don't want to use
202 foreach ( $this->options
->get( 'HiddenPrefs' ) as $pref ) {
203 if ( isset( $defaultPreferences[$pref] ) ) {
204 unset( $defaultPreferences[$pref] );
208 # # Make sure that form fields have their parent set. See T43337.
209 $dummyForm = new HTMLForm( [], $context );
211 $disable = !$user->isAllowed( 'editmyoptions' );
213 $defaultOptions = User
::getDefaultOptions();
214 $userOptions = $user->getOptions();
215 $this->applyFilters( $userOptions, $defaultPreferences, 'filterForForm' );
216 # # Prod in defaults from the user
217 foreach ( $defaultPreferences as $name => &$info ) {
218 $prefFromUser = $this->getOptionFromUser( $name, $info, $userOptions );
219 if ( $disable && !in_array( $name, $this->getSaveBlacklist() ) ) {
220 $info['disabled'] = 'disabled';
222 $field = HTMLForm
::loadInputFromParameters( $name, $info, $dummyForm ); // For validation
223 $globalDefault = $defaultOptions[$name] ??
null;
225 // If it validates, set it as the default
226 if ( isset( $info['default'] ) ) {
227 // Already set, no problem
229 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
230 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
231 $info['default'] = $prefFromUser;
232 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
233 $info['default'] = $globalDefault;
235 $globalDefault = json_encode( $globalDefault );
236 throw new MWException(
237 "Default '$globalDefault' is invalid for preference $name of user $user"
242 return $defaultPreferences;
246 * Pull option from a user account. Handles stuff like array-type preferences.
248 * @param string $name
250 * @param array $userOptions
251 * @return array|string
253 protected function getOptionFromUser( $name, $info, array $userOptions ) {
254 $val = $userOptions[$name] ??
null;
256 // Handling for multiselect preferences
257 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
258 ( isset( $info['class'] ) && $info['class'] == \HTMLMultiSelectField
::class ) ) {
259 $options = HTMLFormField
::flattenOptions( $info['options'] );
260 $prefix = $info['prefix'] ??
$name;
263 foreach ( $options as $value ) {
264 if ( $userOptions["$prefix$value"] ??
false ) {
270 // Handling for checkmatrix preferences
271 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
272 ( isset( $info['class'] ) && $info['class'] == \HTMLCheckMatrix
::class ) ) {
273 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
274 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
275 $prefix = $info['prefix'] ??
$name;
278 foreach ( $columns as $column ) {
279 foreach ( $rows as $row ) {
280 if ( $userOptions["$prefix$column-$row"] ??
false ) {
281 $val[] = "$column-$row";
291 * @todo Inject user Language instead of using context.
293 * @param IContextSource $context
294 * @param array &$defaultPreferences
295 * @param bool $canIPUseHTTPS Whether the user's IP is likely to be able to access the wiki
299 protected function profilePreferences(
300 User
$user, IContextSource
$context, &$defaultPreferences, $canIPUseHTTPS
302 // retrieving user name for GENDER and misc.
303 $userName = $user->getName();
305 # # User info #####################################
307 $defaultPreferences['username'] = [
309 'label-message' => [ 'username', $userName ],
310 'default' => $userName,
311 'section' => 'personal/info',
314 $lang = $context->getLanguage();
316 # Get groups to which the user belongs
317 $userEffectiveGroups = $user->getEffectiveGroups();
318 $userGroupMemberships = $user->getGroupMemberships();
319 $userGroups = $userMembers = $userTempGroups = $userTempMembers = [];
320 foreach ( $userEffectiveGroups as $ueg ) {
322 // Skip the default * group, seems useless here
326 $groupStringOrObject = $userGroupMemberships[$ueg] ??
$ueg;
328 $userG = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html' );
329 $userM = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html',
332 // Store expiring groups separately, so we can place them before non-expiring
333 // groups in the list. This is to avoid the ambiguity of something like
334 // "administrator, bureaucrat (until X date)" -- users might wonder whether the
335 // expiry date applies to both groups, or just the last one
336 if ( $groupStringOrObject instanceof UserGroupMembership
&&
337 $groupStringOrObject->getExpiry()
339 $userTempGroups[] = $userG;
340 $userTempMembers[] = $userM;
342 $userGroups[] = $userG;
343 $userMembers[] = $userM;
347 sort( $userMembers );
348 sort( $userTempGroups );
349 sort( $userTempMembers );
350 $userGroups = array_merge( $userTempGroups, $userGroups );
351 $userMembers = array_merge( $userTempMembers, $userMembers );
353 $defaultPreferences['usergroups'] = [
355 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
356 count( $userGroups ) )->params( $userName )->parse(),
357 'default' => $context->msg( 'prefs-memberingroups-type' )
358 ->rawParams( $lang->commaList( $userGroups ), $lang->commaList( $userMembers ) )
361 'section' => 'personal/info',
364 $contribTitle = SpecialPage
::getTitleFor( "Contributions", $userName );
365 $formattedEditCount = $lang->formatNum( $user->getEditCount() );
366 $editCount = $this->linkRenderer
->makeLink( $contribTitle, $formattedEditCount );
368 $defaultPreferences['editcount'] = [
371 'label-message' => 'prefs-edits',
372 'default' => $editCount,
373 'section' => 'personal/info',
376 if ( $user->getRegistration() ) {
377 $displayUser = $context->getUser();
378 $userRegistration = $user->getRegistration();
379 $defaultPreferences['registrationdate'] = [
381 'label-message' => 'prefs-registration',
382 'default' => $context->msg(
383 'prefs-registration-date-time',
384 $lang->userTimeAndDate( $userRegistration, $displayUser ),
385 $lang->userDate( $userRegistration, $displayUser ),
386 $lang->userTime( $userRegistration, $displayUser )
388 'section' => 'personal/info',
392 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
393 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
395 // Actually changeable stuff
396 $defaultPreferences['realname'] = [
397 // (not really "private", but still shouldn't be edited without permission)
398 'type' => $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'realname' )
400 'default' => $user->getRealName(),
401 'section' => 'personal/info',
402 'label-message' => 'yourrealname',
403 'help-message' => 'prefs-help-realname',
406 if ( $canEditPrivateInfo && $this->authManager
->allowsAuthenticationDataChange(
407 new PasswordAuthenticationRequest(), false )->isGood()
409 $defaultPreferences['password'] = [
412 'default' => (string)new \OOUI\
ButtonWidget( [
413 'href' => SpecialPage
::getTitleFor( 'ChangePassword' )->getLinkURL( [
414 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
416 'label' => $context->msg( 'prefs-resetpass' )->text(),
418 'label-message' => 'yourpassword',
419 'section' => 'personal/info',
422 // Only show prefershttps if secure login is turned on
423 if ( $this->options
->get( 'SecureLogin' ) && $canIPUseHTTPS ) {
424 $defaultPreferences['prefershttps'] = [
426 'label-message' => 'tog-prefershttps',
427 'help-message' => 'prefs-help-prefershttps',
428 'section' => 'personal/info'
432 $languages = Language
::fetchLanguageNames( null, 'mwfile' );
433 $languageCode = $this->options
->get( 'LanguageCode' );
434 if ( !array_key_exists( $languageCode, $languages ) ) {
435 $languages[$languageCode] = $languageCode;
436 // Sort the array again
441 foreach ( $languages as $code => $name ) {
442 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
443 $options[$display] = $code;
445 $defaultPreferences['language'] = [
447 'section' => 'personal/i18n',
448 'options' => $options,
449 'label-message' => 'yourlanguage',
452 $defaultPreferences['gender'] = [
454 'section' => 'personal/i18n',
456 $context->msg( 'parentheses' )
457 ->params( $context->msg( 'gender-unknown' )->plain() )
458 ->escaped() => 'unknown',
459 $context->msg( 'gender-female' )->escaped() => 'female',
460 $context->msg( 'gender-male' )->escaped() => 'male',
462 'label-message' => 'yourgender',
463 'help-message' => 'prefs-help-gender',
466 // see if there are multiple language variants to choose from
467 if ( !$this->options
->get( 'DisableLangConversion' ) ) {
468 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
469 if ( $langCode == $this->contLang
->getCode() ) {
470 if ( !$this->contLang
->hasVariants() ) {
474 $variants = $this->contLang
->getVariants();
476 foreach ( $variants as $v ) {
477 $v = str_replace( '_', '-', strtolower( $v ) );
478 $variantArray[$v] = $lang->getVariantname( $v, false );
482 foreach ( $variantArray as $code => $name ) {
483 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
484 $options[$display] = $code;
487 $defaultPreferences['variant'] = [
488 'label-message' => 'yourvariant',
490 'options' => $options,
491 'section' => 'personal/i18n',
492 'help-message' => 'prefs-help-variant',
495 $defaultPreferences["variant-$langCode"] = [
502 // show a preview of the old signature first
503 $oldsigWikiText = MediaWikiServices
::getInstance()->getParser()->preSaveTransform(
505 $context->getTitle(),
507 ParserOptions
::newFromContext( $context )
509 $oldsigHTML = Parser
::stripOuterParagraph(
510 $context->getOutput()->parseAsContent( $oldsigWikiText )
512 $defaultPreferences['oldsig'] = [
515 'label-message' => 'tog-oldsig',
516 'default' => $oldsigHTML,
517 'section' => 'personal/signature',
519 $defaultPreferences['nickname'] = [
520 'type' => $this->authManager
->allowsPropertyChange( 'nickname' ) ?
'text' : 'info',
521 'maxlength' => $this->options
->get( 'MaxSigChars' ),
522 'label-message' => 'yournick',
523 'validation-callback' => function ( $signature, $alldata, HTMLForm
$form ) {
524 return $this->validateSignature( $signature, $alldata, $form );
526 'section' => 'personal/signature',
527 'filter-callback' => function ( $signature, array $alldata, HTMLForm
$form ) {
528 return $this->cleanSignature( $signature, $alldata, $form );
531 $defaultPreferences['fancysig'] = [
533 'label-message' => 'tog-fancysig',
534 // show general help about signature at the bottom of the section
535 'help-message' => 'prefs-help-signature',
536 'section' => 'personal/signature'
541 if ( $this->options
->get( 'EnableEmail' ) ) {
542 if ( $canViewPrivateInfo ) {
544 $helpMessages[] = $this->options
->get( 'EmailConfirmToEdit' )
545 ?
'prefs-help-email-required'
546 : 'prefs-help-email';
548 if ( $this->options
->get( 'EnableUserEmail' ) ) {
549 // additional messages when users can send email to each other
550 $helpMessages[] = 'prefs-help-email-others';
553 $emailAddress = $user->getEmail() ?
htmlspecialchars( $user->getEmail() ) : '';
554 if ( $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'emailaddress' ) ) {
555 $button = new \OOUI\
ButtonWidget( [
556 'href' => SpecialPage
::getTitleFor( 'ChangeEmail' )->getLinkURL( [
557 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
560 $context->msg( $user->getEmail() ?
'prefs-changeemail' : 'prefs-setemail' )->text(),
563 $emailAddress .= $emailAddress == '' ?
$button : ( '<br />' . $button );
566 $defaultPreferences['emailaddress'] = [
569 'default' => $emailAddress,
570 'label-message' => 'youremail',
571 'section' => 'personal/email',
572 'help-messages' => $helpMessages,
573 # 'cssclass' chosen below
577 $disableEmailPrefs = false;
579 if ( $this->options
->get( 'EmailAuthentication' ) ) {
580 $emailauthenticationclass = 'mw-email-not-authenticated';
581 if ( $user->getEmail() ) {
582 if ( $user->getEmailAuthenticationTimestamp() ) {
583 // date and time are separate parameters to facilitate localisation.
584 // $time is kept for backward compat reasons.
585 // 'emailauthenticated' is also used in SpecialConfirmemail.php
586 $displayUser = $context->getUser();
587 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
588 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
589 $d = $lang->userDate( $emailTimestamp, $displayUser );
590 $t = $lang->userTime( $emailTimestamp, $displayUser );
591 $emailauthenticated = $context->msg( 'emailauthenticated',
592 $time, $d, $t )->parse() . '<br />';
593 $disableEmailPrefs = false;
594 $emailauthenticationclass = 'mw-email-authenticated';
596 $disableEmailPrefs = true;
597 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
598 new \OOUI\
ButtonWidget( [
599 'href' => SpecialPage
::getTitleFor( 'Confirmemail' )->getLinkURL(),
600 'label' => $context->msg( 'emailconfirmlink' )->text(),
602 $emailauthenticationclass = "mw-email-not-authenticated";
605 $disableEmailPrefs = true;
606 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
607 $emailauthenticationclass = 'mw-email-none';
610 if ( $canViewPrivateInfo ) {
611 $defaultPreferences['emailauthentication'] = [
614 'section' => 'personal/email',
615 'label-message' => 'prefs-emailconfirm-label',
616 'default' => $emailauthenticated,
617 # Apply the same CSS class used on the input to the message:
618 'cssclass' => $emailauthenticationclass,
623 if ( $this->options
->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
624 $defaultPreferences['disablemail'] = [
625 'id' => 'wpAllowEmail',
628 'section' => 'personal/email',
629 'label-message' => 'allowemail',
630 'disabled' => $disableEmailPrefs,
633 $defaultPreferences['email-allow-new-users'] = [
634 'id' => 'wpAllowEmailFromNewUsers',
636 'section' => 'personal/email',
637 'label-message' => 'email-allow-new-users-label',
638 'disabled' => $disableEmailPrefs,
641 $defaultPreferences['ccmeonemails'] = [
643 'section' => 'personal/email',
644 'label-message' => 'tog-ccmeonemails',
645 'disabled' => $disableEmailPrefs,
648 if ( $this->options
->get( 'EnableUserEmailBlacklist' ) ) {
649 $defaultPreferences['email-blacklist'] = [
650 'type' => 'usersmultiselect',
651 'label-message' => 'email-blacklist-label',
652 'section' => 'personal/email',
653 'disabled' => $disableEmailPrefs,
654 'filter' => MultiUsernameFilter
::class,
659 if ( $this->options
->get( 'EnotifWatchlist' ) ) {
660 $defaultPreferences['enotifwatchlistpages'] = [
662 'section' => 'personal/email',
663 'label-message' => 'tog-enotifwatchlistpages',
664 'disabled' => $disableEmailPrefs,
667 if ( $this->options
->get( 'EnotifUserTalk' ) ) {
668 $defaultPreferences['enotifusertalkpages'] = [
670 'section' => 'personal/email',
671 'label-message' => 'tog-enotifusertalkpages',
672 'disabled' => $disableEmailPrefs,
675 if ( $this->options
->get( 'EnotifUserTalk' ) ||
676 $this->options
->get( 'EnotifWatchlist' ) ) {
677 if ( $this->options
->get( 'EnotifMinorEdits' ) ) {
678 $defaultPreferences['enotifminoredits'] = [
680 'section' => 'personal/email',
681 'label-message' => 'tog-enotifminoredits',
682 'disabled' => $disableEmailPrefs,
686 if ( $this->options
->get( 'EnotifRevealEditorAddress' ) ) {
687 $defaultPreferences['enotifrevealaddr'] = [
689 'section' => 'personal/email',
690 'label-message' => 'tog-enotifrevealaddr',
691 'disabled' => $disableEmailPrefs,
700 * @param IContextSource $context
701 * @param array &$defaultPreferences
704 protected function skinPreferences( User
$user, IContextSource
$context, &$defaultPreferences ) {
705 # # Skin #####################################
707 // Skin selector, if there is at least one valid skin
708 $skinOptions = $this->generateSkinOptions( $user, $context );
709 if ( $skinOptions ) {
710 $defaultPreferences['skin'] = [
712 'options' => $skinOptions,
713 'section' => 'rendering/skin',
717 $allowUserCss = $this->options
->get( 'AllowUserCss' );
718 $allowUserJs = $this->options
->get( 'AllowUserJs' );
719 # Create links to user CSS/JS pages for all skins
720 # This code is basically copied from generateSkinOptions(). It'd
721 # be nice to somehow merge this back in there to avoid redundancy.
722 if ( $allowUserCss ||
$allowUserJs ) {
724 $userName = $user->getName();
726 if ( $allowUserCss ) {
727 $cssPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.css' );
728 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
729 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
732 if ( $allowUserJs ) {
733 $jsPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.js' );
734 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
735 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
738 $defaultPreferences['commoncssjs'] = [
741 'default' => $context->getLanguage()->pipeList( $linkTools ),
742 'label-message' => 'prefs-common-config',
743 'section' => 'rendering/skin',
749 * @param IContextSource $context
750 * @param array &$defaultPreferences
752 protected function filesPreferences( IContextSource
$context, &$defaultPreferences ) {
753 # # Files #####################################
754 $defaultPreferences['imagesize'] = [
756 'options' => $this->getImageSizes( $context ),
757 'label-message' => 'imagemaxsize',
758 'section' => 'rendering/files',
760 $defaultPreferences['thumbsize'] = [
762 'options' => $this->getThumbSizes( $context ),
763 'label-message' => 'thumbsize',
764 'section' => 'rendering/files',
770 * @param IContextSource $context
771 * @param array &$defaultPreferences
774 protected function datetimePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
775 # # Date and time #####################################
776 $dateOptions = $this->getDateOptions( $context );
777 if ( $dateOptions ) {
778 $defaultPreferences['date'] = [
780 'options' => $dateOptions,
781 'section' => 'rendering/dateformat',
786 $now = wfTimestampNow();
787 $lang = $context->getLanguage();
788 $nowlocal = Xml
::element( 'span', [ 'id' => 'wpLocalTime' ],
789 $lang->userTime( $now, $user ) );
790 $nowserver = $lang->userTime( $now, $user,
791 [ 'format' => false, 'timecorrection' => false ] ) .
792 Html
::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 +
(int)substr( $now, 10, 2 ) );
794 $defaultPreferences['nowserver'] = [
797 'label-message' => 'servertime',
798 'default' => $nowserver,
799 'section' => 'rendering/timeoffset',
802 $defaultPreferences['nowlocal'] = [
805 'label-message' => 'localtime',
806 'default' => $nowlocal,
807 'section' => 'rendering/timeoffset',
810 // Grab existing pref.
811 $tzOffset = $user->getOption( 'timecorrection' );
812 $tz = explode( '|', $tzOffset, 3 );
814 $tzOptions = $this->getTimezoneOptions( $context );
816 $tzSetting = $tzOffset;
817 if ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
818 !in_array( $tzOffset, HTMLFormField
::flattenOptions( $tzOptions ) )
820 // Timezone offset can vary with DST
822 $userTZ = new DateTimeZone( $tz[2] );
823 $minDiff = floor( $userTZ->getOffset( new DateTime( 'now' ) ) / 60 );
824 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
825 } catch ( Exception
$e ) {
826 // User has an invalid time zone set. Fall back to just using the offset
830 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
832 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) %
60 );
835 $defaultPreferences['timecorrection'] = [
836 'class' => \HTMLSelectOrOtherField
::class,
837 'label-message' => 'timezonelegend',
838 'options' => $tzOptions,
839 'default' => $tzSetting,
841 'section' => 'rendering/timeoffset',
842 'id' => 'wpTimeCorrection',
843 'filter' => TimezoneFilter
::class,
844 'placeholder-message' => 'timezone-useoffset-placeholder',
850 * @param MessageLocalizer $l10n
851 * @param array &$defaultPreferences
853 protected function renderingPreferences(
855 MessageLocalizer
$l10n,
858 # # Diffs ####################################
859 $defaultPreferences['diffonly'] = [
861 'section' => 'rendering/diffs',
862 'label-message' => 'tog-diffonly',
864 $defaultPreferences['norollbackdiff'] = [
866 'section' => 'rendering/diffs',
867 'label-message' => 'tog-norollbackdiff',
870 # # Page Rendering ##############################
871 if ( $this->options
->get( 'AllowUserCssPrefs' ) ) {
872 $defaultPreferences['underline'] = [
875 $l10n->msg( 'underline-never' )->text() => 0,
876 $l10n->msg( 'underline-always' )->text() => 1,
877 $l10n->msg( 'underline-default' )->text() => 2,
879 'label-message' => 'tog-underline',
880 'section' => 'rendering/advancedrendering',
884 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
885 $stubThresholdOptions = [ $l10n->msg( 'stub-threshold-disabled' )->text() => 0 ];
886 foreach ( $stubThresholdValues as $value ) {
887 $stubThresholdOptions[$l10n->msg( 'size-bytes', $value )->text()] = $value;
890 $defaultPreferences['stubthreshold'] = [
892 'section' => 'rendering/advancedrendering',
893 'options' => $stubThresholdOptions,
894 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
895 'label-raw' => $l10n->msg( 'stub-threshold' )->rawParams(
897 $l10n->msg( 'stub-threshold-sample-link' )->parse() .
901 $defaultPreferences['showhiddencats'] = [
903 'section' => 'rendering/advancedrendering',
904 'label-message' => 'tog-showhiddencats'
907 $defaultPreferences['numberheadings'] = [
909 'section' => 'rendering/advancedrendering',
910 'label-message' => 'tog-numberheadings',
913 if ( $user->isAllowed( 'rollback' ) ) {
914 $defaultPreferences['showrollbackconfirmation'] = [
916 'section' => 'rendering/advancedrendering',
917 'label-message' => 'tog-showrollbackconfirmation',
924 * @param MessageLocalizer $l10n
925 * @param array &$defaultPreferences
927 protected function editingPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
928 # # Editing #####################################
929 $defaultPreferences['editsectiononrightclick'] = [
931 'section' => 'editing/advancedediting',
932 'label-message' => 'tog-editsectiononrightclick',
934 $defaultPreferences['editondblclick'] = [
936 'section' => 'editing/advancedediting',
937 'label-message' => 'tog-editondblclick',
940 if ( $this->options
->get( 'AllowUserCssPrefs' ) ) {
941 $defaultPreferences['editfont'] = [
943 'section' => 'editing/editor',
944 'label-message' => 'editfont-style',
946 $l10n->msg( 'editfont-monospace' )->text() => 'monospace',
947 $l10n->msg( 'editfont-sansserif' )->text() => 'sans-serif',
948 $l10n->msg( 'editfont-serif' )->text() => 'serif',
953 if ( $user->isAllowed( 'minoredit' ) ) {
954 $defaultPreferences['minordefault'] = [
956 'section' => 'editing/editor',
957 'label-message' => 'tog-minordefault',
961 $defaultPreferences['forceeditsummary'] = [
963 'section' => 'editing/editor',
964 'label-message' => 'tog-forceeditsummary',
966 $defaultPreferences['useeditwarning'] = [
968 'section' => 'editing/editor',
969 'label-message' => 'tog-useeditwarning',
972 $defaultPreferences['previewonfirst'] = [
974 'section' => 'editing/preview',
975 'label-message' => 'tog-previewonfirst',
977 $defaultPreferences['previewontop'] = [
979 'section' => 'editing/preview',
980 'label-message' => 'tog-previewontop',
982 $defaultPreferences['uselivepreview'] = [
984 'section' => 'editing/preview',
985 'label-message' => 'tog-uselivepreview',
991 * @param MessageLocalizer $l10n
992 * @param array &$defaultPreferences
994 protected function rcPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
995 $rcMaxAge = $this->options
->get( 'RCMaxAge' );
996 # # RecentChanges #####################################
997 $defaultPreferences['rcdays'] = [
999 'label-message' => 'recentchangesdays',
1000 'section' => 'rc/displayrc',
1002 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
1003 'help' => $l10n->msg( 'recentchangesdays-max' )->numParams(
1004 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
1006 $defaultPreferences['rclimit'] = [
1010 'label-message' => 'recentchangescount',
1011 'help-message' => 'prefs-help-recentchangescount',
1012 'section' => 'rc/displayrc',
1013 'filter' => IntvalFilter
::class,
1015 $defaultPreferences['usenewrc'] = [
1017 'label-message' => 'tog-usenewrc',
1018 'section' => 'rc/advancedrc',
1020 $defaultPreferences['hideminor'] = [
1022 'label-message' => 'tog-hideminor',
1023 'section' => 'rc/changesrc',
1025 $defaultPreferences['rcfilters-rc-collapsed'] = [
1028 $defaultPreferences['rcfilters-wl-collapsed'] = [
1031 $defaultPreferences['rcfilters-saved-queries'] = [
1034 $defaultPreferences['rcfilters-wl-saved-queries'] = [
1037 // Override RCFilters preferences for RecentChanges 'limit'
1038 $defaultPreferences['rcfilters-limit'] = [
1041 $defaultPreferences['rcfilters-saved-queries-versionbackup'] = [
1044 $defaultPreferences['rcfilters-wl-saved-queries-versionbackup'] = [
1048 if ( $this->options
->get( 'RCWatchCategoryMembership' ) ) {
1049 $defaultPreferences['hidecategorization'] = [
1051 'label-message' => 'tog-hidecategorization',
1052 'section' => 'rc/changesrc',
1056 if ( $user->useRCPatrol() ) {
1057 $defaultPreferences['hidepatrolled'] = [
1059 'section' => 'rc/changesrc',
1060 'label-message' => 'tog-hidepatrolled',
1064 if ( $user->useNPPatrol() ) {
1065 $defaultPreferences['newpageshidepatrolled'] = [
1067 'section' => 'rc/changesrc',
1068 'label-message' => 'tog-newpageshidepatrolled',
1072 if ( $this->options
->get( 'RCShowWatchingUsers' ) ) {
1073 $defaultPreferences['shownumberswatching'] = [
1075 'section' => 'rc/advancedrc',
1076 'label-message' => 'tog-shownumberswatching',
1080 $defaultPreferences['rcenhancedfilters-disable'] = [
1082 'section' => 'rc/advancedrc',
1083 'label-message' => 'rcfilters-preference-label',
1084 'help-message' => 'rcfilters-preference-help',
1090 * @param IContextSource $context
1091 * @param array &$defaultPreferences
1093 protected function watchlistPreferences(
1094 User
$user, IContextSource
$context, &$defaultPreferences
1096 $watchlistdaysMax = ceil( $this->options
->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1098 # # Watchlist #####################################
1099 if ( $user->isAllowed( 'editmywatchlist' ) ) {
1100 $editWatchlistLinks = '';
1101 $editWatchlistModes = [
1102 'edit' => [ 'subpage' => false, 'flags' => [] ],
1103 'raw' => [ 'subpage' => 'raw', 'flags' => [] ],
1104 'clear' => [ 'subpage' => 'clear', 'flags' => [ 'destructive' ] ],
1106 foreach ( $editWatchlistModes as $mode => $options ) {
1107 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1108 $editWatchlistLinks .=
1109 new \OOUI\
ButtonWidget( [
1110 'href' => SpecialPage
::getTitleFor( 'EditWatchlist', $options['subpage'] )->getLinkURL(),
1111 'flags' => $options[ 'flags' ],
1112 'label' => new \OOUI\
HtmlSnippet(
1113 $context->msg( "prefs-editwatchlist-{$mode}" )->parse()
1118 $defaultPreferences['editwatchlist'] = [
1121 'default' => $editWatchlistLinks,
1122 'label-message' => 'prefs-editwatchlist-label',
1123 'section' => 'watchlist/editwatchlist',
1127 $defaultPreferences['watchlistdays'] = [
1130 'max' => $watchlistdaysMax,
1131 'section' => 'watchlist/displaywatchlist',
1132 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1133 $watchlistdaysMax )->escaped(),
1134 'label-message' => 'prefs-watchlist-days',
1136 $defaultPreferences['wllimit'] = [
1140 'label-message' => 'prefs-watchlist-edits',
1141 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1142 'section' => 'watchlist/displaywatchlist',
1143 'filter' => IntvalFilter
::class,
1145 $defaultPreferences['extendwatchlist'] = [
1147 'section' => 'watchlist/advancedwatchlist',
1148 'label-message' => 'tog-extendwatchlist',
1150 $defaultPreferences['watchlisthideminor'] = [
1152 'section' => 'watchlist/changeswatchlist',
1153 'label-message' => 'tog-watchlisthideminor',
1155 $defaultPreferences['watchlisthidebots'] = [
1157 'section' => 'watchlist/changeswatchlist',
1158 'label-message' => 'tog-watchlisthidebots',
1160 $defaultPreferences['watchlisthideown'] = [
1162 'section' => 'watchlist/changeswatchlist',
1163 'label-message' => 'tog-watchlisthideown',
1165 $defaultPreferences['watchlisthideanons'] = [
1167 'section' => 'watchlist/changeswatchlist',
1168 'label-message' => 'tog-watchlisthideanons',
1170 $defaultPreferences['watchlisthideliu'] = [
1172 'section' => 'watchlist/changeswatchlist',
1173 'label-message' => 'tog-watchlisthideliu',
1176 if ( !\SpecialWatchlist
::checkStructuredFilterUiEnabled( $user ) ) {
1177 $defaultPreferences['watchlistreloadautomatically'] = [
1179 'section' => 'watchlist/advancedwatchlist',
1180 'label-message' => 'tog-watchlistreloadautomatically',
1184 $defaultPreferences['watchlistunwatchlinks'] = [
1186 'section' => 'watchlist/advancedwatchlist',
1187 'label-message' => 'tog-watchlistunwatchlinks',
1190 if ( $this->options
->get( 'RCWatchCategoryMembership' ) ) {
1191 $defaultPreferences['watchlisthidecategorization'] = [
1193 'section' => 'watchlist/changeswatchlist',
1194 'label-message' => 'tog-watchlisthidecategorization',
1198 if ( $user->useRCPatrol() ) {
1199 $defaultPreferences['watchlisthidepatrolled'] = [
1201 'section' => 'watchlist/changeswatchlist',
1202 'label-message' => 'tog-watchlisthidepatrolled',
1207 'edit' => 'watchdefault',
1208 'move' => 'watchmoves',
1209 'delete' => 'watchdeletion'
1213 if ( $user->isAllowed( 'createpage' ) ||
$user->isAllowed( 'createtalk' ) ) {
1214 $watchTypes['read'] = 'watchcreations';
1217 if ( $user->isAllowed( 'rollback' ) ) {
1218 $watchTypes['rollback'] = 'watchrollback';
1221 if ( $user->isAllowed( 'upload' ) ) {
1222 $watchTypes['upload'] = 'watchuploads';
1225 foreach ( $watchTypes as $action => $pref ) {
1226 if ( $user->isAllowed( $action ) ) {
1228 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1229 // tog-watchrollback
1230 $defaultPreferences[$pref] = [
1232 'section' => 'watchlist/pageswatchlist',
1233 'label-message' => "tog-$pref",
1238 $defaultPreferences['watchlisttoken'] = [
1242 $tokenButton = new \OOUI\
ButtonWidget( [
1243 'href' => SpecialPage
::getTitleFor( 'ResetTokens' )->getLinkURL( [
1244 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
1246 'label' => $context->msg( 'prefs-watchlist-managetokens' )->text(),
1248 $defaultPreferences['watchlisttoken-info'] = [
1250 'section' => 'watchlist/tokenwatchlist',
1251 'label-message' => 'prefs-watchlist-token',
1252 'help-message' => 'prefs-help-tokenmanagement',
1254 'default' => (string)$tokenButton,
1257 $defaultPreferences['wlenhancedfilters-disable'] = [
1259 'section' => 'watchlist/advancedwatchlist',
1260 'label-message' => 'rcfilters-watchlist-preference-label',
1261 'help-message' => 'rcfilters-watchlist-preference-help',
1266 * @param array &$defaultPreferences
1268 protected function searchPreferences( &$defaultPreferences ) {
1269 foreach ( $this->nsInfo
->getValidNamespaces() as $n ) {
1270 $defaultPreferences['searchNs' . $n] = [
1277 * @param User $user The User object
1278 * @param IContextSource $context
1279 * @return array Text/links to display as key; $skinkey as value
1281 protected function generateSkinOptions( User
$user, IContextSource
$context ) {
1284 $mptitle = Title
::newMainPage();
1285 $previewtext = $context->msg( 'skin-preview' )->escaped();
1287 # Only show skins that aren't disabled in $wgSkipSkins
1288 $validSkinNames = Skin
::getAllowedSkins();
1289 $allInstalledSkins = Skin
::getSkinNames();
1291 // Display the installed skin the user has specifically requested via useskin=….
1292 $useSkin = $context->getRequest()->getRawVal( 'useskin' );
1293 if ( isset( $allInstalledSkins[$useSkin] )
1294 && $context->msg( "skinname-$useSkin" )->exists()
1296 $validSkinNames[$useSkin] = $useSkin;
1299 // Display the skin if the user has set it as a preference already before it was hidden.
1300 $currentUserSkin = $user->getOption( 'skin' );
1301 if ( isset( $allInstalledSkins[$currentUserSkin] )
1302 && $context->msg( "skinname-$currentUserSkin" )->exists()
1304 $validSkinNames[$currentUserSkin] = $currentUserSkin;
1307 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1308 $msg = $context->msg( "skinname-{$skinkey}" );
1309 if ( $msg->exists() ) {
1310 $skinname = htmlspecialchars( $msg->text() );
1314 $defaultSkin = $this->options
->get( 'DefaultSkin' );
1315 $allowUserCss = $this->options
->get( 'AllowUserCss' );
1316 $allowUserJs = $this->options
->get( 'AllowUserJs' );
1318 # Sort by the internal name, so that the ordering is the same for each display language,
1319 # especially if some skin names are translated to use a different alphabet and some are not.
1320 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1321 # Display the default first in the list by comparing it as lesser than any other.
1322 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1325 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1328 return strcasecmp( $a, $b );
1331 $foundDefault = false;
1332 foreach ( $validSkinNames as $skinkey => $sn ) {
1335 # Mark the default skin
1336 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1337 $linkTools[] = $context->msg( 'default' )->escaped();
1338 $foundDefault = true;
1341 # Create preview link
1342 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1343 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1345 # Create links to user CSS/JS pages
1346 if ( $allowUserCss ) {
1347 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1348 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
1349 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
1352 if ( $allowUserJs ) {
1353 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1354 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
1355 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
1358 $display = $sn . ' ' . $context->msg( 'parentheses' )
1359 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1361 $ret[$display] = $skinkey;
1364 if ( !$foundDefault ) {
1365 // If the default skin is not available, things are going to break horribly because the
1366 // default value for skin selector will not be a valid value. Let's just not show it then.
1374 * @param IContextSource $context
1377 protected function getDateOptions( IContextSource
$context ) {
1378 $lang = $context->getLanguage();
1379 $dateopts = $lang->getDatePreferences();
1384 if ( !in_array( 'default', $dateopts ) ) {
1385 $dateopts[] = 'default'; // Make sure default is always valid T21237
1388 // FIXME KLUGE: site default might not be valid for user language
1389 global $wgDefaultUserOptions;
1390 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1391 $wgDefaultUserOptions['date'] = 'default';
1394 $epoch = wfTimestampNow();
1395 foreach ( $dateopts as $key ) {
1396 if ( $key == 'default' ) {
1397 $formatted = $context->msg( 'datedefault' )->escaped();
1399 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1401 $ret[$formatted] = $key;
1408 * @param MessageLocalizer $l10n
1411 protected function getImageSizes( MessageLocalizer
$l10n ) {
1413 $pixels = $l10n->msg( 'unit-pixel' )->text();
1415 foreach ( $this->options
->get( 'ImageLimits' ) as $index => $limits ) {
1416 // Note: A left-to-right marker (U+200E) is inserted, see T144386
1417 $display = "{$limits[0]}\u{200E}×{$limits[1]}$pixels";
1418 $ret[$display] = $index;
1425 * @param MessageLocalizer $l10n
1428 protected function getThumbSizes( MessageLocalizer
$l10n ) {
1430 $pixels = $l10n->msg( 'unit-pixel' )->text();
1432 foreach ( $this->options
->get( 'ThumbLimits' ) as $index => $size ) {
1433 $display = $size . $pixels;
1434 $ret[$display] = $index;
1441 * @param string $signature
1442 * @param array $alldata
1443 * @param HTMLForm $form
1444 * @return bool|string
1446 protected function validateSignature( $signature, $alldata, HTMLForm
$form ) {
1447 $maxSigChars = $this->options
->get( 'MaxSigChars' );
1448 if ( mb_strlen( $signature ) > $maxSigChars ) {
1449 return Xml
::element( 'span', [ 'class' => 'error' ],
1450 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1451 } elseif ( isset( $alldata['fancysig'] ) &&
1452 $alldata['fancysig'] &&
1453 MediaWikiServices
::getInstance()->getParser()->validateSig( $signature ) === false
1455 return Xml
::element(
1457 [ 'class' => 'error' ],
1458 $form->msg( 'badsig' )->text()
1466 * @param string $signature
1467 * @param array $alldata
1468 * @param HTMLForm $form
1471 protected function cleanSignature( $signature, $alldata, HTMLForm
$form ) {
1472 $parser = MediaWikiServices
::getInstance()->getParser();
1473 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1474 $signature = $parser->cleanSig( $signature );
1476 // When no fancy sig used, make sure ~{3,5} get removed.
1477 $signature = Parser
::cleanSigInSig( $signature );
1485 * @param IContextSource $context
1486 * @param string $formClass
1487 * @param array $remove Array of items to remove
1490 public function getForm(
1492 IContextSource
$context,
1493 $formClass = PreferencesFormOOUI
::class,
1496 // We use ButtonWidgets in some of the getPreferences() functions
1497 $context->getOutput()->enableOOUI();
1499 $formDescriptor = $this->getFormDescriptor( $user, $context );
1500 if ( count( $remove ) ) {
1501 $removeKeys = array_flip( $remove );
1502 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1505 // Remove type=api preferences. They are not intended for rendering in the form.
1506 foreach ( $formDescriptor as $name => $info ) {
1507 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1508 unset( $formDescriptor[$name] );
1513 * @var HTMLForm $htmlForm
1515 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1517 // This allows users to opt-in to hidden skins. While this should be discouraged and is not
1518 // discoverable, this allows users to still use hidden skins while preventing new users from
1519 // adopting unsupported skins. If no useskin=… parameter was provided, it will not show up
1520 // in the resulting URL.
1521 $htmlForm->setAction( $context->getTitle()->getLocalURL( [
1522 'useskin' => $context->getRequest()->getRawVal( 'useskin' )
1525 $htmlForm->setModifiedUser( $user );
1526 $htmlForm->setId( 'mw-prefs-form' );
1527 $htmlForm->setAutocomplete( 'off' );
1528 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1529 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1530 $htmlForm->setSubmitTooltip( 'preferences-save' );
1531 $htmlForm->setSubmitID( 'prefcontrol' );
1532 $htmlForm->setSubmitCallback(
1533 function ( array $formData, HTMLForm
$form ) use ( $formDescriptor ) {
1534 return $this->submitForm( $formData, $form, $formDescriptor );
1542 * @param IContextSource $context
1545 protected function getTimezoneOptions( IContextSource
$context ) {
1548 $localTZoffset = $this->options
->get( 'LocalTZoffset' );
1549 $timeZoneList = $this->getTimeZoneList( $context->getLanguage() );
1551 $timestamp = MWTimestamp
::getLocalInstance();
1552 // Check that the LocalTZoffset is the same as the local time zone offset
1553 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1554 $timezoneName = $timestamp->getTimezone()->getName();
1555 // Localize timezone
1556 if ( isset( $timeZoneList[$timezoneName] ) ) {
1557 $timezoneName = $timeZoneList[$timezoneName]['name'];
1559 $server_tz_msg = $context->msg(
1560 'timezoneuseserverdefault',
1564 $tzstring = sprintf(
1566 floor( $localTZoffset / 60 ),
1567 abs( $localTZoffset ) %
60
1569 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1571 $opt[$server_tz_msg] = "System|$localTZoffset";
1572 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1573 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1575 foreach ( $timeZoneList as $timeZoneInfo ) {
1576 $region = $timeZoneInfo['region'];
1577 if ( !isset( $opt[$region] ) ) {
1580 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1586 * Handle the form submission if everything validated properly
1588 * @param array $formData
1589 * @param HTMLForm $form
1590 * @param array[] $formDescriptor
1591 * @return bool|Status|string
1593 protected function saveFormData( $formData, HTMLForm
$form, array $formDescriptor ) {
1594 /** @var \User $user */
1595 $user = $form->getModifiedUser();
1596 $hiddenPrefs = $this->options
->get( 'HiddenPrefs' );
1599 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1600 return Status
::newFatal( 'mypreferencesprotected' );
1604 $this->applyFilters( $formData, $formDescriptor, 'filterFromForm' );
1606 // Fortunately, the realname field is MUCH simpler
1607 // (not really "private", but still shouldn't be edited without permission)
1609 if ( !in_array( 'realname', $hiddenPrefs )
1610 && $user->isAllowed( 'editmyprivateinfo' )
1611 && array_key_exists( 'realname', $formData )
1613 $realName = $formData['realname'];
1614 $user->setRealName( $realName );
1617 if ( $user->isAllowed( 'editmyoptions' ) ) {
1618 $oldUserOptions = $user->getOptions();
1620 foreach ( $this->getSaveBlacklist() as $b ) {
1621 unset( $formData[$b] );
1624 # If users have saved a value for a preference which has subsequently been disabled
1625 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1626 # is subsequently re-enabled
1627 foreach ( $hiddenPrefs as $pref ) {
1628 # If the user has not set a non-default value here, the default will be returned
1629 # and subsequently discarded
1630 $formData[$pref] = $user->getOption( $pref, null, true );
1633 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1635 isset( $formData['rclimit'] ) &&
1636 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1638 $formData['rcfilters-limit'] = $formData['rclimit'];
1641 // Keep old preferences from interfering due to back-compat code, etc.
1642 $user->resetOptions( 'unused', $form->getContext() );
1644 foreach ( $formData as $key => $value ) {
1645 $user->setOption( $key, $value );
1649 'PreferencesFormPreSave',
1650 [ $formData, $form, $user, &$result, $oldUserOptions ]
1654 $user->saveSettings();
1660 * Applies filters to preferences either before or after form usage
1662 * @param array &$preferences
1663 * @param array $formDescriptor
1664 * @param string $verb Name of the filter method to call, either 'filterFromForm' or
1667 protected function applyFilters( array &$preferences, array $formDescriptor, $verb ) {
1668 foreach ( $formDescriptor as $preference => $desc ) {
1669 if ( !isset( $desc['filter'] ) ||
!isset( $preferences[$preference] ) ) {
1672 $filterDesc = $desc['filter'];
1673 if ( $filterDesc instanceof Filter
) {
1674 $filter = $filterDesc;
1675 } elseif ( class_exists( $filterDesc ) ) {
1676 $filter = new $filterDesc();
1677 } elseif ( is_callable( $filterDesc ) ) {
1678 $filter = $filterDesc();
1680 throw new UnexpectedValueException(
1681 "Unrecognized filter type for preference '$preference'"
1684 $preferences[$preference] = $filter->$verb( $preferences[$preference] );
1689 * Save the form data and reload the page
1691 * @param array $formData
1692 * @param HTMLForm $form
1693 * @param array $formDescriptor
1696 protected function submitForm( array $formData, HTMLForm
$form, array $formDescriptor ) {
1697 $res = $this->saveFormData( $formData, $form, $formDescriptor );
1699 if ( $res === true ) {
1700 $context = $form->getContext();
1703 if ( $res === 'eauth' ) {
1704 $urlOptions['eauth'] = 1;
1707 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1709 $url = $form->getTitle()->getFullURL( $urlOptions );
1711 // Set session data for the success message
1712 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1714 $context->getOutput()->redirect( $url );
1717 return ( $res === true ? Status
::newGood() : $res );
1721 * Get a list of all time zones
1722 * @param Language $language Language used for the localized names
1723 * @return array A list of all time zones. The system name of the time zone is used as key and
1724 * the value is an array which contains localized name, the timecorrection value used for
1725 * preferences and the region
1728 protected function getTimeZoneList( Language
$language ) {
1729 $identifiers = DateTimeZone
::listIdentifiers();
1730 // @phan-suppress-next-line PhanTypeComparisonFromArray See phan issue #3162
1731 if ( $identifiers === false ) {
1734 sort( $identifiers );
1737 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1738 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1739 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1740 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1741 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1742 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1743 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1744 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1745 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1746 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1748 asort( $tzRegions );
1752 $now = new DateTime();
1754 foreach ( $identifiers as $identifier ) {
1755 $parts = explode( '/', $identifier, 2 );
1757 // DateTimeZone::listIdentifiers() returns a number of
1758 // backwards-compatibility entries. This filters them out of the
1759 // list presented to the user.
1760 if ( count( $parts ) !== 2 ||
!array_key_exists( $parts[0], $tzRegions ) ) {
1765 $parts[0] = $tzRegions[$parts[0]];
1767 $dateTimeZone = new DateTimeZone( $identifier );
1768 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1770 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1771 $value = "ZoneInfo|$minDiff|$identifier";
1773 $timeZoneList[$identifier] = [
1775 'timecorrection' => $value,
1776 'region' => $parts[0],
1780 return $timeZoneList;