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;
78 * TODO Make this a const when we drop HHVM support (T192166)
83 public static $constructorOptions = [
88 'DisableLangConversion',
89 'EmailAuthentication',
93 'EnableUserEmailBlacklist',
95 'EnotifRevealEditorAddress',
104 'RCShowWatchingUsers',
105 'RCWatchCategoryMembership',
111 * @param array|Config $options Config accepted for backwards compatibility
112 * @param Language $contLang
113 * @param AuthManager $authManager
114 * @param LinkRenderer $linkRenderer
116 public function __construct(
119 AuthManager
$authManager,
120 LinkRenderer
$linkRenderer
122 if ( $options instanceof Config
) {
123 wfDeprecated( __METHOD__
. ' with Config parameter', '1.34' );
124 $options = new ServiceOptions( self
::$constructorOptions, $options );
127 $options->assertRequiredOptions( self
::$constructorOptions );
129 $this->options
= $options;
130 $this->contLang
= $contLang;
131 $this->authManager
= $authManager;
132 $this->linkRenderer
= $linkRenderer;
133 $this->logger
= new NullLogger();
139 public function getSaveBlacklist() {
147 * @throws MWException
149 * @param IContextSource $context
152 public function getFormDescriptor( User
$user, IContextSource
$context ) {
155 OutputPage
::setupOOUI(
156 strtolower( $context->getSkin()->getSkinName() ),
157 $context->getLanguage()->getDir()
160 $canIPUseHTTPS = wfCanIPUseHTTPS( $context->getRequest()->getIP() );
161 $this->profilePreferences( $user, $context, $preferences, $canIPUseHTTPS );
162 $this->skinPreferences( $user, $context, $preferences );
163 $this->datetimePreferences( $user, $context, $preferences );
164 $this->filesPreferences( $context, $preferences );
165 $this->renderingPreferences( $user, $context, $preferences );
166 $this->editingPreferences( $user, $context, $preferences );
167 $this->rcPreferences( $user, $context, $preferences );
168 $this->watchlistPreferences( $user, $context, $preferences );
169 $this->searchPreferences( $preferences );
171 Hooks
::run( 'GetPreferences', [ $user, &$preferences ] );
173 $this->loadPreferenceValues( $user, $context, $preferences );
174 $this->logger
->debug( "Created form descriptor for user '{$user->getName()}'" );
179 * Loads existing values for a given array of preferences
180 * @throws MWException
182 * @param IContextSource $context
183 * @param array &$defaultPreferences Array to load values for
186 private function loadPreferenceValues(
187 User
$user, IContextSource
$context, &$defaultPreferences
189 # # Remove preferences that wikis don't want to use
190 foreach ( $this->options
->get( 'HiddenPrefs' ) as $pref ) {
191 if ( isset( $defaultPreferences[$pref] ) ) {
192 unset( $defaultPreferences[$pref] );
196 # # Make sure that form fields have their parent set. See T43337.
197 $dummyForm = new HTMLForm( [], $context );
199 $disable = !$user->isAllowed( 'editmyoptions' );
201 $defaultOptions = User
::getDefaultOptions();
202 $userOptions = $user->getOptions();
203 $this->applyFilters( $userOptions, $defaultPreferences, 'filterForForm' );
204 # # Prod in defaults from the user
205 foreach ( $defaultPreferences as $name => &$info ) {
206 $prefFromUser = $this->getOptionFromUser( $name, $info, $userOptions );
207 if ( $disable && !in_array( $name, $this->getSaveBlacklist() ) ) {
208 $info['disabled'] = 'disabled';
210 $field = HTMLForm
::loadInputFromParameters( $name, $info, $dummyForm ); // For validation
211 $globalDefault = $defaultOptions[$name] ??
null;
213 // If it validates, set it as the default
214 if ( isset( $info['default'] ) ) {
215 // Already set, no problem
217 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
218 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
219 $info['default'] = $prefFromUser;
220 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
221 $info['default'] = $globalDefault;
223 throw new MWException( "Global default '$globalDefault' is invalid for field $name" );
227 return $defaultPreferences;
231 * Pull option from a user account. Handles stuff like array-type preferences.
233 * @param string $name
235 * @param array $userOptions
236 * @return array|string
238 protected function getOptionFromUser( $name, $info, array $userOptions ) {
239 $val = $userOptions[$name] ??
null;
241 // Handling for multiselect preferences
242 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
243 ( isset( $info['class'] ) && $info['class'] == \HTMLMultiSelectField
::class ) ) {
244 $options = HTMLFormField
::flattenOptions( $info['options'] );
245 $prefix = $info['prefix'] ??
$name;
248 foreach ( $options as $value ) {
249 if ( $userOptions["$prefix$value"] ??
false ) {
255 // Handling for checkmatrix preferences
256 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
257 ( isset( $info['class'] ) && $info['class'] == \HTMLCheckMatrix
::class ) ) {
258 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
259 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
260 $prefix = $info['prefix'] ??
$name;
263 foreach ( $columns as $column ) {
264 foreach ( $rows as $row ) {
265 if ( $userOptions["$prefix$column-$row"] ??
false ) {
266 $val[] = "$column-$row";
276 * @todo Inject user Language instead of using context.
278 * @param IContextSource $context
279 * @param array &$defaultPreferences
280 * @param bool $canIPUseHTTPS Whether the user's IP is likely to be able to access the wiki
284 protected function profilePreferences(
285 User
$user, IContextSource
$context, &$defaultPreferences, $canIPUseHTTPS
287 // retrieving user name for GENDER and misc.
288 $userName = $user->getName();
290 # # User info #####################################
292 $defaultPreferences['username'] = [
294 'label-message' => [ 'username', $userName ],
295 'default' => $userName,
296 'section' => 'personal/info',
299 $lang = $context->getLanguage();
301 # Get groups to which the user belongs
302 $userEffectiveGroups = $user->getEffectiveGroups();
303 $userGroupMemberships = $user->getGroupMemberships();
304 $userGroups = $userMembers = $userTempGroups = $userTempMembers = [];
305 foreach ( $userEffectiveGroups as $ueg ) {
307 // Skip the default * group, seems useless here
311 $groupStringOrObject = $userGroupMemberships[$ueg] ??
$ueg;
313 $userG = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html' );
314 $userM = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html',
317 // Store expiring groups separately, so we can place them before non-expiring
318 // groups in the list. This is to avoid the ambiguity of something like
319 // "administrator, bureaucrat (until X date)" -- users might wonder whether the
320 // expiry date applies to both groups, or just the last one
321 if ( $groupStringOrObject instanceof UserGroupMembership
&&
322 $groupStringOrObject->getExpiry()
324 $userTempGroups[] = $userG;
325 $userTempMembers[] = $userM;
327 $userGroups[] = $userG;
328 $userMembers[] = $userM;
332 sort( $userMembers );
333 sort( $userTempGroups );
334 sort( $userTempMembers );
335 $userGroups = array_merge( $userTempGroups, $userGroups );
336 $userMembers = array_merge( $userTempMembers, $userMembers );
338 $defaultPreferences['usergroups'] = [
340 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
341 count( $userGroups ) )->params( $userName )->parse(),
342 'default' => $context->msg( 'prefs-memberingroups-type' )
343 ->rawParams( $lang->commaList( $userGroups ), $lang->commaList( $userMembers ) )
346 'section' => 'personal/info',
349 $contribTitle = SpecialPage
::getTitleFor( "Contributions", $userName );
350 $formattedEditCount = $lang->formatNum( $user->getEditCount() );
351 $editCount = $this->linkRenderer
->makeLink( $contribTitle, $formattedEditCount );
353 $defaultPreferences['editcount'] = [
356 'label-message' => 'prefs-edits',
357 'default' => $editCount,
358 'section' => 'personal/info',
361 if ( $user->getRegistration() ) {
362 $displayUser = $context->getUser();
363 $userRegistration = $user->getRegistration();
364 $defaultPreferences['registrationdate'] = [
366 'label-message' => 'prefs-registration',
367 'default' => $context->msg(
368 'prefs-registration-date-time',
369 $lang->userTimeAndDate( $userRegistration, $displayUser ),
370 $lang->userDate( $userRegistration, $displayUser ),
371 $lang->userTime( $userRegistration, $displayUser )
373 'section' => 'personal/info',
377 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
378 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
380 // Actually changeable stuff
381 $defaultPreferences['realname'] = [
382 // (not really "private", but still shouldn't be edited without permission)
383 'type' => $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'realname' )
385 'default' => $user->getRealName(),
386 'section' => 'personal/info',
387 'label-message' => 'yourrealname',
388 'help-message' => 'prefs-help-realname',
391 if ( $canEditPrivateInfo && $this->authManager
->allowsAuthenticationDataChange(
392 new PasswordAuthenticationRequest(), false )->isGood()
394 $defaultPreferences['password'] = [
397 'default' => (string)new \OOUI\
ButtonWidget( [
398 'href' => SpecialPage
::getTitleFor( 'ChangePassword' )->getLinkURL( [
399 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
401 'label' => $context->msg( 'prefs-resetpass' )->text(),
403 'label-message' => 'yourpassword',
404 'section' => 'personal/info',
407 // Only show prefershttps if secure login is turned on
408 if ( $this->options
->get( 'SecureLogin' ) && $canIPUseHTTPS ) {
409 $defaultPreferences['prefershttps'] = [
411 'label-message' => 'tog-prefershttps',
412 'help-message' => 'prefs-help-prefershttps',
413 'section' => 'personal/info'
417 $languages = Language
::fetchLanguageNames( null, 'mwfile' );
418 $languageCode = $this->options
->get( 'LanguageCode' );
419 if ( !array_key_exists( $languageCode, $languages ) ) {
420 $languages[$languageCode] = $languageCode;
421 // Sort the array again
426 foreach ( $languages as $code => $name ) {
427 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
428 $options[$display] = $code;
430 $defaultPreferences['language'] = [
432 'section' => 'personal/i18n',
433 'options' => $options,
434 'label-message' => 'yourlanguage',
437 $defaultPreferences['gender'] = [
439 'section' => 'personal/i18n',
441 $context->msg( 'parentheses' )
442 ->params( $context->msg( 'gender-unknown' )->plain() )
443 ->escaped() => 'unknown',
444 $context->msg( 'gender-female' )->escaped() => 'female',
445 $context->msg( 'gender-male' )->escaped() => 'male',
447 'label-message' => 'yourgender',
448 'help-message' => 'prefs-help-gender',
451 // see if there are multiple language variants to choose from
452 if ( !$this->options
->get( 'DisableLangConversion' ) ) {
453 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
454 if ( $langCode == $this->contLang
->getCode() ) {
455 if ( !$this->contLang
->hasVariants() ) {
459 $variants = $this->contLang
->getVariants();
461 foreach ( $variants as $v ) {
462 $v = str_replace( '_', '-', strtolower( $v ) );
463 $variantArray[$v] = $lang->getVariantname( $v, false );
467 foreach ( $variantArray as $code => $name ) {
468 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
469 $options[$display] = $code;
472 $defaultPreferences['variant'] = [
473 'label-message' => 'yourvariant',
475 'options' => $options,
476 'section' => 'personal/i18n',
477 'help-message' => 'prefs-help-variant',
480 $defaultPreferences["variant-$langCode"] = [
487 // Stuff from Language::getExtraUserToggles()
488 // FIXME is this dead code? $extraUserToggles doesn't seem to be defined for any language
489 $toggles = $this->contLang
->getExtraUserToggles();
491 foreach ( $toggles as $toggle ) {
492 $defaultPreferences[$toggle] = [
494 'section' => 'personal/i18n',
495 'label-message' => "tog-$toggle",
499 // show a preview of the old signature first
500 $oldsigWikiText = MediaWikiServices
::getInstance()->getParser()->preSaveTransform(
502 $context->getTitle(),
504 ParserOptions
::newFromContext( $context )
506 $oldsigHTML = Parser
::stripOuterParagraph(
507 $context->getOutput()->parseAsContent( $oldsigWikiText )
509 $defaultPreferences['oldsig'] = [
512 'label-message' => 'tog-oldsig',
513 'default' => $oldsigHTML,
514 'section' => 'personal/signature',
516 $defaultPreferences['nickname'] = [
517 'type' => $this->authManager
->allowsPropertyChange( 'nickname' ) ?
'text' : 'info',
518 'maxlength' => $this->options
->get( 'MaxSigChars' ),
519 'label-message' => 'yournick',
520 'validation-callback' => function ( $signature, $alldata, HTMLForm
$form ) {
521 return $this->validateSignature( $signature, $alldata, $form );
523 'section' => 'personal/signature',
524 'filter-callback' => function ( $signature, array $alldata, HTMLForm
$form ) {
525 return $this->cleanSignature( $signature, $alldata, $form );
528 $defaultPreferences['fancysig'] = [
530 'label-message' => 'tog-fancysig',
531 // show general help about signature at the bottom of the section
532 'help-message' => 'prefs-help-signature',
533 'section' => 'personal/signature'
538 if ( $this->options
->get( 'EnableEmail' ) ) {
539 if ( $canViewPrivateInfo ) {
540 $helpMessages[] = $this->options
->get( 'EmailConfirmToEdit' )
541 ?
'prefs-help-email-required'
542 : 'prefs-help-email';
544 if ( $this->options
->get( 'EnableUserEmail' ) ) {
545 // additional messages when users can send email to each other
546 $helpMessages[] = 'prefs-help-email-others';
549 $emailAddress = $user->getEmail() ?
htmlspecialchars( $user->getEmail() ) : '';
550 if ( $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'emailaddress' ) ) {
551 $button = new \OOUI\
ButtonWidget( [
552 'href' => SpecialPage
::getTitleFor( 'ChangeEmail' )->getLinkURL( [
553 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
556 $context->msg( $user->getEmail() ?
'prefs-changeemail' : 'prefs-setemail' )->text(),
559 $emailAddress .= $emailAddress == '' ?
$button : ( '<br />' . $button );
562 $defaultPreferences['emailaddress'] = [
565 'default' => $emailAddress,
566 'label-message' => 'youremail',
567 'section' => 'personal/email',
568 'help-messages' => $helpMessages,
569 # 'cssclass' chosen below
573 $disableEmailPrefs = false;
575 if ( $this->options
->get( 'EmailAuthentication' ) ) {
576 $emailauthenticationclass = 'mw-email-not-authenticated';
577 if ( $user->getEmail() ) {
578 if ( $user->getEmailAuthenticationTimestamp() ) {
579 // date and time are separate parameters to facilitate localisation.
580 // $time is kept for backward compat reasons.
581 // 'emailauthenticated' is also used in SpecialConfirmemail.php
582 $displayUser = $context->getUser();
583 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
584 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
585 $d = $lang->userDate( $emailTimestamp, $displayUser );
586 $t = $lang->userTime( $emailTimestamp, $displayUser );
587 $emailauthenticated = $context->msg( 'emailauthenticated',
588 $time, $d, $t )->parse() . '<br />';
589 $disableEmailPrefs = false;
590 $emailauthenticationclass = 'mw-email-authenticated';
592 $disableEmailPrefs = true;
593 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
594 new \OOUI\
ButtonWidget( [
595 'href' => SpecialPage
::getTitleFor( 'Confirmemail' )->getLinkURL(),
596 'label' => $context->msg( 'emailconfirmlink' )->text(),
598 $emailauthenticationclass = "mw-email-not-authenticated";
601 $disableEmailPrefs = true;
602 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
603 $emailauthenticationclass = 'mw-email-none';
606 if ( $canViewPrivateInfo ) {
607 $defaultPreferences['emailauthentication'] = [
610 'section' => 'personal/email',
611 'label-message' => 'prefs-emailconfirm-label',
612 'default' => $emailauthenticated,
613 # Apply the same CSS class used on the input to the message:
614 'cssclass' => $emailauthenticationclass,
619 if ( $this->options
->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
620 $defaultPreferences['disablemail'] = [
621 'id' => 'wpAllowEmail',
624 'section' => 'personal/email',
625 'label-message' => 'allowemail',
626 'disabled' => $disableEmailPrefs,
629 $defaultPreferences['email-allow-new-users'] = [
630 'id' => 'wpAllowEmailFromNewUsers',
632 'section' => 'personal/email',
633 'label-message' => 'email-allow-new-users-label',
634 'disabled' => $disableEmailPrefs,
637 $defaultPreferences['ccmeonemails'] = [
639 'section' => 'personal/email',
640 'label-message' => 'tog-ccmeonemails',
641 'disabled' => $disableEmailPrefs,
644 if ( $this->options
->get( 'EnableUserEmailBlacklist' ) ) {
645 $defaultPreferences['email-blacklist'] = [
646 'type' => 'usersmultiselect',
647 'label-message' => 'email-blacklist-label',
648 'section' => 'personal/email',
649 'disabled' => $disableEmailPrefs,
650 'filter' => MultiUsernameFilter
::class,
655 if ( $this->options
->get( 'EnotifWatchlist' ) ) {
656 $defaultPreferences['enotifwatchlistpages'] = [
658 'section' => 'personal/email',
659 'label-message' => 'tog-enotifwatchlistpages',
660 'disabled' => $disableEmailPrefs,
663 if ( $this->options
->get( 'EnotifUserTalk' ) ) {
664 $defaultPreferences['enotifusertalkpages'] = [
666 'section' => 'personal/email',
667 'label-message' => 'tog-enotifusertalkpages',
668 'disabled' => $disableEmailPrefs,
671 if ( $this->options
->get( 'EnotifUserTalk' ) ||
672 $this->options
->get( 'EnotifWatchlist' ) ) {
673 if ( $this->options
->get( 'EnotifMinorEdits' ) ) {
674 $defaultPreferences['enotifminoredits'] = [
676 'section' => 'personal/email',
677 'label-message' => 'tog-enotifminoredits',
678 'disabled' => $disableEmailPrefs,
682 if ( $this->options
->get( 'EnotifRevealEditorAddress' ) ) {
683 $defaultPreferences['enotifrevealaddr'] = [
685 'section' => 'personal/email',
686 'label-message' => 'tog-enotifrevealaddr',
687 'disabled' => $disableEmailPrefs,
696 * @param IContextSource $context
697 * @param array &$defaultPreferences
700 protected function skinPreferences( User
$user, IContextSource
$context, &$defaultPreferences ) {
701 # # Skin #####################################
703 // Skin selector, if there is at least one valid skin
704 $skinOptions = $this->generateSkinOptions( $user, $context );
705 if ( $skinOptions ) {
706 $defaultPreferences['skin'] = [
708 'options' => $skinOptions,
709 'section' => 'rendering/skin',
713 $allowUserCss = $this->options
->get( 'AllowUserCss' );
714 $allowUserJs = $this->options
->get( 'AllowUserJs' );
715 # Create links to user CSS/JS pages for all skins
716 # This code is basically copied from generateSkinOptions(). It'd
717 # be nice to somehow merge this back in there to avoid redundancy.
718 if ( $allowUserCss ||
$allowUserJs ) {
720 $userName = $user->getName();
722 if ( $allowUserCss ) {
723 $cssPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.css' );
724 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
725 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
728 if ( $allowUserJs ) {
729 $jsPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.js' );
730 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
731 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
734 $defaultPreferences['commoncssjs'] = [
737 'default' => $context->getLanguage()->pipeList( $linkTools ),
738 'label-message' => 'prefs-common-config',
739 'section' => 'rendering/skin',
745 * @param IContextSource $context
746 * @param array &$defaultPreferences
748 protected function filesPreferences( IContextSource
$context, &$defaultPreferences ) {
749 # # Files #####################################
750 $defaultPreferences['imagesize'] = [
752 'options' => $this->getImageSizes( $context ),
753 'label-message' => 'imagemaxsize',
754 'section' => 'rendering/files',
756 $defaultPreferences['thumbsize'] = [
758 'options' => $this->getThumbSizes( $context ),
759 'label-message' => 'thumbsize',
760 'section' => 'rendering/files',
766 * @param IContextSource $context
767 * @param array &$defaultPreferences
770 protected function datetimePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
771 # # Date and time #####################################
772 $dateOptions = $this->getDateOptions( $context );
773 if ( $dateOptions ) {
774 $defaultPreferences['date'] = [
776 'options' => $dateOptions,
777 'section' => 'rendering/dateformat',
782 $now = wfTimestampNow();
783 $lang = $context->getLanguage();
784 $nowlocal = Xml
::element( 'span', [ 'id' => 'wpLocalTime' ],
785 $lang->userTime( $now, $user ) );
786 $nowserver = $lang->userTime( $now, $user,
787 [ 'format' => false, 'timecorrection' => false ] ) .
788 Html
::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 +
(int)substr( $now, 10, 2 ) );
790 $defaultPreferences['nowserver'] = [
793 'label-message' => 'servertime',
794 'default' => $nowserver,
795 'section' => 'rendering/timeoffset',
798 $defaultPreferences['nowlocal'] = [
801 'label-message' => 'localtime',
802 'default' => $nowlocal,
803 'section' => 'rendering/timeoffset',
806 // Grab existing pref.
807 $tzOffset = $user->getOption( 'timecorrection' );
808 $tz = explode( '|', $tzOffset, 3 );
810 $tzOptions = $this->getTimezoneOptions( $context );
812 $tzSetting = $tzOffset;
813 if ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
814 !in_array( $tzOffset, HTMLFormField
::flattenOptions( $tzOptions ) )
816 // Timezone offset can vary with DST
818 $userTZ = new DateTimeZone( $tz[2] );
819 $minDiff = floor( $userTZ->getOffset( new DateTime( 'now' ) ) / 60 );
820 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
821 } catch ( Exception
$e ) {
822 // User has an invalid time zone set. Fall back to just using the offset
826 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
828 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) %
60 );
831 $defaultPreferences['timecorrection'] = [
832 'class' => \HTMLSelectOrOtherField
::class,
833 'label-message' => 'timezonelegend',
834 'options' => $tzOptions,
835 'default' => $tzSetting,
837 'section' => 'rendering/timeoffset',
838 'id' => 'wpTimeCorrection',
839 'filter' => TimezoneFilter
::class,
840 'placeholder-message' => 'timezone-useoffset-placeholder',
846 * @param MessageLocalizer $l10n
847 * @param array &$defaultPreferences
849 protected function renderingPreferences(
851 MessageLocalizer
$l10n,
854 # # Diffs ####################################
855 $defaultPreferences['diffonly'] = [
857 'section' => 'rendering/diffs',
858 'label-message' => 'tog-diffonly',
860 $defaultPreferences['norollbackdiff'] = [
862 'section' => 'rendering/diffs',
863 'label-message' => 'tog-norollbackdiff',
866 # # Page Rendering ##############################
867 if ( $this->options
->get( 'AllowUserCssPrefs' ) ) {
868 $defaultPreferences['underline'] = [
871 $l10n->msg( 'underline-never' )->text() => 0,
872 $l10n->msg( 'underline-always' )->text() => 1,
873 $l10n->msg( 'underline-default' )->text() => 2,
875 'label-message' => 'tog-underline',
876 'section' => 'rendering/advancedrendering',
880 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
881 $stubThresholdOptions = [ $l10n->msg( 'stub-threshold-disabled' )->text() => 0 ];
882 foreach ( $stubThresholdValues as $value ) {
883 $stubThresholdOptions[$l10n->msg( 'size-bytes', $value )->text()] = $value;
886 $defaultPreferences['stubthreshold'] = [
888 'section' => 'rendering/advancedrendering',
889 'options' => $stubThresholdOptions,
890 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
891 'label-raw' => $l10n->msg( 'stub-threshold' )->rawParams(
893 $l10n->msg( 'stub-threshold-sample-link' )->parse() .
897 $defaultPreferences['showhiddencats'] = [
899 'section' => 'rendering/advancedrendering',
900 'label-message' => 'tog-showhiddencats'
903 $defaultPreferences['numberheadings'] = [
905 'section' => 'rendering/advancedrendering',
906 'label-message' => 'tog-numberheadings',
909 if ( $user->isAllowed( 'rollback' ) ) {
910 $defaultPreferences['showrollbackconfirmation'] = [
912 'section' => 'rendering/advancedrendering',
913 'label-message' => 'tog-showrollbackconfirmation',
920 * @param MessageLocalizer $l10n
921 * @param array &$defaultPreferences
923 protected function editingPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
924 # # Editing #####################################
925 $defaultPreferences['editsectiononrightclick'] = [
927 'section' => 'editing/advancedediting',
928 'label-message' => 'tog-editsectiononrightclick',
930 $defaultPreferences['editondblclick'] = [
932 'section' => 'editing/advancedediting',
933 'label-message' => 'tog-editondblclick',
936 if ( $this->options
->get( 'AllowUserCssPrefs' ) ) {
937 $defaultPreferences['editfont'] = [
939 'section' => 'editing/editor',
940 'label-message' => 'editfont-style',
942 $l10n->msg( 'editfont-monospace' )->text() => 'monospace',
943 $l10n->msg( 'editfont-sansserif' )->text() => 'sans-serif',
944 $l10n->msg( 'editfont-serif' )->text() => 'serif',
949 if ( $user->isAllowed( 'minoredit' ) ) {
950 $defaultPreferences['minordefault'] = [
952 'section' => 'editing/editor',
953 'label-message' => 'tog-minordefault',
957 $defaultPreferences['forceeditsummary'] = [
959 'section' => 'editing/editor',
960 'label-message' => 'tog-forceeditsummary',
962 $defaultPreferences['useeditwarning'] = [
964 'section' => 'editing/editor',
965 'label-message' => 'tog-useeditwarning',
968 $defaultPreferences['previewonfirst'] = [
970 'section' => 'editing/preview',
971 'label-message' => 'tog-previewonfirst',
973 $defaultPreferences['previewontop'] = [
975 'section' => 'editing/preview',
976 'label-message' => 'tog-previewontop',
978 $defaultPreferences['uselivepreview'] = [
980 'section' => 'editing/preview',
981 'label-message' => 'tog-uselivepreview',
987 * @param MessageLocalizer $l10n
988 * @param array &$defaultPreferences
990 protected function rcPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
991 $rcMaxAge = $this->options
->get( 'RCMaxAge' );
992 # # RecentChanges #####################################
993 $defaultPreferences['rcdays'] = [
995 'label-message' => 'recentchangesdays',
996 'section' => 'rc/displayrc',
998 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
999 'help' => $l10n->msg( 'recentchangesdays-max' )->numParams(
1000 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
1002 $defaultPreferences['rclimit'] = [
1006 'label-message' => 'recentchangescount',
1007 'help-message' => 'prefs-help-recentchangescount',
1008 'section' => 'rc/displayrc',
1009 'filter' => IntvalFilter
::class,
1011 $defaultPreferences['usenewrc'] = [
1013 'label-message' => 'tog-usenewrc',
1014 'section' => 'rc/advancedrc',
1016 $defaultPreferences['hideminor'] = [
1018 'label-message' => 'tog-hideminor',
1019 'section' => 'rc/changesrc',
1021 $defaultPreferences['rcfilters-rc-collapsed'] = [
1024 $defaultPreferences['rcfilters-wl-collapsed'] = [
1027 $defaultPreferences['rcfilters-saved-queries'] = [
1030 $defaultPreferences['rcfilters-wl-saved-queries'] = [
1033 // Override RCFilters preferences for RecentChanges 'limit'
1034 $defaultPreferences['rcfilters-limit'] = [
1037 $defaultPreferences['rcfilters-saved-queries-versionbackup'] = [
1040 $defaultPreferences['rcfilters-wl-saved-queries-versionbackup'] = [
1044 if ( $this->options
->get( 'RCWatchCategoryMembership' ) ) {
1045 $defaultPreferences['hidecategorization'] = [
1047 'label-message' => 'tog-hidecategorization',
1048 'section' => 'rc/changesrc',
1052 if ( $user->useRCPatrol() ) {
1053 $defaultPreferences['hidepatrolled'] = [
1055 'section' => 'rc/changesrc',
1056 'label-message' => 'tog-hidepatrolled',
1060 if ( $user->useNPPatrol() ) {
1061 $defaultPreferences['newpageshidepatrolled'] = [
1063 'section' => 'rc/changesrc',
1064 'label-message' => 'tog-newpageshidepatrolled',
1068 if ( $this->options
->get( 'RCShowWatchingUsers' ) ) {
1069 $defaultPreferences['shownumberswatching'] = [
1071 'section' => 'rc/advancedrc',
1072 'label-message' => 'tog-shownumberswatching',
1076 $defaultPreferences['rcenhancedfilters-disable'] = [
1078 'section' => 'rc/advancedrc',
1079 'label-message' => 'rcfilters-preference-label',
1080 'help-message' => 'rcfilters-preference-help',
1086 * @param IContextSource $context
1087 * @param array &$defaultPreferences
1089 protected function watchlistPreferences(
1090 User
$user, IContextSource
$context, &$defaultPreferences
1092 $watchlistdaysMax = ceil( $this->options
->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1094 # # Watchlist #####################################
1095 if ( $user->isAllowed( 'editmywatchlist' ) ) {
1096 $editWatchlistLinks = '';
1097 $editWatchlistModes = [
1098 'edit' => [ 'subpage' => false, 'flags' => [] ],
1099 'raw' => [ 'subpage' => 'raw', 'flags' => [] ],
1100 'clear' => [ 'subpage' => 'clear', 'flags' => [ 'destructive' ] ],
1102 foreach ( $editWatchlistModes as $mode => $options ) {
1103 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1104 $editWatchlistLinks .=
1105 new \OOUI\
ButtonWidget( [
1106 'href' => SpecialPage
::getTitleFor( 'EditWatchlist', $options['subpage'] )->getLinkURL(),
1107 'flags' => $options[ 'flags' ],
1108 'label' => new \OOUI\
HtmlSnippet(
1109 $context->msg( "prefs-editwatchlist-{$mode}" )->parse()
1114 $defaultPreferences['editwatchlist'] = [
1117 'default' => $editWatchlistLinks,
1118 'label-message' => 'prefs-editwatchlist-label',
1119 'section' => 'watchlist/editwatchlist',
1123 $defaultPreferences['watchlistdays'] = [
1126 'max' => $watchlistdaysMax,
1127 'section' => 'watchlist/displaywatchlist',
1128 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1129 $watchlistdaysMax )->escaped(),
1130 'label-message' => 'prefs-watchlist-days',
1132 $defaultPreferences['wllimit'] = [
1136 'label-message' => 'prefs-watchlist-edits',
1137 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1138 'section' => 'watchlist/displaywatchlist',
1139 'filter' => IntvalFilter
::class,
1141 $defaultPreferences['extendwatchlist'] = [
1143 'section' => 'watchlist/advancedwatchlist',
1144 'label-message' => 'tog-extendwatchlist',
1146 $defaultPreferences['watchlisthideminor'] = [
1148 'section' => 'watchlist/changeswatchlist',
1149 'label-message' => 'tog-watchlisthideminor',
1151 $defaultPreferences['watchlisthidebots'] = [
1153 'section' => 'watchlist/changeswatchlist',
1154 'label-message' => 'tog-watchlisthidebots',
1156 $defaultPreferences['watchlisthideown'] = [
1158 'section' => 'watchlist/changeswatchlist',
1159 'label-message' => 'tog-watchlisthideown',
1161 $defaultPreferences['watchlisthideanons'] = [
1163 'section' => 'watchlist/changeswatchlist',
1164 'label-message' => 'tog-watchlisthideanons',
1166 $defaultPreferences['watchlisthideliu'] = [
1168 'section' => 'watchlist/changeswatchlist',
1169 'label-message' => 'tog-watchlisthideliu',
1172 if ( !\SpecialWatchlist
::checkStructuredFilterUiEnabled( $user ) ) {
1173 $defaultPreferences['watchlistreloadautomatically'] = [
1175 'section' => 'watchlist/advancedwatchlist',
1176 'label-message' => 'tog-watchlistreloadautomatically',
1180 $defaultPreferences['watchlistunwatchlinks'] = [
1182 'section' => 'watchlist/advancedwatchlist',
1183 'label-message' => 'tog-watchlistunwatchlinks',
1186 if ( $this->options
->get( 'RCWatchCategoryMembership' ) ) {
1187 $defaultPreferences['watchlisthidecategorization'] = [
1189 'section' => 'watchlist/changeswatchlist',
1190 'label-message' => 'tog-watchlisthidecategorization',
1194 if ( $user->useRCPatrol() ) {
1195 $defaultPreferences['watchlisthidepatrolled'] = [
1197 'section' => 'watchlist/changeswatchlist',
1198 'label-message' => 'tog-watchlisthidepatrolled',
1203 'edit' => 'watchdefault',
1204 'move' => 'watchmoves',
1205 'delete' => 'watchdeletion'
1209 if ( $user->isAllowed( 'createpage' ) ||
$user->isAllowed( 'createtalk' ) ) {
1210 $watchTypes['read'] = 'watchcreations';
1213 if ( $user->isAllowed( 'rollback' ) ) {
1214 $watchTypes['rollback'] = 'watchrollback';
1217 if ( $user->isAllowed( 'upload' ) ) {
1218 $watchTypes['upload'] = 'watchuploads';
1221 foreach ( $watchTypes as $action => $pref ) {
1222 if ( $user->isAllowed( $action ) ) {
1224 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1225 // tog-watchrollback
1226 $defaultPreferences[$pref] = [
1228 'section' => 'watchlist/pageswatchlist',
1229 'label-message' => "tog-$pref",
1234 $defaultPreferences['watchlisttoken'] = [
1238 $tokenButton = new \OOUI\
ButtonWidget( [
1239 'href' => SpecialPage
::getTitleFor( 'ResetTokens' )->getLinkURL( [
1240 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
1242 'label' => $context->msg( 'prefs-watchlist-managetokens' )->text(),
1244 $defaultPreferences['watchlisttoken-info'] = [
1246 'section' => 'watchlist/tokenwatchlist',
1247 'label-message' => 'prefs-watchlist-token',
1248 'help-message' => 'prefs-help-tokenmanagement',
1250 'default' => (string)$tokenButton,
1253 $defaultPreferences['wlenhancedfilters-disable'] = [
1255 'section' => 'watchlist/advancedwatchlist',
1256 'label-message' => 'rcfilters-watchlist-preference-label',
1257 'help-message' => 'rcfilters-watchlist-preference-help',
1262 * @param array &$defaultPreferences
1264 protected function searchPreferences( &$defaultPreferences ) {
1265 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
1266 $defaultPreferences['searchNs' . $n] = [
1273 * @param User $user The User object
1274 * @param IContextSource $context
1275 * @return array Text/links to display as key; $skinkey as value
1277 protected function generateSkinOptions( User
$user, IContextSource
$context ) {
1280 $mptitle = Title
::newMainPage();
1281 $previewtext = $context->msg( 'skin-preview' )->escaped();
1283 # Only show skins that aren't disabled in $wgSkipSkins
1284 $validSkinNames = Skin
::getAllowedSkins();
1286 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1287 $msg = $context->msg( "skinname-{$skinkey}" );
1288 if ( $msg->exists() ) {
1289 $skinname = htmlspecialchars( $msg->text() );
1293 $defaultSkin = $this->options
->get( 'DefaultSkin' );
1294 $allowUserCss = $this->options
->get( 'AllowUserCss' );
1295 $allowUserJs = $this->options
->get( 'AllowUserJs' );
1297 # Sort by the internal name, so that the ordering is the same for each display language,
1298 # especially if some skin names are translated to use a different alphabet and some are not.
1299 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1300 # Display the default first in the list by comparing it as lesser than any other.
1301 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1304 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1307 return strcasecmp( $a, $b );
1310 $foundDefault = false;
1311 foreach ( $validSkinNames as $skinkey => $sn ) {
1314 # Mark the default skin
1315 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1316 $linkTools[] = $context->msg( 'default' )->escaped();
1317 $foundDefault = true;
1320 # Create preview link
1321 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1322 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1324 # Create links to user CSS/JS pages
1325 if ( $allowUserCss ) {
1326 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1327 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
1328 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
1331 if ( $allowUserJs ) {
1332 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1333 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
1334 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
1337 $display = $sn . ' ' . $context->msg( 'parentheses' )
1338 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1340 $ret[$display] = $skinkey;
1343 if ( !$foundDefault ) {
1344 // If the default skin is not available, things are going to break horribly because the
1345 // default value for skin selector will not be a valid value. Let's just not show it then.
1353 * @param IContextSource $context
1356 protected function getDateOptions( IContextSource
$context ) {
1357 $lang = $context->getLanguage();
1358 $dateopts = $lang->getDatePreferences();
1363 if ( !in_array( 'default', $dateopts ) ) {
1364 $dateopts[] = 'default'; // Make sure default is always valid T21237
1367 // FIXME KLUGE: site default might not be valid for user language
1368 global $wgDefaultUserOptions;
1369 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1370 $wgDefaultUserOptions['date'] = 'default';
1373 $epoch = wfTimestampNow();
1374 foreach ( $dateopts as $key ) {
1375 if ( $key == 'default' ) {
1376 $formatted = $context->msg( 'datedefault' )->escaped();
1378 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1380 $ret[$formatted] = $key;
1387 * @param MessageLocalizer $l10n
1390 protected function getImageSizes( MessageLocalizer
$l10n ) {
1392 $pixels = $l10n->msg( 'unit-pixel' )->text();
1394 foreach ( $this->options
->get( 'ImageLimits' ) as $index => $limits ) {
1395 // Note: A left-to-right marker (U+200E) is inserted, see T144386
1396 $display = "{$limits[0]}\u{200E}×{$limits[1]}$pixels";
1397 $ret[$display] = $index;
1404 * @param MessageLocalizer $l10n
1407 protected function getThumbSizes( MessageLocalizer
$l10n ) {
1409 $pixels = $l10n->msg( 'unit-pixel' )->text();
1411 foreach ( $this->options
->get( 'ThumbLimits' ) as $index => $size ) {
1412 $display = $size . $pixels;
1413 $ret[$display] = $index;
1420 * @param string $signature
1421 * @param array $alldata
1422 * @param HTMLForm $form
1423 * @return bool|string
1425 protected function validateSignature( $signature, $alldata, HTMLForm
$form ) {
1426 $maxSigChars = $this->options
->get( 'MaxSigChars' );
1427 if ( mb_strlen( $signature ) > $maxSigChars ) {
1428 return Xml
::element( 'span', [ 'class' => 'error' ],
1429 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1430 } elseif ( isset( $alldata['fancysig'] ) &&
1431 $alldata['fancysig'] &&
1432 MediaWikiServices
::getInstance()->getParser()->validateSig( $signature ) === false
1434 return Xml
::element(
1436 [ 'class' => 'error' ],
1437 $form->msg( 'badsig' )->text()
1445 * @param string $signature
1446 * @param array $alldata
1447 * @param HTMLForm $form
1450 protected function cleanSignature( $signature, $alldata, HTMLForm
$form ) {
1451 $parser = MediaWikiServices
::getInstance()->getParser();
1452 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1453 $signature = $parser->cleanSig( $signature );
1455 // When no fancy sig used, make sure ~{3,5} get removed.
1456 $signature = Parser
::cleanSigInSig( $signature );
1464 * @param IContextSource $context
1465 * @param string $formClass
1466 * @param array $remove Array of items to remove
1469 public function getForm(
1471 IContextSource
$context,
1472 $formClass = PreferencesFormOOUI
::class,
1475 // We use ButtonWidgets in some of the getPreferences() functions
1476 $context->getOutput()->enableOOUI();
1478 $formDescriptor = $this->getFormDescriptor( $user, $context );
1479 if ( count( $remove ) ) {
1480 $removeKeys = array_flip( $remove );
1481 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1484 // Remove type=api preferences. They are not intended for rendering in the form.
1485 foreach ( $formDescriptor as $name => $info ) {
1486 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1487 unset( $formDescriptor[$name] );
1492 * @var HTMLForm $htmlForm
1494 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1496 $htmlForm->setModifiedUser( $user );
1497 $htmlForm->setId( 'mw-prefs-form' );
1498 $htmlForm->setAutocomplete( 'off' );
1499 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1500 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1501 $htmlForm->setSubmitTooltip( 'preferences-save' );
1502 $htmlForm->setSubmitID( 'prefcontrol' );
1503 $htmlForm->setSubmitCallback(
1504 function ( array $formData, HTMLForm
$form ) use ( $formDescriptor ) {
1505 return $this->submitForm( $formData, $form, $formDescriptor );
1513 * @param IContextSource $context
1516 protected function getTimezoneOptions( IContextSource
$context ) {
1519 $localTZoffset = $this->options
->get( 'LocalTZoffset' );
1520 $timeZoneList = $this->getTimeZoneList( $context->getLanguage() );
1522 $timestamp = MWTimestamp
::getLocalInstance();
1523 // Check that the LocalTZoffset is the same as the local time zone offset
1524 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1525 $timezoneName = $timestamp->getTimezone()->getName();
1526 // Localize timezone
1527 if ( isset( $timeZoneList[$timezoneName] ) ) {
1528 $timezoneName = $timeZoneList[$timezoneName]['name'];
1530 $server_tz_msg = $context->msg(
1531 'timezoneuseserverdefault',
1535 $tzstring = sprintf(
1537 floor( $localTZoffset / 60 ),
1538 abs( $localTZoffset ) %
60
1540 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1542 $opt[$server_tz_msg] = "System|$localTZoffset";
1543 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1544 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1546 foreach ( $timeZoneList as $timeZoneInfo ) {
1547 $region = $timeZoneInfo['region'];
1548 if ( !isset( $opt[$region] ) ) {
1551 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1557 * Handle the form submission if everything validated properly
1559 * @param array $formData
1560 * @param HTMLForm $form
1561 * @param array[] $formDescriptor
1562 * @return bool|Status|string
1564 protected function saveFormData( $formData, HTMLForm
$form, array $formDescriptor ) {
1565 /** @var \User $user */
1566 $user = $form->getModifiedUser();
1567 $hiddenPrefs = $this->options
->get( 'HiddenPrefs' );
1570 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1571 return Status
::newFatal( 'mypreferencesprotected' );
1575 $this->applyFilters( $formData, $formDescriptor, 'filterFromForm' );
1577 // Fortunately, the realname field is MUCH simpler
1578 // (not really "private", but still shouldn't be edited without permission)
1580 if ( !in_array( 'realname', $hiddenPrefs )
1581 && $user->isAllowed( 'editmyprivateinfo' )
1582 && array_key_exists( 'realname', $formData )
1584 $realName = $formData['realname'];
1585 $user->setRealName( $realName );
1588 if ( $user->isAllowed( 'editmyoptions' ) ) {
1589 $oldUserOptions = $user->getOptions();
1591 foreach ( $this->getSaveBlacklist() as $b ) {
1592 unset( $formData[$b] );
1595 # If users have saved a value for a preference which has subsequently been disabled
1596 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1597 # is subsequently re-enabled
1598 foreach ( $hiddenPrefs as $pref ) {
1599 # If the user has not set a non-default value here, the default will be returned
1600 # and subsequently discarded
1601 $formData[$pref] = $user->getOption( $pref, null, true );
1604 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1606 isset( $formData['rclimit'] ) &&
1607 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1609 $formData['rcfilters-limit'] = $formData['rclimit'];
1612 // Keep old preferences from interfering due to back-compat code, etc.
1613 $user->resetOptions( 'unused', $form->getContext() );
1615 foreach ( $formData as $key => $value ) {
1616 $user->setOption( $key, $value );
1620 'PreferencesFormPreSave',
1621 [ $formData, $form, $user, &$result, $oldUserOptions ]
1625 $user->saveSettings();
1631 * Applies filters to preferences either before or after form usage
1633 * @param array &$preferences
1634 * @param array $formDescriptor
1635 * @param string $verb Name of the filter method to call, either 'filterFromForm' or
1638 protected function applyFilters( array &$preferences, array $formDescriptor, $verb ) {
1639 foreach ( $formDescriptor as $preference => $desc ) {
1640 if ( !isset( $desc['filter'] ) ||
!isset( $preferences[$preference] ) ) {
1643 $filterDesc = $desc['filter'];
1644 if ( $filterDesc instanceof Filter
) {
1645 $filter = $filterDesc;
1646 } elseif ( class_exists( $filterDesc ) ) {
1647 $filter = new $filterDesc();
1648 } elseif ( is_callable( $filterDesc ) ) {
1649 $filter = $filterDesc();
1651 throw new UnexpectedValueException(
1652 "Unrecognized filter type for preference '$preference'"
1655 $preferences[$preference] = $filter->$verb( $preferences[$preference] );
1660 * Save the form data and reload the page
1662 * @param array $formData
1663 * @param HTMLForm $form
1664 * @param array $formDescriptor
1667 protected function submitForm( array $formData, HTMLForm
$form, array $formDescriptor ) {
1668 $res = $this->saveFormData( $formData, $form, $formDescriptor );
1670 if ( $res === true ) {
1671 $context = $form->getContext();
1674 if ( $res === 'eauth' ) {
1675 $urlOptions['eauth'] = 1;
1678 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1680 $url = $form->getTitle()->getFullURL( $urlOptions );
1682 // Set session data for the success message
1683 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1685 $context->getOutput()->redirect( $url );
1688 return ( $res === true ? Status
::newGood() : $res );
1692 * Get a list of all time zones
1693 * @param Language $language Language used for the localized names
1694 * @return array A list of all time zones. The system name of the time zone is used as key and
1695 * the value is an array which contains localized name, the timecorrection value used for
1696 * preferences and the region
1699 protected function getTimeZoneList( Language
$language ) {
1700 $identifiers = DateTimeZone
::listIdentifiers();
1701 if ( $identifiers === false ) {
1704 sort( $identifiers );
1707 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1708 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1709 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1710 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1711 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1712 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1713 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1714 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1715 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1716 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1718 asort( $tzRegions );
1722 $now = new DateTime();
1724 foreach ( $identifiers as $identifier ) {
1725 $parts = explode( '/', $identifier, 2 );
1727 // DateTimeZone::listIdentifiers() returns a number of
1728 // backwards-compatibility entries. This filters them out of the
1729 // list presented to the user.
1730 if ( count( $parts ) !== 2 ||
!array_key_exists( $parts[0], $tzRegions ) ) {
1735 $parts[0] = $tzRegions[$parts[0]];
1737 $dateTimeZone = new DateTimeZone( $identifier );
1738 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1740 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1741 $value = "ZoneInfo|$minDiff|$identifier";
1743 $timeZoneList[$identifier] = [
1745 'timecorrection' => $value,
1746 'region' => $parts[0],
1750 return $timeZoneList;