3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 namespace MediaWiki\Preferences
;
36 use LanguageConverter
;
37 use MediaWiki\Auth\AuthManager
;
38 use MediaWiki\Auth\PasswordAuthenticationRequest
;
39 use MediaWiki\Linker\LinkRenderer
;
40 use MediaWiki\MediaWikiServices
;
49 use PreferencesFormOOUI
;
50 use Psr\Log\LoggerAwareTrait
;
51 use Psr\Log\NullLogger
;
54 use SpecialPreferences
;
58 use UserGroupMembership
;
62 * This is the default implementation of PreferencesFactory.
64 class DefaultPreferencesFactory
implements PreferencesFactory
{
70 /** @var Language The wiki's content language, equivalent to $wgContLang. */
73 /** @var AuthManager */
74 protected $authManager;
76 /** @var LinkRenderer */
77 protected $linkRenderer;
80 * @param Config $config
81 * @param Language $contLang
82 * @param AuthManager $authManager
83 * @param LinkRenderer $linkRenderer
85 public function __construct(
88 AuthManager
$authManager,
89 LinkRenderer
$linkRenderer
91 $this->config
= $config;
92 $this->contLang
= $contLang;
93 $this->authManager
= $authManager;
94 $this->linkRenderer
= $linkRenderer;
95 $this->logger
= new NullLogger();
101 protected function getSaveFilters() {
102 // Wrap intval() so that we can pass it multiple parameters and treat all filters the same.
103 $intvalFilter = function ( $value, $alldata ) {
104 return intval( $value );
107 'timecorrection' => [ $this, 'filterTimezoneInput' ],
108 'rclimit' => $intvalFilter,
109 'wllimit' => $intvalFilter,
110 'searchlimit' => $intvalFilter,
117 public function getSaveBlacklist() {
125 * @throws MWException
127 * @param IContextSource $context
130 public function getFormDescriptor( User
$user, IContextSource
$context ) {
133 if ( SpecialPreferences
::isOouiEnabled( $context ) ) {
134 OutputPage
::setupOOUI(
135 strtolower( $context->getSkin()->getSkinName() ),
136 $context->getLanguage()->getDir()
140 $canIPUseHTTPS = wfCanIPUseHTTPS( $context->getRequest()->getIP() );
141 $this->profilePreferences( $user, $context, $preferences, $canIPUseHTTPS );
142 $this->skinPreferences( $user, $context, $preferences );
143 $this->datetimePreferences( $user, $context, $preferences );
144 $this->filesPreferences( $context, $preferences );
145 $this->renderingPreferences( $context, $preferences );
146 $this->editingPreferences( $user, $context, $preferences );
147 $this->rcPreferences( $user, $context, $preferences );
148 $this->watchlistPreferences( $user, $context, $preferences );
149 $this->searchPreferences( $preferences );
151 Hooks
::run( 'GetPreferences', [ $user, &$preferences ] );
153 $this->loadPreferenceValues( $user, $context, $preferences );
154 $this->logger
->debug( "Created form descriptor for user '{$user->getName()}'" );
159 * Loads existing values for a given array of preferences
160 * @throws MWException
162 * @param IContextSource $context
163 * @param array &$defaultPreferences Array to load values for
166 private function loadPreferenceValues(
167 User
$user, IContextSource
$context, &$defaultPreferences
169 # # Remove preferences that wikis don't want to use
170 foreach ( $this->config
->get( 'HiddenPrefs' ) as $pref ) {
171 if ( isset( $defaultPreferences[$pref] ) ) {
172 unset( $defaultPreferences[$pref] );
176 # # Make sure that form fields have their parent set. See T43337.
177 $dummyForm = new HTMLForm( [], $context );
179 $disable = !$user->isAllowed( 'editmyoptions' );
181 $defaultOptions = User
::getDefaultOptions();
182 # # Prod in defaults from the user
183 foreach ( $defaultPreferences as $name => &$info ) {
184 $prefFromUser = $this->getOptionFromUser( $name, $info, $user );
185 if ( $disable && !in_array( $name, $this->getSaveBlacklist() ) ) {
186 $info['disabled'] = 'disabled';
188 $field = HTMLForm
::loadInputFromParameters( $name, $info, $dummyForm ); // For validation
189 $globalDefault = isset( $defaultOptions[$name] )
190 ?
$defaultOptions[$name]
193 // If it validates, set it as the default
194 if ( isset( $info['default'] ) ) {
195 // Already set, no problem
197 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
198 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
199 $info['default'] = $prefFromUser;
200 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
201 $info['default'] = $globalDefault;
203 throw new MWException( "Global default '$globalDefault' is invalid for field $name" );
207 return $defaultPreferences;
211 * Pull option from a user account. Handles stuff like array-type preferences.
213 * @param string $name
216 * @return array|string
218 protected function getOptionFromUser( $name, $info, User
$user ) {
219 $val = $user->getOption( $name );
221 // Handling for multiselect preferences
222 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
223 ( isset( $info['class'] ) && $info['class'] == \HTMLMultiSelectField
::class ) ) {
224 $options = HTMLFormField
::flattenOptions( $info['options'] );
225 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
228 foreach ( $options as $value ) {
229 if ( $user->getOption( "$prefix$value" ) ) {
235 // Handling for checkmatrix preferences
236 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
237 ( isset( $info['class'] ) && $info['class'] == \HTMLCheckMatrix
::class ) ) {
238 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
239 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
240 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
243 foreach ( $columns as $column ) {
244 foreach ( $rows as $row ) {
245 if ( $user->getOption( "$prefix$column-$row" ) ) {
246 $val[] = "$column-$row";
256 * @todo Inject user Language instead of using context.
258 * @param IContextSource $context
259 * @param array &$defaultPreferences
260 * @param bool $canIPUseHTTPS Whether the user's IP is likely to be able to access the wiki
264 protected function profilePreferences(
265 User
$user, IContextSource
$context, &$defaultPreferences, $canIPUseHTTPS
267 $oouiEnabled = SpecialPreferences
::isOouiEnabled( $context );
269 // retrieving user name for GENDER and misc.
270 $userName = $user->getName();
272 # # User info #####################################
274 $defaultPreferences['username'] = [
276 'label-message' => [ 'username', $userName ],
277 'default' => $userName,
278 'section' => 'personal/info',
281 $lang = $context->getLanguage();
283 # Get groups to which the user belongs
284 $userEffectiveGroups = $user->getEffectiveGroups();
285 $userGroupMemberships = $user->getGroupMemberships();
286 $userGroups = $userMembers = $userTempGroups = $userTempMembers = [];
287 foreach ( $userEffectiveGroups as $ueg ) {
289 // Skip the default * group, seems useless here
293 if ( isset( $userGroupMemberships[$ueg] ) ) {
294 $groupStringOrObject = $userGroupMemberships[$ueg];
296 $groupStringOrObject = $ueg;
299 $userG = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html' );
300 $userM = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html',
303 // Store expiring groups separately, so we can place them before non-expiring
304 // groups in the list. This is to avoid the ambiguity of something like
305 // "administrator, bureaucrat (until X date)" -- users might wonder whether the
306 // expiry date applies to both groups, or just the last one
307 if ( $groupStringOrObject instanceof UserGroupMembership
&&
308 $groupStringOrObject->getExpiry()
310 $userTempGroups[] = $userG;
311 $userTempMembers[] = $userM;
313 $userGroups[] = $userG;
314 $userMembers[] = $userM;
318 sort( $userMembers );
319 sort( $userTempGroups );
320 sort( $userTempMembers );
321 $userGroups = array_merge( $userTempGroups, $userGroups );
322 $userMembers = array_merge( $userTempMembers, $userMembers );
324 $defaultPreferences['usergroups'] = [
326 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
327 count( $userGroups ) )->params( $userName )->parse(),
328 'default' => $context->msg( 'prefs-memberingroups-type' )
329 ->rawParams( $lang->commaList( $userGroups ), $lang->commaList( $userMembers ) )
332 'section' => 'personal/info',
335 $contribTitle = SpecialPage
::getTitleFor( "Contributions", $userName );
336 $formattedEditCount = $lang->formatNum( $user->getEditCount() );
337 $editCount = $this->linkRenderer
->makeLink( $contribTitle, $formattedEditCount );
339 $defaultPreferences['editcount'] = [
342 'label-message' => 'prefs-edits',
343 'default' => $editCount,
344 'section' => 'personal/info',
347 if ( $user->getRegistration() ) {
348 $displayUser = $context->getUser();
349 $userRegistration = $user->getRegistration();
350 $defaultPreferences['registrationdate'] = [
352 'label-message' => 'prefs-registration',
353 'default' => $context->msg(
354 'prefs-registration-date-time',
355 $lang->userTimeAndDate( $userRegistration, $displayUser ),
356 $lang->userDate( $userRegistration, $displayUser ),
357 $lang->userTime( $userRegistration, $displayUser )
359 'section' => 'personal/info',
363 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
364 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
366 // Actually changeable stuff
367 $defaultPreferences['realname'] = [
368 // (not really "private", but still shouldn't be edited without permission)
369 'type' => $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'realname' )
371 'default' => $user->getRealName(),
372 'section' => 'personal/info',
373 'label-message' => 'yourrealname',
374 'help-message' => 'prefs-help-realname',
377 if ( $canEditPrivateInfo && $this->authManager
->allowsAuthenticationDataChange(
378 new PasswordAuthenticationRequest(), false )->isGood()
380 if ( $oouiEnabled ) {
381 $link = new \OOUI\
ButtonWidget( [
382 'href' => SpecialPage
::getTitleFor( 'ChangePassword' )->getLinkURL( [
383 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
385 'label' => $context->msg( 'prefs-resetpass' )->text(),
388 $link = $this->linkRenderer
->makeLink( SpecialPage
::getTitleFor( 'ChangePassword' ),
389 $context->msg( 'prefs-resetpass' )->text(), [],
390 [ 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText() ] );
393 $defaultPreferences['password'] = [
396 'default' => (string)$link,
397 'label-message' => 'yourpassword',
398 'section' => 'personal/info',
401 // Only show prefershttps if secure login is turned on
402 if ( $this->config
->get( 'SecureLogin' ) && $canIPUseHTTPS ) {
403 $defaultPreferences['prefershttps'] = [
405 'label-message' => 'tog-prefershttps',
406 'help-message' => 'prefs-help-prefershttps',
407 'section' => 'personal/info'
412 $languages = Language
::fetchLanguageNames( null, 'mw' );
413 $languageCode = $this->config
->get( 'LanguageCode' );
414 if ( !array_key_exists( $languageCode, $languages ) ) {
415 $languages[$languageCode] = $languageCode;
420 foreach ( $languages as $code => $name ) {
421 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
422 $options[$display] = $code;
424 $defaultPreferences['language'] = [
426 'section' => 'personal/i18n',
427 'options' => $options,
428 'label-message' => 'yourlanguage',
431 $defaultPreferences['gender'] = [
433 'section' => 'personal/i18n',
435 $context->msg( 'parentheses' )
436 ->params( $context->msg( 'gender-unknown' )->plain() )
437 ->escaped() => 'unknown',
438 $context->msg( 'gender-female' )->escaped() => 'female',
439 $context->msg( 'gender-male' )->escaped() => 'male',
441 'label-message' => 'yourgender',
442 'help-message' => 'prefs-help-gender',
445 // see if there are multiple language variants to choose from
446 if ( !$this->config
->get( 'DisableLangConversion' ) ) {
447 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
448 if ( $langCode == $this->contLang
->getCode() ) {
449 $variants = $this->contLang
->getVariants();
451 if ( count( $variants ) <= 1 ) {
456 foreach ( $variants as $v ) {
457 $v = str_replace( '_', '-', strtolower( $v ) );
458 $variantArray[$v] = $lang->getVariantname( $v, false );
462 foreach ( $variantArray as $code => $name ) {
463 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
464 $options[$display] = $code;
467 $defaultPreferences['variant'] = [
468 'label-message' => 'yourvariant',
470 'options' => $options,
471 'section' => 'personal/i18n',
472 'help-message' => 'prefs-help-variant',
475 $defaultPreferences["variant-$langCode"] = [
482 // Stuff from Language::getExtraUserToggles()
483 // FIXME is this dead code? $extraUserToggles doesn't seem to be defined for any language
484 $toggles = $this->contLang
->getExtraUserToggles();
486 foreach ( $toggles as $toggle ) {
487 $defaultPreferences[$toggle] = [
489 'section' => 'personal/i18n',
490 'label-message' => "tog-$toggle",
494 // show a preview of the old signature first
495 $oldsigWikiText = MediaWikiServices
::getInstance()->getParser()->preSaveTransform(
497 $context->getTitle(),
499 ParserOptions
::newFromContext( $context )
501 $oldsigHTML = $context->getOutput()->parseInline( $oldsigWikiText, true, true );
502 $defaultPreferences['oldsig'] = [
505 'label-message' => 'tog-oldsig',
506 'default' => $oldsigHTML,
507 'section' => 'personal/signature',
509 $defaultPreferences['nickname'] = [
510 'type' => $this->authManager
->allowsPropertyChange( 'nickname' ) ?
'text' : 'info',
511 'maxlength' => $this->config
->get( 'MaxSigChars' ),
512 'label-message' => 'yournick',
513 'validation-callback' => function ( $signature, $alldata, HTMLForm
$form ) {
514 return $this->validateSignature( $signature, $alldata, $form );
516 'section' => 'personal/signature',
517 'filter-callback' => function ( $signature, array $alldata, HTMLForm
$form ) {
518 return $this->cleanSignature( $signature, $alldata, $form );
521 $defaultPreferences['fancysig'] = [
523 'label-message' => 'tog-fancysig',
524 // show general help about signature at the bottom of the section
525 'help-message' => 'prefs-help-signature',
526 'section' => 'personal/signature'
531 if ( $this->config
->get( 'EnableEmail' ) ) {
532 if ( $canViewPrivateInfo ) {
533 $helpMessages[] = $this->config
->get( 'EmailConfirmToEdit' )
534 ?
'prefs-help-email-required'
535 : 'prefs-help-email';
537 if ( $this->config
->get( 'EnableUserEmail' ) ) {
538 // additional messages when users can send email to each other
539 $helpMessages[] = 'prefs-help-email-others';
542 $emailAddress = $user->getEmail() ?
htmlspecialchars( $user->getEmail() ) : '';
543 if ( $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'emailaddress' ) ) {
544 if ( $oouiEnabled ) {
545 $link = new \OOUI\
ButtonWidget( [
546 'href' => SpecialPage
::getTitleFor( 'ChangeEmail' )->getLinkURL( [
547 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
550 $context->msg( $user->getEmail() ?
'prefs-changeemail' : 'prefs-setemail' )->text(),
553 $emailAddress .= $emailAddress == '' ?
$link : ( '<br />' . $link );
555 $link = $this->linkRenderer
->makeLink(
556 SpecialPage
::getTitleFor( 'ChangeEmail' ),
557 $context->msg( $user->getEmail() ?
'prefs-changeemail' : 'prefs-setemail' )->text(),
559 [ 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText() ] );
561 $emailAddress .= $emailAddress == '' ?
$link : (
562 $context->msg( 'word-separator' )->escaped()
563 . $context->msg( 'parentheses' )->rawParams( $link )->escaped()
568 $defaultPreferences['emailaddress'] = [
571 'default' => $emailAddress,
572 'label-message' => 'youremail',
573 'section' => 'personal/email',
574 'help-messages' => $helpMessages,
575 # 'cssclass' chosen below
579 $disableEmailPrefs = false;
581 if ( $this->config
->get( 'EmailAuthentication' ) ) {
582 $emailauthenticationclass = 'mw-email-not-authenticated';
583 if ( $user->getEmail() ) {
584 if ( $user->getEmailAuthenticationTimestamp() ) {
585 // date and time are separate parameters to facilitate localisation.
586 // $time is kept for backward compat reasons.
587 // 'emailauthenticated' is also used in SpecialConfirmemail.php
588 $displayUser = $context->getUser();
589 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
590 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
591 $d = $lang->userDate( $emailTimestamp, $displayUser );
592 $t = $lang->userTime( $emailTimestamp, $displayUser );
593 $emailauthenticated = $context->msg( 'emailauthenticated',
594 $time, $d, $t )->parse() . '<br />';
595 $disableEmailPrefs = false;
596 $emailauthenticationclass = 'mw-email-authenticated';
598 $disableEmailPrefs = true;
599 if ( $oouiEnabled ) {
600 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
601 new \OOUI\
ButtonWidget( [
602 'href' => SpecialPage
::getTitleFor( 'Confirmemail' )->getLinkURL(),
603 'label' => $context->msg( 'emailconfirmlink' )->text(),
606 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
607 $this->linkRenderer
->makeKnownLink(
608 SpecialPage
::getTitleFor( 'Confirmemail' ),
609 $context->msg( 'emailconfirmlink' )->text()
612 $emailauthenticationclass = "mw-email-not-authenticated";
615 $disableEmailPrefs = true;
616 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
617 $emailauthenticationclass = 'mw-email-none';
620 if ( $canViewPrivateInfo ) {
621 $defaultPreferences['emailauthentication'] = [
624 'section' => 'personal/email',
625 'label-message' => 'prefs-emailconfirm-label',
626 'default' => $emailauthenticated,
627 # Apply the same CSS class used on the input to the message:
628 'cssclass' => $emailauthenticationclass,
633 if ( $this->config
->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
634 $defaultPreferences['disablemail'] = [
635 'id' => 'wpAllowEmail',
638 'section' => 'personal/email',
639 'label-message' => 'allowemail',
640 'disabled' => $disableEmailPrefs,
643 $defaultPreferences['email-allow-new-users'] = [
644 'id' => 'wpAllowEmailFromNewUsers',
646 'section' => 'personal/email',
647 'label-message' => 'email-allow-new-users-label',
648 'disabled' => $disableEmailPrefs,
651 $defaultPreferences['ccmeonemails'] = [
653 'section' => 'personal/email',
654 'label-message' => 'tog-ccmeonemails',
655 'disabled' => $disableEmailPrefs,
658 if ( $this->config
->get( 'EnableUserEmailBlacklist' ) ) {
659 $lookup = CentralIdLookup
::factory();
660 $ids = $user->getOption( 'email-blacklist', [] );
661 $names = $ids ?
$lookup->namesFromCentralIds( $ids, $user ) : [];
663 $defaultPreferences['email-blacklist'] = [
664 'type' => 'usersmultiselect',
665 'label-message' => 'email-blacklist-label',
666 'section' => 'personal/email',
667 'default' => implode( "\n", $names ),
668 'disabled' => $disableEmailPrefs,
673 if ( $this->config
->get( 'EnotifWatchlist' ) ) {
674 $defaultPreferences['enotifwatchlistpages'] = [
676 'section' => 'personal/email',
677 'label-message' => 'tog-enotifwatchlistpages',
678 'disabled' => $disableEmailPrefs,
681 if ( $this->config
->get( 'EnotifUserTalk' ) ) {
682 $defaultPreferences['enotifusertalkpages'] = [
684 'section' => 'personal/email',
685 'label-message' => 'tog-enotifusertalkpages',
686 'disabled' => $disableEmailPrefs,
689 if ( $this->config
->get( 'EnotifUserTalk' ) ||
$this->config
->get( 'EnotifWatchlist' ) ) {
690 if ( $this->config
->get( 'EnotifMinorEdits' ) ) {
691 $defaultPreferences['enotifminoredits'] = [
693 'section' => 'personal/email',
694 'label-message' => 'tog-enotifminoredits',
695 'disabled' => $disableEmailPrefs,
699 if ( $this->config
->get( 'EnotifRevealEditorAddress' ) ) {
700 $defaultPreferences['enotifrevealaddr'] = [
702 'section' => 'personal/email',
703 'label-message' => 'tog-enotifrevealaddr',
704 'disabled' => $disableEmailPrefs,
713 * @param IContextSource $context
714 * @param array &$defaultPreferences
717 protected function skinPreferences( User
$user, IContextSource
$context, &$defaultPreferences ) {
718 # # Skin #####################################
720 // Skin selector, if there is at least one valid skin
721 $skinOptions = $this->generateSkinOptions( $user, $context );
722 if ( $skinOptions ) {
723 $defaultPreferences['skin'] = [
725 'options' => $skinOptions,
726 'section' => 'rendering/skin',
730 $allowUserCss = $this->config
->get( 'AllowUserCss' );
731 $allowUserJs = $this->config
->get( 'AllowUserJs' );
732 # Create links to user CSS/JS pages for all skins
733 # This code is basically copied from generateSkinOptions(). It'd
734 # be nice to somehow merge this back in there to avoid redundancy.
735 if ( $allowUserCss ||
$allowUserJs ) {
737 $userName = $user->getName();
739 if ( $allowUserCss ) {
740 $cssPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.css' );
741 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
742 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
745 if ( $allowUserJs ) {
746 $jsPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.js' );
747 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
748 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
751 $defaultPreferences['commoncssjs'] = [
754 'default' => $context->getLanguage()->pipeList( $linkTools ),
755 'label-message' => 'prefs-common-config',
756 'section' => 'rendering/skin',
762 * @param IContextSource $context
763 * @param array &$defaultPreferences
765 protected function filesPreferences( IContextSource
$context, &$defaultPreferences ) {
766 # # Files #####################################
767 $defaultPreferences['imagesize'] = [
769 'options' => $this->getImageSizes( $context ),
770 'label-message' => 'imagemaxsize',
771 'section' => 'rendering/files',
773 $defaultPreferences['thumbsize'] = [
775 'options' => $this->getThumbSizes( $context ),
776 'label-message' => 'thumbsize',
777 'section' => 'rendering/files',
783 * @param IContextSource $context
784 * @param array &$defaultPreferences
787 protected function datetimePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
788 # # Date and time #####################################
789 $dateOptions = $this->getDateOptions( $context );
790 if ( $dateOptions ) {
791 $defaultPreferences['date'] = [
793 'options' => $dateOptions,
794 'section' => 'rendering/dateformat',
799 $now = wfTimestampNow();
800 $lang = $context->getLanguage();
801 $nowlocal = Xml
::element( 'span', [ 'id' => 'wpLocalTime' ],
802 $lang->userTime( $now, $user ) );
803 $nowserver = $lang->userTime( $now, $user,
804 [ 'format' => false, 'timecorrection' => false ] ) .
805 Html
::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 +
(int)substr( $now, 10, 2 ) );
807 $defaultPreferences['nowserver'] = [
810 'label-message' => 'servertime',
811 'default' => $nowserver,
812 'section' => 'rendering/timeoffset',
815 $defaultPreferences['nowlocal'] = [
818 'label-message' => 'localtime',
819 'default' => $nowlocal,
820 'section' => 'rendering/timeoffset',
823 // Grab existing pref.
824 $tzOffset = $user->getOption( 'timecorrection' );
825 $tz = explode( '|', $tzOffset, 3 );
827 $tzOptions = $this->getTimezoneOptions( $context );
829 $tzSetting = $tzOffset;
830 if ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
831 !in_array( $tzOffset, HTMLFormField
::flattenOptions( $tzOptions ) )
833 // Timezone offset can vary with DST
835 $userTZ = new DateTimeZone( $tz[2] );
836 $minDiff = floor( $userTZ->getOffset( new DateTime( 'now' ) ) / 60 );
837 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
838 } catch ( Exception
$e ) {
839 // User has an invalid time zone set. Fall back to just using the offset
843 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
845 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) %
60 );
848 $defaultPreferences['timecorrection'] = [
849 'class' => \HTMLSelectOrOtherField
::class,
850 'label-message' => 'timezonelegend',
851 'options' => $tzOptions,
852 'default' => $tzSetting,
854 'section' => 'rendering/timeoffset',
855 'id' => 'wpTimeCorrection',
860 * @param MessageLocalizer $l10n
861 * @param array &$defaultPreferences
863 protected function renderingPreferences( MessageLocalizer
$l10n, &$defaultPreferences ) {
864 # # Diffs ####################################
865 $defaultPreferences['diffonly'] = [
867 'section' => 'rendering/diffs',
868 'label-message' => 'tog-diffonly',
870 $defaultPreferences['norollbackdiff'] = [
872 'section' => 'rendering/diffs',
873 'label-message' => 'tog-norollbackdiff',
876 # # Page Rendering ##############################
877 if ( $this->config
->get( 'AllowUserCssPrefs' ) ) {
878 $defaultPreferences['underline'] = [
881 $l10n->msg( 'underline-never' )->text() => 0,
882 $l10n->msg( 'underline-always' )->text() => 1,
883 $l10n->msg( 'underline-default' )->text() => 2,
885 'label-message' => 'tog-underline',
886 'section' => 'rendering/advancedrendering',
890 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
891 $stubThresholdOptions = [ $l10n->msg( 'stub-threshold-disabled' )->text() => 0 ];
892 foreach ( $stubThresholdValues as $value ) {
893 $stubThresholdOptions[$l10n->msg( 'size-bytes', $value )->text()] = $value;
896 $defaultPreferences['stubthreshold'] = [
898 'section' => 'rendering/advancedrendering',
899 'options' => $stubThresholdOptions,
900 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
901 'label-raw' => $l10n->msg( 'stub-threshold' )->rawParams(
902 '<a href="#" class="stub">' .
903 $l10n->msg( 'stub-threshold-sample-link' )->parse() .
907 $defaultPreferences['showhiddencats'] = [
909 'section' => 'rendering/advancedrendering',
910 'label-message' => 'tog-showhiddencats'
913 $defaultPreferences['numberheadings'] = [
915 'section' => 'rendering/advancedrendering',
916 'label-message' => 'tog-numberheadings',
922 * @param MessageLocalizer $l10n
923 * @param array &$defaultPreferences
925 protected function editingPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
926 # # Editing #####################################
927 $defaultPreferences['editsectiononrightclick'] = [
929 'section' => 'editing/advancedediting',
930 'label-message' => 'tog-editsectiononrightclick',
932 $defaultPreferences['editondblclick'] = [
934 'section' => 'editing/advancedediting',
935 'label-message' => 'tog-editondblclick',
938 if ( $this->config
->get( 'AllowUserCssPrefs' ) ) {
939 $defaultPreferences['editfont'] = [
941 'section' => 'editing/editor',
942 'label-message' => 'editfont-style',
944 $l10n->msg( 'editfont-monospace' )->text() => 'monospace',
945 $l10n->msg( 'editfont-sansserif' )->text() => 'sans-serif',
946 $l10n->msg( 'editfont-serif' )->text() => 'serif',
951 if ( $user->isAllowed( 'minoredit' ) ) {
952 $defaultPreferences['minordefault'] = [
954 'section' => 'editing/editor',
955 'label-message' => 'tog-minordefault',
959 $defaultPreferences['forceeditsummary'] = [
961 'section' => 'editing/editor',
962 'label-message' => 'tog-forceeditsummary',
964 $defaultPreferences['useeditwarning'] = [
966 'section' => 'editing/editor',
967 'label-message' => 'tog-useeditwarning',
969 $defaultPreferences['showtoolbar'] = [
971 'section' => 'editing/editor',
972 'label-message' => 'tog-showtoolbar',
975 $defaultPreferences['previewonfirst'] = [
977 'section' => 'editing/preview',
978 'label-message' => 'tog-previewonfirst',
980 $defaultPreferences['previewontop'] = [
982 'section' => 'editing/preview',
983 'label-message' => 'tog-previewontop',
985 $defaultPreferences['uselivepreview'] = [
987 'section' => 'editing/preview',
988 'label-message' => 'tog-uselivepreview',
994 * @param MessageLocalizer $l10n
995 * @param array &$defaultPreferences
997 protected function rcPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
998 $rcMaxAge = $this->config
->get( 'RCMaxAge' );
999 # # RecentChanges #####################################
1000 $defaultPreferences['rcdays'] = [
1002 'label-message' => 'recentchangesdays',
1003 'section' => 'rc/displayrc',
1005 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
1006 'help' => $l10n->msg( 'recentchangesdays-max' )->numParams(
1007 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
1009 $defaultPreferences['rclimit'] = [
1013 'label-message' => 'recentchangescount',
1014 'help-message' => 'prefs-help-recentchangescount',
1015 'section' => 'rc/displayrc',
1017 $defaultPreferences['usenewrc'] = [
1019 'label-message' => 'tog-usenewrc',
1020 'section' => 'rc/advancedrc',
1022 $defaultPreferences['hideminor'] = [
1024 'label-message' => 'tog-hideminor',
1025 'section' => 'rc/advancedrc',
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->config
->get( 'RCWatchCategoryMembership' ) ) {
1045 $defaultPreferences['hidecategorization'] = [
1047 'label-message' => 'tog-hidecategorization',
1048 'section' => 'rc/advancedrc',
1052 if ( $user->useRCPatrol() ) {
1053 $defaultPreferences['hidepatrolled'] = [
1055 'section' => 'rc/advancedrc',
1056 'label-message' => 'tog-hidepatrolled',
1060 if ( $user->useNPPatrol() ) {
1061 $defaultPreferences['newpageshidepatrolled'] = [
1063 'section' => 'rc/advancedrc',
1064 'label-message' => 'tog-newpageshidepatrolled',
1068 if ( $this->config
->get( 'RCShowWatchingUsers' ) ) {
1069 $defaultPreferences['shownumberswatching'] = [
1071 'section' => 'rc/advancedrc',
1072 'label-message' => 'tog-shownumberswatching',
1076 if ( $this->config
->get( 'StructuredChangeFiltersShowPreference' ) ) {
1077 $defaultPreferences['rcenhancedfilters-disable'] = [
1079 'section' => 'rc/opt-out',
1080 'label-message' => 'rcfilters-preference-label',
1081 'help-message' => 'rcfilters-preference-help',
1088 * @param IContextSource $context
1089 * @param array &$defaultPreferences
1091 protected function watchlistPreferences(
1092 User
$user, IContextSource
$context, &$defaultPreferences
1094 $oouiEnabled = SpecialPreferences
::isOouiEnabled( $context );
1096 $watchlistdaysMax = ceil( $this->config
->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1098 # # Watchlist #####################################
1099 if ( $user->isAllowed( 'editmywatchlist' ) ) {
1100 $editWatchlistLinks = '';
1101 $editWatchlistLinksOld = [];
1102 $editWatchlistModes = [
1103 'edit' => [ 'subpage' => false, 'flags' => [] ],
1104 'raw' => [ 'subpage' => 'raw', 'flags' => [] ],
1105 'clear' => [ 'subpage' => 'clear', 'flags' => [ 'destructive' ] ],
1107 foreach ( $editWatchlistModes as $mode => $options ) {
1108 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1109 if ( $oouiEnabled ) {
1110 $editWatchlistLinks .=
1111 new \OOUI\
ButtonWidget( [
1112 'href' => SpecialPage
::getTitleFor( 'EditWatchlist', $options['subpage'] )->getLinkURL(),
1113 'flags' => $options[ 'flags' ],
1114 'label' => new \OOUI\
HtmlSnippet(
1115 $context->msg( "prefs-editwatchlist-{$mode}" )->parse()
1119 $editWatchlistLinksOld[] = $this->linkRenderer
->makeKnownLink(
1120 SpecialPage
::getTitleFor( 'EditWatchlist', $options['subpage'] ),
1121 new HtmlArmor( $context->msg( "prefs-editwatchlist-{$mode}" )->parse() )
1126 $defaultPreferences['editwatchlist'] = [
1129 'default' => $oouiEnabled ?
1130 $editWatchlistLinks :
1131 $context->getLanguage()->pipeList( $editWatchlistLinksOld ),
1132 'label-message' => 'prefs-editwatchlist-label',
1133 'section' => 'watchlist/editwatchlist',
1137 $defaultPreferences['watchlistdays'] = [
1140 'max' => $watchlistdaysMax,
1141 'section' => 'watchlist/displaywatchlist',
1142 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1143 $watchlistdaysMax )->escaped(),
1144 'label-message' => 'prefs-watchlist-days',
1146 $defaultPreferences['wllimit'] = [
1150 'label-message' => 'prefs-watchlist-edits',
1151 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1152 'section' => 'watchlist/displaywatchlist',
1154 $defaultPreferences['extendwatchlist'] = [
1156 'section' => 'watchlist/advancedwatchlist',
1157 'label-message' => 'tog-extendwatchlist',
1159 $defaultPreferences['watchlisthideminor'] = [
1161 'section' => 'watchlist/advancedwatchlist',
1162 'label-message' => 'tog-watchlisthideminor',
1164 $defaultPreferences['watchlisthidebots'] = [
1166 'section' => 'watchlist/advancedwatchlist',
1167 'label-message' => 'tog-watchlisthidebots',
1169 $defaultPreferences['watchlisthideown'] = [
1171 'section' => 'watchlist/advancedwatchlist',
1172 'label-message' => 'tog-watchlisthideown',
1174 $defaultPreferences['watchlisthideanons'] = [
1176 'section' => 'watchlist/advancedwatchlist',
1177 'label-message' => 'tog-watchlisthideanons',
1179 $defaultPreferences['watchlisthideliu'] = [
1181 'section' => 'watchlist/advancedwatchlist',
1182 'label-message' => 'tog-watchlisthideliu',
1185 if ( !\SpecialWatchlist
::checkStructuredFilterUiEnabled(
1189 $defaultPreferences['watchlistreloadautomatically'] = [
1191 'section' => 'watchlist/advancedwatchlist',
1192 'label-message' => 'tog-watchlistreloadautomatically',
1196 $defaultPreferences['watchlistunwatchlinks'] = [
1198 'section' => 'watchlist/advancedwatchlist',
1199 'label-message' => 'tog-watchlistunwatchlinks',
1202 if ( $this->config
->get( 'RCWatchCategoryMembership' ) ) {
1203 $defaultPreferences['watchlisthidecategorization'] = [
1205 'section' => 'watchlist/advancedwatchlist',
1206 'label-message' => 'tog-watchlisthidecategorization',
1210 if ( $user->useRCPatrol() ) {
1211 $defaultPreferences['watchlisthidepatrolled'] = [
1213 'section' => 'watchlist/advancedwatchlist',
1214 'label-message' => 'tog-watchlisthidepatrolled',
1219 'edit' => 'watchdefault',
1220 'move' => 'watchmoves',
1221 'delete' => 'watchdeletion'
1225 if ( $user->isAllowed( 'createpage' ) ||
$user->isAllowed( 'createtalk' ) ) {
1226 $watchTypes['read'] = 'watchcreations';
1229 if ( $user->isAllowed( 'rollback' ) ) {
1230 $watchTypes['rollback'] = 'watchrollback';
1233 if ( $user->isAllowed( 'upload' ) ) {
1234 $watchTypes['upload'] = 'watchuploads';
1237 foreach ( $watchTypes as $action => $pref ) {
1238 if ( $user->isAllowed( $action ) ) {
1240 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1241 // tog-watchrollback
1242 $defaultPreferences[$pref] = [
1244 'section' => 'watchlist/advancedwatchlist',
1245 'label-message' => "tog-$pref",
1250 $defaultPreferences['watchlisttoken'] = [
1254 if ( $oouiEnabled ) {
1255 $tokenButton = new \OOUI\
ButtonWidget( [
1256 'href' => SpecialPage
::getTitleFor( 'ResetTokens' )->getLinkURL( [
1257 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
1259 'label' => $context->msg( 'prefs-watchlist-managetokens' )->text(),
1261 $defaultPreferences['watchlisttoken-info'] = [
1263 'section' => 'watchlist/tokenwatchlist',
1264 'label-message' => 'prefs-watchlist-token',
1265 'help-message' => 'prefs-help-tokenmanagement',
1267 'default' => (string)$tokenButton,
1270 $defaultPreferences['watchlisttoken-info'] = [
1272 'section' => 'watchlist/tokenwatchlist',
1273 'label-message' => 'prefs-watchlist-token',
1274 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1275 'help-message' => 'prefs-help-watchlist-token2',
1279 if ( $this->config
->get( 'StructuredChangeFiltersShowWatchlistPreference' ) ) {
1280 $defaultPreferences['wlenhancedfilters-disable'] = [
1282 'section' => 'watchlist/opt-out',
1283 'label-message' => 'rcfilters-watchlist-preference-label',
1284 'help-message' => 'rcfilters-watchlist-preference-help',
1290 * @param array &$defaultPreferences
1292 protected function searchPreferences( &$defaultPreferences ) {
1293 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
1294 $defaultPreferences['searchNs' . $n] = [
1301 * @param User $user The User object
1302 * @param IContextSource $context
1303 * @return array Text/links to display as key; $skinkey as value
1305 protected function generateSkinOptions( User
$user, IContextSource
$context ) {
1308 $mptitle = Title
::newMainPage();
1309 $previewtext = $context->msg( 'skin-preview' )->escaped();
1311 # Only show skins that aren't disabled in $wgSkipSkins
1312 $validSkinNames = Skin
::getAllowedSkins();
1314 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1315 $msg = $context->msg( "skinname-{$skinkey}" );
1316 if ( $msg->exists() ) {
1317 $skinname = htmlspecialchars( $msg->text() );
1321 $defaultSkin = $this->config
->get( 'DefaultSkin' );
1322 $allowUserCss = $this->config
->get( 'AllowUserCss' );
1323 $allowUserJs = $this->config
->get( 'AllowUserJs' );
1325 # Sort by the internal name, so that the ordering is the same for each display language,
1326 # especially if some skin names are translated to use a different alphabet and some are not.
1327 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1328 # Display the default first in the list by comparing it as lesser than any other.
1329 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1332 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1335 return strcasecmp( $a, $b );
1338 $foundDefault = false;
1339 foreach ( $validSkinNames as $skinkey => $sn ) {
1342 # Mark the default skin
1343 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1344 $linkTools[] = $context->msg( 'default' )->escaped();
1345 $foundDefault = true;
1348 # Create preview link
1349 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1350 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1352 # Create links to user CSS/JS pages
1353 if ( $allowUserCss ) {
1354 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1355 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
1356 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
1359 if ( $allowUserJs ) {
1360 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1361 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
1362 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
1365 $display = $sn . ' ' . $context->msg( 'parentheses' )
1366 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1368 $ret[$display] = $skinkey;
1371 if ( !$foundDefault ) {
1372 // If the default skin is not available, things are going to break horribly because the
1373 // default value for skin selector will not be a valid value. Let's just not show it then.
1381 * @param IContextSource $context
1384 protected function getDateOptions( IContextSource
$context ) {
1385 $lang = $context->getLanguage();
1386 $dateopts = $lang->getDatePreferences();
1391 if ( !in_array( 'default', $dateopts ) ) {
1392 $dateopts[] = 'default'; // Make sure default is always valid T21237
1395 // FIXME KLUGE: site default might not be valid for user language
1396 global $wgDefaultUserOptions;
1397 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1398 $wgDefaultUserOptions['date'] = 'default';
1401 $epoch = wfTimestampNow();
1402 foreach ( $dateopts as $key ) {
1403 if ( $key == 'default' ) {
1404 $formatted = $context->msg( 'datedefault' )->escaped();
1406 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1408 $ret[$formatted] = $key;
1415 * @param MessageLocalizer $l10n
1418 protected function getImageSizes( MessageLocalizer
$l10n ) {
1420 $pixels = $l10n->msg( 'unit-pixel' )->text();
1422 foreach ( $this->config
->get( 'ImageLimits' ) as $index => $limits ) {
1423 // Note: A left-to-right marker (\u200e) is inserted, see T144386
1424 $display = "{$limits[0]}" . json_decode( '"\u200e"' ) . "×{$limits[1]}" . $pixels;
1425 $ret[$display] = $index;
1432 * @param MessageLocalizer $l10n
1435 protected function getThumbSizes( MessageLocalizer
$l10n ) {
1437 $pixels = $l10n->msg( 'unit-pixel' )->text();
1439 foreach ( $this->config
->get( 'ThumbLimits' ) as $index => $size ) {
1440 $display = $size . $pixels;
1441 $ret[$display] = $index;
1448 * @param string $signature
1449 * @param array $alldata
1450 * @param HTMLForm $form
1451 * @return bool|string
1453 protected function validateSignature( $signature, $alldata, HTMLForm
$form ) {
1454 $maxSigChars = $this->config
->get( 'MaxSigChars' );
1455 if ( mb_strlen( $signature ) > $maxSigChars ) {
1456 return Xml
::element( 'span', [ 'class' => 'error' ],
1457 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1458 } elseif ( isset( $alldata['fancysig'] ) &&
1459 $alldata['fancysig'] &&
1460 MediaWikiServices
::getInstance()->getParser()->validateSig( $signature ) === false
1462 return Xml
::element(
1464 [ 'class' => 'error' ],
1465 $form->msg( 'badsig' )->text()
1473 * @param string $signature
1474 * @param array $alldata
1475 * @param HTMLForm $form
1478 protected function cleanSignature( $signature, $alldata, HTMLForm
$form ) {
1479 $parser = MediaWikiServices
::getInstance()->getParser();
1480 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1481 $signature = $parser->cleanSig( $signature );
1483 // When no fancy sig used, make sure ~{3,5} get removed.
1484 $signature = Parser
::cleanSigInSig( $signature );
1492 * @param IContextSource $context
1493 * @param string $formClass
1494 * @param array $remove Array of items to remove
1495 * @return PreferencesForm
1497 public function getForm(
1499 IContextSource
$context,
1500 $formClass = PreferencesFormOOUI
::class,
1503 if ( SpecialPreferences
::isOouiEnabled( $context ) ) {
1504 // We use ButtonWidgets in some of the getPreferences() functions
1505 $context->getOutput()->enableOOUI();
1508 $formDescriptor = $this->getFormDescriptor( $user, $context );
1509 if ( count( $remove ) ) {
1510 $removeKeys = array_flip( $remove );
1511 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1514 // Remove type=api preferences. They are not intended for rendering in the form.
1515 foreach ( $formDescriptor as $name => $info ) {
1516 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1517 unset( $formDescriptor[$name] );
1522 * @var $htmlForm PreferencesForm
1524 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1526 $htmlForm->setModifiedUser( $user );
1527 $htmlForm->setId( 'mw-prefs-form' );
1528 $htmlForm->setAutocomplete( 'off' );
1529 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1530 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1531 $htmlForm->setSubmitTooltip( 'preferences-save' );
1532 $htmlForm->setSubmitID( 'prefcontrol' );
1533 $htmlForm->setSubmitCallback( function ( array $formData, PreferencesForm
$form ) {
1534 return $this->submitForm( $formData, $form );
1541 * @param IContextSource $context
1544 protected function getTimezoneOptions( IContextSource
$context ) {
1547 $localTZoffset = $this->config
->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'];
1586 * @param array $alldata
1589 protected function filterTimezoneInput( $tz, array $alldata ) {
1590 $data = explode( '|', $tz, 3 );
1591 switch ( $data[0] ) {
1595 if ( count( $data ) === 3 ) {
1596 // Make sure this timezone exists
1598 new DateTimeZone( $data[2] );
1599 // If the constructor didn't throw, we know it's valid
1601 } catch ( Exception
$e ) {
1602 // Not a valid timezone
1607 // If the supplied timezone doesn't exist, fall back to the encoded offset
1608 return 'Offset|' . intval( $tz[1] );
1614 $data = explode( ':', $tz, 2 );
1615 if ( count( $data ) == 2 ) {
1616 $data[0] = intval( $data[0] );
1617 $data[1] = intval( $data[1] );
1618 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1619 if ( $data[0] < 0 ) {
1620 $minDiff = - $minDiff;
1623 $minDiff = intval( $data[0] ) * 60;
1626 # Max is +14:00 and min is -12:00, see:
1627 # https://en.wikipedia.org/wiki/Timezone
1628 $minDiff = min( $minDiff, 840 ); # 14:00
1629 $minDiff = max( $minDiff, -720 ); # -12:00
1630 return 'Offset|' . $minDiff;
1635 * Handle the form submission if everything validated properly
1637 * @param array $formData
1638 * @param PreferencesForm $form
1639 * @return bool|Status|string
1641 protected function saveFormData( $formData, PreferencesForm
$form ) {
1642 $user = $form->getModifiedUser();
1643 $hiddenPrefs = $this->config
->get( 'HiddenPrefs' );
1646 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1647 return Status
::newFatal( 'mypreferencesprotected' );
1651 foreach ( array_keys( $formData ) as $name ) {
1652 $filters = $this->getSaveFilters();
1653 if ( isset( $filters[$name] ) ) {
1654 $formData[$name] = call_user_func( $filters[$name], $formData[$name], $formData );
1658 // Fortunately, the realname field is MUCH simpler
1659 // (not really "private", but still shouldn't be edited without permission)
1661 if ( !in_array( 'realname', $hiddenPrefs )
1662 && $user->isAllowed( 'editmyprivateinfo' )
1663 && array_key_exists( 'realname', $formData )
1665 $realName = $formData['realname'];
1666 $user->setRealName( $realName );
1669 if ( $user->isAllowed( 'editmyoptions' ) ) {
1670 $oldUserOptions = $user->getOptions();
1672 foreach ( $this->getSaveBlacklist() as $b ) {
1673 unset( $formData[$b] );
1676 # If users have saved a value for a preference which has subsequently been disabled
1677 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1678 # is subsequently re-enabled
1679 foreach ( $hiddenPrefs as $pref ) {
1680 # If the user has not set a non-default value here, the default will be returned
1681 # and subsequently discarded
1682 $formData[$pref] = $user->getOption( $pref, null, true );
1685 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1687 isset( $formData['rclimit'] ) &&
1688 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1690 $formData['rcfilters-limit'] = $formData['rclimit'];
1693 // Keep old preferences from interfering due to back-compat code, etc.
1694 $user->resetOptions( 'unused', $form->getContext() );
1696 foreach ( $formData as $key => $value ) {
1697 $user->setOption( $key, $value );
1701 'PreferencesFormPreSave',
1702 [ $formData, $form, $user, &$result, $oldUserOptions ]
1706 AuthManager
::callLegacyAuthPlugin( 'updateExternalDB', [ $user ] );
1707 $user->saveSettings();
1713 * DO NOT USE. Temporary function to punch hole for the Preferences class.
1715 * @deprecated since 1.31, its inception
1717 * @param array $formData
1718 * @param PreferencesForm $form
1719 * @return bool|Status|string
1721 public function legacySaveFormData( $formData, PreferencesForm
$form ) {
1722 return $this->saveFormData( $formData, $form );
1726 * Save the form data and reload the page
1728 * @param array $formData
1729 * @param PreferencesForm $form
1732 protected function submitForm( array $formData, PreferencesForm
$form ) {
1733 $res = $this->saveFormData( $formData, $form );
1736 $context = $form->getContext();
1740 if ( $res === 'eauth' ) {
1741 $urlOptions['eauth'] = 1;
1745 $context->getRequest()->getFuzzyBool( 'ooui' ) !==
1746 $context->getConfig()->get( 'OOUIPreferences' )
1748 $urlOptions[ 'ooui' ] = $context->getRequest()->getFuzzyBool( 'ooui' ) ?
1 : 0;
1751 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1753 $url = $form->getTitle()->getFullURL( $urlOptions );
1755 // Set session data for the success message
1756 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1758 $context->getOutput()->redirect( $url );
1761 return Status
::newGood();
1765 * DO NOT USE. Temporary function to punch hole for the Preferences class.
1767 * @deprecated since 1.31, its inception
1769 * @param array $formData
1770 * @param PreferencesForm $form
1773 public function legacySubmitForm( array $formData, PreferencesForm
$form ) {
1774 return $this->submitForm( $formData, $form );
1778 * Get a list of all time zones
1779 * @param Language $language Language used for the localized names
1780 * @return array A list of all time zones. The system name of the time zone is used as key and
1781 * the value is an array which contains localized name, the timecorrection value used for
1782 * preferences and the region
1785 protected function getTimeZoneList( Language
$language ) {
1786 $identifiers = DateTimeZone
::listIdentifiers();
1787 if ( $identifiers === false ) {
1790 sort( $identifiers );
1793 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1794 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1795 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1796 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1797 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1798 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1799 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1800 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1801 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1802 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1804 asort( $tzRegions );
1808 $now = new DateTime();
1810 foreach ( $identifiers as $identifier ) {
1811 $parts = explode( '/', $identifier, 2 );
1813 // DateTimeZone::listIdentifiers() returns a number of
1814 // backwards-compatibility entries. This filters them out of the
1815 // list presented to the user.
1816 if ( count( $parts ) !== 2 ||
!array_key_exists( $parts[0], $tzRegions ) ) {
1821 $parts[0] = $tzRegions[$parts[0]];
1823 $dateTimeZone = new DateTimeZone( $identifier );
1824 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1826 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1827 $value = "ZoneInfo|$minDiff|$identifier";
1829 $timeZoneList[$identifier] = [
1831 'timecorrection' => $value,
1832 'region' => $parts[0],
1836 return $timeZoneList;