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
;
36 use LanguageConverter
;
37 use MediaWiki\Auth\AuthManager
;
38 use MediaWiki\Auth\PasswordAuthenticationRequest
;
39 use MediaWiki\Linker\LinkRenderer
;
40 use MediaWiki\MediaWikiServices
;
48 use PreferencesFormLegacy
;
49 use Psr\Log\LoggerAwareTrait
;
50 use Psr\Log\NullLogger
;
53 use SpecialPreferences
;
57 use UserGroupMembership
;
61 * This is the default implementation of PreferencesFactory.
63 class DefaultPreferencesFactory
implements PreferencesFactory
{
69 /** @var Language The wiki's content language, equivalent to $wgContLang. */
72 /** @var AuthManager */
73 protected $authManager;
75 /** @var LinkRenderer */
76 protected $linkRenderer;
79 * @param Config $config
80 * @param Language $contLang
81 * @param AuthManager $authManager
82 * @param LinkRenderer $linkRenderer
84 public function __construct(
87 AuthManager
$authManager,
88 LinkRenderer
$linkRenderer
90 $this->config
= $config;
91 $this->contLang
= $contLang;
92 $this->authManager
= $authManager;
93 $this->linkRenderer
= $linkRenderer;
94 $this->logger
= new NullLogger();
100 protected function getSaveFilters() {
101 // Wrap intval() so that we can pass it multiple parameters and treat all filters the same.
102 $intvalFilter = function ( $value, $alldata ) {
103 return intval( $value );
106 'timecorrection' => [ $this, 'filterTimezoneInput' ],
107 'rclimit' => $intvalFilter,
108 'wllimit' => $intvalFilter,
109 'searchlimit' => $intvalFilter,
116 public function getSaveBlacklist() {
124 * @throws MWException
126 * @param IContextSource $context
129 public function getFormDescriptor( User
$user, IContextSource
$context ) {
132 if ( SpecialPreferences
::isOouiEnabled( $context ) ) {
133 OutputPage
::setupOOUI(
134 strtolower( $context->getSkin()->getSkinName() ),
135 $context->getLanguage()->getDir()
139 $canIPUseHTTPS = wfCanIPUseHTTPS( $context->getRequest()->getIP() );
140 $this->profilePreferences( $user, $context, $preferences, $canIPUseHTTPS );
141 $this->skinPreferences( $user, $context, $preferences );
142 $this->datetimePreferences( $user, $context, $preferences );
143 $this->filesPreferences( $context, $preferences );
144 $this->renderingPreferences( $context, $preferences );
145 $this->editingPreferences( $user, $context, $preferences );
146 $this->rcPreferences( $user, $context, $preferences );
147 $this->watchlistPreferences( $user, $context, $preferences );
148 $this->searchPreferences( $preferences );
150 Hooks
::run( 'GetPreferences', [ $user, &$preferences ] );
152 $this->loadPreferenceValues( $user, $context, $preferences );
153 $this->logger
->debug( "Created form descriptor for user '{$user->getName()}'" );
158 * Loads existing values for a given array of preferences
159 * @throws MWException
161 * @param IContextSource $context
162 * @param array &$defaultPreferences Array to load values for
165 private function loadPreferenceValues(
166 User
$user, IContextSource
$context, &$defaultPreferences
168 # # Remove preferences that wikis don't want to use
169 foreach ( $this->config
->get( 'HiddenPrefs' ) as $pref ) {
170 if ( isset( $defaultPreferences[$pref] ) ) {
171 unset( $defaultPreferences[$pref] );
175 # # Make sure that form fields have their parent set. See T43337.
176 $dummyForm = new HTMLForm( [], $context );
178 $disable = !$user->isAllowed( 'editmyoptions' );
180 $defaultOptions = User
::getDefaultOptions();
181 # # Prod in defaults from the user
182 foreach ( $defaultPreferences as $name => &$info ) {
183 $prefFromUser = $this->getOptionFromUser( $name, $info, $user );
184 if ( $disable && !in_array( $name, $this->getSaveBlacklist() ) ) {
185 $info['disabled'] = 'disabled';
187 $field = HTMLForm
::loadInputFromParameters( $name, $info, $dummyForm ); // For validation
188 $globalDefault = $defaultOptions[$name] ??
null;
190 // If it validates, set it as the default
191 if ( isset( $info['default'] ) ) {
192 // Already set, no problem
194 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
195 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
196 $info['default'] = $prefFromUser;
197 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
198 $info['default'] = $globalDefault;
200 throw new MWException( "Global default '$globalDefault' is invalid for field $name" );
204 return $defaultPreferences;
208 * Pull option from a user account. Handles stuff like array-type preferences.
210 * @param string $name
213 * @return array|string
215 protected function getOptionFromUser( $name, $info, User
$user ) {
216 $val = $user->getOption( $name );
218 // Handling for multiselect preferences
219 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
220 ( isset( $info['class'] ) && $info['class'] == \HTMLMultiSelectField
::class ) ) {
221 $options = HTMLFormField
::flattenOptions( $info['options'] );
222 $prefix = $info['prefix'] ??
$name;
225 foreach ( $options as $value ) {
226 if ( $user->getOption( "$prefix$value" ) ) {
232 // Handling for checkmatrix preferences
233 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
234 ( isset( $info['class'] ) && $info['class'] == \HTMLCheckMatrix
::class ) ) {
235 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
236 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
237 $prefix = $info['prefix'] ??
$name;
240 foreach ( $columns as $column ) {
241 foreach ( $rows as $row ) {
242 if ( $user->getOption( "$prefix$column-$row" ) ) {
243 $val[] = "$column-$row";
253 * @todo Inject user Language instead of using context.
255 * @param IContextSource $context
256 * @param array &$defaultPreferences
257 * @param bool $canIPUseHTTPS Whether the user's IP is likely to be able to access the wiki
261 protected function profilePreferences(
262 User
$user, IContextSource
$context, &$defaultPreferences, $canIPUseHTTPS
264 $oouiEnabled = SpecialPreferences
::isOouiEnabled( $context );
266 // retrieving user name for GENDER and misc.
267 $userName = $user->getName();
269 # # User info #####################################
271 $defaultPreferences['username'] = [
273 'label-message' => [ 'username', $userName ],
274 'default' => $userName,
275 'section' => 'personal/info',
278 $lang = $context->getLanguage();
280 # Get groups to which the user belongs
281 $userEffectiveGroups = $user->getEffectiveGroups();
282 $userGroupMemberships = $user->getGroupMemberships();
283 $userGroups = $userMembers = $userTempGroups = $userTempMembers = [];
284 foreach ( $userEffectiveGroups as $ueg ) {
286 // Skip the default * group, seems useless here
290 if ( isset( $userGroupMemberships[$ueg] ) ) {
291 $groupStringOrObject = $userGroupMemberships[$ueg];
293 $groupStringOrObject = $ueg;
296 $userG = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html' );
297 $userM = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html',
300 // Store expiring groups separately, so we can place them before non-expiring
301 // groups in the list. This is to avoid the ambiguity of something like
302 // "administrator, bureaucrat (until X date)" -- users might wonder whether the
303 // expiry date applies to both groups, or just the last one
304 if ( $groupStringOrObject instanceof UserGroupMembership
&&
305 $groupStringOrObject->getExpiry()
307 $userTempGroups[] = $userG;
308 $userTempMembers[] = $userM;
310 $userGroups[] = $userG;
311 $userMembers[] = $userM;
315 sort( $userMembers );
316 sort( $userTempGroups );
317 sort( $userTempMembers );
318 $userGroups = array_merge( $userTempGroups, $userGroups );
319 $userMembers = array_merge( $userTempMembers, $userMembers );
321 $defaultPreferences['usergroups'] = [
323 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
324 count( $userGroups ) )->params( $userName )->parse(),
325 'default' => $context->msg( 'prefs-memberingroups-type' )
326 ->rawParams( $lang->commaList( $userGroups ), $lang->commaList( $userMembers ) )
329 'section' => 'personal/info',
332 $contribTitle = SpecialPage
::getTitleFor( "Contributions", $userName );
333 $formattedEditCount = $lang->formatNum( $user->getEditCount() );
334 $editCount = $this->linkRenderer
->makeLink( $contribTitle, $formattedEditCount );
336 $defaultPreferences['editcount'] = [
339 'label-message' => 'prefs-edits',
340 'default' => $editCount,
341 'section' => 'personal/info',
344 if ( $user->getRegistration() ) {
345 $displayUser = $context->getUser();
346 $userRegistration = $user->getRegistration();
347 $defaultPreferences['registrationdate'] = [
349 'label-message' => 'prefs-registration',
350 'default' => $context->msg(
351 'prefs-registration-date-time',
352 $lang->userTimeAndDate( $userRegistration, $displayUser ),
353 $lang->userDate( $userRegistration, $displayUser ),
354 $lang->userTime( $userRegistration, $displayUser )
356 'section' => 'personal/info',
360 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
361 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
363 // Actually changeable stuff
364 $defaultPreferences['realname'] = [
365 // (not really "private", but still shouldn't be edited without permission)
366 'type' => $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'realname' )
368 'default' => $user->getRealName(),
369 'section' => 'personal/info',
370 'label-message' => 'yourrealname',
371 'help-message' => 'prefs-help-realname',
374 if ( $canEditPrivateInfo && $this->authManager
->allowsAuthenticationDataChange(
375 new PasswordAuthenticationRequest(), false )->isGood()
377 if ( $oouiEnabled ) {
378 $link = new \OOUI\
ButtonWidget( [
379 'href' => SpecialPage
::getTitleFor( 'ChangePassword' )->getLinkURL( [
380 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
382 'label' => $context->msg( 'prefs-resetpass' )->text(),
385 $link = $this->linkRenderer
->makeLink( SpecialPage
::getTitleFor( 'ChangePassword' ),
386 $context->msg( 'prefs-resetpass' )->text(), [],
387 [ 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText() ] );
390 $defaultPreferences['password'] = [
393 'default' => (string)$link,
394 'label-message' => 'yourpassword',
395 'section' => 'personal/info',
398 // Only show prefershttps if secure login is turned on
399 if ( $this->config
->get( 'SecureLogin' ) && $canIPUseHTTPS ) {
400 $defaultPreferences['prefershttps'] = [
402 'label-message' => 'tog-prefershttps',
403 'help-message' => 'prefs-help-prefershttps',
404 'section' => 'personal/info'
409 $languages = Language
::fetchLanguageNames( null, 'mwfile' );
410 $languageCode = $this->config
->get( 'LanguageCode' );
411 if ( !array_key_exists( $languageCode, $languages ) ) {
412 $languages[$languageCode] = $languageCode;
413 // Sort the array again
418 foreach ( $languages as $code => $name ) {
419 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
420 $options[$display] = $code;
422 $defaultPreferences['language'] = [
424 'section' => 'personal/i18n',
425 'options' => $options,
426 'label-message' => 'yourlanguage',
429 $defaultPreferences['gender'] = [
431 'section' => 'personal/i18n',
433 $context->msg( 'parentheses' )
434 ->params( $context->msg( 'gender-unknown' )->plain() )
435 ->escaped() => 'unknown',
436 $context->msg( 'gender-female' )->escaped() => 'female',
437 $context->msg( 'gender-male' )->escaped() => 'male',
439 'label-message' => 'yourgender',
440 'help-message' => 'prefs-help-gender',
443 // see if there are multiple language variants to choose from
444 if ( !$this->config
->get( 'DisableLangConversion' ) ) {
445 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
446 if ( $langCode == $this->contLang
->getCode() ) {
447 if ( !$this->contLang
->hasVariants() ) {
451 $variants = $this->contLang
->getVariants();
453 foreach ( $variants as $v ) {
454 $v = str_replace( '_', '-', strtolower( $v ) );
455 $variantArray[$v] = $lang->getVariantname( $v, false );
459 foreach ( $variantArray as $code => $name ) {
460 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
461 $options[$display] = $code;
464 $defaultPreferences['variant'] = [
465 'label-message' => 'yourvariant',
467 'options' => $options,
468 'section' => 'personal/i18n',
469 'help-message' => 'prefs-help-variant',
472 $defaultPreferences["variant-$langCode"] = [
479 // Stuff from Language::getExtraUserToggles()
480 // FIXME is this dead code? $extraUserToggles doesn't seem to be defined for any language
481 $toggles = $this->contLang
->getExtraUserToggles();
483 foreach ( $toggles as $toggle ) {
484 $defaultPreferences[$toggle] = [
486 'section' => 'personal/i18n',
487 'label-message' => "tog-$toggle",
491 // show a preview of the old signature first
492 $oldsigWikiText = MediaWikiServices
::getInstance()->getParser()->preSaveTransform(
494 $context->getTitle(),
496 ParserOptions
::newFromContext( $context )
498 $oldsigHTML = $context->getOutput()->parseInline( $oldsigWikiText, true, true );
499 $defaultPreferences['oldsig'] = [
502 'label-message' => 'tog-oldsig',
503 'default' => $oldsigHTML,
504 'section' => 'personal/signature',
506 $defaultPreferences['nickname'] = [
507 'type' => $this->authManager
->allowsPropertyChange( 'nickname' ) ?
'text' : 'info',
508 'maxlength' => $this->config
->get( 'MaxSigChars' ),
509 'label-message' => 'yournick',
510 'validation-callback' => function ( $signature, $alldata, HTMLForm
$form ) {
511 return $this->validateSignature( $signature, $alldata, $form );
513 'section' => 'personal/signature',
514 'filter-callback' => function ( $signature, array $alldata, HTMLForm
$form ) {
515 return $this->cleanSignature( $signature, $alldata, $form );
518 $defaultPreferences['fancysig'] = [
520 'label-message' => 'tog-fancysig',
521 // show general help about signature at the bottom of the section
522 'help-message' => 'prefs-help-signature',
523 'section' => 'personal/signature'
528 if ( $this->config
->get( 'EnableEmail' ) ) {
529 if ( $canViewPrivateInfo ) {
530 $helpMessages[] = $this->config
->get( 'EmailConfirmToEdit' )
531 ?
'prefs-help-email-required'
532 : 'prefs-help-email';
534 if ( $this->config
->get( 'EnableUserEmail' ) ) {
535 // additional messages when users can send email to each other
536 $helpMessages[] = 'prefs-help-email-others';
539 $emailAddress = $user->getEmail() ?
htmlspecialchars( $user->getEmail() ) : '';
540 if ( $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'emailaddress' ) ) {
541 if ( $oouiEnabled ) {
542 $link = new \OOUI\
ButtonWidget( [
543 'href' => SpecialPage
::getTitleFor( 'ChangeEmail' )->getLinkURL( [
544 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
547 $context->msg( $user->getEmail() ?
'prefs-changeemail' : 'prefs-setemail' )->text(),
550 $emailAddress .= $emailAddress == '' ?
$link : ( '<br />' . $link );
552 $link = $this->linkRenderer
->makeLink(
553 SpecialPage
::getTitleFor( 'ChangeEmail' ),
554 $context->msg( $user->getEmail() ?
'prefs-changeemail' : 'prefs-setemail' )->text(),
556 [ 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText() ] );
558 $emailAddress .= $emailAddress == '' ?
$link : (
559 $context->msg( 'word-separator' )->escaped()
560 . $context->msg( 'parentheses' )->rawParams( $link )->escaped()
565 $defaultPreferences['emailaddress'] = [
568 'default' => $emailAddress,
569 'label-message' => 'youremail',
570 'section' => 'personal/email',
571 'help-messages' => $helpMessages,
572 # 'cssclass' chosen below
576 $disableEmailPrefs = false;
578 if ( $this->config
->get( 'EmailAuthentication' ) ) {
579 $emailauthenticationclass = 'mw-email-not-authenticated';
580 if ( $user->getEmail() ) {
581 if ( $user->getEmailAuthenticationTimestamp() ) {
582 // date and time are separate parameters to facilitate localisation.
583 // $time is kept for backward compat reasons.
584 // 'emailauthenticated' is also used in SpecialConfirmemail.php
585 $displayUser = $context->getUser();
586 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
587 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
588 $d = $lang->userDate( $emailTimestamp, $displayUser );
589 $t = $lang->userTime( $emailTimestamp, $displayUser );
590 $emailauthenticated = $context->msg( 'emailauthenticated',
591 $time, $d, $t )->parse() . '<br />';
592 $disableEmailPrefs = false;
593 $emailauthenticationclass = 'mw-email-authenticated';
595 $disableEmailPrefs = true;
596 if ( $oouiEnabled ) {
597 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
598 new \OOUI\
ButtonWidget( [
599 'href' => SpecialPage
::getTitleFor( 'Confirmemail' )->getLinkURL(),
600 'label' => $context->msg( 'emailconfirmlink' )->text(),
603 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
604 $this->linkRenderer
->makeKnownLink(
605 SpecialPage
::getTitleFor( 'Confirmemail' ),
606 $context->msg( 'emailconfirmlink' )->text()
609 $emailauthenticationclass = "mw-email-not-authenticated";
612 $disableEmailPrefs = true;
613 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
614 $emailauthenticationclass = 'mw-email-none';
617 if ( $canViewPrivateInfo ) {
618 $defaultPreferences['emailauthentication'] = [
621 'section' => 'personal/email',
622 'label-message' => 'prefs-emailconfirm-label',
623 'default' => $emailauthenticated,
624 # Apply the same CSS class used on the input to the message:
625 'cssclass' => $emailauthenticationclass,
630 if ( $this->config
->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
631 $defaultPreferences['disablemail'] = [
632 'id' => 'wpAllowEmail',
635 'section' => 'personal/email',
636 'label-message' => 'allowemail',
637 'disabled' => $disableEmailPrefs,
640 $defaultPreferences['email-allow-new-users'] = [
641 'id' => 'wpAllowEmailFromNewUsers',
643 'section' => 'personal/email',
644 'label-message' => 'email-allow-new-users-label',
645 'disabled' => $disableEmailPrefs,
648 $defaultPreferences['ccmeonemails'] = [
650 'section' => 'personal/email',
651 'label-message' => 'tog-ccmeonemails',
652 'disabled' => $disableEmailPrefs,
655 if ( $this->config
->get( 'EnableUserEmailBlacklist' ) ) {
656 $lookup = CentralIdLookup
::factory();
657 $ids = $user->getOption( 'email-blacklist', [] );
658 $names = $ids ?
$lookup->namesFromCentralIds( $ids, $user ) : [];
660 $defaultPreferences['email-blacklist'] = [
661 'type' => 'usersmultiselect',
662 'label-message' => 'email-blacklist-label',
663 'section' => 'personal/email',
664 'default' => implode( "\n", $names ),
665 'disabled' => $disableEmailPrefs,
670 if ( $this->config
->get( 'EnotifWatchlist' ) ) {
671 $defaultPreferences['enotifwatchlistpages'] = [
673 'section' => 'personal/email',
674 'label-message' => 'tog-enotifwatchlistpages',
675 'disabled' => $disableEmailPrefs,
678 if ( $this->config
->get( 'EnotifUserTalk' ) ) {
679 $defaultPreferences['enotifusertalkpages'] = [
681 'section' => 'personal/email',
682 'label-message' => 'tog-enotifusertalkpages',
683 'disabled' => $disableEmailPrefs,
686 if ( $this->config
->get( 'EnotifUserTalk' ) ||
$this->config
->get( 'EnotifWatchlist' ) ) {
687 if ( $this->config
->get( 'EnotifMinorEdits' ) ) {
688 $defaultPreferences['enotifminoredits'] = [
690 'section' => 'personal/email',
691 'label-message' => 'tog-enotifminoredits',
692 'disabled' => $disableEmailPrefs,
696 if ( $this->config
->get( 'EnotifRevealEditorAddress' ) ) {
697 $defaultPreferences['enotifrevealaddr'] = [
699 'section' => 'personal/email',
700 'label-message' => 'tog-enotifrevealaddr',
701 'disabled' => $disableEmailPrefs,
710 * @param IContextSource $context
711 * @param array &$defaultPreferences
714 protected function skinPreferences( User
$user, IContextSource
$context, &$defaultPreferences ) {
715 # # Skin #####################################
717 // Skin selector, if there is at least one valid skin
718 $skinOptions = $this->generateSkinOptions( $user, $context );
719 if ( $skinOptions ) {
720 $defaultPreferences['skin'] = [
722 'options' => $skinOptions,
723 'section' => 'rendering/skin',
727 $allowUserCss = $this->config
->get( 'AllowUserCss' );
728 $allowUserJs = $this->config
->get( 'AllowUserJs' );
729 # Create links to user CSS/JS pages for all skins
730 # This code is basically copied from generateSkinOptions(). It'd
731 # be nice to somehow merge this back in there to avoid redundancy.
732 if ( $allowUserCss ||
$allowUserJs ) {
734 $userName = $user->getName();
736 if ( $allowUserCss ) {
737 $cssPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.css' );
738 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
739 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
742 if ( $allowUserJs ) {
743 $jsPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.js' );
744 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
745 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
748 $defaultPreferences['commoncssjs'] = [
751 'default' => $context->getLanguage()->pipeList( $linkTools ),
752 'label-message' => 'prefs-common-config',
753 'section' => 'rendering/skin',
759 * @param IContextSource $context
760 * @param array &$defaultPreferences
762 protected function filesPreferences( IContextSource
$context, &$defaultPreferences ) {
763 # # Files #####################################
764 $defaultPreferences['imagesize'] = [
766 'options' => $this->getImageSizes( $context ),
767 'label-message' => 'imagemaxsize',
768 'section' => 'rendering/files',
770 $defaultPreferences['thumbsize'] = [
772 'options' => $this->getThumbSizes( $context ),
773 'label-message' => 'thumbsize',
774 'section' => 'rendering/files',
780 * @param IContextSource $context
781 * @param array &$defaultPreferences
784 protected function datetimePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
785 # # Date and time #####################################
786 $dateOptions = $this->getDateOptions( $context );
787 if ( $dateOptions ) {
788 $defaultPreferences['date'] = [
790 'options' => $dateOptions,
791 'section' => 'rendering/dateformat',
796 $now = wfTimestampNow();
797 $lang = $context->getLanguage();
798 $nowlocal = Xml
::element( 'span', [ 'id' => 'wpLocalTime' ],
799 $lang->userTime( $now, $user ) );
800 $nowserver = $lang->userTime( $now, $user,
801 [ 'format' => false, 'timecorrection' => false ] ) .
802 Html
::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 +
(int)substr( $now, 10, 2 ) );
804 $defaultPreferences['nowserver'] = [
807 'label-message' => 'servertime',
808 'default' => $nowserver,
809 'section' => 'rendering/timeoffset',
812 $defaultPreferences['nowlocal'] = [
815 'label-message' => 'localtime',
816 'default' => $nowlocal,
817 'section' => 'rendering/timeoffset',
820 // Grab existing pref.
821 $tzOffset = $user->getOption( 'timecorrection' );
822 $tz = explode( '|', $tzOffset, 3 );
824 $tzOptions = $this->getTimezoneOptions( $context );
826 $tzSetting = $tzOffset;
827 if ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
828 !in_array( $tzOffset, HTMLFormField
::flattenOptions( $tzOptions ) )
830 // Timezone offset can vary with DST
832 $userTZ = new DateTimeZone( $tz[2] );
833 $minDiff = floor( $userTZ->getOffset( new DateTime( 'now' ) ) / 60 );
834 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
835 } catch ( Exception
$e ) {
836 // User has an invalid time zone set. Fall back to just using the offset
840 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
842 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) %
60 );
845 $defaultPreferences['timecorrection'] = [
846 'class' => \HTMLSelectOrOtherField
::class,
847 'label-message' => 'timezonelegend',
848 'options' => $tzOptions,
849 'default' => $tzSetting,
851 'section' => 'rendering/timeoffset',
852 'id' => 'wpTimeCorrection',
857 * @param MessageLocalizer $l10n
858 * @param array &$defaultPreferences
860 protected function renderingPreferences( MessageLocalizer
$l10n, &$defaultPreferences ) {
861 # # Diffs ####################################
862 $defaultPreferences['diffonly'] = [
864 'section' => 'rendering/diffs',
865 'label-message' => 'tog-diffonly',
867 $defaultPreferences['norollbackdiff'] = [
869 'section' => 'rendering/diffs',
870 'label-message' => 'tog-norollbackdiff',
873 # # Page Rendering ##############################
874 if ( $this->config
->get( 'AllowUserCssPrefs' ) ) {
875 $defaultPreferences['underline'] = [
878 $l10n->msg( 'underline-never' )->text() => 0,
879 $l10n->msg( 'underline-always' )->text() => 1,
880 $l10n->msg( 'underline-default' )->text() => 2,
882 'label-message' => 'tog-underline',
883 'section' => 'rendering/advancedrendering',
887 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
888 $stubThresholdOptions = [ $l10n->msg( 'stub-threshold-disabled' )->text() => 0 ];
889 foreach ( $stubThresholdValues as $value ) {
890 $stubThresholdOptions[$l10n->msg( 'size-bytes', $value )->text()] = $value;
893 $defaultPreferences['stubthreshold'] = [
895 'section' => 'rendering/advancedrendering',
896 'options' => $stubThresholdOptions,
897 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
898 'label-raw' => $l10n->msg( 'stub-threshold' )->rawParams(
899 '<a href="#" class="stub">' .
900 $l10n->msg( 'stub-threshold-sample-link' )->parse() .
904 $defaultPreferences['showhiddencats'] = [
906 'section' => 'rendering/advancedrendering',
907 'label-message' => 'tog-showhiddencats'
910 $defaultPreferences['numberheadings'] = [
912 'section' => 'rendering/advancedrendering',
913 'label-message' => 'tog-numberheadings',
919 * @param MessageLocalizer $l10n
920 * @param array &$defaultPreferences
922 protected function editingPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
923 # # Editing #####################################
924 $defaultPreferences['editsectiononrightclick'] = [
926 'section' => 'editing/advancedediting',
927 'label-message' => 'tog-editsectiononrightclick',
929 $defaultPreferences['editondblclick'] = [
931 'section' => 'editing/advancedediting',
932 'label-message' => 'tog-editondblclick',
935 if ( $this->config
->get( 'AllowUserCssPrefs' ) ) {
936 $defaultPreferences['editfont'] = [
938 'section' => 'editing/editor',
939 'label-message' => 'editfont-style',
941 $l10n->msg( 'editfont-monospace' )->text() => 'monospace',
942 $l10n->msg( 'editfont-sansserif' )->text() => 'sans-serif',
943 $l10n->msg( 'editfont-serif' )->text() => 'serif',
948 if ( $user->isAllowed( 'minoredit' ) ) {
949 $defaultPreferences['minordefault'] = [
951 'section' => 'editing/editor',
952 'label-message' => 'tog-minordefault',
956 $defaultPreferences['forceeditsummary'] = [
958 'section' => 'editing/editor',
959 'label-message' => 'tog-forceeditsummary',
961 $defaultPreferences['useeditwarning'] = [
963 'section' => 'editing/editor',
964 'label-message' => 'tog-useeditwarning',
966 $defaultPreferences['showtoolbar'] = [
968 'section' => 'editing/editor',
969 'label-message' => 'tog-showtoolbar',
972 $defaultPreferences['previewonfirst'] = [
974 'section' => 'editing/preview',
975 'label-message' => 'tog-previewonfirst',
977 $defaultPreferences['previewontop'] = [
979 'section' => 'editing/preview',
980 'label-message' => 'tog-previewontop',
982 $defaultPreferences['uselivepreview'] = [
984 'section' => 'editing/preview',
985 'label-message' => 'tog-uselivepreview',
991 * @param MessageLocalizer $l10n
992 * @param array &$defaultPreferences
994 protected function rcPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
995 $rcMaxAge = $this->config
->get( 'RCMaxAge' );
996 # # RecentChanges #####################################
997 $defaultPreferences['rcdays'] = [
999 'label-message' => 'recentchangesdays',
1000 'section' => 'rc/displayrc',
1002 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
1003 'help' => $l10n->msg( 'recentchangesdays-max' )->numParams(
1004 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
1006 $defaultPreferences['rclimit'] = [
1010 'label-message' => 'recentchangescount',
1011 'help-message' => 'prefs-help-recentchangescount',
1012 'section' => 'rc/displayrc',
1014 $defaultPreferences['usenewrc'] = [
1016 'label-message' => 'tog-usenewrc',
1017 'section' => 'rc/advancedrc',
1019 $defaultPreferences['hideminor'] = [
1021 'label-message' => 'tog-hideminor',
1022 'section' => 'rc/advancedrc',
1024 $defaultPreferences['rcfilters-rc-collapsed'] = [
1027 $defaultPreferences['rcfilters-wl-collapsed'] = [
1030 $defaultPreferences['rcfilters-saved-queries'] = [
1033 $defaultPreferences['rcfilters-wl-saved-queries'] = [
1036 // Override RCFilters preferences for RecentChanges 'limit'
1037 $defaultPreferences['rcfilters-limit'] = [
1040 $defaultPreferences['rcfilters-saved-queries-versionbackup'] = [
1043 $defaultPreferences['rcfilters-wl-saved-queries-versionbackup'] = [
1047 if ( $this->config
->get( 'RCWatchCategoryMembership' ) ) {
1048 $defaultPreferences['hidecategorization'] = [
1050 'label-message' => 'tog-hidecategorization',
1051 'section' => 'rc/advancedrc',
1055 if ( $user->useRCPatrol() ) {
1056 $defaultPreferences['hidepatrolled'] = [
1058 'section' => 'rc/advancedrc',
1059 'label-message' => 'tog-hidepatrolled',
1063 if ( $user->useNPPatrol() ) {
1064 $defaultPreferences['newpageshidepatrolled'] = [
1066 'section' => 'rc/advancedrc',
1067 'label-message' => 'tog-newpageshidepatrolled',
1071 if ( $this->config
->get( 'RCShowWatchingUsers' ) ) {
1072 $defaultPreferences['shownumberswatching'] = [
1074 'section' => 'rc/advancedrc',
1075 'label-message' => 'tog-shownumberswatching',
1079 if ( $this->config
->get( 'StructuredChangeFiltersShowPreference' ) ) {
1080 $defaultPreferences['rcenhancedfilters-disable'] = [
1082 'section' => 'rc/optoutrc',
1083 'label-message' => 'rcfilters-preference-label',
1084 'help-message' => 'rcfilters-preference-help',
1091 * @param IContextSource $context
1092 * @param array &$defaultPreferences
1094 protected function watchlistPreferences(
1095 User
$user, IContextSource
$context, &$defaultPreferences
1097 $oouiEnabled = SpecialPreferences
::isOouiEnabled( $context );
1099 $watchlistdaysMax = ceil( $this->config
->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1101 # # Watchlist #####################################
1102 if ( $user->isAllowed( 'editmywatchlist' ) ) {
1103 $editWatchlistLinks = '';
1104 $editWatchlistLinksOld = [];
1105 $editWatchlistModes = [
1106 'edit' => [ 'subpage' => false, 'flags' => [] ],
1107 'raw' => [ 'subpage' => 'raw', 'flags' => [] ],
1108 'clear' => [ 'subpage' => 'clear', 'flags' => [ 'destructive' ] ],
1110 foreach ( $editWatchlistModes as $mode => $options ) {
1111 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1112 if ( $oouiEnabled ) {
1113 $editWatchlistLinks .=
1114 new \OOUI\
ButtonWidget( [
1115 'href' => SpecialPage
::getTitleFor( 'EditWatchlist', $options['subpage'] )->getLinkURL(),
1116 'flags' => $options[ 'flags' ],
1117 'label' => new \OOUI\
HtmlSnippet(
1118 $context->msg( "prefs-editwatchlist-{$mode}" )->parse()
1122 $editWatchlistLinksOld[] = $this->linkRenderer
->makeKnownLink(
1123 SpecialPage
::getTitleFor( 'EditWatchlist', $options['subpage'] ),
1124 new HtmlArmor( $context->msg( "prefs-editwatchlist-{$mode}" )->parse() )
1129 $defaultPreferences['editwatchlist'] = [
1132 'default' => $oouiEnabled ?
1133 $editWatchlistLinks :
1134 $context->getLanguage()->pipeList( $editWatchlistLinksOld ),
1135 'label-message' => 'prefs-editwatchlist-label',
1136 'section' => 'watchlist/editwatchlist',
1140 $defaultPreferences['watchlistdays'] = [
1143 'max' => $watchlistdaysMax,
1144 'section' => 'watchlist/displaywatchlist',
1145 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1146 $watchlistdaysMax )->escaped(),
1147 'label-message' => 'prefs-watchlist-days',
1149 $defaultPreferences['wllimit'] = [
1153 'label-message' => 'prefs-watchlist-edits',
1154 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1155 'section' => 'watchlist/displaywatchlist',
1157 $defaultPreferences['extendwatchlist'] = [
1159 'section' => 'watchlist/advancedwatchlist',
1160 'label-message' => 'tog-extendwatchlist',
1162 $defaultPreferences['watchlisthideminor'] = [
1164 'section' => 'watchlist/advancedwatchlist',
1165 'label-message' => 'tog-watchlisthideminor',
1167 $defaultPreferences['watchlisthidebots'] = [
1169 'section' => 'watchlist/advancedwatchlist',
1170 'label-message' => 'tog-watchlisthidebots',
1172 $defaultPreferences['watchlisthideown'] = [
1174 'section' => 'watchlist/advancedwatchlist',
1175 'label-message' => 'tog-watchlisthideown',
1177 $defaultPreferences['watchlisthideanons'] = [
1179 'section' => 'watchlist/advancedwatchlist',
1180 'label-message' => 'tog-watchlisthideanons',
1182 $defaultPreferences['watchlisthideliu'] = [
1184 'section' => 'watchlist/advancedwatchlist',
1185 'label-message' => 'tog-watchlisthideliu',
1188 if ( !\SpecialWatchlist
::checkStructuredFilterUiEnabled(
1192 $defaultPreferences['watchlistreloadautomatically'] = [
1194 'section' => 'watchlist/advancedwatchlist',
1195 'label-message' => 'tog-watchlistreloadautomatically',
1199 $defaultPreferences['watchlistunwatchlinks'] = [
1201 'section' => 'watchlist/advancedwatchlist',
1202 'label-message' => 'tog-watchlistunwatchlinks',
1205 if ( $this->config
->get( 'RCWatchCategoryMembership' ) ) {
1206 $defaultPreferences['watchlisthidecategorization'] = [
1208 'section' => 'watchlist/advancedwatchlist',
1209 'label-message' => 'tog-watchlisthidecategorization',
1213 if ( $user->useRCPatrol() ) {
1214 $defaultPreferences['watchlisthidepatrolled'] = [
1216 'section' => 'watchlist/advancedwatchlist',
1217 'label-message' => 'tog-watchlisthidepatrolled',
1222 'edit' => 'watchdefault',
1223 'move' => 'watchmoves',
1224 'delete' => 'watchdeletion'
1228 if ( $user->isAllowed( 'createpage' ) ||
$user->isAllowed( 'createtalk' ) ) {
1229 $watchTypes['read'] = 'watchcreations';
1232 if ( $user->isAllowed( 'rollback' ) ) {
1233 $watchTypes['rollback'] = 'watchrollback';
1236 if ( $user->isAllowed( 'upload' ) ) {
1237 $watchTypes['upload'] = 'watchuploads';
1240 foreach ( $watchTypes as $action => $pref ) {
1241 if ( $user->isAllowed( $action ) ) {
1243 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1244 // tog-watchrollback
1245 $defaultPreferences[$pref] = [
1247 'section' => 'watchlist/advancedwatchlist',
1248 'label-message' => "tog-$pref",
1253 $defaultPreferences['watchlisttoken'] = [
1257 if ( $oouiEnabled ) {
1258 $tokenButton = new \OOUI\
ButtonWidget( [
1259 'href' => SpecialPage
::getTitleFor( 'ResetTokens' )->getLinkURL( [
1260 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
1262 'label' => $context->msg( 'prefs-watchlist-managetokens' )->text(),
1264 $defaultPreferences['watchlisttoken-info'] = [
1266 'section' => 'watchlist/tokenwatchlist',
1267 'label-message' => 'prefs-watchlist-token',
1268 'help-message' => 'prefs-help-tokenmanagement',
1270 'default' => (string)$tokenButton,
1273 $defaultPreferences['watchlisttoken-info'] = [
1275 'section' => 'watchlist/tokenwatchlist',
1276 'label-message' => 'prefs-watchlist-token',
1277 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1278 'help-message' => 'prefs-help-watchlist-token2',
1282 if ( $this->config
->get( 'StructuredChangeFiltersShowWatchlistPreference' ) ) {
1283 $defaultPreferences['wlenhancedfilters-disable'] = [
1285 'section' => 'watchlist/optoutwatchlist',
1286 'label-message' => 'rcfilters-watchlist-preference-label',
1287 'help-message' => 'rcfilters-watchlist-preference-help',
1293 * @param array &$defaultPreferences
1295 protected function searchPreferences( &$defaultPreferences ) {
1296 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
1297 $defaultPreferences['searchNs' . $n] = [
1304 * @param User $user The User object
1305 * @param IContextSource $context
1306 * @return array Text/links to display as key; $skinkey as value
1308 protected function generateSkinOptions( User
$user, IContextSource
$context ) {
1311 $mptitle = Title
::newMainPage();
1312 $previewtext = $context->msg( 'skin-preview' )->escaped();
1314 # Only show skins that aren't disabled in $wgSkipSkins
1315 $validSkinNames = Skin
::getAllowedSkins();
1317 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1318 $msg = $context->msg( "skinname-{$skinkey}" );
1319 if ( $msg->exists() ) {
1320 $skinname = htmlspecialchars( $msg->text() );
1324 $defaultSkin = $this->config
->get( 'DefaultSkin' );
1325 $allowUserCss = $this->config
->get( 'AllowUserCss' );
1326 $allowUserJs = $this->config
->get( 'AllowUserJs' );
1328 # Sort by the internal name, so that the ordering is the same for each display language,
1329 # especially if some skin names are translated to use a different alphabet and some are not.
1330 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1331 # Display the default first in the list by comparing it as lesser than any other.
1332 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1335 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1338 return strcasecmp( $a, $b );
1341 $foundDefault = false;
1342 foreach ( $validSkinNames as $skinkey => $sn ) {
1345 # Mark the default skin
1346 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1347 $linkTools[] = $context->msg( 'default' )->escaped();
1348 $foundDefault = true;
1351 # Create preview link
1352 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1353 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1355 # Create links to user CSS/JS pages
1356 if ( $allowUserCss ) {
1357 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1358 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
1359 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
1362 if ( $allowUserJs ) {
1363 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1364 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
1365 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
1368 $display = $sn . ' ' . $context->msg( 'parentheses' )
1369 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1371 $ret[$display] = $skinkey;
1374 if ( !$foundDefault ) {
1375 // If the default skin is not available, things are going to break horribly because the
1376 // default value for skin selector will not be a valid value. Let's just not show it then.
1384 * @param IContextSource $context
1387 protected function getDateOptions( IContextSource
$context ) {
1388 $lang = $context->getLanguage();
1389 $dateopts = $lang->getDatePreferences();
1394 if ( !in_array( 'default', $dateopts ) ) {
1395 $dateopts[] = 'default'; // Make sure default is always valid T21237
1398 // FIXME KLUGE: site default might not be valid for user language
1399 global $wgDefaultUserOptions;
1400 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1401 $wgDefaultUserOptions['date'] = 'default';
1404 $epoch = wfTimestampNow();
1405 foreach ( $dateopts as $key ) {
1406 if ( $key == 'default' ) {
1407 $formatted = $context->msg( 'datedefault' )->escaped();
1409 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1411 $ret[$formatted] = $key;
1418 * @param MessageLocalizer $l10n
1421 protected function getImageSizes( MessageLocalizer
$l10n ) {
1423 $pixels = $l10n->msg( 'unit-pixel' )->text();
1425 foreach ( $this->config
->get( 'ImageLimits' ) as $index => $limits ) {
1426 // Note: A left-to-right marker (U+200E) is inserted, see T144386
1427 $display = "{$limits[0]}\u{200E}×{$limits[1]}$pixels";
1428 $ret[$display] = $index;
1435 * @param MessageLocalizer $l10n
1438 protected function getThumbSizes( MessageLocalizer
$l10n ) {
1440 $pixels = $l10n->msg( 'unit-pixel' )->text();
1442 foreach ( $this->config
->get( 'ThumbLimits' ) as $index => $size ) {
1443 $display = $size . $pixels;
1444 $ret[$display] = $index;
1451 * @param string $signature
1452 * @param array $alldata
1453 * @param HTMLForm $form
1454 * @return bool|string
1456 protected function validateSignature( $signature, $alldata, HTMLForm
$form ) {
1457 $maxSigChars = $this->config
->get( 'MaxSigChars' );
1458 if ( mb_strlen( $signature ) > $maxSigChars ) {
1459 return Xml
::element( 'span', [ 'class' => 'error' ],
1460 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1461 } elseif ( isset( $alldata['fancysig'] ) &&
1462 $alldata['fancysig'] &&
1463 MediaWikiServices
::getInstance()->getParser()->validateSig( $signature ) === false
1465 return Xml
::element(
1467 [ 'class' => 'error' ],
1468 $form->msg( 'badsig' )->text()
1476 * @param string $signature
1477 * @param array $alldata
1478 * @param HTMLForm $form
1481 protected function cleanSignature( $signature, $alldata, HTMLForm
$form ) {
1482 $parser = MediaWikiServices
::getInstance()->getParser();
1483 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1484 $signature = $parser->cleanSig( $signature );
1486 // When no fancy sig used, make sure ~{3,5} get removed.
1487 $signature = Parser
::cleanSigInSig( $signature );
1495 * @param IContextSource $context
1496 * @param string $formClass
1497 * @param array $remove Array of items to remove
1500 public function getForm(
1502 IContextSource
$context,
1503 $formClass = PreferencesFormLegacy
::class,
1506 if ( SpecialPreferences
::isOouiEnabled( $context ) ) {
1507 // We use ButtonWidgets in some of the getPreferences() functions
1508 $context->getOutput()->enableOOUI();
1511 $formDescriptor = $this->getFormDescriptor( $user, $context );
1512 if ( count( $remove ) ) {
1513 $removeKeys = array_flip( $remove );
1514 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1517 // Remove type=api preferences. They are not intended for rendering in the form.
1518 foreach ( $formDescriptor as $name => $info ) {
1519 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1520 unset( $formDescriptor[$name] );
1525 * @var $htmlForm HTMLForm
1527 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1529 $htmlForm->setModifiedUser( $user );
1530 $htmlForm->setId( 'mw-prefs-form' );
1531 $htmlForm->setAutocomplete( 'off' );
1532 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1533 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1534 $htmlForm->setSubmitTooltip( 'preferences-save' );
1535 $htmlForm->setSubmitID( 'prefcontrol' );
1536 $htmlForm->setSubmitCallback( function ( array $formData, HTMLForm
$form ) {
1537 return $this->submitForm( $formData, $form );
1544 * @param IContextSource $context
1547 protected function getTimezoneOptions( IContextSource
$context ) {
1550 $localTZoffset = $this->config
->get( 'LocalTZoffset' );
1551 $timeZoneList = $this->getTimeZoneList( $context->getLanguage() );
1553 $timestamp = MWTimestamp
::getLocalInstance();
1554 // Check that the LocalTZoffset is the same as the local time zone offset
1555 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1556 $timezoneName = $timestamp->getTimezone()->getName();
1557 // Localize timezone
1558 if ( isset( $timeZoneList[$timezoneName] ) ) {
1559 $timezoneName = $timeZoneList[$timezoneName]['name'];
1561 $server_tz_msg = $context->msg(
1562 'timezoneuseserverdefault',
1566 $tzstring = sprintf(
1568 floor( $localTZoffset / 60 ),
1569 abs( $localTZoffset ) %
60
1571 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1573 $opt[$server_tz_msg] = "System|$localTZoffset";
1574 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1575 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1577 foreach ( $timeZoneList as $timeZoneInfo ) {
1578 $region = $timeZoneInfo['region'];
1579 if ( !isset( $opt[$region] ) ) {
1582 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1589 * @param array $alldata
1592 protected function filterTimezoneInput( $tz, array $alldata ) {
1593 $data = explode( '|', $tz, 3 );
1594 switch ( $data[0] ) {
1598 if ( count( $data ) === 3 ) {
1599 // Make sure this timezone exists
1601 new DateTimeZone( $data[2] );
1602 // If the constructor didn't throw, we know it's valid
1604 } catch ( Exception
$e ) {
1605 // Not a valid timezone
1610 // If the supplied timezone doesn't exist, fall back to the encoded offset
1611 return 'Offset|' . intval( $tz[1] );
1617 $data = explode( ':', $tz, 2 );
1618 if ( count( $data ) == 2 ) {
1619 $data[0] = intval( $data[0] );
1620 $data[1] = intval( $data[1] );
1621 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1622 if ( $data[0] < 0 ) {
1623 $minDiff = - $minDiff;
1626 $minDiff = intval( $data[0] ) * 60;
1629 # Max is +14:00 and min is -12:00, see:
1630 # https://en.wikipedia.org/wiki/Timezone
1631 $minDiff = min( $minDiff, 840 ); # 14:00
1632 $minDiff = max( $minDiff, -720 ); # -12:00
1633 return 'Offset|' . $minDiff;
1638 * Handle the form submission if everything validated properly
1640 * @param array $formData
1641 * @param HTMLForm $form
1642 * @return bool|Status|string
1644 protected function saveFormData( $formData, HTMLForm
$form ) {
1645 $user = $form->getModifiedUser();
1646 $hiddenPrefs = $this->config
->get( 'HiddenPrefs' );
1649 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1650 return Status
::newFatal( 'mypreferencesprotected' );
1654 foreach ( array_keys( $formData ) as $name ) {
1655 $filters = $this->getSaveFilters();
1656 if ( isset( $filters[$name] ) ) {
1657 $formData[$name] = call_user_func( $filters[$name], $formData[$name], $formData );
1661 // Fortunately, the realname field is MUCH simpler
1662 // (not really "private", but still shouldn't be edited without permission)
1664 if ( !in_array( 'realname', $hiddenPrefs )
1665 && $user->isAllowed( 'editmyprivateinfo' )
1666 && array_key_exists( 'realname', $formData )
1668 $realName = $formData['realname'];
1669 $user->setRealName( $realName );
1672 if ( $user->isAllowed( 'editmyoptions' ) ) {
1673 $oldUserOptions = $user->getOptions();
1675 foreach ( $this->getSaveBlacklist() as $b ) {
1676 unset( $formData[$b] );
1679 # If users have saved a value for a preference which has subsequently been disabled
1680 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1681 # is subsequently re-enabled
1682 foreach ( $hiddenPrefs as $pref ) {
1683 # If the user has not set a non-default value here, the default will be returned
1684 # and subsequently discarded
1685 $formData[$pref] = $user->getOption( $pref, null, true );
1688 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1690 isset( $formData['rclimit'] ) &&
1691 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1693 $formData['rcfilters-limit'] = $formData['rclimit'];
1696 // Keep old preferences from interfering due to back-compat code, etc.
1697 $user->resetOptions( 'unused', $form->getContext() );
1699 foreach ( $formData as $key => $value ) {
1700 $user->setOption( $key, $value );
1704 'PreferencesFormPreSave',
1705 [ $formData, $form, $user, &$result, $oldUserOptions ]
1709 AuthManager
::callLegacyAuthPlugin( 'updateExternalDB', [ $user ] );
1710 $user->saveSettings();
1716 * DO NOT USE. Temporary function to punch hole for the Preferences class.
1718 * @deprecated since 1.31, its inception
1720 * @param array $formData
1721 * @param HTMLForm $form
1722 * @return bool|Status|string
1724 public function legacySaveFormData( $formData, HTMLForm
$form ) {
1725 return $this->saveFormData( $formData, $form );
1729 * Save the form data and reload the page
1731 * @param array $formData
1732 * @param HTMLForm $form
1735 protected function submitForm( array $formData, HTMLForm
$form ) {
1736 $res = $this->saveFormData( $formData, $form );
1738 if ( $res === true ) {
1739 $context = $form->getContext();
1742 if ( $res === 'eauth' ) {
1743 $urlOptions['eauth'] = 1;
1747 $context->getRequest()->getFuzzyBool( 'ooui' ) !==
1748 $context->getConfig()->get( 'OOUIPreferences' )
1750 $urlOptions[ 'ooui' ] = $context->getRequest()->getFuzzyBool( 'ooui' ) ?
1 : 0;
1753 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1755 $url = $form->getTitle()->getFullURL( $urlOptions );
1757 // Set session data for the success message
1758 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1760 $context->getOutput()->redirect( $url );
1763 return ( $res === true ? Status
::newGood() : $res );
1767 * DO NOT USE. Temporary function to punch hole for the Preferences class.
1769 * @deprecated since 1.31, its inception
1771 * @param array $formData
1772 * @param HTMLForm $form
1775 public function legacySubmitForm( array $formData, HTMLForm
$form ) {
1776 return $this->submitForm( $formData, $form );
1780 * Get a list of all time zones
1781 * @param Language $language Language used for the localized names
1782 * @return array A list of all time zones. The system name of the time zone is used as key and
1783 * the value is an array which contains localized name, the timecorrection value used for
1784 * preferences and the region
1787 protected function getTimeZoneList( Language
$language ) {
1788 $identifiers = DateTimeZone
::listIdentifiers();
1789 if ( $identifiers === false ) {
1792 sort( $identifiers );
1795 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1796 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1797 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1798 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1799 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1800 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1801 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1802 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1803 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1804 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1806 asort( $tzRegions );
1810 $now = new DateTime();
1812 foreach ( $identifiers as $identifier ) {
1813 $parts = explode( '/', $identifier, 2 );
1815 // DateTimeZone::listIdentifiers() returns a number of
1816 // backwards-compatibility entries. This filters them out of the
1817 // list presented to the user.
1818 if ( count( $parts ) !== 2 ||
!array_key_exists( $parts[0], $tzRegions ) ) {
1823 $parts[0] = $tzRegions[$parts[0]];
1825 $dateTimeZone = new DateTimeZone( $identifier );
1826 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1828 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1829 $value = "ZoneInfo|$minDiff|$identifier";
1831 $timeZoneList[$identifier] = [
1833 'timecorrection' => $value,
1834 'region' => $parts[0],
1838 return $timeZoneList;