3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 namespace MediaWiki\Preferences
;
34 use LanguageConverter
;
35 use MediaWiki\Auth\AuthManager
;
36 use MediaWiki\Auth\PasswordAuthenticationRequest
;
37 use MediaWiki\Config\ServiceOptions
;
38 use MediaWiki\Linker\LinkRenderer
;
39 use MediaWiki\MediaWikiServices
;
47 use PreferencesFormOOUI
;
48 use Psr\Log\LoggerAwareTrait
;
49 use Psr\Log\NullLogger
;
54 use UnexpectedValueException
;
56 use UserGroupMembership
;
60 * This is the default implementation of PreferencesFactory.
62 class DefaultPreferencesFactory
implements PreferencesFactory
{
65 /** @var ServiceOptions */
68 /** @var Language The wiki's content language. */
71 /** @var AuthManager */
72 protected $authManager;
74 /** @var LinkRenderer */
75 protected $linkRenderer;
77 /** @var NamespaceInfo */
81 * TODO Make this a const when we drop HHVM support (T192166)
86 public static $constructorOptions = [
91 'DisableLangConversion',
92 'EmailAuthentication',
96 'EnableUserEmailBlacklist',
98 'EnotifRevealEditorAddress',
107 'RCShowWatchingUsers',
108 'RCWatchCategoryMembership',
114 * Do not call this directly. Get it from MediaWikiServices.
116 * @param ServiceOptions|Config $options Config accepted for backwards compatibility
117 * @param Language $contLang
118 * @param AuthManager $authManager
119 * @param LinkRenderer $linkRenderer
120 * @param NamespaceInfo|null $nsInfo
122 public function __construct(
125 AuthManager
$authManager,
126 LinkRenderer
$linkRenderer,
127 NamespaceInfo
$nsInfo = null
129 if ( $options instanceof Config
) {
130 wfDeprecated( __METHOD__
. ' with Config parameter', '1.34' );
131 $options = new ServiceOptions( self
::$constructorOptions, $options );
134 $options->assertRequiredOptions( self
::$constructorOptions );
137 wfDeprecated( __METHOD__
. ' with no NamespaceInfo argument', '1.34' );
138 $nsInfo = MediaWikiServices
::getInstance()->getNamespaceInfo();
140 $this->options
= $options;
141 $this->contLang
= $contLang;
142 $this->authManager
= $authManager;
143 $this->linkRenderer
= $linkRenderer;
144 $this->nsInfo
= $nsInfo;
145 $this->logger
= new NullLogger();
151 public function getSaveBlacklist() {
159 * @throws MWException
161 * @param IContextSource $context
164 public function getFormDescriptor( User
$user, IContextSource
$context ) {
167 OutputPage
::setupOOUI(
168 strtolower( $context->getSkin()->getSkinName() ),
169 $context->getLanguage()->getDir()
172 $canIPUseHTTPS = wfCanIPUseHTTPS( $context->getRequest()->getIP() );
173 $this->profilePreferences( $user, $context, $preferences, $canIPUseHTTPS );
174 $this->skinPreferences( $user, $context, $preferences );
175 $this->datetimePreferences( $user, $context, $preferences );
176 $this->filesPreferences( $context, $preferences );
177 $this->renderingPreferences( $user, $context, $preferences );
178 $this->editingPreferences( $user, $context, $preferences );
179 $this->rcPreferences( $user, $context, $preferences );
180 $this->watchlistPreferences( $user, $context, $preferences );
181 $this->searchPreferences( $preferences );
183 Hooks
::run( 'GetPreferences', [ $user, &$preferences ] );
185 $this->loadPreferenceValues( $user, $context, $preferences );
186 $this->logger
->debug( "Created form descriptor for user '{$user->getName()}'" );
191 * Loads existing values for a given array of preferences
192 * @throws MWException
194 * @param IContextSource $context
195 * @param array &$defaultPreferences Array to load values for
198 private function loadPreferenceValues(
199 User
$user, IContextSource
$context, &$defaultPreferences
201 # # Remove preferences that wikis don't want to use
202 foreach ( $this->options
->get( 'HiddenPrefs' ) as $pref ) {
203 if ( isset( $defaultPreferences[$pref] ) ) {
204 unset( $defaultPreferences[$pref] );
208 # # Make sure that form fields have their parent set. See T43337.
209 $dummyForm = new HTMLForm( [], $context );
211 $disable = !$user->isAllowed( 'editmyoptions' );
213 $defaultOptions = User
::getDefaultOptions();
214 $userOptions = $user->getOptions();
215 $this->applyFilters( $userOptions, $defaultPreferences, 'filterForForm' );
216 # # Prod in defaults from the user
217 foreach ( $defaultPreferences as $name => &$info ) {
218 $prefFromUser = $this->getOptionFromUser( $name, $info, $userOptions );
219 if ( $disable && !in_array( $name, $this->getSaveBlacklist() ) ) {
220 $info['disabled'] = 'disabled';
222 $field = HTMLForm
::loadInputFromParameters( $name, $info, $dummyForm ); // For validation
223 $globalDefault = $defaultOptions[$name] ??
null;
225 // If it validates, set it as the default
226 if ( isset( $info['default'] ) ) {
227 // Already set, no problem
229 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
230 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
231 $info['default'] = $prefFromUser;
232 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
233 $info['default'] = $globalDefault;
235 $globalDefault = json_encode( $globalDefault );
236 throw new MWException(
237 "Default '$globalDefault' is invalid for preference $name of user $user"
242 return $defaultPreferences;
246 * Pull option from a user account. Handles stuff like array-type preferences.
248 * @param string $name
250 * @param array $userOptions
251 * @return array|string
253 protected function getOptionFromUser( $name, $info, array $userOptions ) {
254 $val = $userOptions[$name] ??
null;
256 // Handling for multiselect preferences
257 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
258 ( isset( $info['class'] ) && $info['class'] == \HTMLMultiSelectField
::class ) ) {
259 $options = HTMLFormField
::flattenOptions( $info['options'] );
260 $prefix = $info['prefix'] ??
$name;
263 foreach ( $options as $value ) {
264 if ( $userOptions["$prefix$value"] ??
false ) {
270 // Handling for checkmatrix preferences
271 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
272 ( isset( $info['class'] ) && $info['class'] == \HTMLCheckMatrix
::class ) ) {
273 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
274 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
275 $prefix = $info['prefix'] ??
$name;
278 foreach ( $columns as $column ) {
279 foreach ( $rows as $row ) {
280 if ( $userOptions["$prefix$column-$row"] ??
false ) {
281 $val[] = "$column-$row";
291 * @todo Inject user Language instead of using context.
293 * @param IContextSource $context
294 * @param array &$defaultPreferences
295 * @param bool $canIPUseHTTPS Whether the user's IP is likely to be able to access the wiki
299 protected function profilePreferences(
300 User
$user, IContextSource
$context, &$defaultPreferences, $canIPUseHTTPS
302 // retrieving user name for GENDER and misc.
303 $userName = $user->getName();
305 # # User info #####################################
307 $defaultPreferences['username'] = [
309 'label-message' => [ 'username', $userName ],
310 'default' => $userName,
311 'section' => 'personal/info',
314 $lang = $context->getLanguage();
316 # Get groups to which the user belongs
317 $userEffectiveGroups = $user->getEffectiveGroups();
318 $userGroupMemberships = $user->getGroupMemberships();
319 $userGroups = $userMembers = $userTempGroups = $userTempMembers = [];
320 foreach ( $userEffectiveGroups as $ueg ) {
322 // Skip the default * group, seems useless here
326 $groupStringOrObject = $userGroupMemberships[$ueg] ??
$ueg;
328 $userG = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html' );
329 $userM = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html',
332 // Store expiring groups separately, so we can place them before non-expiring
333 // groups in the list. This is to avoid the ambiguity of something like
334 // "administrator, bureaucrat (until X date)" -- users might wonder whether the
335 // expiry date applies to both groups, or just the last one
336 if ( $groupStringOrObject instanceof UserGroupMembership
&&
337 $groupStringOrObject->getExpiry()
339 $userTempGroups[] = $userG;
340 $userTempMembers[] = $userM;
342 $userGroups[] = $userG;
343 $userMembers[] = $userM;
347 sort( $userMembers );
348 sort( $userTempGroups );
349 sort( $userTempMembers );
350 $userGroups = array_merge( $userTempGroups, $userGroups );
351 $userMembers = array_merge( $userTempMembers, $userMembers );
353 $defaultPreferences['usergroups'] = [
355 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
356 count( $userGroups ) )->params( $userName )->parse(),
357 'default' => $context->msg( 'prefs-memberingroups-type' )
358 ->rawParams( $lang->commaList( $userGroups ), $lang->commaList( $userMembers ) )
361 'section' => 'personal/info',
364 $contribTitle = SpecialPage
::getTitleFor( "Contributions", $userName );
365 $formattedEditCount = $lang->formatNum( $user->getEditCount() );
366 $editCount = $this->linkRenderer
->makeLink( $contribTitle, $formattedEditCount );
368 $defaultPreferences['editcount'] = [
371 'label-message' => 'prefs-edits',
372 'default' => $editCount,
373 'section' => 'personal/info',
376 if ( $user->getRegistration() ) {
377 $displayUser = $context->getUser();
378 $userRegistration = $user->getRegistration();
379 $defaultPreferences['registrationdate'] = [
381 'label-message' => 'prefs-registration',
382 'default' => $context->msg(
383 'prefs-registration-date-time',
384 $lang->userTimeAndDate( $userRegistration, $displayUser ),
385 $lang->userDate( $userRegistration, $displayUser ),
386 $lang->userTime( $userRegistration, $displayUser )
388 'section' => 'personal/info',
392 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
393 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
395 // Actually changeable stuff
396 $defaultPreferences['realname'] = [
397 // (not really "private", but still shouldn't be edited without permission)
398 'type' => $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'realname' )
400 'default' => $user->getRealName(),
401 'section' => 'personal/info',
402 'label-message' => 'yourrealname',
403 'help-message' => 'prefs-help-realname',
406 if ( $canEditPrivateInfo && $this->authManager
->allowsAuthenticationDataChange(
407 new PasswordAuthenticationRequest(), false )->isGood()
409 $defaultPreferences['password'] = [
412 'default' => (string)new \OOUI\
ButtonWidget( [
413 'href' => SpecialPage
::getTitleFor( 'ChangePassword' )->getLinkURL( [
414 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
416 'label' => $context->msg( 'prefs-resetpass' )->text(),
418 'label-message' => 'yourpassword',
419 'section' => 'personal/info',
422 // Only show prefershttps if secure login is turned on
423 if ( $this->options
->get( 'SecureLogin' ) && $canIPUseHTTPS ) {
424 $defaultPreferences['prefershttps'] = [
426 'label-message' => 'tog-prefershttps',
427 'help-message' => 'prefs-help-prefershttps',
428 'section' => 'personal/info'
432 $languages = Language
::fetchLanguageNames( null, 'mwfile' );
433 $languageCode = $this->options
->get( 'LanguageCode' );
434 if ( !array_key_exists( $languageCode, $languages ) ) {
435 $languages[$languageCode] = $languageCode;
436 // Sort the array again
441 foreach ( $languages as $code => $name ) {
442 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
443 $options[$display] = $code;
445 $defaultPreferences['language'] = [
447 'section' => 'personal/i18n',
448 'options' => $options,
449 'label-message' => 'yourlanguage',
452 $defaultPreferences['gender'] = [
454 'section' => 'personal/i18n',
456 $context->msg( 'parentheses' )
457 ->params( $context->msg( 'gender-unknown' )->plain() )
458 ->escaped() => 'unknown',
459 $context->msg( 'gender-female' )->escaped() => 'female',
460 $context->msg( 'gender-male' )->escaped() => 'male',
462 'label-message' => 'yourgender',
463 'help-message' => 'prefs-help-gender',
466 // see if there are multiple language variants to choose from
467 if ( !$this->options
->get( 'DisableLangConversion' ) ) {
468 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
469 if ( $langCode == $this->contLang
->getCode() ) {
470 if ( !$this->contLang
->hasVariants() ) {
474 $variants = $this->contLang
->getVariants();
476 foreach ( $variants as $v ) {
477 $v = str_replace( '_', '-', strtolower( $v ) );
478 $variantArray[$v] = $lang->getVariantname( $v, false );
482 foreach ( $variantArray as $code => $name ) {
483 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
484 $options[$display] = $code;
487 $defaultPreferences['variant'] = [
488 'label-message' => 'yourvariant',
490 'options' => $options,
491 'section' => 'personal/i18n',
492 'help-message' => 'prefs-help-variant',
495 $defaultPreferences["variant-$langCode"] = [
502 // show a preview of the old signature first
503 $oldsigWikiText = MediaWikiServices
::getInstance()->getParser()->preSaveTransform(
505 $context->getTitle(),
507 ParserOptions
::newFromContext( $context )
509 $oldsigHTML = Parser
::stripOuterParagraph(
510 $context->getOutput()->parseAsContent( $oldsigWikiText )
512 $defaultPreferences['oldsig'] = [
515 'label-message' => 'tog-oldsig',
516 'default' => $oldsigHTML,
517 'section' => 'personal/signature',
519 $defaultPreferences['nickname'] = [
520 'type' => $this->authManager
->allowsPropertyChange( 'nickname' ) ?
'text' : 'info',
521 'maxlength' => $this->options
->get( 'MaxSigChars' ),
522 'label-message' => 'yournick',
523 'validation-callback' => function ( $signature, $alldata, HTMLForm
$form ) {
524 return $this->validateSignature( $signature, $alldata, $form );
526 'section' => 'personal/signature',
527 'filter-callback' => function ( $signature, array $alldata, HTMLForm
$form ) {
528 return $this->cleanSignature( $signature, $alldata, $form );
531 $defaultPreferences['fancysig'] = [
533 'label-message' => 'tog-fancysig',
534 // show general help about signature at the bottom of the section
535 'help-message' => 'prefs-help-signature',
536 'section' => 'personal/signature'
541 if ( $this->options
->get( 'EnableEmail' ) ) {
542 if ( $canViewPrivateInfo ) {
543 $helpMessages[] = $this->options
->get( 'EmailConfirmToEdit' )
544 ?
'prefs-help-email-required'
545 : 'prefs-help-email';
547 if ( $this->options
->get( 'EnableUserEmail' ) ) {
548 // additional messages when users can send email to each other
549 $helpMessages[] = 'prefs-help-email-others';
552 $emailAddress = $user->getEmail() ?
htmlspecialchars( $user->getEmail() ) : '';
553 if ( $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'emailaddress' ) ) {
554 $button = new \OOUI\
ButtonWidget( [
555 'href' => SpecialPage
::getTitleFor( 'ChangeEmail' )->getLinkURL( [
556 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
559 $context->msg( $user->getEmail() ?
'prefs-changeemail' : 'prefs-setemail' )->text(),
562 $emailAddress .= $emailAddress == '' ?
$button : ( '<br />' . $button );
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->options
->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 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
597 new \OOUI\
ButtonWidget( [
598 'href' => SpecialPage
::getTitleFor( 'Confirmemail' )->getLinkURL(),
599 'label' => $context->msg( 'emailconfirmlink' )->text(),
601 $emailauthenticationclass = "mw-email-not-authenticated";
604 $disableEmailPrefs = true;
605 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
606 $emailauthenticationclass = 'mw-email-none';
609 if ( $canViewPrivateInfo ) {
610 $defaultPreferences['emailauthentication'] = [
613 'section' => 'personal/email',
614 'label-message' => 'prefs-emailconfirm-label',
615 'default' => $emailauthenticated,
616 # Apply the same CSS class used on the input to the message:
617 'cssclass' => $emailauthenticationclass,
622 if ( $this->options
->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
623 $defaultPreferences['disablemail'] = [
624 'id' => 'wpAllowEmail',
627 'section' => 'personal/email',
628 'label-message' => 'allowemail',
629 'disabled' => $disableEmailPrefs,
632 $defaultPreferences['email-allow-new-users'] = [
633 'id' => 'wpAllowEmailFromNewUsers',
635 'section' => 'personal/email',
636 'label-message' => 'email-allow-new-users-label',
637 'disabled' => $disableEmailPrefs,
640 $defaultPreferences['ccmeonemails'] = [
642 'section' => 'personal/email',
643 'label-message' => 'tog-ccmeonemails',
644 'disabled' => $disableEmailPrefs,
647 if ( $this->options
->get( 'EnableUserEmailBlacklist' ) ) {
648 $defaultPreferences['email-blacklist'] = [
649 'type' => 'usersmultiselect',
650 'label-message' => 'email-blacklist-label',
651 'section' => 'personal/email',
652 'disabled' => $disableEmailPrefs,
653 'filter' => MultiUsernameFilter
::class,
658 if ( $this->options
->get( 'EnotifWatchlist' ) ) {
659 $defaultPreferences['enotifwatchlistpages'] = [
661 'section' => 'personal/email',
662 'label-message' => 'tog-enotifwatchlistpages',
663 'disabled' => $disableEmailPrefs,
666 if ( $this->options
->get( 'EnotifUserTalk' ) ) {
667 $defaultPreferences['enotifusertalkpages'] = [
669 'section' => 'personal/email',
670 'label-message' => 'tog-enotifusertalkpages',
671 'disabled' => $disableEmailPrefs,
674 if ( $this->options
->get( 'EnotifUserTalk' ) ||
675 $this->options
->get( 'EnotifWatchlist' ) ) {
676 if ( $this->options
->get( 'EnotifMinorEdits' ) ) {
677 $defaultPreferences['enotifminoredits'] = [
679 'section' => 'personal/email',
680 'label-message' => 'tog-enotifminoredits',
681 'disabled' => $disableEmailPrefs,
685 if ( $this->options
->get( 'EnotifRevealEditorAddress' ) ) {
686 $defaultPreferences['enotifrevealaddr'] = [
688 'section' => 'personal/email',
689 'label-message' => 'tog-enotifrevealaddr',
690 'disabled' => $disableEmailPrefs,
699 * @param IContextSource $context
700 * @param array &$defaultPreferences
703 protected function skinPreferences( User
$user, IContextSource
$context, &$defaultPreferences ) {
704 # # Skin #####################################
706 // Skin selector, if there is at least one valid skin
707 $skinOptions = $this->generateSkinOptions( $user, $context );
708 if ( $skinOptions ) {
709 $defaultPreferences['skin'] = [
711 'options' => $skinOptions,
712 'section' => 'rendering/skin',
716 $allowUserCss = $this->options
->get( 'AllowUserCss' );
717 $allowUserJs = $this->options
->get( 'AllowUserJs' );
718 # Create links to user CSS/JS pages for all skins
719 # This code is basically copied from generateSkinOptions(). It'd
720 # be nice to somehow merge this back in there to avoid redundancy.
721 if ( $allowUserCss ||
$allowUserJs ) {
723 $userName = $user->getName();
725 if ( $allowUserCss ) {
726 $cssPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.css' );
727 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
728 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
731 if ( $allowUserJs ) {
732 $jsPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.js' );
733 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
734 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
737 $defaultPreferences['commoncssjs'] = [
740 'default' => $context->getLanguage()->pipeList( $linkTools ),
741 'label-message' => 'prefs-common-config',
742 'section' => 'rendering/skin',
748 * @param IContextSource $context
749 * @param array &$defaultPreferences
751 protected function filesPreferences( IContextSource
$context, &$defaultPreferences ) {
752 # # Files #####################################
753 $defaultPreferences['imagesize'] = [
755 'options' => $this->getImageSizes( $context ),
756 'label-message' => 'imagemaxsize',
757 'section' => 'rendering/files',
759 $defaultPreferences['thumbsize'] = [
761 'options' => $this->getThumbSizes( $context ),
762 'label-message' => 'thumbsize',
763 'section' => 'rendering/files',
769 * @param IContextSource $context
770 * @param array &$defaultPreferences
773 protected function datetimePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
774 # # Date and time #####################################
775 $dateOptions = $this->getDateOptions( $context );
776 if ( $dateOptions ) {
777 $defaultPreferences['date'] = [
779 'options' => $dateOptions,
780 'section' => 'rendering/dateformat',
785 $now = wfTimestampNow();
786 $lang = $context->getLanguage();
787 $nowlocal = Xml
::element( 'span', [ 'id' => 'wpLocalTime' ],
788 $lang->userTime( $now, $user ) );
789 $nowserver = $lang->userTime( $now, $user,
790 [ 'format' => false, 'timecorrection' => false ] ) .
791 Html
::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 +
(int)substr( $now, 10, 2 ) );
793 $defaultPreferences['nowserver'] = [
796 'label-message' => 'servertime',
797 'default' => $nowserver,
798 'section' => 'rendering/timeoffset',
801 $defaultPreferences['nowlocal'] = [
804 'label-message' => 'localtime',
805 'default' => $nowlocal,
806 'section' => 'rendering/timeoffset',
809 // Grab existing pref.
810 $tzOffset = $user->getOption( 'timecorrection' );
811 $tz = explode( '|', $tzOffset, 3 );
813 $tzOptions = $this->getTimezoneOptions( $context );
815 $tzSetting = $tzOffset;
816 if ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
817 !in_array( $tzOffset, HTMLFormField
::flattenOptions( $tzOptions ) )
819 // Timezone offset can vary with DST
821 $userTZ = new DateTimeZone( $tz[2] );
822 $minDiff = floor( $userTZ->getOffset( new DateTime( 'now' ) ) / 60 );
823 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
824 } catch ( Exception
$e ) {
825 // User has an invalid time zone set. Fall back to just using the offset
829 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
831 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) %
60 );
834 $defaultPreferences['timecorrection'] = [
835 'class' => \HTMLSelectOrOtherField
::class,
836 'label-message' => 'timezonelegend',
837 'options' => $tzOptions,
838 'default' => $tzSetting,
840 'section' => 'rendering/timeoffset',
841 'id' => 'wpTimeCorrection',
842 'filter' => TimezoneFilter
::class,
843 'placeholder-message' => 'timezone-useoffset-placeholder',
849 * @param MessageLocalizer $l10n
850 * @param array &$defaultPreferences
852 protected function renderingPreferences(
854 MessageLocalizer
$l10n,
857 # # Diffs ####################################
858 $defaultPreferences['diffonly'] = [
860 'section' => 'rendering/diffs',
861 'label-message' => 'tog-diffonly',
863 $defaultPreferences['norollbackdiff'] = [
865 'section' => 'rendering/diffs',
866 'label-message' => 'tog-norollbackdiff',
869 # # Page Rendering ##############################
870 if ( $this->options
->get( 'AllowUserCssPrefs' ) ) {
871 $defaultPreferences['underline'] = [
874 $l10n->msg( 'underline-never' )->text() => 0,
875 $l10n->msg( 'underline-always' )->text() => 1,
876 $l10n->msg( 'underline-default' )->text() => 2,
878 'label-message' => 'tog-underline',
879 'section' => 'rendering/advancedrendering',
883 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
884 $stubThresholdOptions = [ $l10n->msg( 'stub-threshold-disabled' )->text() => 0 ];
885 foreach ( $stubThresholdValues as $value ) {
886 $stubThresholdOptions[$l10n->msg( 'size-bytes', $value )->text()] = $value;
889 $defaultPreferences['stubthreshold'] = [
891 'section' => 'rendering/advancedrendering',
892 'options' => $stubThresholdOptions,
893 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
894 'label-raw' => $l10n->msg( 'stub-threshold' )->rawParams(
896 $l10n->msg( 'stub-threshold-sample-link' )->parse() .
900 $defaultPreferences['showhiddencats'] = [
902 'section' => 'rendering/advancedrendering',
903 'label-message' => 'tog-showhiddencats'
906 $defaultPreferences['numberheadings'] = [
908 'section' => 'rendering/advancedrendering',
909 'label-message' => 'tog-numberheadings',
912 if ( $user->isAllowed( 'rollback' ) ) {
913 $defaultPreferences['showrollbackconfirmation'] = [
915 'section' => 'rendering/advancedrendering',
916 'label-message' => 'tog-showrollbackconfirmation',
923 * @param MessageLocalizer $l10n
924 * @param array &$defaultPreferences
926 protected function editingPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
927 # # Editing #####################################
928 $defaultPreferences['editsectiononrightclick'] = [
930 'section' => 'editing/advancedediting',
931 'label-message' => 'tog-editsectiononrightclick',
933 $defaultPreferences['editondblclick'] = [
935 'section' => 'editing/advancedediting',
936 'label-message' => 'tog-editondblclick',
939 if ( $this->options
->get( 'AllowUserCssPrefs' ) ) {
940 $defaultPreferences['editfont'] = [
942 'section' => 'editing/editor',
943 'label-message' => 'editfont-style',
945 $l10n->msg( 'editfont-monospace' )->text() => 'monospace',
946 $l10n->msg( 'editfont-sansserif' )->text() => 'sans-serif',
947 $l10n->msg( 'editfont-serif' )->text() => 'serif',
952 if ( $user->isAllowed( 'minoredit' ) ) {
953 $defaultPreferences['minordefault'] = [
955 'section' => 'editing/editor',
956 'label-message' => 'tog-minordefault',
960 $defaultPreferences['forceeditsummary'] = [
962 'section' => 'editing/editor',
963 'label-message' => 'tog-forceeditsummary',
965 $defaultPreferences['useeditwarning'] = [
967 'section' => 'editing/editor',
968 'label-message' => 'tog-useeditwarning',
971 $defaultPreferences['previewonfirst'] = [
973 'section' => 'editing/preview',
974 'label-message' => 'tog-previewonfirst',
976 $defaultPreferences['previewontop'] = [
978 'section' => 'editing/preview',
979 'label-message' => 'tog-previewontop',
981 $defaultPreferences['uselivepreview'] = [
983 'section' => 'editing/preview',
984 'label-message' => 'tog-uselivepreview',
990 * @param MessageLocalizer $l10n
991 * @param array &$defaultPreferences
993 protected function rcPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
994 $rcMaxAge = $this->options
->get( 'RCMaxAge' );
995 # # RecentChanges #####################################
996 $defaultPreferences['rcdays'] = [
998 'label-message' => 'recentchangesdays',
999 'section' => 'rc/displayrc',
1001 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
1002 'help' => $l10n->msg( 'recentchangesdays-max' )->numParams(
1003 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
1005 $defaultPreferences['rclimit'] = [
1009 'label-message' => 'recentchangescount',
1010 'help-message' => 'prefs-help-recentchangescount',
1011 'section' => 'rc/displayrc',
1012 'filter' => IntvalFilter
::class,
1014 $defaultPreferences['usenewrc'] = [
1016 'label-message' => 'tog-usenewrc',
1017 'section' => 'rc/advancedrc',
1019 $defaultPreferences['hideminor'] = [
1021 'label-message' => 'tog-hideminor',
1022 'section' => 'rc/changesrc',
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->options
->get( 'RCWatchCategoryMembership' ) ) {
1048 $defaultPreferences['hidecategorization'] = [
1050 'label-message' => 'tog-hidecategorization',
1051 'section' => 'rc/changesrc',
1055 if ( $user->useRCPatrol() ) {
1056 $defaultPreferences['hidepatrolled'] = [
1058 'section' => 'rc/changesrc',
1059 'label-message' => 'tog-hidepatrolled',
1063 if ( $user->useNPPatrol() ) {
1064 $defaultPreferences['newpageshidepatrolled'] = [
1066 'section' => 'rc/changesrc',
1067 'label-message' => 'tog-newpageshidepatrolled',
1071 if ( $this->options
->get( 'RCShowWatchingUsers' ) ) {
1072 $defaultPreferences['shownumberswatching'] = [
1074 'section' => 'rc/advancedrc',
1075 'label-message' => 'tog-shownumberswatching',
1079 $defaultPreferences['rcenhancedfilters-disable'] = [
1081 'section' => 'rc/advancedrc',
1082 'label-message' => 'rcfilters-preference-label',
1083 'help-message' => 'rcfilters-preference-help',
1089 * @param IContextSource $context
1090 * @param array &$defaultPreferences
1092 protected function watchlistPreferences(
1093 User
$user, IContextSource
$context, &$defaultPreferences
1095 $watchlistdaysMax = ceil( $this->options
->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1097 # # Watchlist #####################################
1098 if ( $user->isAllowed( 'editmywatchlist' ) ) {
1099 $editWatchlistLinks = '';
1100 $editWatchlistModes = [
1101 'edit' => [ 'subpage' => false, 'flags' => [] ],
1102 'raw' => [ 'subpage' => 'raw', 'flags' => [] ],
1103 'clear' => [ 'subpage' => 'clear', 'flags' => [ 'destructive' ] ],
1105 foreach ( $editWatchlistModes as $mode => $options ) {
1106 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1107 $editWatchlistLinks .=
1108 new \OOUI\
ButtonWidget( [
1109 'href' => SpecialPage
::getTitleFor( 'EditWatchlist', $options['subpage'] )->getLinkURL(),
1110 'flags' => $options[ 'flags' ],
1111 'label' => new \OOUI\
HtmlSnippet(
1112 $context->msg( "prefs-editwatchlist-{$mode}" )->parse()
1117 $defaultPreferences['editwatchlist'] = [
1120 'default' => $editWatchlistLinks,
1121 'label-message' => 'prefs-editwatchlist-label',
1122 'section' => 'watchlist/editwatchlist',
1126 $defaultPreferences['watchlistdays'] = [
1129 'max' => $watchlistdaysMax,
1130 'section' => 'watchlist/displaywatchlist',
1131 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1132 $watchlistdaysMax )->escaped(),
1133 'label-message' => 'prefs-watchlist-days',
1135 $defaultPreferences['wllimit'] = [
1139 'label-message' => 'prefs-watchlist-edits',
1140 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1141 'section' => 'watchlist/displaywatchlist',
1142 'filter' => IntvalFilter
::class,
1144 $defaultPreferences['extendwatchlist'] = [
1146 'section' => 'watchlist/advancedwatchlist',
1147 'label-message' => 'tog-extendwatchlist',
1149 $defaultPreferences['watchlisthideminor'] = [
1151 'section' => 'watchlist/changeswatchlist',
1152 'label-message' => 'tog-watchlisthideminor',
1154 $defaultPreferences['watchlisthidebots'] = [
1156 'section' => 'watchlist/changeswatchlist',
1157 'label-message' => 'tog-watchlisthidebots',
1159 $defaultPreferences['watchlisthideown'] = [
1161 'section' => 'watchlist/changeswatchlist',
1162 'label-message' => 'tog-watchlisthideown',
1164 $defaultPreferences['watchlisthideanons'] = [
1166 'section' => 'watchlist/changeswatchlist',
1167 'label-message' => 'tog-watchlisthideanons',
1169 $defaultPreferences['watchlisthideliu'] = [
1171 'section' => 'watchlist/changeswatchlist',
1172 'label-message' => 'tog-watchlisthideliu',
1175 if ( !\SpecialWatchlist
::checkStructuredFilterUiEnabled( $user ) ) {
1176 $defaultPreferences['watchlistreloadautomatically'] = [
1178 'section' => 'watchlist/advancedwatchlist',
1179 'label-message' => 'tog-watchlistreloadautomatically',
1183 $defaultPreferences['watchlistunwatchlinks'] = [
1185 'section' => 'watchlist/advancedwatchlist',
1186 'label-message' => 'tog-watchlistunwatchlinks',
1189 if ( $this->options
->get( 'RCWatchCategoryMembership' ) ) {
1190 $defaultPreferences['watchlisthidecategorization'] = [
1192 'section' => 'watchlist/changeswatchlist',
1193 'label-message' => 'tog-watchlisthidecategorization',
1197 if ( $user->useRCPatrol() ) {
1198 $defaultPreferences['watchlisthidepatrolled'] = [
1200 'section' => 'watchlist/changeswatchlist',
1201 'label-message' => 'tog-watchlisthidepatrolled',
1206 'edit' => 'watchdefault',
1207 'move' => 'watchmoves',
1208 'delete' => 'watchdeletion'
1212 if ( $user->isAllowed( 'createpage' ) ||
$user->isAllowed( 'createtalk' ) ) {
1213 $watchTypes['read'] = 'watchcreations';
1216 if ( $user->isAllowed( 'rollback' ) ) {
1217 $watchTypes['rollback'] = 'watchrollback';
1220 if ( $user->isAllowed( 'upload' ) ) {
1221 $watchTypes['upload'] = 'watchuploads';
1224 foreach ( $watchTypes as $action => $pref ) {
1225 if ( $user->isAllowed( $action ) ) {
1227 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1228 // tog-watchrollback
1229 $defaultPreferences[$pref] = [
1231 'section' => 'watchlist/pageswatchlist',
1232 'label-message' => "tog-$pref",
1237 $defaultPreferences['watchlisttoken'] = [
1241 $tokenButton = new \OOUI\
ButtonWidget( [
1242 'href' => SpecialPage
::getTitleFor( 'ResetTokens' )->getLinkURL( [
1243 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
1245 'label' => $context->msg( 'prefs-watchlist-managetokens' )->text(),
1247 $defaultPreferences['watchlisttoken-info'] = [
1249 'section' => 'watchlist/tokenwatchlist',
1250 'label-message' => 'prefs-watchlist-token',
1251 'help-message' => 'prefs-help-tokenmanagement',
1253 'default' => (string)$tokenButton,
1256 $defaultPreferences['wlenhancedfilters-disable'] = [
1258 'section' => 'watchlist/advancedwatchlist',
1259 'label-message' => 'rcfilters-watchlist-preference-label',
1260 'help-message' => 'rcfilters-watchlist-preference-help',
1265 * @param array &$defaultPreferences
1267 protected function searchPreferences( &$defaultPreferences ) {
1268 foreach ( $this->nsInfo
->getValidNamespaces() as $n ) {
1269 $defaultPreferences['searchNs' . $n] = [
1276 * @param User $user The User object
1277 * @param IContextSource $context
1278 * @return array Text/links to display as key; $skinkey as value
1280 protected function generateSkinOptions( User
$user, IContextSource
$context ) {
1283 $mptitle = Title
::newMainPage();
1284 $previewtext = $context->msg( 'skin-preview' )->escaped();
1286 # Only show skins that aren't disabled in $wgSkipSkins
1287 $validSkinNames = Skin
::getAllowedSkins();
1288 $allInstalledSkins = Skin
::getSkinNames();
1290 // Display the installed skin the user has specifically requested via useskin=….
1291 $useSkin = $context->getRequest()->getRawVal( 'useskin' );
1292 if ( isset( $allInstalledSkins[$useSkin] )
1293 && $context->msg( "skinname-$useSkin" )->exists()
1295 $validSkinNames[$useSkin] = $useSkin;
1298 // Display the skin if the user has set it as a preference already before it was hidden.
1299 $currentUserSkin = $user->getOption( 'skin' );
1300 if ( isset( $allInstalledSkins[$currentUserSkin] )
1301 && $context->msg( "skinname-$currentUserSkin" )->exists()
1303 $validSkinNames[$currentUserSkin] = $currentUserSkin;
1306 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1307 $msg = $context->msg( "skinname-{$skinkey}" );
1308 if ( $msg->exists() ) {
1309 $skinname = htmlspecialchars( $msg->text() );
1313 $defaultSkin = $this->options
->get( 'DefaultSkin' );
1314 $allowUserCss = $this->options
->get( 'AllowUserCss' );
1315 $allowUserJs = $this->options
->get( 'AllowUserJs' );
1317 # Sort by the internal name, so that the ordering is the same for each display language,
1318 # especially if some skin names are translated to use a different alphabet and some are not.
1319 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1320 # Display the default first in the list by comparing it as lesser than any other.
1321 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1324 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1327 return strcasecmp( $a, $b );
1330 $foundDefault = false;
1331 foreach ( $validSkinNames as $skinkey => $sn ) {
1334 # Mark the default skin
1335 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1336 $linkTools[] = $context->msg( 'default' )->escaped();
1337 $foundDefault = true;
1340 # Create preview link
1341 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1342 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1344 # Create links to user CSS/JS pages
1345 if ( $allowUserCss ) {
1346 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1347 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
1348 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
1351 if ( $allowUserJs ) {
1352 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1353 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
1354 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
1357 $display = $sn . ' ' . $context->msg( 'parentheses' )
1358 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1360 $ret[$display] = $skinkey;
1363 if ( !$foundDefault ) {
1364 // If the default skin is not available, things are going to break horribly because the
1365 // default value for skin selector will not be a valid value. Let's just not show it then.
1373 * @param IContextSource $context
1376 protected function getDateOptions( IContextSource
$context ) {
1377 $lang = $context->getLanguage();
1378 $dateopts = $lang->getDatePreferences();
1383 if ( !in_array( 'default', $dateopts ) ) {
1384 $dateopts[] = 'default'; // Make sure default is always valid T21237
1387 // FIXME KLUGE: site default might not be valid for user language
1388 global $wgDefaultUserOptions;
1389 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1390 $wgDefaultUserOptions['date'] = 'default';
1393 $epoch = wfTimestampNow();
1394 foreach ( $dateopts as $key ) {
1395 if ( $key == 'default' ) {
1396 $formatted = $context->msg( 'datedefault' )->escaped();
1398 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1400 $ret[$formatted] = $key;
1407 * @param MessageLocalizer $l10n
1410 protected function getImageSizes( MessageLocalizer
$l10n ) {
1412 $pixels = $l10n->msg( 'unit-pixel' )->text();
1414 foreach ( $this->options
->get( 'ImageLimits' ) as $index => $limits ) {
1415 // Note: A left-to-right marker (U+200E) is inserted, see T144386
1416 $display = "{$limits[0]}\u{200E}×{$limits[1]}$pixels";
1417 $ret[$display] = $index;
1424 * @param MessageLocalizer $l10n
1427 protected function getThumbSizes( MessageLocalizer
$l10n ) {
1429 $pixels = $l10n->msg( 'unit-pixel' )->text();
1431 foreach ( $this->options
->get( 'ThumbLimits' ) as $index => $size ) {
1432 $display = $size . $pixels;
1433 $ret[$display] = $index;
1440 * @param string $signature
1441 * @param array $alldata
1442 * @param HTMLForm $form
1443 * @return bool|string
1445 protected function validateSignature( $signature, $alldata, HTMLForm
$form ) {
1446 $maxSigChars = $this->options
->get( 'MaxSigChars' );
1447 if ( mb_strlen( $signature ) > $maxSigChars ) {
1448 return Xml
::element( 'span', [ 'class' => 'error' ],
1449 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1450 } elseif ( isset( $alldata['fancysig'] ) &&
1451 $alldata['fancysig'] &&
1452 MediaWikiServices
::getInstance()->getParser()->validateSig( $signature ) === false
1454 return Xml
::element(
1456 [ 'class' => 'error' ],
1457 $form->msg( 'badsig' )->text()
1465 * @param string $signature
1466 * @param array $alldata
1467 * @param HTMLForm $form
1470 protected function cleanSignature( $signature, $alldata, HTMLForm
$form ) {
1471 $parser = MediaWikiServices
::getInstance()->getParser();
1472 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1473 $signature = $parser->cleanSig( $signature );
1475 // When no fancy sig used, make sure ~{3,5} get removed.
1476 $signature = Parser
::cleanSigInSig( $signature );
1484 * @param IContextSource $context
1485 * @param string $formClass
1486 * @param array $remove Array of items to remove
1489 public function getForm(
1491 IContextSource
$context,
1492 $formClass = PreferencesFormOOUI
::class,
1495 // We use ButtonWidgets in some of the getPreferences() functions
1496 $context->getOutput()->enableOOUI();
1498 $formDescriptor = $this->getFormDescriptor( $user, $context );
1499 if ( count( $remove ) ) {
1500 $removeKeys = array_flip( $remove );
1501 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1504 // Remove type=api preferences. They are not intended for rendering in the form.
1505 foreach ( $formDescriptor as $name => $info ) {
1506 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1507 unset( $formDescriptor[$name] );
1512 * @var HTMLForm $htmlForm
1514 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1516 // This allows users to opt-in to hidden skins. While this should be discouraged and is not
1517 // discoverable, this allows users to still use hidden skins while preventing new users from
1518 // adopting unsupported skins. If no useskin=… parameter was provided, it will not show up
1519 // in the resulting URL.
1520 $htmlForm->setAction( $context->getTitle()->getLocalURL( [
1521 'useskin' => $context->getRequest()->getRawVal( 'useskin' )
1524 $htmlForm->setModifiedUser( $user );
1525 $htmlForm->setId( 'mw-prefs-form' );
1526 $htmlForm->setAutocomplete( 'off' );
1527 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1528 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1529 $htmlForm->setSubmitTooltip( 'preferences-save' );
1530 $htmlForm->setSubmitID( 'prefcontrol' );
1531 $htmlForm->setSubmitCallback(
1532 function ( array $formData, HTMLForm
$form ) use ( $formDescriptor ) {
1533 return $this->submitForm( $formData, $form, $formDescriptor );
1541 * @param IContextSource $context
1544 protected function getTimezoneOptions( IContextSource
$context ) {
1547 $localTZoffset = $this->options
->get( 'LocalTZoffset' );
1548 $timeZoneList = $this->getTimeZoneList( $context->getLanguage() );
1550 $timestamp = MWTimestamp
::getLocalInstance();
1551 // Check that the LocalTZoffset is the same as the local time zone offset
1552 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1553 $timezoneName = $timestamp->getTimezone()->getName();
1554 // Localize timezone
1555 if ( isset( $timeZoneList[$timezoneName] ) ) {
1556 $timezoneName = $timeZoneList[$timezoneName]['name'];
1558 $server_tz_msg = $context->msg(
1559 'timezoneuseserverdefault',
1563 $tzstring = sprintf(
1565 floor( $localTZoffset / 60 ),
1566 abs( $localTZoffset ) %
60
1568 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1570 $opt[$server_tz_msg] = "System|$localTZoffset";
1571 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1572 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1574 foreach ( $timeZoneList as $timeZoneInfo ) {
1575 $region = $timeZoneInfo['region'];
1576 if ( !isset( $opt[$region] ) ) {
1579 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1585 * Handle the form submission if everything validated properly
1587 * @param array $formData
1588 * @param HTMLForm $form
1589 * @param array[] $formDescriptor
1590 * @return bool|Status|string
1592 protected function saveFormData( $formData, HTMLForm
$form, array $formDescriptor ) {
1593 /** @var \User $user */
1594 $user = $form->getModifiedUser();
1595 $hiddenPrefs = $this->options
->get( 'HiddenPrefs' );
1598 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1599 return Status
::newFatal( 'mypreferencesprotected' );
1603 $this->applyFilters( $formData, $formDescriptor, 'filterFromForm' );
1605 // Fortunately, the realname field is MUCH simpler
1606 // (not really "private", but still shouldn't be edited without permission)
1608 if ( !in_array( 'realname', $hiddenPrefs )
1609 && $user->isAllowed( 'editmyprivateinfo' )
1610 && array_key_exists( 'realname', $formData )
1612 $realName = $formData['realname'];
1613 $user->setRealName( $realName );
1616 if ( $user->isAllowed( 'editmyoptions' ) ) {
1617 $oldUserOptions = $user->getOptions();
1619 foreach ( $this->getSaveBlacklist() as $b ) {
1620 unset( $formData[$b] );
1623 # If users have saved a value for a preference which has subsequently been disabled
1624 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1625 # is subsequently re-enabled
1626 foreach ( $hiddenPrefs as $pref ) {
1627 # If the user has not set a non-default value here, the default will be returned
1628 # and subsequently discarded
1629 $formData[$pref] = $user->getOption( $pref, null, true );
1632 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1634 isset( $formData['rclimit'] ) &&
1635 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1637 $formData['rcfilters-limit'] = $formData['rclimit'];
1640 // Keep old preferences from interfering due to back-compat code, etc.
1641 $user->resetOptions( 'unused', $form->getContext() );
1643 foreach ( $formData as $key => $value ) {
1644 $user->setOption( $key, $value );
1648 'PreferencesFormPreSave',
1649 [ $formData, $form, $user, &$result, $oldUserOptions ]
1653 $user->saveSettings();
1659 * Applies filters to preferences either before or after form usage
1661 * @param array &$preferences
1662 * @param array $formDescriptor
1663 * @param string $verb Name of the filter method to call, either 'filterFromForm' or
1666 protected function applyFilters( array &$preferences, array $formDescriptor, $verb ) {
1667 foreach ( $formDescriptor as $preference => $desc ) {
1668 if ( !isset( $desc['filter'] ) ||
!isset( $preferences[$preference] ) ) {
1671 $filterDesc = $desc['filter'];
1672 if ( $filterDesc instanceof Filter
) {
1673 $filter = $filterDesc;
1674 } elseif ( class_exists( $filterDesc ) ) {
1675 $filter = new $filterDesc();
1676 } elseif ( is_callable( $filterDesc ) ) {
1677 $filter = $filterDesc();
1679 throw new UnexpectedValueException(
1680 "Unrecognized filter type for preference '$preference'"
1683 $preferences[$preference] = $filter->$verb( $preferences[$preference] );
1688 * Save the form data and reload the page
1690 * @param array $formData
1691 * @param HTMLForm $form
1692 * @param array $formDescriptor
1695 protected function submitForm( array $formData, HTMLForm
$form, array $formDescriptor ) {
1696 $res = $this->saveFormData( $formData, $form, $formDescriptor );
1698 if ( $res === true ) {
1699 $context = $form->getContext();
1702 if ( $res === 'eauth' ) {
1703 $urlOptions['eauth'] = 1;
1706 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1708 $url = $form->getTitle()->getFullURL( $urlOptions );
1710 // Set session data for the success message
1711 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1713 $context->getOutput()->redirect( $url );
1716 return ( $res === true ? Status
::newGood() : $res );
1720 * Get a list of all time zones
1721 * @param Language $language Language used for the localized names
1722 * @return array A list of all time zones. The system name of the time zone is used as key and
1723 * the value is an array which contains localized name, the timecorrection value used for
1724 * preferences and the region
1727 protected function getTimeZoneList( Language
$language ) {
1728 $identifiers = DateTimeZone
::listIdentifiers();
1729 if ( $identifiers === false ) {
1732 sort( $identifiers );
1735 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1736 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1737 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1738 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1739 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1740 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1741 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1742 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1743 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1744 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1746 asort( $tzRegions );
1750 $now = new DateTime();
1752 foreach ( $identifiers as $identifier ) {
1753 $parts = explode( '/', $identifier, 2 );
1755 // DateTimeZone::listIdentifiers() returns a number of
1756 // backwards-compatibility entries. This filters them out of the
1757 // list presented to the user.
1758 if ( count( $parts ) !== 2 ||
!array_key_exists( $parts[0], $tzRegions ) ) {
1763 $parts[0] = $tzRegions[$parts[0]];
1765 $dateTimeZone = new DateTimeZone( $identifier );
1766 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1768 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1769 $value = "ZoneInfo|$minDiff|$identifier";
1771 $timeZoneList[$identifier] = [
1773 'timecorrection' => $value,
1774 'region' => $parts[0],
1778 return $timeZoneList;