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 array|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 // Stuff from Language::getExtraUserToggles()
500 // FIXME is this dead code? $extraUserToggles doesn't seem to be defined for any language
501 $toggles = $this->contLang
->getExtraUserToggles();
503 foreach ( $toggles as $toggle ) {
504 $defaultPreferences[$toggle] = [
506 'section' => 'personal/i18n',
507 'label-message' => "tog-$toggle",
511 // show a preview of the old signature first
512 $oldsigWikiText = MediaWikiServices
::getInstance()->getParser()->preSaveTransform(
514 $context->getTitle(),
516 ParserOptions
::newFromContext( $context )
518 $oldsigHTML = Parser
::stripOuterParagraph(
519 $context->getOutput()->parseAsContent( $oldsigWikiText )
521 $defaultPreferences['oldsig'] = [
524 'label-message' => 'tog-oldsig',
525 'default' => $oldsigHTML,
526 'section' => 'personal/signature',
528 $defaultPreferences['nickname'] = [
529 'type' => $this->authManager
->allowsPropertyChange( 'nickname' ) ?
'text' : 'info',
530 'maxlength' => $this->options
->get( 'MaxSigChars' ),
531 'label-message' => 'yournick',
532 'validation-callback' => function ( $signature, $alldata, HTMLForm
$form ) {
533 return $this->validateSignature( $signature, $alldata, $form );
535 'section' => 'personal/signature',
536 'filter-callback' => function ( $signature, array $alldata, HTMLForm
$form ) {
537 return $this->cleanSignature( $signature, $alldata, $form );
540 $defaultPreferences['fancysig'] = [
542 'label-message' => 'tog-fancysig',
543 // show general help about signature at the bottom of the section
544 'help-message' => 'prefs-help-signature',
545 'section' => 'personal/signature'
550 if ( $this->options
->get( 'EnableEmail' ) ) {
551 if ( $canViewPrivateInfo ) {
552 $helpMessages[] = $this->options
->get( 'EmailConfirmToEdit' )
553 ?
'prefs-help-email-required'
554 : 'prefs-help-email';
556 if ( $this->options
->get( 'EnableUserEmail' ) ) {
557 // additional messages when users can send email to each other
558 $helpMessages[] = 'prefs-help-email-others';
561 $emailAddress = $user->getEmail() ?
htmlspecialchars( $user->getEmail() ) : '';
562 if ( $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'emailaddress' ) ) {
563 $button = new \OOUI\
ButtonWidget( [
564 'href' => SpecialPage
::getTitleFor( 'ChangeEmail' )->getLinkURL( [
565 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
568 $context->msg( $user->getEmail() ?
'prefs-changeemail' : 'prefs-setemail' )->text(),
571 $emailAddress .= $emailAddress == '' ?
$button : ( '<br />' . $button );
574 $defaultPreferences['emailaddress'] = [
577 'default' => $emailAddress,
578 'label-message' => 'youremail',
579 'section' => 'personal/email',
580 'help-messages' => $helpMessages,
581 # 'cssclass' chosen below
585 $disableEmailPrefs = false;
587 if ( $this->options
->get( 'EmailAuthentication' ) ) {
588 $emailauthenticationclass = 'mw-email-not-authenticated';
589 if ( $user->getEmail() ) {
590 if ( $user->getEmailAuthenticationTimestamp() ) {
591 // date and time are separate parameters to facilitate localisation.
592 // $time is kept for backward compat reasons.
593 // 'emailauthenticated' is also used in SpecialConfirmemail.php
594 $displayUser = $context->getUser();
595 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
596 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
597 $d = $lang->userDate( $emailTimestamp, $displayUser );
598 $t = $lang->userTime( $emailTimestamp, $displayUser );
599 $emailauthenticated = $context->msg( 'emailauthenticated',
600 $time, $d, $t )->parse() . '<br />';
601 $disableEmailPrefs = false;
602 $emailauthenticationclass = 'mw-email-authenticated';
604 $disableEmailPrefs = true;
605 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
606 new \OOUI\
ButtonWidget( [
607 'href' => SpecialPage
::getTitleFor( 'Confirmemail' )->getLinkURL(),
608 'label' => $context->msg( 'emailconfirmlink' )->text(),
610 $emailauthenticationclass = "mw-email-not-authenticated";
613 $disableEmailPrefs = true;
614 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
615 $emailauthenticationclass = 'mw-email-none';
618 if ( $canViewPrivateInfo ) {
619 $defaultPreferences['emailauthentication'] = [
622 'section' => 'personal/email',
623 'label-message' => 'prefs-emailconfirm-label',
624 'default' => $emailauthenticated,
625 # Apply the same CSS class used on the input to the message:
626 'cssclass' => $emailauthenticationclass,
631 if ( $this->options
->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
632 $defaultPreferences['disablemail'] = [
633 'id' => 'wpAllowEmail',
636 'section' => 'personal/email',
637 'label-message' => 'allowemail',
638 'disabled' => $disableEmailPrefs,
641 $defaultPreferences['email-allow-new-users'] = [
642 'id' => 'wpAllowEmailFromNewUsers',
644 'section' => 'personal/email',
645 'label-message' => 'email-allow-new-users-label',
646 'disabled' => $disableEmailPrefs,
649 $defaultPreferences['ccmeonemails'] = [
651 'section' => 'personal/email',
652 'label-message' => 'tog-ccmeonemails',
653 'disabled' => $disableEmailPrefs,
656 if ( $this->options
->get( 'EnableUserEmailBlacklist' ) ) {
657 $defaultPreferences['email-blacklist'] = [
658 'type' => 'usersmultiselect',
659 'label-message' => 'email-blacklist-label',
660 'section' => 'personal/email',
661 'disabled' => $disableEmailPrefs,
662 'filter' => MultiUsernameFilter
::class,
667 if ( $this->options
->get( 'EnotifWatchlist' ) ) {
668 $defaultPreferences['enotifwatchlistpages'] = [
670 'section' => 'personal/email',
671 'label-message' => 'tog-enotifwatchlistpages',
672 'disabled' => $disableEmailPrefs,
675 if ( $this->options
->get( 'EnotifUserTalk' ) ) {
676 $defaultPreferences['enotifusertalkpages'] = [
678 'section' => 'personal/email',
679 'label-message' => 'tog-enotifusertalkpages',
680 'disabled' => $disableEmailPrefs,
683 if ( $this->options
->get( 'EnotifUserTalk' ) ||
684 $this->options
->get( 'EnotifWatchlist' ) ) {
685 if ( $this->options
->get( 'EnotifMinorEdits' ) ) {
686 $defaultPreferences['enotifminoredits'] = [
688 'section' => 'personal/email',
689 'label-message' => 'tog-enotifminoredits',
690 'disabled' => $disableEmailPrefs,
694 if ( $this->options
->get( 'EnotifRevealEditorAddress' ) ) {
695 $defaultPreferences['enotifrevealaddr'] = [
697 'section' => 'personal/email',
698 'label-message' => 'tog-enotifrevealaddr',
699 'disabled' => $disableEmailPrefs,
708 * @param IContextSource $context
709 * @param array &$defaultPreferences
712 protected function skinPreferences( User
$user, IContextSource
$context, &$defaultPreferences ) {
713 # # Skin #####################################
715 // Skin selector, if there is at least one valid skin
716 $skinOptions = $this->generateSkinOptions( $user, $context );
717 if ( $skinOptions ) {
718 $defaultPreferences['skin'] = [
720 'options' => $skinOptions,
721 'section' => 'rendering/skin',
725 $allowUserCss = $this->options
->get( 'AllowUserCss' );
726 $allowUserJs = $this->options
->get( 'AllowUserJs' );
727 # Create links to user CSS/JS pages for all skins
728 # This code is basically copied from generateSkinOptions(). It'd
729 # be nice to somehow merge this back in there to avoid redundancy.
730 if ( $allowUserCss ||
$allowUserJs ) {
732 $userName = $user->getName();
734 if ( $allowUserCss ) {
735 $cssPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.css' );
736 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
737 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
740 if ( $allowUserJs ) {
741 $jsPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.js' );
742 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
743 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
746 $defaultPreferences['commoncssjs'] = [
749 'default' => $context->getLanguage()->pipeList( $linkTools ),
750 'label-message' => 'prefs-common-config',
751 'section' => 'rendering/skin',
757 * @param IContextSource $context
758 * @param array &$defaultPreferences
760 protected function filesPreferences( IContextSource
$context, &$defaultPreferences ) {
761 # # Files #####################################
762 $defaultPreferences['imagesize'] = [
764 'options' => $this->getImageSizes( $context ),
765 'label-message' => 'imagemaxsize',
766 'section' => 'rendering/files',
768 $defaultPreferences['thumbsize'] = [
770 'options' => $this->getThumbSizes( $context ),
771 'label-message' => 'thumbsize',
772 'section' => 'rendering/files',
778 * @param IContextSource $context
779 * @param array &$defaultPreferences
782 protected function datetimePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
783 # # Date and time #####################################
784 $dateOptions = $this->getDateOptions( $context );
785 if ( $dateOptions ) {
786 $defaultPreferences['date'] = [
788 'options' => $dateOptions,
789 'section' => 'rendering/dateformat',
794 $now = wfTimestampNow();
795 $lang = $context->getLanguage();
796 $nowlocal = Xml
::element( 'span', [ 'id' => 'wpLocalTime' ],
797 $lang->userTime( $now, $user ) );
798 $nowserver = $lang->userTime( $now, $user,
799 [ 'format' => false, 'timecorrection' => false ] ) .
800 Html
::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 +
(int)substr( $now, 10, 2 ) );
802 $defaultPreferences['nowserver'] = [
805 'label-message' => 'servertime',
806 'default' => $nowserver,
807 'section' => 'rendering/timeoffset',
810 $defaultPreferences['nowlocal'] = [
813 'label-message' => 'localtime',
814 'default' => $nowlocal,
815 'section' => 'rendering/timeoffset',
818 // Grab existing pref.
819 $tzOffset = $user->getOption( 'timecorrection' );
820 $tz = explode( '|', $tzOffset, 3 );
822 $tzOptions = $this->getTimezoneOptions( $context );
824 $tzSetting = $tzOffset;
825 if ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
826 !in_array( $tzOffset, HTMLFormField
::flattenOptions( $tzOptions ) )
828 // Timezone offset can vary with DST
830 $userTZ = new DateTimeZone( $tz[2] );
831 $minDiff = floor( $userTZ->getOffset( new DateTime( 'now' ) ) / 60 );
832 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
833 } catch ( Exception
$e ) {
834 // User has an invalid time zone set. Fall back to just using the offset
838 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
840 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) %
60 );
843 $defaultPreferences['timecorrection'] = [
844 'class' => \HTMLSelectOrOtherField
::class,
845 'label-message' => 'timezonelegend',
846 'options' => $tzOptions,
847 'default' => $tzSetting,
849 'section' => 'rendering/timeoffset',
850 'id' => 'wpTimeCorrection',
851 'filter' => TimezoneFilter
::class,
852 'placeholder-message' => 'timezone-useoffset-placeholder',
858 * @param MessageLocalizer $l10n
859 * @param array &$defaultPreferences
861 protected function renderingPreferences(
863 MessageLocalizer
$l10n,
866 # # Diffs ####################################
867 $defaultPreferences['diffonly'] = [
869 'section' => 'rendering/diffs',
870 'label-message' => 'tog-diffonly',
872 $defaultPreferences['norollbackdiff'] = [
874 'section' => 'rendering/diffs',
875 'label-message' => 'tog-norollbackdiff',
878 # # Page Rendering ##############################
879 if ( $this->options
->get( 'AllowUserCssPrefs' ) ) {
880 $defaultPreferences['underline'] = [
883 $l10n->msg( 'underline-never' )->text() => 0,
884 $l10n->msg( 'underline-always' )->text() => 1,
885 $l10n->msg( 'underline-default' )->text() => 2,
887 'label-message' => 'tog-underline',
888 'section' => 'rendering/advancedrendering',
892 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
893 $stubThresholdOptions = [ $l10n->msg( 'stub-threshold-disabled' )->text() => 0 ];
894 foreach ( $stubThresholdValues as $value ) {
895 $stubThresholdOptions[$l10n->msg( 'size-bytes', $value )->text()] = $value;
898 $defaultPreferences['stubthreshold'] = [
900 'section' => 'rendering/advancedrendering',
901 'options' => $stubThresholdOptions,
902 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
903 'label-raw' => $l10n->msg( 'stub-threshold' )->rawParams(
905 $l10n->msg( 'stub-threshold-sample-link' )->parse() .
909 $defaultPreferences['showhiddencats'] = [
911 'section' => 'rendering/advancedrendering',
912 'label-message' => 'tog-showhiddencats'
915 $defaultPreferences['numberheadings'] = [
917 'section' => 'rendering/advancedrendering',
918 'label-message' => 'tog-numberheadings',
921 if ( $user->isAllowed( 'rollback' ) ) {
922 $defaultPreferences['showrollbackconfirmation'] = [
924 'section' => 'rendering/advancedrendering',
925 'label-message' => 'tog-showrollbackconfirmation',
932 * @param MessageLocalizer $l10n
933 * @param array &$defaultPreferences
935 protected function editingPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
936 # # Editing #####################################
937 $defaultPreferences['editsectiononrightclick'] = [
939 'section' => 'editing/advancedediting',
940 'label-message' => 'tog-editsectiononrightclick',
942 $defaultPreferences['editondblclick'] = [
944 'section' => 'editing/advancedediting',
945 'label-message' => 'tog-editondblclick',
948 if ( $this->options
->get( 'AllowUserCssPrefs' ) ) {
949 $defaultPreferences['editfont'] = [
951 'section' => 'editing/editor',
952 'label-message' => 'editfont-style',
954 $l10n->msg( 'editfont-monospace' )->text() => 'monospace',
955 $l10n->msg( 'editfont-sansserif' )->text() => 'sans-serif',
956 $l10n->msg( 'editfont-serif' )->text() => 'serif',
961 if ( $user->isAllowed( 'minoredit' ) ) {
962 $defaultPreferences['minordefault'] = [
964 'section' => 'editing/editor',
965 'label-message' => 'tog-minordefault',
969 $defaultPreferences['forceeditsummary'] = [
971 'section' => 'editing/editor',
972 'label-message' => 'tog-forceeditsummary',
974 $defaultPreferences['useeditwarning'] = [
976 'section' => 'editing/editor',
977 'label-message' => 'tog-useeditwarning',
980 $defaultPreferences['previewonfirst'] = [
982 'section' => 'editing/preview',
983 'label-message' => 'tog-previewonfirst',
985 $defaultPreferences['previewontop'] = [
987 'section' => 'editing/preview',
988 'label-message' => 'tog-previewontop',
990 $defaultPreferences['uselivepreview'] = [
992 'section' => 'editing/preview',
993 'label-message' => 'tog-uselivepreview',
999 * @param MessageLocalizer $l10n
1000 * @param array &$defaultPreferences
1002 protected function rcPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
1003 $rcMaxAge = $this->options
->get( 'RCMaxAge' );
1004 # # RecentChanges #####################################
1005 $defaultPreferences['rcdays'] = [
1007 'label-message' => 'recentchangesdays',
1008 'section' => 'rc/displayrc',
1010 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
1011 'help' => $l10n->msg( 'recentchangesdays-max' )->numParams(
1012 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
1014 $defaultPreferences['rclimit'] = [
1018 'label-message' => 'recentchangescount',
1019 'help-message' => 'prefs-help-recentchangescount',
1020 'section' => 'rc/displayrc',
1021 'filter' => IntvalFilter
::class,
1023 $defaultPreferences['usenewrc'] = [
1025 'label-message' => 'tog-usenewrc',
1026 'section' => 'rc/advancedrc',
1028 $defaultPreferences['hideminor'] = [
1030 'label-message' => 'tog-hideminor',
1031 'section' => 'rc/changesrc',
1033 $defaultPreferences['rcfilters-rc-collapsed'] = [
1036 $defaultPreferences['rcfilters-wl-collapsed'] = [
1039 $defaultPreferences['rcfilters-saved-queries'] = [
1042 $defaultPreferences['rcfilters-wl-saved-queries'] = [
1045 // Override RCFilters preferences for RecentChanges 'limit'
1046 $defaultPreferences['rcfilters-limit'] = [
1049 $defaultPreferences['rcfilters-saved-queries-versionbackup'] = [
1052 $defaultPreferences['rcfilters-wl-saved-queries-versionbackup'] = [
1056 if ( $this->options
->get( 'RCWatchCategoryMembership' ) ) {
1057 $defaultPreferences['hidecategorization'] = [
1059 'label-message' => 'tog-hidecategorization',
1060 'section' => 'rc/changesrc',
1064 if ( $user->useRCPatrol() ) {
1065 $defaultPreferences['hidepatrolled'] = [
1067 'section' => 'rc/changesrc',
1068 'label-message' => 'tog-hidepatrolled',
1072 if ( $user->useNPPatrol() ) {
1073 $defaultPreferences['newpageshidepatrolled'] = [
1075 'section' => 'rc/changesrc',
1076 'label-message' => 'tog-newpageshidepatrolled',
1080 if ( $this->options
->get( 'RCShowWatchingUsers' ) ) {
1081 $defaultPreferences['shownumberswatching'] = [
1083 'section' => 'rc/advancedrc',
1084 'label-message' => 'tog-shownumberswatching',
1088 $defaultPreferences['rcenhancedfilters-disable'] = [
1090 'section' => 'rc/advancedrc',
1091 'label-message' => 'rcfilters-preference-label',
1092 'help-message' => 'rcfilters-preference-help',
1098 * @param IContextSource $context
1099 * @param array &$defaultPreferences
1101 protected function watchlistPreferences(
1102 User
$user, IContextSource
$context, &$defaultPreferences
1104 $watchlistdaysMax = ceil( $this->options
->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1106 # # Watchlist #####################################
1107 if ( $user->isAllowed( 'editmywatchlist' ) ) {
1108 $editWatchlistLinks = '';
1109 $editWatchlistModes = [
1110 'edit' => [ 'subpage' => false, 'flags' => [] ],
1111 'raw' => [ 'subpage' => 'raw', 'flags' => [] ],
1112 'clear' => [ 'subpage' => 'clear', 'flags' => [ 'destructive' ] ],
1114 foreach ( $editWatchlistModes as $mode => $options ) {
1115 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1116 $editWatchlistLinks .=
1117 new \OOUI\
ButtonWidget( [
1118 'href' => SpecialPage
::getTitleFor( 'EditWatchlist', $options['subpage'] )->getLinkURL(),
1119 'flags' => $options[ 'flags' ],
1120 'label' => new \OOUI\
HtmlSnippet(
1121 $context->msg( "prefs-editwatchlist-{$mode}" )->parse()
1126 $defaultPreferences['editwatchlist'] = [
1129 'default' => $editWatchlistLinks,
1130 'label-message' => 'prefs-editwatchlist-label',
1131 'section' => 'watchlist/editwatchlist',
1135 $defaultPreferences['watchlistdays'] = [
1138 'max' => $watchlistdaysMax,
1139 'section' => 'watchlist/displaywatchlist',
1140 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1141 $watchlistdaysMax )->escaped(),
1142 'label-message' => 'prefs-watchlist-days',
1144 $defaultPreferences['wllimit'] = [
1148 'label-message' => 'prefs-watchlist-edits',
1149 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1150 'section' => 'watchlist/displaywatchlist',
1151 'filter' => IntvalFilter
::class,
1153 $defaultPreferences['extendwatchlist'] = [
1155 'section' => 'watchlist/advancedwatchlist',
1156 'label-message' => 'tog-extendwatchlist',
1158 $defaultPreferences['watchlisthideminor'] = [
1160 'section' => 'watchlist/changeswatchlist',
1161 'label-message' => 'tog-watchlisthideminor',
1163 $defaultPreferences['watchlisthidebots'] = [
1165 'section' => 'watchlist/changeswatchlist',
1166 'label-message' => 'tog-watchlisthidebots',
1168 $defaultPreferences['watchlisthideown'] = [
1170 'section' => 'watchlist/changeswatchlist',
1171 'label-message' => 'tog-watchlisthideown',
1173 $defaultPreferences['watchlisthideanons'] = [
1175 'section' => 'watchlist/changeswatchlist',
1176 'label-message' => 'tog-watchlisthideanons',
1178 $defaultPreferences['watchlisthideliu'] = [
1180 'section' => 'watchlist/changeswatchlist',
1181 'label-message' => 'tog-watchlisthideliu',
1184 if ( !\SpecialWatchlist
::checkStructuredFilterUiEnabled( $user ) ) {
1185 $defaultPreferences['watchlistreloadautomatically'] = [
1187 'section' => 'watchlist/advancedwatchlist',
1188 'label-message' => 'tog-watchlistreloadautomatically',
1192 $defaultPreferences['watchlistunwatchlinks'] = [
1194 'section' => 'watchlist/advancedwatchlist',
1195 'label-message' => 'tog-watchlistunwatchlinks',
1198 if ( $this->options
->get( 'RCWatchCategoryMembership' ) ) {
1199 $defaultPreferences['watchlisthidecategorization'] = [
1201 'section' => 'watchlist/changeswatchlist',
1202 'label-message' => 'tog-watchlisthidecategorization',
1206 if ( $user->useRCPatrol() ) {
1207 $defaultPreferences['watchlisthidepatrolled'] = [
1209 'section' => 'watchlist/changeswatchlist',
1210 'label-message' => 'tog-watchlisthidepatrolled',
1215 'edit' => 'watchdefault',
1216 'move' => 'watchmoves',
1217 'delete' => 'watchdeletion'
1221 if ( $user->isAllowed( 'createpage' ) ||
$user->isAllowed( 'createtalk' ) ) {
1222 $watchTypes['read'] = 'watchcreations';
1225 if ( $user->isAllowed( 'rollback' ) ) {
1226 $watchTypes['rollback'] = 'watchrollback';
1229 if ( $user->isAllowed( 'upload' ) ) {
1230 $watchTypes['upload'] = 'watchuploads';
1233 foreach ( $watchTypes as $action => $pref ) {
1234 if ( $user->isAllowed( $action ) ) {
1236 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1237 // tog-watchrollback
1238 $defaultPreferences[$pref] = [
1240 'section' => 'watchlist/pageswatchlist',
1241 'label-message' => "tog-$pref",
1246 $defaultPreferences['watchlisttoken'] = [
1250 $tokenButton = new \OOUI\
ButtonWidget( [
1251 'href' => SpecialPage
::getTitleFor( 'ResetTokens' )->getLinkURL( [
1252 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
1254 'label' => $context->msg( 'prefs-watchlist-managetokens' )->text(),
1256 $defaultPreferences['watchlisttoken-info'] = [
1258 'section' => 'watchlist/tokenwatchlist',
1259 'label-message' => 'prefs-watchlist-token',
1260 'help-message' => 'prefs-help-tokenmanagement',
1262 'default' => (string)$tokenButton,
1265 $defaultPreferences['wlenhancedfilters-disable'] = [
1267 'section' => 'watchlist/advancedwatchlist',
1268 'label-message' => 'rcfilters-watchlist-preference-label',
1269 'help-message' => 'rcfilters-watchlist-preference-help',
1274 * @param array &$defaultPreferences
1276 protected function searchPreferences( &$defaultPreferences ) {
1277 foreach ( $this->nsInfo
->getValidNamespaces() as $n ) {
1278 $defaultPreferences['searchNs' . $n] = [
1285 * @param User $user The User object
1286 * @param IContextSource $context
1287 * @return array Text/links to display as key; $skinkey as value
1289 protected function generateSkinOptions( User
$user, IContextSource
$context ) {
1292 $mptitle = Title
::newMainPage();
1293 $previewtext = $context->msg( 'skin-preview' )->escaped();
1295 # Only show skins that aren't disabled in $wgSkipSkins
1296 $validSkinNames = Skin
::getAllowedSkins();
1297 $allInstalledSkins = Skin
::getSkinNames();
1299 // Display the installed skin the user has specifically requested via useskin=….
1300 $useSkin = $context->getRequest()->getRawVal( 'useskin' );
1301 if ( isset( $allInstalledSkins[$useSkin] )
1302 && $context->msg( "skinname-$useSkin" )->exists()
1304 $validSkinNames[$useSkin] = $useSkin;
1307 // Display the skin if the user has set it as a preference already before it was hidden.
1308 $currentUserSkin = $user->getOption( 'skin' );
1309 if ( isset( $allInstalledSkins[$currentUserSkin] )
1310 && $context->msg( "skinname-$useSkin" )->exists()
1312 $validSkinNames[$currentUserSkin] = $currentUserSkin;
1315 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1316 $msg = $context->msg( "skinname-{$skinkey}" );
1317 if ( $msg->exists() ) {
1318 $skinname = htmlspecialchars( $msg->text() );
1322 $defaultSkin = $this->options
->get( 'DefaultSkin' );
1323 $allowUserCss = $this->options
->get( 'AllowUserCss' );
1324 $allowUserJs = $this->options
->get( 'AllowUserJs' );
1326 # Sort by the internal name, so that the ordering is the same for each display language,
1327 # especially if some skin names are translated to use a different alphabet and some are not.
1328 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1329 # Display the default first in the list by comparing it as lesser than any other.
1330 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1333 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1336 return strcasecmp( $a, $b );
1339 $foundDefault = false;
1340 foreach ( $validSkinNames as $skinkey => $sn ) {
1343 # Mark the default skin
1344 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1345 $linkTools[] = $context->msg( 'default' )->escaped();
1346 $foundDefault = true;
1349 # Create preview link
1350 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1351 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1353 # Create links to user CSS/JS pages
1354 if ( $allowUserCss ) {
1355 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1356 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
1357 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
1360 if ( $allowUserJs ) {
1361 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1362 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
1363 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
1366 $display = $sn . ' ' . $context->msg( 'parentheses' )
1367 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1369 $ret[$display] = $skinkey;
1372 if ( !$foundDefault ) {
1373 // If the default skin is not available, things are going to break horribly because the
1374 // default value for skin selector will not be a valid value. Let's just not show it then.
1382 * @param IContextSource $context
1385 protected function getDateOptions( IContextSource
$context ) {
1386 $lang = $context->getLanguage();
1387 $dateopts = $lang->getDatePreferences();
1392 if ( !in_array( 'default', $dateopts ) ) {
1393 $dateopts[] = 'default'; // Make sure default is always valid T21237
1396 // FIXME KLUGE: site default might not be valid for user language
1397 global $wgDefaultUserOptions;
1398 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1399 $wgDefaultUserOptions['date'] = 'default';
1402 $epoch = wfTimestampNow();
1403 foreach ( $dateopts as $key ) {
1404 if ( $key == 'default' ) {
1405 $formatted = $context->msg( 'datedefault' )->escaped();
1407 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1409 $ret[$formatted] = $key;
1416 * @param MessageLocalizer $l10n
1419 protected function getImageSizes( MessageLocalizer
$l10n ) {
1421 $pixels = $l10n->msg( 'unit-pixel' )->text();
1423 foreach ( $this->options
->get( 'ImageLimits' ) as $index => $limits ) {
1424 // Note: A left-to-right marker (U+200E) is inserted, see T144386
1425 $display = "{$limits[0]}\u{200E}×{$limits[1]}$pixels";
1426 $ret[$display] = $index;
1433 * @param MessageLocalizer $l10n
1436 protected function getThumbSizes( MessageLocalizer
$l10n ) {
1438 $pixels = $l10n->msg( 'unit-pixel' )->text();
1440 foreach ( $this->options
->get( 'ThumbLimits' ) as $index => $size ) {
1441 $display = $size . $pixels;
1442 $ret[$display] = $index;
1449 * @param string $signature
1450 * @param array $alldata
1451 * @param HTMLForm $form
1452 * @return bool|string
1454 protected function validateSignature( $signature, $alldata, HTMLForm
$form ) {
1455 $maxSigChars = $this->options
->get( 'MaxSigChars' );
1456 if ( mb_strlen( $signature ) > $maxSigChars ) {
1457 return Xml
::element( 'span', [ 'class' => 'error' ],
1458 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1459 } elseif ( isset( $alldata['fancysig'] ) &&
1460 $alldata['fancysig'] &&
1461 MediaWikiServices
::getInstance()->getParser()->validateSig( $signature ) === false
1463 return Xml
::element(
1465 [ 'class' => 'error' ],
1466 $form->msg( 'badsig' )->text()
1474 * @param string $signature
1475 * @param array $alldata
1476 * @param HTMLForm $form
1479 protected function cleanSignature( $signature, $alldata, HTMLForm
$form ) {
1480 $parser = MediaWikiServices
::getInstance()->getParser();
1481 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1482 $signature = $parser->cleanSig( $signature );
1484 // When no fancy sig used, make sure ~{3,5} get removed.
1485 $signature = Parser
::cleanSigInSig( $signature );
1493 * @param IContextSource $context
1494 * @param string $formClass
1495 * @param array $remove Array of items to remove
1498 public function getForm(
1500 IContextSource
$context,
1501 $formClass = PreferencesFormOOUI
::class,
1504 // We use ButtonWidgets in some of the getPreferences() functions
1505 $context->getOutput()->enableOOUI();
1507 $formDescriptor = $this->getFormDescriptor( $user, $context );
1508 if ( count( $remove ) ) {
1509 $removeKeys = array_flip( $remove );
1510 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1513 // Remove type=api preferences. They are not intended for rendering in the form.
1514 foreach ( $formDescriptor as $name => $info ) {
1515 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1516 unset( $formDescriptor[$name] );
1521 * @var HTMLForm $htmlForm
1523 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1525 // This allows users to opt-in to hidden skins. While this should be discouraged and is not
1526 // discoverable, this allows users to still use hidden skins while preventing new users from
1527 // adopting unsupported skins. If no useskin=… parameter was provided, it will not show up
1528 // in the resulting URL.
1529 $htmlForm->setAction( $context->getTitle()->getLocalURL( [
1530 'useskin' => $context->getRequest()->getRawVal( 'useskin' )
1533 $htmlForm->setModifiedUser( $user );
1534 $htmlForm->setId( 'mw-prefs-form' );
1535 $htmlForm->setAutocomplete( 'off' );
1536 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1537 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1538 $htmlForm->setSubmitTooltip( 'preferences-save' );
1539 $htmlForm->setSubmitID( 'prefcontrol' );
1540 $htmlForm->setSubmitCallback(
1541 function ( array $formData, HTMLForm
$form ) use ( $formDescriptor ) {
1542 return $this->submitForm( $formData, $form, $formDescriptor );
1550 * @param IContextSource $context
1553 protected function getTimezoneOptions( IContextSource
$context ) {
1556 $localTZoffset = $this->options
->get( 'LocalTZoffset' );
1557 $timeZoneList = $this->getTimeZoneList( $context->getLanguage() );
1559 $timestamp = MWTimestamp
::getLocalInstance();
1560 // Check that the LocalTZoffset is the same as the local time zone offset
1561 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1562 $timezoneName = $timestamp->getTimezone()->getName();
1563 // Localize timezone
1564 if ( isset( $timeZoneList[$timezoneName] ) ) {
1565 $timezoneName = $timeZoneList[$timezoneName]['name'];
1567 $server_tz_msg = $context->msg(
1568 'timezoneuseserverdefault',
1572 $tzstring = sprintf(
1574 floor( $localTZoffset / 60 ),
1575 abs( $localTZoffset ) %
60
1577 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1579 $opt[$server_tz_msg] = "System|$localTZoffset";
1580 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1581 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1583 foreach ( $timeZoneList as $timeZoneInfo ) {
1584 $region = $timeZoneInfo['region'];
1585 if ( !isset( $opt[$region] ) ) {
1588 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1594 * Handle the form submission if everything validated properly
1596 * @param array $formData
1597 * @param HTMLForm $form
1598 * @param array[] $formDescriptor
1599 * @return bool|Status|string
1601 protected function saveFormData( $formData, HTMLForm
$form, array $formDescriptor ) {
1602 /** @var \User $user */
1603 $user = $form->getModifiedUser();
1604 $hiddenPrefs = $this->options
->get( 'HiddenPrefs' );
1607 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1608 return Status
::newFatal( 'mypreferencesprotected' );
1612 $this->applyFilters( $formData, $formDescriptor, 'filterFromForm' );
1614 // Fortunately, the realname field is MUCH simpler
1615 // (not really "private", but still shouldn't be edited without permission)
1617 if ( !in_array( 'realname', $hiddenPrefs )
1618 && $user->isAllowed( 'editmyprivateinfo' )
1619 && array_key_exists( 'realname', $formData )
1621 $realName = $formData['realname'];
1622 $user->setRealName( $realName );
1625 if ( $user->isAllowed( 'editmyoptions' ) ) {
1626 $oldUserOptions = $user->getOptions();
1628 foreach ( $this->getSaveBlacklist() as $b ) {
1629 unset( $formData[$b] );
1632 # If users have saved a value for a preference which has subsequently been disabled
1633 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1634 # is subsequently re-enabled
1635 foreach ( $hiddenPrefs as $pref ) {
1636 # If the user has not set a non-default value here, the default will be returned
1637 # and subsequently discarded
1638 $formData[$pref] = $user->getOption( $pref, null, true );
1641 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1643 isset( $formData['rclimit'] ) &&
1644 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1646 $formData['rcfilters-limit'] = $formData['rclimit'];
1649 // Keep old preferences from interfering due to back-compat code, etc.
1650 $user->resetOptions( 'unused', $form->getContext() );
1652 foreach ( $formData as $key => $value ) {
1653 $user->setOption( $key, $value );
1657 'PreferencesFormPreSave',
1658 [ $formData, $form, $user, &$result, $oldUserOptions ]
1662 $user->saveSettings();
1668 * Applies filters to preferences either before or after form usage
1670 * @param array &$preferences
1671 * @param array $formDescriptor
1672 * @param string $verb Name of the filter method to call, either 'filterFromForm' or
1675 protected function applyFilters( array &$preferences, array $formDescriptor, $verb ) {
1676 foreach ( $formDescriptor as $preference => $desc ) {
1677 if ( !isset( $desc['filter'] ) ||
!isset( $preferences[$preference] ) ) {
1680 $filterDesc = $desc['filter'];
1681 if ( $filterDesc instanceof Filter
) {
1682 $filter = $filterDesc;
1683 } elseif ( class_exists( $filterDesc ) ) {
1684 $filter = new $filterDesc();
1685 } elseif ( is_callable( $filterDesc ) ) {
1686 $filter = $filterDesc();
1688 throw new UnexpectedValueException(
1689 "Unrecognized filter type for preference '$preference'"
1692 $preferences[$preference] = $filter->$verb( $preferences[$preference] );
1697 * Save the form data and reload the page
1699 * @param array $formData
1700 * @param HTMLForm $form
1701 * @param array $formDescriptor
1704 protected function submitForm( array $formData, HTMLForm
$form, array $formDescriptor ) {
1705 $res = $this->saveFormData( $formData, $form, $formDescriptor );
1707 if ( $res === true ) {
1708 $context = $form->getContext();
1711 if ( $res === 'eauth' ) {
1712 $urlOptions['eauth'] = 1;
1715 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1717 $url = $form->getTitle()->getFullURL( $urlOptions );
1719 // Set session data for the success message
1720 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1722 $context->getOutput()->redirect( $url );
1725 return ( $res === true ? Status
::newGood() : $res );
1729 * Get a list of all time zones
1730 * @param Language $language Language used for the localized names
1731 * @return array A list of all time zones. The system name of the time zone is used as key and
1732 * the value is an array which contains localized name, the timecorrection value used for
1733 * preferences and the region
1736 protected function getTimeZoneList( Language
$language ) {
1737 $identifiers = DateTimeZone
::listIdentifiers();
1738 if ( $identifiers === false ) {
1741 sort( $identifiers );
1744 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1745 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1746 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1747 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1748 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1749 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1750 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1751 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1752 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1753 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1755 asort( $tzRegions );
1759 $now = new DateTime();
1761 foreach ( $identifiers as $identifier ) {
1762 $parts = explode( '/', $identifier, 2 );
1764 // DateTimeZone::listIdentifiers() returns a number of
1765 // backwards-compatibility entries. This filters them out of the
1766 // list presented to the user.
1767 if ( count( $parts ) !== 2 ||
!array_key_exists( $parts[0], $tzRegions ) ) {
1772 $parts[0] = $tzRegions[$parts[0]];
1774 $dateTimeZone = new DateTimeZone( $identifier );
1775 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1777 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1778 $value = "ZoneInfo|$minDiff|$identifier";
1780 $timeZoneList[$identifier] = [
1782 'timecorrection' => $value,
1783 'region' => $parts[0],
1787 return $timeZoneList;