3 * Form to edit user preferences.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
22 use MediaWiki\Auth\AuthManager
;
23 use MediaWiki\Auth\PasswordAuthenticationRequest
;
24 use MediaWiki\MediaWikiServices
;
27 * We're now using the HTMLForm object with some customisation to generate the
28 * Preferences form. This object handles generic submission, CSRF protection,
29 * layout and other logic in a reusable manner. We subclass it as a PreferencesForm
30 * to make some minor customisations.
32 * In order to generate the form, the HTMLForm object needs an array structure
33 * detailing the form fields available, and that's what this class is for. Each
34 * element of the array is a basic property-list, including the type of field,
35 * the label it is to be given in the form, callbacks for validation and
36 * 'filtering', and other pertinent information. Note that the 'default' field
37 * is named for generic forms, and does not represent the preference's default
38 * (which is stored in $wgDefaultUserOptions), but the default for the form
39 * field, which should be whatever the user has set for that preference. There
40 * is no need to override it unless you have some special storage logic (for
41 * instance, those not presently stored as options, but which are best set from
42 * the user preferences view).
44 * Field types are implemented as subclasses of the generic HTMLFormField
45 * object, and typically implement at least getInputHTML, which generates the
46 * HTML for the input field to be placed in the table.
48 * Once fields have been retrieved and validated, submission logic is handed
49 * over to the tryUISubmit static method of this class.
53 protected static $defaultPreferences = null;
56 protected static $saveFilters = [
57 'timecorrection' => [ 'Preferences', 'filterTimezoneInput' ],
58 'cols' => [ 'Preferences', 'filterIntval' ],
59 'rows' => [ 'Preferences', 'filterIntval' ],
60 'rclimit' => [ 'Preferences', 'filterIntval' ],
61 'wllimit' => [ 'Preferences', 'filterIntval' ],
62 'searchlimit' => [ 'Preferences', 'filterIntval' ],
65 // Stuff that shouldn't be saved as a preference.
66 private static $saveBlacklist = [
74 static function getSaveBlacklist() {
75 return self
::$saveBlacklist;
81 * @param IContextSource $context
84 static function getPreferences( $user, IContextSource
$context ) {
85 if ( self
::$defaultPreferences ) {
86 return self
::$defaultPreferences;
89 $defaultPreferences = [];
91 self
::profilePreferences( $user, $context, $defaultPreferences );
92 self
::skinPreferences( $user, $context, $defaultPreferences );
93 self
::datetimePreferences( $user, $context, $defaultPreferences );
94 self
::filesPreferences( $user, $context, $defaultPreferences );
95 self
::renderingPreferences( $user, $context, $defaultPreferences );
96 self
::editingPreferences( $user, $context, $defaultPreferences );
97 self
::rcPreferences( $user, $context, $defaultPreferences );
98 self
::watchlistPreferences( $user, $context, $defaultPreferences );
99 self
::searchPreferences( $user, $context, $defaultPreferences );
100 self
::miscPreferences( $user, $context, $defaultPreferences );
102 Hooks
::run( 'GetPreferences', [ $user, &$defaultPreferences ] );
104 self
::loadPreferenceValues( $user, $context, $defaultPreferences );
105 self
::$defaultPreferences = $defaultPreferences;
106 return $defaultPreferences;
110 * Loads existing values for a given array of preferences
111 * @throws MWException
113 * @param IContextSource $context
114 * @param array $defaultPreferences Array to load values for
117 static function loadPreferenceValues( $user, $context, &$defaultPreferences ) {
118 # # Remove preferences that wikis don't want to use
119 foreach ( $context->getConfig()->get( 'HiddenPrefs' ) as $pref ) {
120 if ( isset( $defaultPreferences[$pref] ) ) {
121 unset( $defaultPreferences[$pref] );
125 # # Make sure that form fields have their parent set. See bug 41337.
126 $dummyForm = new HTMLForm( [], $context );
128 $disable = !$user->isAllowed( 'editmyoptions' );
130 $defaultOptions = User
::getDefaultOptions();
131 # # Prod in defaults from the user
132 foreach ( $defaultPreferences as $name => &$info ) {
133 $prefFromUser = self
::getOptionFromUser( $name, $info, $user );
134 if ( $disable && !in_array( $name, self
::$saveBlacklist ) ) {
135 $info['disabled'] = 'disabled';
137 $field = HTMLForm
::loadInputFromParameters( $name, $info, $dummyForm ); // For validation
138 $globalDefault = isset( $defaultOptions[$name] )
139 ?
$defaultOptions[$name]
142 // If it validates, set it as the default
143 if ( isset( $info['default'] ) ) {
144 // Already set, no problem
146 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
147 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
148 $info['default'] = $prefFromUser;
149 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
150 $info['default'] = $globalDefault;
152 throw new MWException( "Global default '$globalDefault' is invalid for field $name" );
156 return $defaultPreferences;
160 * Pull option from a user account. Handles stuff like array-type preferences.
162 * @param string $name
165 * @return array|string
167 static function getOptionFromUser( $name, $info, $user ) {
168 $val = $user->getOption( $name );
170 // Handling for multiselect preferences
171 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
172 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
173 $options = HTMLFormField
::flattenOptions( $info['options'] );
174 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
177 foreach ( $options as $value ) {
178 if ( $user->getOption( "$prefix$value" ) ) {
184 // Handling for checkmatrix preferences
185 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
186 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
187 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
188 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
189 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
192 foreach ( $columns as $column ) {
193 foreach ( $rows as $row ) {
194 if ( $user->getOption( "$prefix$column-$row" ) ) {
195 $val[] = "$column-$row";
206 * @param IContextSource $context
207 * @param array $defaultPreferences
210 static function profilePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
211 global $wgContLang, $wgParser;
213 $authManager = AuthManager
::singleton();
214 $config = $context->getConfig();
215 // retrieving user name for GENDER and misc.
216 $userName = $user->getName();
218 # # User info #####################################
220 $defaultPreferences['username'] = [
222 'label-message' => [ 'username', $userName ],
223 'default' => $userName,
224 'section' => 'personal/info',
227 # Get groups to which the user belongs
228 $userEffectiveGroups = $user->getEffectiveGroups();
229 $userGroups = $userMembers = [];
230 foreach ( $userEffectiveGroups as $ueg ) {
232 // Skip the default * group, seems useless here
235 $groupName = User
::getGroupName( $ueg );
236 $userGroups[] = User
::makeGroupLinkHTML( $ueg, $groupName );
238 $memberName = User
::getGroupMember( $ueg, $userName );
239 $userMembers[] = User
::makeGroupLinkHTML( $ueg, $memberName );
241 asort( $userGroups );
242 asort( $userMembers );
244 $lang = $context->getLanguage();
246 $defaultPreferences['usergroups'] = [
248 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
249 count( $userGroups ) )->params( $userName )->parse(),
250 'default' => $context->msg( 'prefs-memberingroups-type' )
251 ->rawParams( $lang->commaList( $userGroups ), $lang->commaList( $userMembers ) )
254 'section' => 'personal/info',
257 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
259 $editCount = $linkRenderer->makeLink( SpecialPage
::getTitleFor( "Contributions", $userName ),
260 $lang->formatNum( $user->getEditCount() ) );
262 $defaultPreferences['editcount'] = [
265 'label-message' => 'prefs-edits',
266 'default' => $editCount,
267 'section' => 'personal/info',
270 if ( $user->getRegistration() ) {
271 $displayUser = $context->getUser();
272 $userRegistration = $user->getRegistration();
273 $defaultPreferences['registrationdate'] = [
275 'label-message' => 'prefs-registration',
276 'default' => $context->msg(
277 'prefs-registration-date-time',
278 $lang->userTimeAndDate( $userRegistration, $displayUser ),
279 $lang->userDate( $userRegistration, $displayUser ),
280 $lang->userTime( $userRegistration, $displayUser )
282 'section' => 'personal/info',
286 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
287 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
289 // Actually changeable stuff
290 $defaultPreferences['realname'] = [
291 // (not really "private", but still shouldn't be edited without permission)
292 'type' => $canEditPrivateInfo && $authManager->allowsPropertyChange( 'realname' )
294 'default' => $user->getRealName(),
295 'section' => 'personal/info',
296 'label-message' => 'yourrealname',
297 'help-message' => 'prefs-help-realname',
300 if ( $canEditPrivateInfo && $authManager->allowsAuthenticationDataChange(
301 new PasswordAuthenticationRequest(), false )->isGood()
303 $link = $linkRenderer->makeLink( SpecialPage
::getTitleFor( 'ChangePassword' ),
304 $context->msg( 'prefs-resetpass' )->text(), [],
305 [ 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText() ] );
307 $defaultPreferences['password'] = [
311 'label-message' => 'yourpassword',
312 'section' => 'personal/info',
315 // Only show prefershttps if secure login is turned on
316 if ( $config->get( 'SecureLogin' ) && wfCanIPUseHTTPS( $context->getRequest()->getIP() ) ) {
317 $defaultPreferences['prefershttps'] = [
319 'label-message' => 'tog-prefershttps',
320 'help-message' => 'prefs-help-prefershttps',
321 'section' => 'personal/info'
326 $languages = Language
::fetchLanguageNames( null, 'mw' );
327 $languageCode = $config->get( 'LanguageCode' );
328 if ( !array_key_exists( $languageCode, $languages ) ) {
329 $languages[$languageCode] = $languageCode;
334 foreach ( $languages as $code => $name ) {
335 $display = wfBCP47( $code ) . ' - ' . $name;
336 $options[$display] = $code;
338 $defaultPreferences['language'] = [
340 'section' => 'personal/i18n',
341 'options' => $options,
342 'label-message' => 'yourlanguage',
345 $defaultPreferences['gender'] = [
347 'section' => 'personal/i18n',
349 $context->msg( 'parentheses' )
350 ->params( $context->msg( 'gender-unknown' )->plain() )
351 ->escaped() => 'unknown',
352 $context->msg( 'gender-female' )->escaped() => 'female',
353 $context->msg( 'gender-male' )->escaped() => 'male',
355 'label-message' => 'yourgender',
356 'help-message' => 'prefs-help-gender',
359 // see if there are multiple language variants to choose from
360 if ( !$config->get( 'DisableLangConversion' ) ) {
361 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
362 if ( $langCode == $wgContLang->getCode() ) {
363 $variants = $wgContLang->getVariants();
365 if ( count( $variants ) <= 1 ) {
370 foreach ( $variants as $v ) {
371 $v = str_replace( '_', '-', strtolower( $v ) );
372 $variantArray[$v] = $lang->getVariantname( $v, false );
376 foreach ( $variantArray as $code => $name ) {
377 $display = wfBCP47( $code ) . ' - ' . $name;
378 $options[$display] = $code;
381 $defaultPreferences['variant'] = [
382 'label-message' => 'yourvariant',
384 'options' => $options,
385 'section' => 'personal/i18n',
386 'help-message' => 'prefs-help-variant',
389 $defaultPreferences["variant-$langCode"] = [
396 // Stuff from Language::getExtraUserToggles()
397 // FIXME is this dead code? $extraUserToggles doesn't seem to be defined for any language
398 $toggles = $wgContLang->getExtraUserToggles();
400 foreach ( $toggles as $toggle ) {
401 $defaultPreferences[$toggle] = [
403 'section' => 'personal/i18n',
404 'label-message' => "tog-$toggle",
408 // show a preview of the old signature first
409 $oldsigWikiText = $wgParser->preSaveTransform(
411 $context->getTitle(),
413 ParserOptions
::newFromContext( $context )
415 $oldsigHTML = $context->getOutput()->parseInline( $oldsigWikiText, true, true );
416 $defaultPreferences['oldsig'] = [
419 'label-message' => 'tog-oldsig',
420 'default' => $oldsigHTML,
421 'section' => 'personal/signature',
423 $defaultPreferences['nickname'] = [
424 'type' => $authManager->allowsPropertyChange( 'nickname' ) ?
'text' : 'info',
425 'maxlength' => $config->get( 'MaxSigChars' ),
426 'label-message' => 'yournick',
427 'validation-callback' => [ 'Preferences', 'validateSignature' ],
428 'section' => 'personal/signature',
429 'filter-callback' => [ 'Preferences', 'cleanSignature' ],
431 $defaultPreferences['fancysig'] = [
433 'label-message' => 'tog-fancysig',
434 // show general help about signature at the bottom of the section
435 'help-message' => 'prefs-help-signature',
436 'section' => 'personal/signature'
441 if ( $config->get( 'EnableEmail' ) ) {
442 if ( $canViewPrivateInfo ) {
443 $helpMessages[] = $config->get( 'EmailConfirmToEdit' )
444 ?
'prefs-help-email-required'
445 : 'prefs-help-email';
447 if ( $config->get( 'EnableUserEmail' ) ) {
448 // additional messages when users can send email to each other
449 $helpMessages[] = 'prefs-help-email-others';
452 $emailAddress = $user->getEmail() ?
htmlspecialchars( $user->getEmail() ) : '';
453 if ( $canEditPrivateInfo && $authManager->allowsPropertyChange( 'emailaddress' ) ) {
454 $link = $linkRenderer->makeLink(
455 SpecialPage
::getTitleFor( 'ChangeEmail' ),
456 $context->msg( $user->getEmail() ?
'prefs-changeemail' : 'prefs-setemail' )->text(),
458 [ 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText() ] );
460 $emailAddress .= $emailAddress == '' ?
$link : (
461 $context->msg( 'word-separator' )->escaped()
462 . $context->msg( 'parentheses' )->rawParams( $link )->escaped()
466 $defaultPreferences['emailaddress'] = [
469 'default' => $emailAddress,
470 'label-message' => 'youremail',
471 'section' => 'personal/email',
472 'help-messages' => $helpMessages,
473 # 'cssclass' chosen below
477 $disableEmailPrefs = false;
479 if ( $config->get( 'EmailAuthentication' ) ) {
480 $emailauthenticationclass = 'mw-email-not-authenticated';
481 if ( $user->getEmail() ) {
482 if ( $user->getEmailAuthenticationTimestamp() ) {
483 // date and time are separate parameters to facilitate localisation.
484 // $time is kept for backward compat reasons.
485 // 'emailauthenticated' is also used in SpecialConfirmemail.php
486 $displayUser = $context->getUser();
487 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
488 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
489 $d = $lang->userDate( $emailTimestamp, $displayUser );
490 $t = $lang->userTime( $emailTimestamp, $displayUser );
491 $emailauthenticated = $context->msg( 'emailauthenticated',
492 $time, $d, $t )->parse() . '<br />';
493 $disableEmailPrefs = false;
494 $emailauthenticationclass = 'mw-email-authenticated';
496 $disableEmailPrefs = true;
497 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
499 SpecialPage
::getTitleFor( 'Confirmemail' ),
500 $context->msg( 'emailconfirmlink' )->escaped()
502 $emailauthenticationclass = "mw-email-not-authenticated";
505 $disableEmailPrefs = true;
506 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
507 $emailauthenticationclass = 'mw-email-none';
510 if ( $canViewPrivateInfo ) {
511 $defaultPreferences['emailauthentication'] = [
514 'section' => 'personal/email',
515 'label-message' => 'prefs-emailconfirm-label',
516 'default' => $emailauthenticated,
517 # Apply the same CSS class used on the input to the message:
518 'cssclass' => $emailauthenticationclass,
523 if ( $config->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
524 $defaultPreferences['disablemail'] = [
527 'section' => 'personal/email',
528 'label-message' => 'allowemail',
529 'disabled' => $disableEmailPrefs,
531 $defaultPreferences['ccmeonemails'] = [
533 'section' => 'personal/email',
534 'label-message' => 'tog-ccmeonemails',
535 'disabled' => $disableEmailPrefs,
539 if ( $config->get( 'EnotifWatchlist' ) ) {
540 $defaultPreferences['enotifwatchlistpages'] = [
542 'section' => 'personal/email',
543 'label-message' => 'tog-enotifwatchlistpages',
544 'disabled' => $disableEmailPrefs,
547 if ( $config->get( 'EnotifUserTalk' ) ) {
548 $defaultPreferences['enotifusertalkpages'] = [
550 'section' => 'personal/email',
551 'label-message' => 'tog-enotifusertalkpages',
552 'disabled' => $disableEmailPrefs,
555 if ( $config->get( 'EnotifUserTalk' ) ||
$config->get( 'EnotifWatchlist' ) ) {
556 if ( $config->get( 'EnotifMinorEdits' ) ) {
557 $defaultPreferences['enotifminoredits'] = [
559 'section' => 'personal/email',
560 'label-message' => 'tog-enotifminoredits',
561 'disabled' => $disableEmailPrefs,
565 if ( $config->get( 'EnotifRevealEditorAddress' ) ) {
566 $defaultPreferences['enotifrevealaddr'] = [
568 'section' => 'personal/email',
569 'label-message' => 'tog-enotifrevealaddr',
570 'disabled' => $disableEmailPrefs,
579 * @param IContextSource $context
580 * @param array $defaultPreferences
583 static function skinPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
584 # # Skin #####################################
586 // Skin selector, if there is at least one valid skin
587 $skinOptions = self
::generateSkinOptions( $user, $context );
588 if ( $skinOptions ) {
589 $defaultPreferences['skin'] = [
591 'options' => $skinOptions,
593 'section' => 'rendering/skin',
597 $config = $context->getConfig();
598 $allowUserCss = $config->get( 'AllowUserCss' );
599 $allowUserJs = $config->get( 'AllowUserJs' );
600 # Create links to user CSS/JS pages for all skins
601 # This code is basically copied from generateSkinOptions(). It'd
602 # be nice to somehow merge this back in there to avoid redundancy.
603 if ( $allowUserCss ||
$allowUserJs ) {
605 $userName = $user->getName();
607 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
608 if ( $allowUserCss ) {
609 $cssPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.css' );
610 $linkTools[] = $linkRenderer->makeLink( $cssPage, $context->msg( 'prefs-custom-css' )->text() );
613 if ( $allowUserJs ) {
614 $jsPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.js' );
615 $linkTools[] = $linkRenderer->makeLink( $jsPage, $context->msg( 'prefs-custom-js' )->text() );
618 $defaultPreferences['commoncssjs'] = [
621 'default' => $context->getLanguage()->pipeList( $linkTools ),
622 'label-message' => 'prefs-common-css-js',
623 'section' => 'rendering/skin',
630 * @param IContextSource $context
631 * @param array $defaultPreferences
633 static function filesPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
634 # # Files #####################################
635 $defaultPreferences['imagesize'] = [
637 'options' => self
::getImageSizes( $context ),
638 'label-message' => 'imagemaxsize',
639 'section' => 'rendering/files',
641 $defaultPreferences['thumbsize'] = [
643 'options' => self
::getThumbSizes( $context ),
644 'label-message' => 'thumbsize',
645 'section' => 'rendering/files',
651 * @param IContextSource $context
652 * @param array $defaultPreferences
655 static function datetimePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
656 # # Date and time #####################################
657 $dateOptions = self
::getDateOptions( $context );
658 if ( $dateOptions ) {
659 $defaultPreferences['date'] = [
661 'options' => $dateOptions,
663 'section' => 'rendering/dateformat',
668 $now = wfTimestampNow();
669 $lang = $context->getLanguage();
670 $nowlocal = Xml
::element( 'span', [ 'id' => 'wpLocalTime' ],
671 $lang->userTime( $now, $user ) );
672 $nowserver = $lang->userTime( $now, $user,
673 [ 'format' => false, 'timecorrection' => false ] ) .
674 Html
::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 +
(int)substr( $now, 10, 2 ) );
676 $defaultPreferences['nowserver'] = [
679 'label-message' => 'servertime',
680 'default' => $nowserver,
681 'section' => 'rendering/timeoffset',
684 $defaultPreferences['nowlocal'] = [
687 'label-message' => 'localtime',
688 'default' => $nowlocal,
689 'section' => 'rendering/timeoffset',
692 // Grab existing pref.
693 $tzOffset = $user->getOption( 'timecorrection' );
694 $tz = explode( '|', $tzOffset, 3 );
696 $tzOptions = self
::getTimezoneOptions( $context );
698 $tzSetting = $tzOffset;
699 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
701 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) %
60 );
702 } elseif ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
703 !in_array( $tzOffset, HTMLFormField
::flattenOptions( $tzOptions ) )
705 # Timezone offset can vary with DST
706 $userTZ = timezone_open( $tz[2] );
707 if ( $userTZ !== false ) {
708 $minDiff = floor( timezone_offset_get( $userTZ, date_create( 'now' ) ) / 60 );
709 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
713 $defaultPreferences['timecorrection'] = [
714 'class' => 'HTMLSelectOrOtherField',
715 'label-message' => 'timezonelegend',
716 'options' => $tzOptions,
717 'default' => $tzSetting,
719 'section' => 'rendering/timeoffset',
725 * @param IContextSource $context
726 * @param array $defaultPreferences
728 static function renderingPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
729 # # Diffs ####################################
730 $defaultPreferences['diffonly'] = [
732 'section' => 'rendering/diffs',
733 'label-message' => 'tog-diffonly',
735 $defaultPreferences['norollbackdiff'] = [
737 'section' => 'rendering/diffs',
738 'label-message' => 'tog-norollbackdiff',
741 # # Page Rendering ##############################
742 if ( $context->getConfig()->get( 'AllowUserCssPrefs' ) ) {
743 $defaultPreferences['underline'] = [
746 $context->msg( 'underline-never' )->text() => 0,
747 $context->msg( 'underline-always' )->text() => 1,
748 $context->msg( 'underline-default' )->text() => 2,
750 'label-message' => 'tog-underline',
751 'section' => 'rendering/advancedrendering',
755 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
756 $stubThresholdOptions = [ $context->msg( 'stub-threshold-disabled' )->text() => 0 ];
757 foreach ( $stubThresholdValues as $value ) {
758 $stubThresholdOptions[$context->msg( 'size-bytes', $value )->text()] = $value;
761 $defaultPreferences['stubthreshold'] = [
763 'section' => 'rendering/advancedrendering',
764 'options' => $stubThresholdOptions,
765 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
766 'label-raw' => $context->msg( 'stub-threshold' )->rawParams(
767 '<a href="#" class="stub">' .
768 $context->msg( 'stub-threshold-sample-link' )->parse() .
772 $defaultPreferences['showhiddencats'] = [
774 'section' => 'rendering/advancedrendering',
775 'label-message' => 'tog-showhiddencats'
778 $defaultPreferences['numberheadings'] = [
780 'section' => 'rendering/advancedrendering',
781 'label-message' => 'tog-numberheadings',
787 * @param IContextSource $context
788 * @param array $defaultPreferences
790 static function editingPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
791 # # Editing #####################################
792 $defaultPreferences['editsectiononrightclick'] = [
794 'section' => 'editing/advancedediting',
795 'label-message' => 'tog-editsectiononrightclick',
797 $defaultPreferences['editondblclick'] = [
799 'section' => 'editing/advancedediting',
800 'label-message' => 'tog-editondblclick',
803 if ( $context->getConfig()->get( 'AllowUserCssPrefs' ) ) {
804 $defaultPreferences['editfont'] = [
806 'section' => 'editing/editor',
807 'label-message' => 'editfont-style',
809 $context->msg( 'editfont-default' )->text() => 'default',
810 $context->msg( 'editfont-monospace' )->text() => 'monospace',
811 $context->msg( 'editfont-sansserif' )->text() => 'sans-serif',
812 $context->msg( 'editfont-serif' )->text() => 'serif',
816 $defaultPreferences['cols'] = [
818 'label-message' => 'columns',
819 'section' => 'editing/editor',
823 $defaultPreferences['rows'] = [
825 'label-message' => 'rows',
826 'section' => 'editing/editor',
830 if ( $user->isAllowed( 'minoredit' ) ) {
831 $defaultPreferences['minordefault'] = [
833 'section' => 'editing/editor',
834 'label-message' => 'tog-minordefault',
837 $defaultPreferences['forceeditsummary'] = [
839 'section' => 'editing/editor',
840 'label-message' => 'tog-forceeditsummary',
842 $defaultPreferences['useeditwarning'] = [
844 'section' => 'editing/editor',
845 'label-message' => 'tog-useeditwarning',
847 $defaultPreferences['showtoolbar'] = [
849 'section' => 'editing/editor',
850 'label-message' => 'tog-showtoolbar',
853 $defaultPreferences['previewonfirst'] = [
855 'section' => 'editing/preview',
856 'label-message' => 'tog-previewonfirst',
858 $defaultPreferences['previewontop'] = [
860 'section' => 'editing/preview',
861 'label-message' => 'tog-previewontop',
863 $defaultPreferences['uselivepreview'] = [
865 'section' => 'editing/preview',
866 'label-message' => 'tog-uselivepreview',
872 * @param IContextSource $context
873 * @param array $defaultPreferences
875 static function rcPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
876 $config = $context->getConfig();
877 $rcMaxAge = $config->get( 'RCMaxAge' );
878 # # RecentChanges #####################################
879 $defaultPreferences['rcdays'] = [
881 'label-message' => 'recentchangesdays',
882 'section' => 'rc/displayrc',
884 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
885 'help' => $context->msg( 'recentchangesdays-max' )->numParams(
886 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
888 $defaultPreferences['rclimit'] = [
890 'label-message' => 'recentchangescount',
891 'help-message' => 'prefs-help-recentchangescount',
892 'section' => 'rc/displayrc',
894 $defaultPreferences['usenewrc'] = [
896 'label-message' => 'tog-usenewrc',
897 'section' => 'rc/advancedrc',
899 $defaultPreferences['hideminor'] = [
901 'label-message' => 'tog-hideminor',
902 'section' => 'rc/advancedrc',
905 if ( $config->get( 'RCWatchCategoryMembership' ) ) {
906 $defaultPreferences['hidecategorization'] = [
908 'label-message' => 'tog-hidecategorization',
909 'section' => 'rc/advancedrc',
913 if ( $user->useRCPatrol() ) {
914 $defaultPreferences['hidepatrolled'] = [
916 'section' => 'rc/advancedrc',
917 'label-message' => 'tog-hidepatrolled',
921 if ( $user->useNPPatrol() ) {
922 $defaultPreferences['newpageshidepatrolled'] = [
924 'section' => 'rc/advancedrc',
925 'label-message' => 'tog-newpageshidepatrolled',
929 if ( $config->get( 'RCShowWatchingUsers' ) ) {
930 $defaultPreferences['shownumberswatching'] = [
932 'section' => 'rc/advancedrc',
933 'label-message' => 'tog-shownumberswatching',
940 * @param IContextSource $context
941 * @param array $defaultPreferences
943 static function watchlistPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
944 $config = $context->getConfig();
945 $watchlistdaysMax = ceil( $config->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
947 # # Watchlist #####################################
948 if ( $user->isAllowed( 'editmywatchlist' ) ) {
949 $editWatchlistLinks = [];
950 $editWatchlistModes = [
951 'edit' => [ 'EditWatchlist', false ],
952 'raw' => [ 'EditWatchlist', 'raw' ],
953 'clear' => [ 'EditWatchlist', 'clear' ],
955 foreach ( $editWatchlistModes as $editWatchlistMode => $mode ) {
956 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
957 $editWatchlistLinks[] = Linker
::linkKnown(
958 SpecialPage
::getTitleFor( $mode[0], $mode[1] ),
959 $context->msg( "prefs-editwatchlist-{$editWatchlistMode}" )->parse()
963 $defaultPreferences['editwatchlist'] = [
966 'default' => $context->getLanguage()->pipeList( $editWatchlistLinks ),
967 'label-message' => 'prefs-editwatchlist-label',
968 'section' => 'watchlist/editwatchlist',
972 $defaultPreferences['watchlistdays'] = [
975 'max' => $watchlistdaysMax,
976 'section' => 'watchlist/displaywatchlist',
977 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
978 $watchlistdaysMax )->escaped(),
979 'label-message' => 'prefs-watchlist-days',
981 $defaultPreferences['wllimit'] = [
985 'label-message' => 'prefs-watchlist-edits',
986 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
987 'section' => 'watchlist/displaywatchlist',
989 $defaultPreferences['extendwatchlist'] = [
991 'section' => 'watchlist/advancedwatchlist',
992 'label-message' => 'tog-extendwatchlist',
994 $defaultPreferences['watchlisthideminor'] = [
996 'section' => 'watchlist/advancedwatchlist',
997 'label-message' => 'tog-watchlisthideminor',
999 $defaultPreferences['watchlisthidebots'] = [
1001 'section' => 'watchlist/advancedwatchlist',
1002 'label-message' => 'tog-watchlisthidebots',
1004 $defaultPreferences['watchlisthideown'] = [
1006 'section' => 'watchlist/advancedwatchlist',
1007 'label-message' => 'tog-watchlisthideown',
1009 $defaultPreferences['watchlisthideanons'] = [
1011 'section' => 'watchlist/advancedwatchlist',
1012 'label-message' => 'tog-watchlisthideanons',
1014 $defaultPreferences['watchlisthideliu'] = [
1016 'section' => 'watchlist/advancedwatchlist',
1017 'label-message' => 'tog-watchlisthideliu',
1019 $defaultPreferences['watchlistreloadautomatically'] = [
1021 'section' => 'watchlist/advancedwatchlist',
1022 'label-message' => 'tog-watchlistreloadautomatically',
1025 if ( $config->get( 'RCWatchCategoryMembership' ) ) {
1026 $defaultPreferences['watchlisthidecategorization'] = [
1028 'section' => 'watchlist/advancedwatchlist',
1029 'label-message' => 'tog-watchlisthidecategorization',
1033 if ( $user->useRCPatrol() ) {
1034 $defaultPreferences['watchlisthidepatrolled'] = [
1036 'section' => 'watchlist/advancedwatchlist',
1037 'label-message' => 'tog-watchlisthidepatrolled',
1042 'edit' => 'watchdefault',
1043 'move' => 'watchmoves',
1044 'delete' => 'watchdeletion'
1048 if ( $user->isAllowed( 'createpage' ) ||
$user->isAllowed( 'createtalk' ) ) {
1049 $watchTypes['read'] = 'watchcreations';
1052 if ( $user->isAllowed( 'rollback' ) ) {
1053 $watchTypes['rollback'] = 'watchrollback';
1056 if ( $user->isAllowed( 'upload' ) ) {
1057 $watchTypes['upload'] = 'watchuploads';
1060 foreach ( $watchTypes as $action => $pref ) {
1061 if ( $user->isAllowed( $action ) ) {
1063 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1064 // tog-watchrollback
1065 $defaultPreferences[$pref] = [
1067 'section' => 'watchlist/advancedwatchlist',
1068 'label-message' => "tog-$pref",
1073 if ( $config->get( 'EnableAPI' ) ) {
1074 $defaultPreferences['watchlisttoken'] = [
1077 $defaultPreferences['watchlisttoken-info'] = [
1079 'section' => 'watchlist/tokenwatchlist',
1080 'label-message' => 'prefs-watchlist-token',
1081 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1082 'help-message' => 'prefs-help-watchlist-token2',
1089 * @param IContextSource $context
1090 * @param array $defaultPreferences
1092 static function searchPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
1093 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
1094 $defaultPreferences['searchNs' . $n] = [
1101 * Dummy, kept for backwards-compatibility.
1103 static function miscPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
1107 * @param User $user The User object
1108 * @param IContextSource $context
1109 * @return array Text/links to display as key; $skinkey as value
1111 static function generateSkinOptions( $user, IContextSource
$context ) {
1114 $mptitle = Title
::newMainPage();
1115 $previewtext = $context->msg( 'skin-preview' )->escaped();
1117 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1119 # Only show skins that aren't disabled in $wgSkipSkins
1120 $validSkinNames = Skin
::getAllowedSkins();
1122 # Sort by UI skin name. First though need to update validSkinNames as sometimes
1123 # the skinkey & UI skinname differ (e.g. "standard" skinkey is "Classic" in the UI).
1124 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1125 $msg = $context->msg( "skinname-{$skinkey}" );
1126 if ( $msg->exists() ) {
1127 $skinname = htmlspecialchars( $msg->text() );
1130 asort( $validSkinNames );
1132 $config = $context->getConfig();
1133 $defaultSkin = $config->get( 'DefaultSkin' );
1134 $allowUserCss = $config->get( 'AllowUserCss' );
1135 $allowUserJs = $config->get( 'AllowUserJs' );
1137 $foundDefault = false;
1138 foreach ( $validSkinNames as $skinkey => $sn ) {
1141 # Mark the default skin
1142 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1143 $linkTools[] = $context->msg( 'default' )->escaped();
1144 $foundDefault = true;
1147 # Create preview link
1148 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1149 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1151 # Create links to user CSS/JS pages
1152 if ( $allowUserCss ) {
1153 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1154 $linkTools[] = $linkRenderer->makeLink( $cssPage, $context->msg( 'prefs-custom-css' )->text() );
1157 if ( $allowUserJs ) {
1158 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1159 $linkTools[] = $linkRenderer->makeLink( $jsPage, $context->msg( 'prefs-custom-js' )->text() );
1162 $display = $sn . ' ' . $context->msg( 'parentheses' )
1163 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1165 $ret[$display] = $skinkey;
1168 if ( !$foundDefault ) {
1169 // If the default skin is not available, things are going to break horribly because the
1170 // default value for skin selector will not be a valid value. Let's just not show it then.
1178 * @param IContextSource $context
1181 static function getDateOptions( IContextSource
$context ) {
1182 $lang = $context->getLanguage();
1183 $dateopts = $lang->getDatePreferences();
1188 if ( !in_array( 'default', $dateopts ) ) {
1189 $dateopts[] = 'default'; // Make sure default is always valid
1193 // FIXME KLUGE: site default might not be valid for user language
1194 global $wgDefaultUserOptions;
1195 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1196 $wgDefaultUserOptions['date'] = 'default';
1199 $epoch = wfTimestampNow();
1200 foreach ( $dateopts as $key ) {
1201 if ( $key == 'default' ) {
1202 $formatted = $context->msg( 'datedefault' )->escaped();
1204 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1206 $ret[$formatted] = $key;
1213 * @param IContextSource $context
1216 static function getImageSizes( IContextSource
$context ) {
1218 $pixels = $context->msg( 'unit-pixel' )->text();
1220 foreach ( $context->getConfig()->get( 'ImageLimits' ) as $index => $limits ) {
1221 $display = "{$limits[0]}×{$limits[1]}" . $pixels;
1222 $ret[$display] = $index;
1229 * @param IContextSource $context
1232 static function getThumbSizes( IContextSource
$context ) {
1234 $pixels = $context->msg( 'unit-pixel' )->text();
1236 foreach ( $context->getConfig()->get( 'ThumbLimits' ) as $index => $size ) {
1237 $display = $size . $pixels;
1238 $ret[$display] = $index;
1245 * @param string $signature
1246 * @param array $alldata
1247 * @param HTMLForm $form
1248 * @return bool|string
1250 static function validateSignature( $signature, $alldata, $form ) {
1252 $maxSigChars = $form->getConfig()->get( 'MaxSigChars' );
1253 if ( mb_strlen( $signature ) > $maxSigChars ) {
1254 return Xml
::element( 'span', [ 'class' => 'error' ],
1255 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1256 } elseif ( isset( $alldata['fancysig'] ) &&
1257 $alldata['fancysig'] &&
1258 $wgParser->validateSig( $signature ) === false
1260 return Xml
::element(
1262 [ 'class' => 'error' ],
1263 $form->msg( 'badsig' )->text()
1271 * @param string $signature
1272 * @param array $alldata
1273 * @param HTMLForm $form
1276 static function cleanSignature( $signature, $alldata, $form ) {
1277 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1279 $signature = $wgParser->cleanSig( $signature );
1281 // When no fancy sig used, make sure ~{3,5} get removed.
1282 $signature = Parser
::cleanSigInSig( $signature );
1290 * @param IContextSource $context
1291 * @param string $formClass
1292 * @param array $remove Array of items to remove
1293 * @return PreferencesForm|HtmlForm
1295 static function getFormObject(
1297 IContextSource
$context,
1298 $formClass = 'PreferencesForm',
1301 $formDescriptor = Preferences
::getPreferences( $user, $context );
1302 if ( count( $remove ) ) {
1303 $removeKeys = array_flip( $remove );
1304 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1307 // Remove type=api preferences. They are not intended for rendering in the form.
1308 foreach ( $formDescriptor as $name => $info ) {
1309 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1310 unset( $formDescriptor[$name] );
1315 * @var $htmlForm PreferencesForm
1317 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1319 $htmlForm->setModifiedUser( $user );
1320 $htmlForm->setId( 'mw-prefs-form' );
1321 $htmlForm->setAutocomplete( 'off' );
1322 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1323 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1324 $htmlForm->setSubmitTooltip( 'preferences-save' );
1325 $htmlForm->setSubmitID( 'prefsubmit' );
1326 $htmlForm->setSubmitCallback( [ 'Preferences', 'tryFormSubmit' ] );
1332 * @param IContextSource $context
1335 static function getTimezoneOptions( IContextSource
$context ) {
1338 $localTZoffset = $context->getConfig()->get( 'LocalTZoffset' );
1339 $timeZoneList = self
::getTimeZoneList( $context->getLanguage() );
1341 $timestamp = MWTimestamp
::getLocalInstance();
1342 // Check that the LocalTZoffset is the same as the local time zone offset
1343 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1344 $timezoneName = $timestamp->getTimezone()->getName();
1345 // Localize timezone
1346 if ( isset( $timeZoneList[$timezoneName] ) ) {
1347 $timezoneName = $timeZoneList[$timezoneName]['name'];
1349 $server_tz_msg = $context->msg(
1350 'timezoneuseserverdefault',
1354 $tzstring = sprintf(
1356 floor( $localTZoffset / 60 ),
1357 abs( $localTZoffset ) %
60
1359 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1361 $opt[$server_tz_msg] = "System|$localTZoffset";
1362 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1363 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1365 foreach ( $timeZoneList as $timeZoneInfo ) {
1366 $region = $timeZoneInfo['region'];
1367 if ( !isset( $opt[$region] ) ) {
1370 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1376 * @param string $value
1377 * @param array $alldata
1380 static function filterIntval( $value, $alldata ) {
1381 return intval( $value );
1386 * @param array $alldata
1389 static function filterTimezoneInput( $tz, $alldata ) {
1390 $data = explode( '|', $tz, 3 );
1391 switch ( $data[0] ) {
1396 $data = explode( ':', $tz, 2 );
1397 if ( count( $data ) == 2 ) {
1398 $data[0] = intval( $data[0] );
1399 $data[1] = intval( $data[1] );
1400 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1401 if ( $data[0] < 0 ) {
1402 $minDiff = - $minDiff;
1405 $minDiff = intval( $data[0] ) * 60;
1408 # Max is +14:00 and min is -12:00, see:
1409 # https://en.wikipedia.org/wiki/Timezone
1410 $minDiff = min( $minDiff, 840 ); # 14:00
1411 $minDiff = max( $minDiff, - 720 ); # -12:00
1412 return 'Offset|' . $minDiff;
1417 * Handle the form submission if everything validated properly
1419 * @param array $formData
1420 * @param PreferencesForm $form
1421 * @return bool|Status|string
1423 static function tryFormSubmit( $formData, $form ) {
1424 $user = $form->getModifiedUser();
1425 $hiddenPrefs = $form->getConfig()->get( 'HiddenPrefs' );
1428 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1429 return Status
::newFatal( 'mypreferencesprotected' );
1433 foreach ( array_keys( $formData ) as $name ) {
1434 if ( isset( self
::$saveFilters[$name] ) ) {
1436 call_user_func( self
::$saveFilters[$name], $formData[$name], $formData );
1440 // Fortunately, the realname field is MUCH simpler
1441 // (not really "private", but still shouldn't be edited without permission)
1443 if ( !in_array( 'realname', $hiddenPrefs )
1444 && $user->isAllowed( 'editmyprivateinfo' )
1445 && array_key_exists( 'realname', $formData )
1447 $realName = $formData['realname'];
1448 $user->setRealName( $realName );
1451 if ( $user->isAllowed( 'editmyoptions' ) ) {
1452 foreach ( self
::$saveBlacklist as $b ) {
1453 unset( $formData[$b] );
1456 # If users have saved a value for a preference which has subsequently been disabled
1457 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1458 # is subsequently re-enabled
1459 foreach ( $hiddenPrefs as $pref ) {
1460 # If the user has not set a non-default value here, the default will be returned
1461 # and subsequently discarded
1462 $formData[$pref] = $user->getOption( $pref, null, true );
1465 // Keep old preferences from interfering due to back-compat code, etc.
1466 $user->resetOptions( 'unused', $form->getContext() );
1468 foreach ( $formData as $key => $value ) {
1469 $user->setOption( $key, $value );
1472 Hooks
::run( 'PreferencesFormPreSave', [ $formData, $form, $user, &$result ] );
1475 MediaWiki\Auth\AuthManager
::callLegacyAuthPlugin( 'updateExternalDB', [ $user ] );
1476 $user->saveSettings();
1482 * @param array $formData
1483 * @param PreferencesForm $form
1486 public static function tryUISubmit( $formData, $form ) {
1487 $res = self
::tryFormSubmit( $formData, $form );
1492 if ( $res === 'eauth' ) {
1493 $urlOptions['eauth'] = 1;
1496 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1498 $url = $form->getTitle()->getFullURL( $urlOptions );
1500 $context = $form->getContext();
1501 // Set session data for the success message
1502 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1504 $context->getOutput()->redirect( $url );
1507 return Status
::newGood();
1511 * Get a list of all time zones
1512 * @param Language $language Language used for the localized names
1513 * @return array A list of all time zones. The system name of the time zone is used as key and
1514 * the value is an array which contains localized name, the timecorrection value used for
1515 * preferences and the region
1518 public static function getTimeZoneList( Language
$language ) {
1519 $identifiers = DateTimeZone
::listIdentifiers();
1520 if ( $identifiers === false ) {
1523 sort( $identifiers );
1526 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1527 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1528 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1529 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1530 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1531 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1532 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1533 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1534 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1535 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1537 asort( $tzRegions );
1541 $now = new DateTime();
1543 foreach ( $identifiers as $identifier ) {
1544 $parts = explode( '/', $identifier, 2 );
1546 // DateTimeZone::listIdentifiers() returns a number of
1547 // backwards-compatibility entries. This filters them out of the
1548 // list presented to the user.
1549 if ( count( $parts ) !== 2 ||
!array_key_exists( $parts[0], $tzRegions ) ) {
1554 $parts[0] = $tzRegions[$parts[0]];
1556 $dateTimeZone = new DateTimeZone( $identifier );
1557 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1559 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1560 $value = "ZoneInfo|$minDiff|$identifier";
1562 $timeZoneList[$identifier] = [
1564 'timecorrection' => $value,
1565 'region' => $parts[0],
1569 return $timeZoneList;
1573 /** Some tweaks to allow js prefs to work */
1574 class PreferencesForm
extends HTMLForm
{
1575 // Override default value from HTMLForm
1576 protected $mSubSectionBeforeFields = false;
1578 private $modifiedUser;
1583 public function setModifiedUser( $user ) {
1584 $this->modifiedUser
= $user;
1590 public function getModifiedUser() {
1591 if ( $this->modifiedUser
=== null ) {
1592 return $this->getUser();
1594 return $this->modifiedUser
;
1599 * Get extra parameters for the query string when redirecting after
1604 public function getExtraSuccessRedirectParameters() {
1609 * @param string $html
1612 function wrapForm( $html ) {
1613 $html = Xml
::tags( 'div', [ 'id' => 'preferences' ], $html );
1615 return parent
::wrapForm( $html );
1621 function getButtons() {
1622 $attrs = [ 'id' => 'mw-prefs-restoreprefs' ];
1624 if ( !$this->getModifiedUser()->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1628 $html = parent
::getButtons();
1630 if ( $this->getModifiedUser()->isAllowed( 'editmyoptions' ) ) {
1631 $t = SpecialPage
::getTitleFor( 'Preferences', 'reset' );
1633 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1634 $html .= "\n" . $linkRenderer->makeLink( $t, $this->msg( 'restoreprefs' )->text(),
1635 Html
::buttonAttributes( $attrs, [ 'mw-ui-quiet' ] ) );
1637 $html = Xml
::tags( 'div', [ 'class' => 'mw-prefs-buttons' ], $html );
1644 * Separate multi-option preferences into multiple preferences, since we
1645 * have to store them separately
1646 * @param array $data
1649 function filterDataForSubmit( $data ) {
1650 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1651 if ( $field instanceof HTMLNestedFilterable
) {
1652 $info = $field->mParams
;
1653 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $fieldname;
1654 foreach ( $field->filterDataForSubmit( $data[$fieldname] ) as $key => $value ) {
1655 $data["$prefix$key"] = $value;
1657 unset( $data[$fieldname] );
1665 * Get the whole body of the form.
1668 function getBody() {
1669 return $this->displaySection( $this->mFieldTree
, '', 'mw-prefsection-' );
1673 * Get the "<legend>" for a given section key. Normally this is the
1674 * prefs-$key message but we'll allow extensions to override it.
1675 * @param string $key
1678 function getLegend( $key ) {
1679 $legend = parent
::getLegend( $key );
1680 Hooks
::run( 'PreferencesGetLegend', [ $this, $key, &$legend ] );
1685 * Get the keys of each top level preference section.
1686 * @return array of section keys
1688 function getPreferenceSections() {
1689 return array_keys( array_filter( $this->mFieldTree
, 'is_array' ) );