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 throw new MWException( "Global default '$globalDefault' is invalid for field $name" );
239 return $defaultPreferences;
243 * Pull option from a user account. Handles stuff like array-type preferences.
245 * @param string $name
247 * @param array $userOptions
248 * @return array|string
250 protected function getOptionFromUser( $name, $info, array $userOptions ) {
251 $val = $userOptions[$name] ??
null;
253 // Handling for multiselect preferences
254 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
255 ( isset( $info['class'] ) && $info['class'] == \HTMLMultiSelectField
::class ) ) {
256 $options = HTMLFormField
::flattenOptions( $info['options'] );
257 $prefix = $info['prefix'] ??
$name;
260 foreach ( $options as $value ) {
261 if ( $userOptions["$prefix$value"] ??
false ) {
267 // Handling for checkmatrix preferences
268 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
269 ( isset( $info['class'] ) && $info['class'] == \HTMLCheckMatrix
::class ) ) {
270 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
271 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
272 $prefix = $info['prefix'] ??
$name;
275 foreach ( $columns as $column ) {
276 foreach ( $rows as $row ) {
277 if ( $userOptions["$prefix$column-$row"] ??
false ) {
278 $val[] = "$column-$row";
288 * @todo Inject user Language instead of using context.
290 * @param IContextSource $context
291 * @param array &$defaultPreferences
292 * @param bool $canIPUseHTTPS Whether the user's IP is likely to be able to access the wiki
296 protected function profilePreferences(
297 User
$user, IContextSource
$context, &$defaultPreferences, $canIPUseHTTPS
299 // retrieving user name for GENDER and misc.
300 $userName = $user->getName();
302 # # User info #####################################
304 $defaultPreferences['username'] = [
306 'label-message' => [ 'username', $userName ],
307 'default' => $userName,
308 'section' => 'personal/info',
311 $lang = $context->getLanguage();
313 # Get groups to which the user belongs
314 $userEffectiveGroups = $user->getEffectiveGroups();
315 $userGroupMemberships = $user->getGroupMemberships();
316 $userGroups = $userMembers = $userTempGroups = $userTempMembers = [];
317 foreach ( $userEffectiveGroups as $ueg ) {
319 // Skip the default * group, seems useless here
323 $groupStringOrObject = $userGroupMemberships[$ueg] ??
$ueg;
325 $userG = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html' );
326 $userM = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html',
329 // Store expiring groups separately, so we can place them before non-expiring
330 // groups in the list. This is to avoid the ambiguity of something like
331 // "administrator, bureaucrat (until X date)" -- users might wonder whether the
332 // expiry date applies to both groups, or just the last one
333 if ( $groupStringOrObject instanceof UserGroupMembership
&&
334 $groupStringOrObject->getExpiry()
336 $userTempGroups[] = $userG;
337 $userTempMembers[] = $userM;
339 $userGroups[] = $userG;
340 $userMembers[] = $userM;
344 sort( $userMembers );
345 sort( $userTempGroups );
346 sort( $userTempMembers );
347 $userGroups = array_merge( $userTempGroups, $userGroups );
348 $userMembers = array_merge( $userTempMembers, $userMembers );
350 $defaultPreferences['usergroups'] = [
352 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
353 count( $userGroups ) )->params( $userName )->parse(),
354 'default' => $context->msg( 'prefs-memberingroups-type' )
355 ->rawParams( $lang->commaList( $userGroups ), $lang->commaList( $userMembers ) )
358 'section' => 'personal/info',
361 $contribTitle = SpecialPage
::getTitleFor( "Contributions", $userName );
362 $formattedEditCount = $lang->formatNum( $user->getEditCount() );
363 $editCount = $this->linkRenderer
->makeLink( $contribTitle, $formattedEditCount );
365 $defaultPreferences['editcount'] = [
368 'label-message' => 'prefs-edits',
369 'default' => $editCount,
370 'section' => 'personal/info',
373 if ( $user->getRegistration() ) {
374 $displayUser = $context->getUser();
375 $userRegistration = $user->getRegistration();
376 $defaultPreferences['registrationdate'] = [
378 'label-message' => 'prefs-registration',
379 'default' => $context->msg(
380 'prefs-registration-date-time',
381 $lang->userTimeAndDate( $userRegistration, $displayUser ),
382 $lang->userDate( $userRegistration, $displayUser ),
383 $lang->userTime( $userRegistration, $displayUser )
385 'section' => 'personal/info',
389 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
390 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
392 // Actually changeable stuff
393 $defaultPreferences['realname'] = [
394 // (not really "private", but still shouldn't be edited without permission)
395 'type' => $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'realname' )
397 'default' => $user->getRealName(),
398 'section' => 'personal/info',
399 'label-message' => 'yourrealname',
400 'help-message' => 'prefs-help-realname',
403 if ( $canEditPrivateInfo && $this->authManager
->allowsAuthenticationDataChange(
404 new PasswordAuthenticationRequest(), false )->isGood()
406 $defaultPreferences['password'] = [
409 'default' => (string)new \OOUI\
ButtonWidget( [
410 'href' => SpecialPage
::getTitleFor( 'ChangePassword' )->getLinkURL( [
411 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
413 'label' => $context->msg( 'prefs-resetpass' )->text(),
415 'label-message' => 'yourpassword',
416 'section' => 'personal/info',
419 // Only show prefershttps if secure login is turned on
420 if ( $this->options
->get( 'SecureLogin' ) && $canIPUseHTTPS ) {
421 $defaultPreferences['prefershttps'] = [
423 'label-message' => 'tog-prefershttps',
424 'help-message' => 'prefs-help-prefershttps',
425 'section' => 'personal/info'
429 $languages = Language
::fetchLanguageNames( null, 'mwfile' );
430 $languageCode = $this->options
->get( 'LanguageCode' );
431 if ( !array_key_exists( $languageCode, $languages ) ) {
432 $languages[$languageCode] = $languageCode;
433 // Sort the array again
438 foreach ( $languages as $code => $name ) {
439 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
440 $options[$display] = $code;
442 $defaultPreferences['language'] = [
444 'section' => 'personal/i18n',
445 'options' => $options,
446 'label-message' => 'yourlanguage',
449 $defaultPreferences['gender'] = [
451 'section' => 'personal/i18n',
453 $context->msg( 'parentheses' )
454 ->params( $context->msg( 'gender-unknown' )->plain() )
455 ->escaped() => 'unknown',
456 $context->msg( 'gender-female' )->escaped() => 'female',
457 $context->msg( 'gender-male' )->escaped() => 'male',
459 'label-message' => 'yourgender',
460 'help-message' => 'prefs-help-gender',
463 // see if there are multiple language variants to choose from
464 if ( !$this->options
->get( 'DisableLangConversion' ) ) {
465 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
466 if ( $langCode == $this->contLang
->getCode() ) {
467 if ( !$this->contLang
->hasVariants() ) {
471 $variants = $this->contLang
->getVariants();
473 foreach ( $variants as $v ) {
474 $v = str_replace( '_', '-', strtolower( $v ) );
475 $variantArray[$v] = $lang->getVariantname( $v, false );
479 foreach ( $variantArray as $code => $name ) {
480 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
481 $options[$display] = $code;
484 $defaultPreferences['variant'] = [
485 'label-message' => 'yourvariant',
487 'options' => $options,
488 'section' => 'personal/i18n',
489 'help-message' => 'prefs-help-variant',
492 $defaultPreferences["variant-$langCode"] = [
499 // show a preview of the old signature first
500 $oldsigWikiText = MediaWikiServices
::getInstance()->getParser()->preSaveTransform(
502 $context->getTitle(),
504 ParserOptions
::newFromContext( $context )
506 $oldsigHTML = Parser
::stripOuterParagraph(
507 $context->getOutput()->parseAsContent( $oldsigWikiText )
509 $defaultPreferences['oldsig'] = [
512 'label-message' => 'tog-oldsig',
513 'default' => $oldsigHTML,
514 'section' => 'personal/signature',
516 $defaultPreferences['nickname'] = [
517 'type' => $this->authManager
->allowsPropertyChange( 'nickname' ) ?
'text' : 'info',
518 'maxlength' => $this->options
->get( 'MaxSigChars' ),
519 'label-message' => 'yournick',
520 'validation-callback' => function ( $signature, $alldata, HTMLForm
$form ) {
521 return $this->validateSignature( $signature, $alldata, $form );
523 'section' => 'personal/signature',
524 'filter-callback' => function ( $signature, array $alldata, HTMLForm
$form ) {
525 return $this->cleanSignature( $signature, $alldata, $form );
528 $defaultPreferences['fancysig'] = [
530 'label-message' => 'tog-fancysig',
531 // show general help about signature at the bottom of the section
532 'help-message' => 'prefs-help-signature',
533 'section' => 'personal/signature'
538 if ( $this->options
->get( 'EnableEmail' ) ) {
539 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( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
620 $defaultPreferences['disablemail'] = [
621 'id' => 'wpAllowEmail',
624 'section' => 'personal/email',
625 'label-message' => 'allowemail',
626 'disabled' => $disableEmailPrefs,
629 $defaultPreferences['email-allow-new-users'] = [
630 'id' => 'wpAllowEmailFromNewUsers',
632 'section' => 'personal/email',
633 'label-message' => 'email-allow-new-users-label',
634 'disabled' => $disableEmailPrefs,
637 $defaultPreferences['ccmeonemails'] = [
639 'section' => 'personal/email',
640 'label-message' => 'tog-ccmeonemails',
641 'disabled' => $disableEmailPrefs,
644 if ( $this->options
->get( 'EnableUserEmailBlacklist' ) ) {
645 $defaultPreferences['email-blacklist'] = [
646 'type' => 'usersmultiselect',
647 'label-message' => 'email-blacklist-label',
648 'section' => 'personal/email',
649 'disabled' => $disableEmailPrefs,
650 'filter' => MultiUsernameFilter
::class,
655 if ( $this->options
->get( 'EnotifWatchlist' ) ) {
656 $defaultPreferences['enotifwatchlistpages'] = [
658 'section' => 'personal/email',
659 'label-message' => 'tog-enotifwatchlistpages',
660 'disabled' => $disableEmailPrefs,
663 if ( $this->options
->get( 'EnotifUserTalk' ) ) {
664 $defaultPreferences['enotifusertalkpages'] = [
666 'section' => 'personal/email',
667 'label-message' => 'tog-enotifusertalkpages',
668 'disabled' => $disableEmailPrefs,
671 if ( $this->options
->get( 'EnotifUserTalk' ) ||
672 $this->options
->get( 'EnotifWatchlist' ) ) {
673 if ( $this->options
->get( 'EnotifMinorEdits' ) ) {
674 $defaultPreferences['enotifminoredits'] = [
676 'section' => 'personal/email',
677 'label-message' => 'tog-enotifminoredits',
678 'disabled' => $disableEmailPrefs,
682 if ( $this->options
->get( 'EnotifRevealEditorAddress' ) ) {
683 $defaultPreferences['enotifrevealaddr'] = [
685 'section' => 'personal/email',
686 'label-message' => 'tog-enotifrevealaddr',
687 'disabled' => $disableEmailPrefs,
696 * @param IContextSource $context
697 * @param array &$defaultPreferences
700 protected function skinPreferences( User
$user, IContextSource
$context, &$defaultPreferences ) {
701 # # Skin #####################################
703 // Skin selector, if there is at least one valid skin
704 $skinOptions = $this->generateSkinOptions( $user, $context );
705 if ( $skinOptions ) {
706 $defaultPreferences['skin'] = [
708 'options' => $skinOptions,
709 'section' => 'rendering/skin',
713 $allowUserCss = $this->options
->get( 'AllowUserCss' );
714 $allowUserJs = $this->options
->get( 'AllowUserJs' );
715 # Create links to user CSS/JS pages for all skins
716 # This code is basically copied from generateSkinOptions(). It'd
717 # be nice to somehow merge this back in there to avoid redundancy.
718 if ( $allowUserCss ||
$allowUserJs ) {
720 $userName = $user->getName();
722 if ( $allowUserCss ) {
723 $cssPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.css' );
724 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
725 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
728 if ( $allowUserJs ) {
729 $jsPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.js' );
730 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
731 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
734 $defaultPreferences['commoncssjs'] = [
737 'default' => $context->getLanguage()->pipeList( $linkTools ),
738 'label-message' => 'prefs-common-config',
739 'section' => 'rendering/skin',
745 * @param IContextSource $context
746 * @param array &$defaultPreferences
748 protected function filesPreferences( IContextSource
$context, &$defaultPreferences ) {
749 # # Files #####################################
750 $defaultPreferences['imagesize'] = [
752 'options' => $this->getImageSizes( $context ),
753 'label-message' => 'imagemaxsize',
754 'section' => 'rendering/files',
756 $defaultPreferences['thumbsize'] = [
758 'options' => $this->getThumbSizes( $context ),
759 'label-message' => 'thumbsize',
760 'section' => 'rendering/files',
766 * @param IContextSource $context
767 * @param array &$defaultPreferences
770 protected function datetimePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
771 # # Date and time #####################################
772 $dateOptions = $this->getDateOptions( $context );
773 if ( $dateOptions ) {
774 $defaultPreferences['date'] = [
776 'options' => $dateOptions,
777 'section' => 'rendering/dateformat',
782 $now = wfTimestampNow();
783 $lang = $context->getLanguage();
784 $nowlocal = Xml
::element( 'span', [ 'id' => 'wpLocalTime' ],
785 $lang->userTime( $now, $user ) );
786 $nowserver = $lang->userTime( $now, $user,
787 [ 'format' => false, 'timecorrection' => false ] ) .
788 Html
::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 +
(int)substr( $now, 10, 2 ) );
790 $defaultPreferences['nowserver'] = [
793 'label-message' => 'servertime',
794 'default' => $nowserver,
795 'section' => 'rendering/timeoffset',
798 $defaultPreferences['nowlocal'] = [
801 'label-message' => 'localtime',
802 'default' => $nowlocal,
803 'section' => 'rendering/timeoffset',
806 // Grab existing pref.
807 $tzOffset = $user->getOption( 'timecorrection' );
808 $tz = explode( '|', $tzOffset, 3 );
810 $tzOptions = $this->getTimezoneOptions( $context );
812 $tzSetting = $tzOffset;
813 if ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
814 !in_array( $tzOffset, HTMLFormField
::flattenOptions( $tzOptions ) )
816 // Timezone offset can vary with DST
818 $userTZ = new DateTimeZone( $tz[2] );
819 $minDiff = floor( $userTZ->getOffset( new DateTime( 'now' ) ) / 60 );
820 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
821 } catch ( Exception
$e ) {
822 // User has an invalid time zone set. Fall back to just using the offset
826 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
828 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) %
60 );
831 $defaultPreferences['timecorrection'] = [
832 'class' => \HTMLSelectOrOtherField
::class,
833 'label-message' => 'timezonelegend',
834 'options' => $tzOptions,
835 'default' => $tzSetting,
837 'section' => 'rendering/timeoffset',
838 'id' => 'wpTimeCorrection',
839 'filter' => TimezoneFilter
::class,
840 'placeholder-message' => 'timezone-useoffset-placeholder',
846 * @param MessageLocalizer $l10n
847 * @param array &$defaultPreferences
849 protected function renderingPreferences(
851 MessageLocalizer
$l10n,
854 # # Diffs ####################################
855 $defaultPreferences['diffonly'] = [
857 'section' => 'rendering/diffs',
858 'label-message' => 'tog-diffonly',
860 $defaultPreferences['norollbackdiff'] = [
862 'section' => 'rendering/diffs',
863 'label-message' => 'tog-norollbackdiff',
866 # # Page Rendering ##############################
867 if ( $this->options
->get( 'AllowUserCssPrefs' ) ) {
868 $defaultPreferences['underline'] = [
871 $l10n->msg( 'underline-never' )->text() => 0,
872 $l10n->msg( 'underline-always' )->text() => 1,
873 $l10n->msg( 'underline-default' )->text() => 2,
875 'label-message' => 'tog-underline',
876 'section' => 'rendering/advancedrendering',
880 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
881 $stubThresholdOptions = [ $l10n->msg( 'stub-threshold-disabled' )->text() => 0 ];
882 foreach ( $stubThresholdValues as $value ) {
883 $stubThresholdOptions[$l10n->msg( 'size-bytes', $value )->text()] = $value;
886 $defaultPreferences['stubthreshold'] = [
888 'section' => 'rendering/advancedrendering',
889 'options' => $stubThresholdOptions,
890 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
891 'label-raw' => $l10n->msg( 'stub-threshold' )->rawParams(
893 $l10n->msg( 'stub-threshold-sample-link' )->parse() .
897 $defaultPreferences['showhiddencats'] = [
899 'section' => 'rendering/advancedrendering',
900 'label-message' => 'tog-showhiddencats'
903 $defaultPreferences['numberheadings'] = [
905 'section' => 'rendering/advancedrendering',
906 'label-message' => 'tog-numberheadings',
909 if ( $user->isAllowed( 'rollback' ) ) {
910 $defaultPreferences['showrollbackconfirmation'] = [
912 'section' => 'rendering/advancedrendering',
913 'label-message' => 'tog-showrollbackconfirmation',
920 * @param MessageLocalizer $l10n
921 * @param array &$defaultPreferences
923 protected function editingPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
924 # # Editing #####################################
925 $defaultPreferences['editsectiononrightclick'] = [
927 'section' => 'editing/advancedediting',
928 'label-message' => 'tog-editsectiononrightclick',
930 $defaultPreferences['editondblclick'] = [
932 'section' => 'editing/advancedediting',
933 'label-message' => 'tog-editondblclick',
936 if ( $this->options
->get( 'AllowUserCssPrefs' ) ) {
937 $defaultPreferences['editfont'] = [
939 'section' => 'editing/editor',
940 'label-message' => 'editfont-style',
942 $l10n->msg( 'editfont-monospace' )->text() => 'monospace',
943 $l10n->msg( 'editfont-sansserif' )->text() => 'sans-serif',
944 $l10n->msg( 'editfont-serif' )->text() => 'serif',
949 if ( $user->isAllowed( 'minoredit' ) ) {
950 $defaultPreferences['minordefault'] = [
952 'section' => 'editing/editor',
953 'label-message' => 'tog-minordefault',
957 $defaultPreferences['forceeditsummary'] = [
959 'section' => 'editing/editor',
960 'label-message' => 'tog-forceeditsummary',
962 $defaultPreferences['useeditwarning'] = [
964 'section' => 'editing/editor',
965 'label-message' => 'tog-useeditwarning',
968 $defaultPreferences['previewonfirst'] = [
970 'section' => 'editing/preview',
971 'label-message' => 'tog-previewonfirst',
973 $defaultPreferences['previewontop'] = [
975 'section' => 'editing/preview',
976 'label-message' => 'tog-previewontop',
978 $defaultPreferences['uselivepreview'] = [
980 'section' => 'editing/preview',
981 'label-message' => 'tog-uselivepreview',
987 * @param MessageLocalizer $l10n
988 * @param array &$defaultPreferences
990 protected function rcPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
991 $rcMaxAge = $this->options
->get( 'RCMaxAge' );
992 # # RecentChanges #####################################
993 $defaultPreferences['rcdays'] = [
995 'label-message' => 'recentchangesdays',
996 'section' => 'rc/displayrc',
998 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
999 'help' => $l10n->msg( 'recentchangesdays-max' )->numParams(
1000 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
1002 $defaultPreferences['rclimit'] = [
1006 'label-message' => 'recentchangescount',
1007 'help-message' => 'prefs-help-recentchangescount',
1008 'section' => 'rc/displayrc',
1009 'filter' => IntvalFilter
::class,
1011 $defaultPreferences['usenewrc'] = [
1013 'label-message' => 'tog-usenewrc',
1014 'section' => 'rc/advancedrc',
1016 $defaultPreferences['hideminor'] = [
1018 'label-message' => 'tog-hideminor',
1019 'section' => 'rc/changesrc',
1021 $defaultPreferences['rcfilters-rc-collapsed'] = [
1024 $defaultPreferences['rcfilters-wl-collapsed'] = [
1027 $defaultPreferences['rcfilters-saved-queries'] = [
1030 $defaultPreferences['rcfilters-wl-saved-queries'] = [
1033 // Override RCFilters preferences for RecentChanges 'limit'
1034 $defaultPreferences['rcfilters-limit'] = [
1037 $defaultPreferences['rcfilters-saved-queries-versionbackup'] = [
1040 $defaultPreferences['rcfilters-wl-saved-queries-versionbackup'] = [
1044 if ( $this->options
->get( 'RCWatchCategoryMembership' ) ) {
1045 $defaultPreferences['hidecategorization'] = [
1047 'label-message' => 'tog-hidecategorization',
1048 'section' => 'rc/changesrc',
1052 if ( $user->useRCPatrol() ) {
1053 $defaultPreferences['hidepatrolled'] = [
1055 'section' => 'rc/changesrc',
1056 'label-message' => 'tog-hidepatrolled',
1060 if ( $user->useNPPatrol() ) {
1061 $defaultPreferences['newpageshidepatrolled'] = [
1063 'section' => 'rc/changesrc',
1064 'label-message' => 'tog-newpageshidepatrolled',
1068 if ( $this->options
->get( 'RCShowWatchingUsers' ) ) {
1069 $defaultPreferences['shownumberswatching'] = [
1071 'section' => 'rc/advancedrc',
1072 'label-message' => 'tog-shownumberswatching',
1076 $defaultPreferences['rcenhancedfilters-disable'] = [
1078 'section' => 'rc/advancedrc',
1079 'label-message' => 'rcfilters-preference-label',
1080 'help-message' => 'rcfilters-preference-help',
1086 * @param IContextSource $context
1087 * @param array &$defaultPreferences
1089 protected function watchlistPreferences(
1090 User
$user, IContextSource
$context, &$defaultPreferences
1092 $watchlistdaysMax = ceil( $this->options
->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1094 # # Watchlist #####################################
1095 if ( $user->isAllowed( 'editmywatchlist' ) ) {
1096 $editWatchlistLinks = '';
1097 $editWatchlistModes = [
1098 'edit' => [ 'subpage' => false, 'flags' => [] ],
1099 'raw' => [ 'subpage' => 'raw', 'flags' => [] ],
1100 'clear' => [ 'subpage' => 'clear', 'flags' => [ 'destructive' ] ],
1102 foreach ( $editWatchlistModes as $mode => $options ) {
1103 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1104 $editWatchlistLinks .=
1105 new \OOUI\
ButtonWidget( [
1106 'href' => SpecialPage
::getTitleFor( 'EditWatchlist', $options['subpage'] )->getLinkURL(),
1107 'flags' => $options[ 'flags' ],
1108 'label' => new \OOUI\
HtmlSnippet(
1109 $context->msg( "prefs-editwatchlist-{$mode}" )->parse()
1114 $defaultPreferences['editwatchlist'] = [
1117 'default' => $editWatchlistLinks,
1118 'label-message' => 'prefs-editwatchlist-label',
1119 'section' => 'watchlist/editwatchlist',
1123 $defaultPreferences['watchlistdays'] = [
1126 'max' => $watchlistdaysMax,
1127 'section' => 'watchlist/displaywatchlist',
1128 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1129 $watchlistdaysMax )->escaped(),
1130 'label-message' => 'prefs-watchlist-days',
1132 $defaultPreferences['wllimit'] = [
1136 'label-message' => 'prefs-watchlist-edits',
1137 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1138 'section' => 'watchlist/displaywatchlist',
1139 'filter' => IntvalFilter
::class,
1141 $defaultPreferences['extendwatchlist'] = [
1143 'section' => 'watchlist/advancedwatchlist',
1144 'label-message' => 'tog-extendwatchlist',
1146 $defaultPreferences['watchlisthideminor'] = [
1148 'section' => 'watchlist/changeswatchlist',
1149 'label-message' => 'tog-watchlisthideminor',
1151 $defaultPreferences['watchlisthidebots'] = [
1153 'section' => 'watchlist/changeswatchlist',
1154 'label-message' => 'tog-watchlisthidebots',
1156 $defaultPreferences['watchlisthideown'] = [
1158 'section' => 'watchlist/changeswatchlist',
1159 'label-message' => 'tog-watchlisthideown',
1161 $defaultPreferences['watchlisthideanons'] = [
1163 'section' => 'watchlist/changeswatchlist',
1164 'label-message' => 'tog-watchlisthideanons',
1166 $defaultPreferences['watchlisthideliu'] = [
1168 'section' => 'watchlist/changeswatchlist',
1169 'label-message' => 'tog-watchlisthideliu',
1172 if ( !\SpecialWatchlist
::checkStructuredFilterUiEnabled( $user ) ) {
1173 $defaultPreferences['watchlistreloadautomatically'] = [
1175 'section' => 'watchlist/advancedwatchlist',
1176 'label-message' => 'tog-watchlistreloadautomatically',
1180 $defaultPreferences['watchlistunwatchlinks'] = [
1182 'section' => 'watchlist/advancedwatchlist',
1183 'label-message' => 'tog-watchlistunwatchlinks',
1186 if ( $this->options
->get( 'RCWatchCategoryMembership' ) ) {
1187 $defaultPreferences['watchlisthidecategorization'] = [
1189 'section' => 'watchlist/changeswatchlist',
1190 'label-message' => 'tog-watchlisthidecategorization',
1194 if ( $user->useRCPatrol() ) {
1195 $defaultPreferences['watchlisthidepatrolled'] = [
1197 'section' => 'watchlist/changeswatchlist',
1198 'label-message' => 'tog-watchlisthidepatrolled',
1203 'edit' => 'watchdefault',
1204 'move' => 'watchmoves',
1205 'delete' => 'watchdeletion'
1209 if ( $user->isAllowed( 'createpage' ) ||
$user->isAllowed( 'createtalk' ) ) {
1210 $watchTypes['read'] = 'watchcreations';
1213 if ( $user->isAllowed( 'rollback' ) ) {
1214 $watchTypes['rollback'] = 'watchrollback';
1217 if ( $user->isAllowed( 'upload' ) ) {
1218 $watchTypes['upload'] = 'watchuploads';
1221 foreach ( $watchTypes as $action => $pref ) {
1222 if ( $user->isAllowed( $action ) ) {
1224 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1225 // tog-watchrollback
1226 $defaultPreferences[$pref] = [
1228 'section' => 'watchlist/pageswatchlist',
1229 'label-message' => "tog-$pref",
1234 $defaultPreferences['watchlisttoken'] = [
1238 $tokenButton = new \OOUI\
ButtonWidget( [
1239 'href' => SpecialPage
::getTitleFor( 'ResetTokens' )->getLinkURL( [
1240 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
1242 'label' => $context->msg( 'prefs-watchlist-managetokens' )->text(),
1244 $defaultPreferences['watchlisttoken-info'] = [
1246 'section' => 'watchlist/tokenwatchlist',
1247 'label-message' => 'prefs-watchlist-token',
1248 'help-message' => 'prefs-help-tokenmanagement',
1250 'default' => (string)$tokenButton,
1253 $defaultPreferences['wlenhancedfilters-disable'] = [
1255 'section' => 'watchlist/advancedwatchlist',
1256 'label-message' => 'rcfilters-watchlist-preference-label',
1257 'help-message' => 'rcfilters-watchlist-preference-help',
1262 * @param array &$defaultPreferences
1264 protected function searchPreferences( &$defaultPreferences ) {
1265 foreach ( $this->nsInfo
->getValidNamespaces() as $n ) {
1266 $defaultPreferences['searchNs' . $n] = [
1273 * @param User $user The User object
1274 * @param IContextSource $context
1275 * @return array Text/links to display as key; $skinkey as value
1277 protected function generateSkinOptions( User
$user, IContextSource
$context ) {
1280 $mptitle = Title
::newMainPage();
1281 $previewtext = $context->msg( 'skin-preview' )->escaped();
1283 # Only show skins that aren't disabled in $wgSkipSkins
1284 $validSkinNames = Skin
::getAllowedSkins();
1285 $allInstalledSkins = Skin
::getSkinNames();
1287 // Display the installed skin the user has specifically requested via useskin=….
1288 $useSkin = $context->getRequest()->getRawVal( 'useskin' );
1289 if ( isset( $allInstalledSkins[$useSkin] )
1290 && $context->msg( "skinname-$useSkin" )->exists()
1292 $validSkinNames[$useSkin] = $useSkin;
1295 // Display the skin if the user has set it as a preference already before it was hidden.
1296 $currentUserSkin = $user->getOption( 'skin' );
1297 if ( isset( $allInstalledSkins[$currentUserSkin] )
1298 && $context->msg( "skinname-$currentUserSkin" )->exists()
1300 $validSkinNames[$currentUserSkin] = $currentUserSkin;
1303 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1304 $msg = $context->msg( "skinname-{$skinkey}" );
1305 if ( $msg->exists() ) {
1306 $skinname = htmlspecialchars( $msg->text() );
1310 $defaultSkin = $this->options
->get( 'DefaultSkin' );
1311 $allowUserCss = $this->options
->get( 'AllowUserCss' );
1312 $allowUserJs = $this->options
->get( 'AllowUserJs' );
1314 # Sort by the internal name, so that the ordering is the same for each display language,
1315 # especially if some skin names are translated to use a different alphabet and some are not.
1316 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1317 # Display the default first in the list by comparing it as lesser than any other.
1318 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1321 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1324 return strcasecmp( $a, $b );
1327 $foundDefault = false;
1328 foreach ( $validSkinNames as $skinkey => $sn ) {
1331 # Mark the default skin
1332 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1333 $linkTools[] = $context->msg( 'default' )->escaped();
1334 $foundDefault = true;
1337 # Create preview link
1338 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1339 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1341 # Create links to user CSS/JS pages
1342 if ( $allowUserCss ) {
1343 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1344 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
1345 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
1348 if ( $allowUserJs ) {
1349 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1350 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
1351 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
1354 $display = $sn . ' ' . $context->msg( 'parentheses' )
1355 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1357 $ret[$display] = $skinkey;
1360 if ( !$foundDefault ) {
1361 // If the default skin is not available, things are going to break horribly because the
1362 // default value for skin selector will not be a valid value. Let's just not show it then.
1370 * @param IContextSource $context
1373 protected function getDateOptions( IContextSource
$context ) {
1374 $lang = $context->getLanguage();
1375 $dateopts = $lang->getDatePreferences();
1380 if ( !in_array( 'default', $dateopts ) ) {
1381 $dateopts[] = 'default'; // Make sure default is always valid T21237
1384 // FIXME KLUGE: site default might not be valid for user language
1385 global $wgDefaultUserOptions;
1386 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1387 $wgDefaultUserOptions['date'] = 'default';
1390 $epoch = wfTimestampNow();
1391 foreach ( $dateopts as $key ) {
1392 if ( $key == 'default' ) {
1393 $formatted = $context->msg( 'datedefault' )->escaped();
1395 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1397 $ret[$formatted] = $key;
1404 * @param MessageLocalizer $l10n
1407 protected function getImageSizes( MessageLocalizer
$l10n ) {
1409 $pixels = $l10n->msg( 'unit-pixel' )->text();
1411 foreach ( $this->options
->get( 'ImageLimits' ) as $index => $limits ) {
1412 // Note: A left-to-right marker (U+200E) is inserted, see T144386
1413 $display = "{$limits[0]}\u{200E}×{$limits[1]}$pixels";
1414 $ret[$display] = $index;
1421 * @param MessageLocalizer $l10n
1424 protected function getThumbSizes( MessageLocalizer
$l10n ) {
1426 $pixels = $l10n->msg( 'unit-pixel' )->text();
1428 foreach ( $this->options
->get( 'ThumbLimits' ) as $index => $size ) {
1429 $display = $size . $pixels;
1430 $ret[$display] = $index;
1437 * @param string $signature
1438 * @param array $alldata
1439 * @param HTMLForm $form
1440 * @return bool|string
1442 protected function validateSignature( $signature, $alldata, HTMLForm
$form ) {
1443 $maxSigChars = $this->options
->get( 'MaxSigChars' );
1444 if ( mb_strlen( $signature ) > $maxSigChars ) {
1445 return Xml
::element( 'span', [ 'class' => 'error' ],
1446 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1447 } elseif ( isset( $alldata['fancysig'] ) &&
1448 $alldata['fancysig'] &&
1449 MediaWikiServices
::getInstance()->getParser()->validateSig( $signature ) === false
1451 return Xml
::element(
1453 [ 'class' => 'error' ],
1454 $form->msg( 'badsig' )->text()
1462 * @param string $signature
1463 * @param array $alldata
1464 * @param HTMLForm $form
1467 protected function cleanSignature( $signature, $alldata, HTMLForm
$form ) {
1468 $parser = MediaWikiServices
::getInstance()->getParser();
1469 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1470 $signature = $parser->cleanSig( $signature );
1472 // When no fancy sig used, make sure ~{3,5} get removed.
1473 $signature = Parser
::cleanSigInSig( $signature );
1481 * @param IContextSource $context
1482 * @param string $formClass
1483 * @param array $remove Array of items to remove
1486 public function getForm(
1488 IContextSource
$context,
1489 $formClass = PreferencesFormOOUI
::class,
1492 // We use ButtonWidgets in some of the getPreferences() functions
1493 $context->getOutput()->enableOOUI();
1495 $formDescriptor = $this->getFormDescriptor( $user, $context );
1496 if ( count( $remove ) ) {
1497 $removeKeys = array_flip( $remove );
1498 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1501 // Remove type=api preferences. They are not intended for rendering in the form.
1502 foreach ( $formDescriptor as $name => $info ) {
1503 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1504 unset( $formDescriptor[$name] );
1509 * @var HTMLForm $htmlForm
1511 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1513 // This allows users to opt-in to hidden skins. While this should be discouraged and is not
1514 // discoverable, this allows users to still use hidden skins while preventing new users from
1515 // adopting unsupported skins. If no useskin=… parameter was provided, it will not show up
1516 // in the resulting URL.
1517 $htmlForm->setAction( $context->getTitle()->getLocalURL( [
1518 'useskin' => $context->getRequest()->getRawVal( 'useskin' )
1521 $htmlForm->setModifiedUser( $user );
1522 $htmlForm->setId( 'mw-prefs-form' );
1523 $htmlForm->setAutocomplete( 'off' );
1524 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1525 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1526 $htmlForm->setSubmitTooltip( 'preferences-save' );
1527 $htmlForm->setSubmitID( 'prefcontrol' );
1528 $htmlForm->setSubmitCallback(
1529 function ( array $formData, HTMLForm
$form ) use ( $formDescriptor ) {
1530 return $this->submitForm( $formData, $form, $formDescriptor );
1538 * @param IContextSource $context
1541 protected function getTimezoneOptions( IContextSource
$context ) {
1544 $localTZoffset = $this->options
->get( 'LocalTZoffset' );
1545 $timeZoneList = $this->getTimeZoneList( $context->getLanguage() );
1547 $timestamp = MWTimestamp
::getLocalInstance();
1548 // Check that the LocalTZoffset is the same as the local time zone offset
1549 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1550 $timezoneName = $timestamp->getTimezone()->getName();
1551 // Localize timezone
1552 if ( isset( $timeZoneList[$timezoneName] ) ) {
1553 $timezoneName = $timeZoneList[$timezoneName]['name'];
1555 $server_tz_msg = $context->msg(
1556 'timezoneuseserverdefault',
1560 $tzstring = sprintf(
1562 floor( $localTZoffset / 60 ),
1563 abs( $localTZoffset ) %
60
1565 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1567 $opt[$server_tz_msg] = "System|$localTZoffset";
1568 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1569 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1571 foreach ( $timeZoneList as $timeZoneInfo ) {
1572 $region = $timeZoneInfo['region'];
1573 if ( !isset( $opt[$region] ) ) {
1576 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1582 * Handle the form submission if everything validated properly
1584 * @param array $formData
1585 * @param HTMLForm $form
1586 * @param array[] $formDescriptor
1587 * @return bool|Status|string
1589 protected function saveFormData( $formData, HTMLForm
$form, array $formDescriptor ) {
1590 /** @var \User $user */
1591 $user = $form->getModifiedUser();
1592 $hiddenPrefs = $this->options
->get( 'HiddenPrefs' );
1595 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1596 return Status
::newFatal( 'mypreferencesprotected' );
1600 $this->applyFilters( $formData, $formDescriptor, 'filterFromForm' );
1602 // Fortunately, the realname field is MUCH simpler
1603 // (not really "private", but still shouldn't be edited without permission)
1605 if ( !in_array( 'realname', $hiddenPrefs )
1606 && $user->isAllowed( 'editmyprivateinfo' )
1607 && array_key_exists( 'realname', $formData )
1609 $realName = $formData['realname'];
1610 $user->setRealName( $realName );
1613 if ( $user->isAllowed( 'editmyoptions' ) ) {
1614 $oldUserOptions = $user->getOptions();
1616 foreach ( $this->getSaveBlacklist() as $b ) {
1617 unset( $formData[$b] );
1620 # If users have saved a value for a preference which has subsequently been disabled
1621 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1622 # is subsequently re-enabled
1623 foreach ( $hiddenPrefs as $pref ) {
1624 # If the user has not set a non-default value here, the default will be returned
1625 # and subsequently discarded
1626 $formData[$pref] = $user->getOption( $pref, null, true );
1629 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1631 isset( $formData['rclimit'] ) &&
1632 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1634 $formData['rcfilters-limit'] = $formData['rclimit'];
1637 // Keep old preferences from interfering due to back-compat code, etc.
1638 $user->resetOptions( 'unused', $form->getContext() );
1640 foreach ( $formData as $key => $value ) {
1641 $user->setOption( $key, $value );
1645 'PreferencesFormPreSave',
1646 [ $formData, $form, $user, &$result, $oldUserOptions ]
1650 $user->saveSettings();
1656 * Applies filters to preferences either before or after form usage
1658 * @param array &$preferences
1659 * @param array $formDescriptor
1660 * @param string $verb Name of the filter method to call, either 'filterFromForm' or
1663 protected function applyFilters( array &$preferences, array $formDescriptor, $verb ) {
1664 foreach ( $formDescriptor as $preference => $desc ) {
1665 if ( !isset( $desc['filter'] ) ||
!isset( $preferences[$preference] ) ) {
1668 $filterDesc = $desc['filter'];
1669 if ( $filterDesc instanceof Filter
) {
1670 $filter = $filterDesc;
1671 } elseif ( class_exists( $filterDesc ) ) {
1672 $filter = new $filterDesc();
1673 } elseif ( is_callable( $filterDesc ) ) {
1674 $filter = $filterDesc();
1676 throw new UnexpectedValueException(
1677 "Unrecognized filter type for preference '$preference'"
1680 $preferences[$preference] = $filter->$verb( $preferences[$preference] );
1685 * Save the form data and reload the page
1687 * @param array $formData
1688 * @param HTMLForm $form
1689 * @param array $formDescriptor
1692 protected function submitForm( array $formData, HTMLForm
$form, array $formDescriptor ) {
1693 $res = $this->saveFormData( $formData, $form, $formDescriptor );
1695 if ( $res === true ) {
1696 $context = $form->getContext();
1699 if ( $res === 'eauth' ) {
1700 $urlOptions['eauth'] = 1;
1703 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1705 $url = $form->getTitle()->getFullURL( $urlOptions );
1707 // Set session data for the success message
1708 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1710 $context->getOutput()->redirect( $url );
1713 return ( $res === true ? Status
::newGood() : $res );
1717 * Get a list of all time zones
1718 * @param Language $language Language used for the localized names
1719 * @return array A list of all time zones. The system name of the time zone is used as key and
1720 * the value is an array which contains localized name, the timecorrection value used for
1721 * preferences and the region
1724 protected function getTimeZoneList( Language
$language ) {
1725 $identifiers = DateTimeZone
::listIdentifiers();
1726 if ( $identifiers === false ) {
1729 sort( $identifiers );
1732 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1733 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1734 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1735 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1736 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1737 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1738 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1739 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1740 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1741 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1743 asort( $tzRegions );
1747 $now = new DateTime();
1749 foreach ( $identifiers as $identifier ) {
1750 $parts = explode( '/', $identifier, 2 );
1752 // DateTimeZone::listIdentifiers() returns a number of
1753 // backwards-compatibility entries. This filters them out of the
1754 // list presented to the user.
1755 if ( count( $parts ) !== 2 ||
!array_key_exists( $parts[0], $tzRegions ) ) {
1760 $parts[0] = $tzRegions[$parts[0]];
1762 $dateTimeZone = new DateTimeZone( $identifier );
1763 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1765 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1766 $value = "ZoneInfo|$minDiff|$identifier";
1768 $timeZoneList[$identifier] = [
1770 'timecorrection' => $value,
1771 'region' => $parts[0],
1775 return $timeZoneList;