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 'rclimit' => [ 'Preferences', 'filterIntval' ],
59 'wllimit' => [ 'Preferences', 'filterIntval' ],
60 'searchlimit' => [ 'Preferences', 'filterIntval' ],
63 // Stuff that shouldn't be saved as a preference.
64 private static $saveBlacklist = [
72 static function getSaveBlacklist() {
73 return self
::$saveBlacklist;
79 * @param IContextSource $context
82 static function getPreferences( $user, IContextSource
$context ) {
83 if ( self
::$defaultPreferences ) {
84 return self
::$defaultPreferences;
87 $defaultPreferences = [];
89 self
::profilePreferences( $user, $context, $defaultPreferences );
90 self
::skinPreferences( $user, $context, $defaultPreferences );
91 self
::datetimePreferences( $user, $context, $defaultPreferences );
92 self
::filesPreferences( $user, $context, $defaultPreferences );
93 self
::renderingPreferences( $user, $context, $defaultPreferences );
94 self
::editingPreferences( $user, $context, $defaultPreferences );
95 self
::rcPreferences( $user, $context, $defaultPreferences );
96 self
::watchlistPreferences( $user, $context, $defaultPreferences );
97 self
::searchPreferences( $user, $context, $defaultPreferences );
98 self
::miscPreferences( $user, $context, $defaultPreferences );
100 Hooks
::run( 'GetPreferences', [ $user, &$defaultPreferences ] );
102 self
::loadPreferenceValues( $user, $context, $defaultPreferences );
103 self
::$defaultPreferences = $defaultPreferences;
104 return $defaultPreferences;
108 * Loads existing values for a given array of preferences
109 * @throws MWException
111 * @param IContextSource $context
112 * @param array &$defaultPreferences Array to load values for
115 static function loadPreferenceValues( $user, $context, &$defaultPreferences ) {
116 # # Remove preferences that wikis don't want to use
117 foreach ( $context->getConfig()->get( 'HiddenPrefs' ) as $pref ) {
118 if ( isset( $defaultPreferences[$pref] ) ) {
119 unset( $defaultPreferences[$pref] );
123 # # Make sure that form fields have their parent set. See T43337.
124 $dummyForm = new HTMLForm( [], $context );
126 $disable = !$user->isAllowed( 'editmyoptions' );
128 $defaultOptions = User
::getDefaultOptions();
129 # # Prod in defaults from the user
130 foreach ( $defaultPreferences as $name => &$info ) {
131 $prefFromUser = self
::getOptionFromUser( $name, $info, $user );
132 if ( $disable && !in_array( $name, self
::$saveBlacklist ) ) {
133 $info['disabled'] = 'disabled';
135 $field = HTMLForm
::loadInputFromParameters( $name, $info, $dummyForm ); // For validation
136 $globalDefault = isset( $defaultOptions[$name] )
137 ?
$defaultOptions[$name]
140 // If it validates, set it as the default
141 if ( isset( $info['default'] ) ) {
142 // Already set, no problem
144 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
145 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
146 $info['default'] = $prefFromUser;
147 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
148 $info['default'] = $globalDefault;
150 throw new MWException( "Global default '$globalDefault' is invalid for field $name" );
154 return $defaultPreferences;
158 * Pull option from a user account. Handles stuff like array-type preferences.
160 * @param string $name
163 * @return array|string
165 static function getOptionFromUser( $name, $info, $user ) {
166 $val = $user->getOption( $name );
168 // Handling for multiselect preferences
169 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
170 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
171 $options = HTMLFormField
::flattenOptions( $info['options'] );
172 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
175 foreach ( $options as $value ) {
176 if ( $user->getOption( "$prefix$value" ) ) {
182 // Handling for checkmatrix preferences
183 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
184 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
185 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
186 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
187 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
190 foreach ( $columns as $column ) {
191 foreach ( $rows as $row ) {
192 if ( $user->getOption( "$prefix$column-$row" ) ) {
193 $val[] = "$column-$row";
204 * @param IContextSource $context
205 * @param array &$defaultPreferences
208 static function profilePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
209 global $wgContLang, $wgParser;
211 $authManager = AuthManager
::singleton();
212 $config = $context->getConfig();
213 // retrieving user name for GENDER and misc.
214 $userName = $user->getName();
216 # # User info #####################################
218 $defaultPreferences['username'] = [
220 'label-message' => [ 'username', $userName ],
221 'default' => $userName,
222 'section' => 'personal/info',
225 $lang = $context->getLanguage();
227 # Get groups to which the user belongs
228 $userEffectiveGroups = $user->getEffectiveGroups();
229 $userGroupMemberships = $user->getGroupMemberships();
230 $userGroups = $userMembers = $userTempGroups = $userTempMembers = [];
231 foreach ( $userEffectiveGroups as $ueg ) {
233 // Skip the default * group, seems useless here
237 if ( isset( $userGroupMemberships[$ueg] ) ) {
238 $groupStringOrObject = $userGroupMemberships[$ueg];
240 $groupStringOrObject = $ueg;
243 $userG = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html' );
244 $userM = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html',
247 // Store expiring groups separately, so we can place them before non-expiring
248 // groups in the list. This is to avoid the ambiguity of something like
249 // "administrator, bureaucrat (until X date)" -- users might wonder whether the
250 // expiry date applies to both groups, or just the last one
251 if ( $groupStringOrObject instanceof UserGroupMembership
&&
252 $groupStringOrObject->getExpiry()
254 $userTempGroups[] = $userG;
255 $userTempMembers[] = $userM;
257 $userGroups[] = $userG;
258 $userMembers[] = $userM;
262 sort( $userMembers );
263 sort( $userTempGroups );
264 sort( $userTempMembers );
265 $userGroups = array_merge( $userTempGroups, $userGroups );
266 $userMembers = array_merge( $userTempMembers, $userMembers );
268 $defaultPreferences['usergroups'] = [
270 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
271 count( $userGroups ) )->params( $userName )->parse(),
272 'default' => $context->msg( 'prefs-memberingroups-type' )
273 ->rawParams( $lang->commaList( $userGroups ), $lang->commaList( $userMembers ) )
276 'section' => 'personal/info',
279 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
281 $editCount = $linkRenderer->makeLink( SpecialPage
::getTitleFor( "Contributions", $userName ),
282 $lang->formatNum( $user->getEditCount() ) );
284 $defaultPreferences['editcount'] = [
287 'label-message' => 'prefs-edits',
288 'default' => $editCount,
289 'section' => 'personal/info',
292 if ( $user->getRegistration() ) {
293 $displayUser = $context->getUser();
294 $userRegistration = $user->getRegistration();
295 $defaultPreferences['registrationdate'] = [
297 'label-message' => 'prefs-registration',
298 'default' => $context->msg(
299 'prefs-registration-date-time',
300 $lang->userTimeAndDate( $userRegistration, $displayUser ),
301 $lang->userDate( $userRegistration, $displayUser ),
302 $lang->userTime( $userRegistration, $displayUser )
304 'section' => 'personal/info',
308 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
309 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
311 // Actually changeable stuff
312 $defaultPreferences['realname'] = [
313 // (not really "private", but still shouldn't be edited without permission)
314 'type' => $canEditPrivateInfo && $authManager->allowsPropertyChange( 'realname' )
316 'default' => $user->getRealName(),
317 'section' => 'personal/info',
318 'label-message' => 'yourrealname',
319 'help-message' => 'prefs-help-realname',
322 if ( $canEditPrivateInfo && $authManager->allowsAuthenticationDataChange(
323 new PasswordAuthenticationRequest(), false )->isGood()
325 $link = $linkRenderer->makeLink( SpecialPage
::getTitleFor( 'ChangePassword' ),
326 $context->msg( 'prefs-resetpass' )->text(), [],
327 [ 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText() ] );
329 $defaultPreferences['password'] = [
333 'label-message' => 'yourpassword',
334 'section' => 'personal/info',
337 // Only show prefershttps if secure login is turned on
338 if ( $config->get( 'SecureLogin' ) && wfCanIPUseHTTPS( $context->getRequest()->getIP() ) ) {
339 $defaultPreferences['prefershttps'] = [
341 'label-message' => 'tog-prefershttps',
342 'help-message' => 'prefs-help-prefershttps',
343 'section' => 'personal/info'
348 $languages = Language
::fetchLanguageNames( null, 'mw' );
349 $languageCode = $config->get( 'LanguageCode' );
350 if ( !array_key_exists( $languageCode, $languages ) ) {
351 $languages[$languageCode] = $languageCode;
356 foreach ( $languages as $code => $name ) {
357 $display = wfBCP47( $code ) . ' - ' . $name;
358 $options[$display] = $code;
360 $defaultPreferences['language'] = [
362 'section' => 'personal/i18n',
363 'options' => $options,
364 'label-message' => 'yourlanguage',
367 $defaultPreferences['gender'] = [
369 'section' => 'personal/i18n',
371 $context->msg( 'parentheses' )
372 ->params( $context->msg( 'gender-unknown' )->plain() )
373 ->escaped() => 'unknown',
374 $context->msg( 'gender-female' )->escaped() => 'female',
375 $context->msg( 'gender-male' )->escaped() => 'male',
377 'label-message' => 'yourgender',
378 'help-message' => 'prefs-help-gender',
381 // see if there are multiple language variants to choose from
382 if ( !$config->get( 'DisableLangConversion' ) ) {
383 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
384 if ( $langCode == $wgContLang->getCode() ) {
385 $variants = $wgContLang->getVariants();
387 if ( count( $variants ) <= 1 ) {
392 foreach ( $variants as $v ) {
393 $v = str_replace( '_', '-', strtolower( $v ) );
394 $variantArray[$v] = $lang->getVariantname( $v, false );
398 foreach ( $variantArray as $code => $name ) {
399 $display = wfBCP47( $code ) . ' - ' . $name;
400 $options[$display] = $code;
403 $defaultPreferences['variant'] = [
404 'label-message' => 'yourvariant',
406 'options' => $options,
407 'section' => 'personal/i18n',
408 'help-message' => 'prefs-help-variant',
411 $defaultPreferences["variant-$langCode"] = [
418 // Stuff from Language::getExtraUserToggles()
419 // FIXME is this dead code? $extraUserToggles doesn't seem to be defined for any language
420 $toggles = $wgContLang->getExtraUserToggles();
422 foreach ( $toggles as $toggle ) {
423 $defaultPreferences[$toggle] = [
425 'section' => 'personal/i18n',
426 'label-message' => "tog-$toggle",
430 // show a preview of the old signature first
431 $oldsigWikiText = $wgParser->preSaveTransform(
433 $context->getTitle(),
435 ParserOptions
::newFromContext( $context )
437 $oldsigHTML = $context->getOutput()->parseInline( $oldsigWikiText, true, true );
438 $defaultPreferences['oldsig'] = [
441 'label-message' => 'tog-oldsig',
442 'default' => $oldsigHTML,
443 'section' => 'personal/signature',
445 $defaultPreferences['nickname'] = [
446 'type' => $authManager->allowsPropertyChange( 'nickname' ) ?
'text' : 'info',
447 'maxlength' => $config->get( 'MaxSigChars' ),
448 'label-message' => 'yournick',
449 'validation-callback' => [ 'Preferences', 'validateSignature' ],
450 'section' => 'personal/signature',
451 'filter-callback' => [ 'Preferences', 'cleanSignature' ],
453 $defaultPreferences['fancysig'] = [
455 'label-message' => 'tog-fancysig',
456 // show general help about signature at the bottom of the section
457 'help-message' => 'prefs-help-signature',
458 'section' => 'personal/signature'
463 if ( $config->get( 'EnableEmail' ) ) {
464 if ( $canViewPrivateInfo ) {
465 $helpMessages[] = $config->get( 'EmailConfirmToEdit' )
466 ?
'prefs-help-email-required'
467 : 'prefs-help-email';
469 if ( $config->get( 'EnableUserEmail' ) ) {
470 // additional messages when users can send email to each other
471 $helpMessages[] = 'prefs-help-email-others';
474 $emailAddress = $user->getEmail() ?
htmlspecialchars( $user->getEmail() ) : '';
475 if ( $canEditPrivateInfo && $authManager->allowsPropertyChange( 'emailaddress' ) ) {
476 $link = $linkRenderer->makeLink(
477 SpecialPage
::getTitleFor( 'ChangeEmail' ),
478 $context->msg( $user->getEmail() ?
'prefs-changeemail' : 'prefs-setemail' )->text(),
480 [ 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText() ] );
482 $emailAddress .= $emailAddress == '' ?
$link : (
483 $context->msg( 'word-separator' )->escaped()
484 . $context->msg( 'parentheses' )->rawParams( $link )->escaped()
488 $defaultPreferences['emailaddress'] = [
491 'default' => $emailAddress,
492 'label-message' => 'youremail',
493 'section' => 'personal/email',
494 'help-messages' => $helpMessages,
495 # 'cssclass' chosen below
499 $disableEmailPrefs = false;
501 if ( $config->get( 'EmailAuthentication' ) ) {
502 $emailauthenticationclass = 'mw-email-not-authenticated';
503 if ( $user->getEmail() ) {
504 if ( $user->getEmailAuthenticationTimestamp() ) {
505 // date and time are separate parameters to facilitate localisation.
506 // $time is kept for backward compat reasons.
507 // 'emailauthenticated' is also used in SpecialConfirmemail.php
508 $displayUser = $context->getUser();
509 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
510 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
511 $d = $lang->userDate( $emailTimestamp, $displayUser );
512 $t = $lang->userTime( $emailTimestamp, $displayUser );
513 $emailauthenticated = $context->msg( 'emailauthenticated',
514 $time, $d, $t )->parse() . '<br />';
515 $disableEmailPrefs = false;
516 $emailauthenticationclass = 'mw-email-authenticated';
518 $disableEmailPrefs = true;
519 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
520 $linkRenderer->makeKnownLink(
521 SpecialPage
::getTitleFor( 'Confirmemail' ),
522 $context->msg( 'emailconfirmlink' )->text()
524 $emailauthenticationclass = "mw-email-not-authenticated";
527 $disableEmailPrefs = true;
528 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
529 $emailauthenticationclass = 'mw-email-none';
532 if ( $canViewPrivateInfo ) {
533 $defaultPreferences['emailauthentication'] = [
536 'section' => 'personal/email',
537 'label-message' => 'prefs-emailconfirm-label',
538 'default' => $emailauthenticated,
539 # Apply the same CSS class used on the input to the message:
540 'cssclass' => $emailauthenticationclass,
545 if ( $config->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
546 $defaultPreferences['disablemail'] = [
549 'section' => 'personal/email',
550 'label-message' => 'allowemail',
551 'disabled' => $disableEmailPrefs,
553 $defaultPreferences['ccmeonemails'] = [
555 'section' => 'personal/email',
556 'label-message' => 'tog-ccmeonemails',
557 'disabled' => $disableEmailPrefs,
561 if ( $config->get( 'EnotifWatchlist' ) ) {
562 $defaultPreferences['enotifwatchlistpages'] = [
564 'section' => 'personal/email',
565 'label-message' => 'tog-enotifwatchlistpages',
566 'disabled' => $disableEmailPrefs,
569 if ( $config->get( 'EnotifUserTalk' ) ) {
570 $defaultPreferences['enotifusertalkpages'] = [
572 'section' => 'personal/email',
573 'label-message' => 'tog-enotifusertalkpages',
574 'disabled' => $disableEmailPrefs,
577 if ( $config->get( 'EnotifUserTalk' ) ||
$config->get( 'EnotifWatchlist' ) ) {
578 if ( $config->get( 'EnotifMinorEdits' ) ) {
579 $defaultPreferences['enotifminoredits'] = [
581 'section' => 'personal/email',
582 'label-message' => 'tog-enotifminoredits',
583 'disabled' => $disableEmailPrefs,
587 if ( $config->get( 'EnotifRevealEditorAddress' ) ) {
588 $defaultPreferences['enotifrevealaddr'] = [
590 'section' => 'personal/email',
591 'label-message' => 'tog-enotifrevealaddr',
592 'disabled' => $disableEmailPrefs,
601 * @param IContextSource $context
602 * @param array &$defaultPreferences
605 static function skinPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
606 # # Skin #####################################
608 // Skin selector, if there is at least one valid skin
609 $skinOptions = self
::generateSkinOptions( $user, $context );
610 if ( $skinOptions ) {
611 $defaultPreferences['skin'] = [
613 'options' => $skinOptions,
615 'section' => 'rendering/skin',
619 $config = $context->getConfig();
620 $allowUserCss = $config->get( 'AllowUserCss' );
621 $allowUserJs = $config->get( 'AllowUserJs' );
622 # Create links to user CSS/JS pages for all skins
623 # This code is basically copied from generateSkinOptions(). It'd
624 # be nice to somehow merge this back in there to avoid redundancy.
625 if ( $allowUserCss ||
$allowUserJs ) {
627 $userName = $user->getName();
629 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
630 if ( $allowUserCss ) {
631 $cssPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.css' );
632 $linkTools[] = $linkRenderer->makeLink( $cssPage, $context->msg( 'prefs-custom-css' )->text() );
635 if ( $allowUserJs ) {
636 $jsPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.js' );
637 $linkTools[] = $linkRenderer->makeLink( $jsPage, $context->msg( 'prefs-custom-js' )->text() );
640 $defaultPreferences['commoncssjs'] = [
643 'default' => $context->getLanguage()->pipeList( $linkTools ),
644 'label-message' => 'prefs-common-css-js',
645 'section' => 'rendering/skin',
652 * @param IContextSource $context
653 * @param array &$defaultPreferences
655 static function filesPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
656 # # Files #####################################
657 $defaultPreferences['imagesize'] = [
659 'options' => self
::getImageSizes( $context ),
660 'label-message' => 'imagemaxsize',
661 'section' => 'rendering/files',
663 $defaultPreferences['thumbsize'] = [
665 'options' => self
::getThumbSizes( $context ),
666 'label-message' => 'thumbsize',
667 'section' => 'rendering/files',
673 * @param IContextSource $context
674 * @param array &$defaultPreferences
677 static function datetimePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
678 # # Date and time #####################################
679 $dateOptions = self
::getDateOptions( $context );
680 if ( $dateOptions ) {
681 $defaultPreferences['date'] = [
683 'options' => $dateOptions,
685 'section' => 'rendering/dateformat',
690 $now = wfTimestampNow();
691 $lang = $context->getLanguage();
692 $nowlocal = Xml
::element( 'span', [ 'id' => 'wpLocalTime' ],
693 $lang->userTime( $now, $user ) );
694 $nowserver = $lang->userTime( $now, $user,
695 [ 'format' => false, 'timecorrection' => false ] ) .
696 Html
::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 +
(int)substr( $now, 10, 2 ) );
698 $defaultPreferences['nowserver'] = [
701 'label-message' => 'servertime',
702 'default' => $nowserver,
703 'section' => 'rendering/timeoffset',
706 $defaultPreferences['nowlocal'] = [
709 'label-message' => 'localtime',
710 'default' => $nowlocal,
711 'section' => 'rendering/timeoffset',
714 // Grab existing pref.
715 $tzOffset = $user->getOption( 'timecorrection' );
716 $tz = explode( '|', $tzOffset, 3 );
718 $tzOptions = self
::getTimezoneOptions( $context );
720 $tzSetting = $tzOffset;
721 if ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
722 !in_array( $tzOffset, HTMLFormField
::flattenOptions( $tzOptions ) )
724 // Timezone offset can vary with DST
726 $userTZ = new DateTimeZone( $tz[2] );
727 $minDiff = floor( $userTZ->getOffset( new DateTime( 'now' ) ) / 60 );
728 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
729 } catch ( Exception
$e ) {
730 // User has an invalid time zone set. Fall back to just using the offset
734 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
736 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) %
60 );
739 $defaultPreferences['timecorrection'] = [
740 'class' => 'HTMLSelectOrOtherField',
741 'label-message' => 'timezonelegend',
742 'options' => $tzOptions,
743 'default' => $tzSetting,
745 'section' => 'rendering/timeoffset',
751 * @param IContextSource $context
752 * @param array &$defaultPreferences
754 static function renderingPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
755 # # Diffs ####################################
756 $defaultPreferences['diffonly'] = [
758 'section' => 'rendering/diffs',
759 'label-message' => 'tog-diffonly',
761 $defaultPreferences['norollbackdiff'] = [
763 'section' => 'rendering/diffs',
764 'label-message' => 'tog-norollbackdiff',
767 # # Page Rendering ##############################
768 if ( $context->getConfig()->get( 'AllowUserCssPrefs' ) ) {
769 $defaultPreferences['underline'] = [
772 $context->msg( 'underline-never' )->text() => 0,
773 $context->msg( 'underline-always' )->text() => 1,
774 $context->msg( 'underline-default' )->text() => 2,
776 'label-message' => 'tog-underline',
777 'section' => 'rendering/advancedrendering',
781 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
782 $stubThresholdOptions = [ $context->msg( 'stub-threshold-disabled' )->text() => 0 ];
783 foreach ( $stubThresholdValues as $value ) {
784 $stubThresholdOptions[$context->msg( 'size-bytes', $value )->text()] = $value;
787 $defaultPreferences['stubthreshold'] = [
789 'section' => 'rendering/advancedrendering',
790 'options' => $stubThresholdOptions,
791 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
792 'label-raw' => $context->msg( 'stub-threshold' )->rawParams(
793 '<a href="#" class="stub">' .
794 $context->msg( 'stub-threshold-sample-link' )->parse() .
798 $defaultPreferences['showhiddencats'] = [
800 'section' => 'rendering/advancedrendering',
801 'label-message' => 'tog-showhiddencats'
804 $defaultPreferences['numberheadings'] = [
806 'section' => 'rendering/advancedrendering',
807 'label-message' => 'tog-numberheadings',
813 * @param IContextSource $context
814 * @param array &$defaultPreferences
816 static function editingPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
817 # # Editing #####################################
818 $defaultPreferences['editsectiononrightclick'] = [
820 'section' => 'editing/advancedediting',
821 'label-message' => 'tog-editsectiononrightclick',
823 $defaultPreferences['editondblclick'] = [
825 'section' => 'editing/advancedediting',
826 'label-message' => 'tog-editondblclick',
829 if ( $context->getConfig()->get( 'AllowUserCssPrefs' ) ) {
830 $defaultPreferences['editfont'] = [
832 'section' => 'editing/editor',
833 'label-message' => 'editfont-style',
835 $context->msg( 'editfont-default' )->text() => 'default',
836 $context->msg( 'editfont-monospace' )->text() => 'monospace',
837 $context->msg( 'editfont-sansserif' )->text() => 'sans-serif',
838 $context->msg( 'editfont-serif' )->text() => 'serif',
843 if ( $user->isAllowed( 'minoredit' ) ) {
844 $defaultPreferences['minordefault'] = [
846 'section' => 'editing/editor',
847 'label-message' => 'tog-minordefault',
851 $defaultPreferences['forceeditsummary'] = [
853 'section' => 'editing/editor',
854 'label-message' => 'tog-forceeditsummary',
856 $defaultPreferences['useeditwarning'] = [
858 'section' => 'editing/editor',
859 'label-message' => 'tog-useeditwarning',
861 $defaultPreferences['showtoolbar'] = [
863 'section' => 'editing/editor',
864 'label-message' => 'tog-showtoolbar',
867 $defaultPreferences['previewonfirst'] = [
869 'section' => 'editing/preview',
870 'label-message' => 'tog-previewonfirst',
872 $defaultPreferences['previewontop'] = [
874 'section' => 'editing/preview',
875 'label-message' => 'tog-previewontop',
877 $defaultPreferences['uselivepreview'] = [
879 'section' => 'editing/preview',
880 'label-message' => 'tog-uselivepreview',
886 * @param IContextSource $context
887 * @param array &$defaultPreferences
889 static function rcPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
890 $config = $context->getConfig();
891 $rcMaxAge = $config->get( 'RCMaxAge' );
892 # # RecentChanges #####################################
893 $defaultPreferences['rcdays'] = [
895 'label-message' => 'recentchangesdays',
896 'section' => 'rc/displayrc',
898 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
899 'help' => $context->msg( 'recentchangesdays-max' )->numParams(
900 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
902 $defaultPreferences['rclimit'] = [
906 'label-message' => 'recentchangescount',
907 'help-message' => 'prefs-help-recentchangescount',
908 'section' => 'rc/displayrc',
910 $defaultPreferences['usenewrc'] = [
912 'label-message' => 'tog-usenewrc',
913 'section' => 'rc/advancedrc',
915 $defaultPreferences['hideminor'] = [
917 'label-message' => 'tog-hideminor',
918 'section' => 'rc/advancedrc',
920 $defaultPreferences['rcfilters-saved-queries'] = [
923 $defaultPreferences['rcfilters-rclimit'] = [
927 if ( $config->get( 'RCWatchCategoryMembership' ) ) {
928 $defaultPreferences['hidecategorization'] = [
930 'label-message' => 'tog-hidecategorization',
931 'section' => 'rc/advancedrc',
935 if ( $user->useRCPatrol() ) {
936 $defaultPreferences['hidepatrolled'] = [
938 'section' => 'rc/advancedrc',
939 'label-message' => 'tog-hidepatrolled',
943 if ( $user->useNPPatrol() ) {
944 $defaultPreferences['newpageshidepatrolled'] = [
946 'section' => 'rc/advancedrc',
947 'label-message' => 'tog-newpageshidepatrolled',
951 if ( $config->get( 'RCShowWatchingUsers' ) ) {
952 $defaultPreferences['shownumberswatching'] = [
954 'section' => 'rc/advancedrc',
955 'label-message' => 'tog-shownumberswatching',
962 * @param IContextSource $context
963 * @param array &$defaultPreferences
965 static function watchlistPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
966 $config = $context->getConfig();
967 $watchlistdaysMax = ceil( $config->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
969 # # Watchlist #####################################
970 if ( $user->isAllowed( 'editmywatchlist' ) ) {
971 $editWatchlistLinks = [];
972 $editWatchlistModes = [
973 'edit' => [ 'EditWatchlist', false ],
974 'raw' => [ 'EditWatchlist', 'raw' ],
975 'clear' => [ 'EditWatchlist', 'clear' ],
977 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
978 foreach ( $editWatchlistModes as $editWatchlistMode => $mode ) {
979 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
980 $editWatchlistLinks[] = $linkRenderer->makeKnownLink(
981 SpecialPage
::getTitleFor( $mode[0], $mode[1] ),
982 new HtmlArmor( $context->msg( "prefs-editwatchlist-{$editWatchlistMode}" )->parse() )
986 $defaultPreferences['editwatchlist'] = [
989 'default' => $context->getLanguage()->pipeList( $editWatchlistLinks ),
990 'label-message' => 'prefs-editwatchlist-label',
991 'section' => 'watchlist/editwatchlist',
995 $defaultPreferences['watchlistdays'] = [
998 'max' => $watchlistdaysMax,
999 'section' => 'watchlist/displaywatchlist',
1000 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1001 $watchlistdaysMax )->escaped(),
1002 'label-message' => 'prefs-watchlist-days',
1004 $defaultPreferences['wllimit'] = [
1008 'label-message' => 'prefs-watchlist-edits',
1009 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1010 'section' => 'watchlist/displaywatchlist',
1012 $defaultPreferences['extendwatchlist'] = [
1014 'section' => 'watchlist/advancedwatchlist',
1015 'label-message' => 'tog-extendwatchlist',
1017 $defaultPreferences['watchlisthideminor'] = [
1019 'section' => 'watchlist/advancedwatchlist',
1020 'label-message' => 'tog-watchlisthideminor',
1022 $defaultPreferences['watchlisthidebots'] = [
1024 'section' => 'watchlist/advancedwatchlist',
1025 'label-message' => 'tog-watchlisthidebots',
1027 $defaultPreferences['watchlisthideown'] = [
1029 'section' => 'watchlist/advancedwatchlist',
1030 'label-message' => 'tog-watchlisthideown',
1032 $defaultPreferences['watchlisthideanons'] = [
1034 'section' => 'watchlist/advancedwatchlist',
1035 'label-message' => 'tog-watchlisthideanons',
1037 $defaultPreferences['watchlisthideliu'] = [
1039 'section' => 'watchlist/advancedwatchlist',
1040 'label-message' => 'tog-watchlisthideliu',
1042 $defaultPreferences['watchlistreloadautomatically'] = [
1044 'section' => 'watchlist/advancedwatchlist',
1045 'label-message' => 'tog-watchlistreloadautomatically',
1048 if ( $config->get( 'RCWatchCategoryMembership' ) ) {
1049 $defaultPreferences['watchlisthidecategorization'] = [
1051 'section' => 'watchlist/advancedwatchlist',
1052 'label-message' => 'tog-watchlisthidecategorization',
1056 if ( $user->useRCPatrol() ) {
1057 $defaultPreferences['watchlisthidepatrolled'] = [
1059 'section' => 'watchlist/advancedwatchlist',
1060 'label-message' => 'tog-watchlisthidepatrolled',
1065 'edit' => 'watchdefault',
1066 'move' => 'watchmoves',
1067 'delete' => 'watchdeletion'
1071 if ( $user->isAllowed( 'createpage' ) ||
$user->isAllowed( 'createtalk' ) ) {
1072 $watchTypes['read'] = 'watchcreations';
1075 if ( $user->isAllowed( 'rollback' ) ) {
1076 $watchTypes['rollback'] = 'watchrollback';
1079 if ( $user->isAllowed( 'upload' ) ) {
1080 $watchTypes['upload'] = 'watchuploads';
1083 foreach ( $watchTypes as $action => $pref ) {
1084 if ( $user->isAllowed( $action ) ) {
1086 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1087 // tog-watchrollback
1088 $defaultPreferences[$pref] = [
1090 'section' => 'watchlist/advancedwatchlist',
1091 'label-message' => "tog-$pref",
1096 if ( $config->get( 'EnableAPI' ) ) {
1097 $defaultPreferences['watchlisttoken'] = [
1100 $defaultPreferences['watchlisttoken-info'] = [
1102 'section' => 'watchlist/tokenwatchlist',
1103 'label-message' => 'prefs-watchlist-token',
1104 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1105 'help-message' => 'prefs-help-watchlist-token2',
1112 * @param IContextSource $context
1113 * @param array &$defaultPreferences
1115 static function searchPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
1116 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
1117 $defaultPreferences['searchNs' . $n] = [
1124 * Dummy, kept for backwards-compatibility.
1126 static function miscPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
1130 * @param User $user The User object
1131 * @param IContextSource $context
1132 * @return array Text/links to display as key; $skinkey as value
1134 static function generateSkinOptions( $user, IContextSource
$context ) {
1137 $mptitle = Title
::newMainPage();
1138 $previewtext = $context->msg( 'skin-preview' )->escaped();
1140 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1142 # Only show skins that aren't disabled in $wgSkipSkins
1143 $validSkinNames = Skin
::getAllowedSkins();
1145 # Sort by UI skin name. First though need to update validSkinNames as sometimes
1146 # the skinkey & UI skinname differ (e.g. "standard" skinkey is "Classic" in the UI).
1147 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1148 $msg = $context->msg( "skinname-{$skinkey}" );
1149 if ( $msg->exists() ) {
1150 $skinname = htmlspecialchars( $msg->text() );
1153 asort( $validSkinNames );
1155 $config = $context->getConfig();
1156 $defaultSkin = $config->get( 'DefaultSkin' );
1157 $allowUserCss = $config->get( 'AllowUserCss' );
1158 $allowUserJs = $config->get( 'AllowUserJs' );
1160 $foundDefault = false;
1161 foreach ( $validSkinNames as $skinkey => $sn ) {
1164 # Mark the default skin
1165 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1166 $linkTools[] = $context->msg( 'default' )->escaped();
1167 $foundDefault = true;
1170 # Create preview link
1171 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1172 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1174 # Create links to user CSS/JS pages
1175 if ( $allowUserCss ) {
1176 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1177 $linkTools[] = $linkRenderer->makeLink( $cssPage, $context->msg( 'prefs-custom-css' )->text() );
1180 if ( $allowUserJs ) {
1181 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1182 $linkTools[] = $linkRenderer->makeLink( $jsPage, $context->msg( 'prefs-custom-js' )->text() );
1185 $display = $sn . ' ' . $context->msg( 'parentheses' )
1186 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1188 $ret[$display] = $skinkey;
1191 if ( !$foundDefault ) {
1192 // If the default skin is not available, things are going to break horribly because the
1193 // default value for skin selector will not be a valid value. Let's just not show it then.
1201 * @param IContextSource $context
1204 static function getDateOptions( IContextSource
$context ) {
1205 $lang = $context->getLanguage();
1206 $dateopts = $lang->getDatePreferences();
1211 if ( !in_array( 'default', $dateopts ) ) {
1212 $dateopts[] = 'default'; // Make sure default is always valid T21237
1215 // FIXME KLUGE: site default might not be valid for user language
1216 global $wgDefaultUserOptions;
1217 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1218 $wgDefaultUserOptions['date'] = 'default';
1221 $epoch = wfTimestampNow();
1222 foreach ( $dateopts as $key ) {
1223 if ( $key == 'default' ) {
1224 $formatted = $context->msg( 'datedefault' )->escaped();
1226 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1228 $ret[$formatted] = $key;
1235 * @param IContextSource $context
1238 static function getImageSizes( IContextSource
$context ) {
1240 $pixels = $context->msg( 'unit-pixel' )->text();
1242 foreach ( $context->getConfig()->get( 'ImageLimits' ) as $index => $limits ) {
1243 // Note: A left-to-right marker (\u200e) is inserted, see T144386
1244 $display = "{$limits[0]}" . json_decode( '"\u200e"' ) . "×{$limits[1]}" . $pixels;
1245 $ret[$display] = $index;
1252 * @param IContextSource $context
1255 static function getThumbSizes( IContextSource
$context ) {
1257 $pixels = $context->msg( 'unit-pixel' )->text();
1259 foreach ( $context->getConfig()->get( 'ThumbLimits' ) as $index => $size ) {
1260 $display = $size . $pixels;
1261 $ret[$display] = $index;
1268 * @param string $signature
1269 * @param array $alldata
1270 * @param HTMLForm $form
1271 * @return bool|string
1273 static function validateSignature( $signature, $alldata, $form ) {
1275 $maxSigChars = $form->getConfig()->get( 'MaxSigChars' );
1276 if ( mb_strlen( $signature ) > $maxSigChars ) {
1277 return Xml
::element( 'span', [ 'class' => 'error' ],
1278 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1279 } elseif ( isset( $alldata['fancysig'] ) &&
1280 $alldata['fancysig'] &&
1281 $wgParser->validateSig( $signature ) === false
1283 return Xml
::element(
1285 [ 'class' => 'error' ],
1286 $form->msg( 'badsig' )->text()
1294 * @param string $signature
1295 * @param array $alldata
1296 * @param HTMLForm $form
1299 static function cleanSignature( $signature, $alldata, $form ) {
1300 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1302 $signature = $wgParser->cleanSig( $signature );
1304 // When no fancy sig used, make sure ~{3,5} get removed.
1305 $signature = Parser
::cleanSigInSig( $signature );
1313 * @param IContextSource $context
1314 * @param string $formClass
1315 * @param array $remove Array of items to remove
1316 * @return PreferencesForm|HtmlForm
1318 static function getFormObject(
1320 IContextSource
$context,
1321 $formClass = 'PreferencesForm',
1324 $formDescriptor = self
::getPreferences( $user, $context );
1325 if ( count( $remove ) ) {
1326 $removeKeys = array_flip( $remove );
1327 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1330 // Remove type=api preferences. They are not intended for rendering in the form.
1331 foreach ( $formDescriptor as $name => $info ) {
1332 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1333 unset( $formDescriptor[$name] );
1338 * @var $htmlForm PreferencesForm
1340 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1342 $htmlForm->setModifiedUser( $user );
1343 $htmlForm->setId( 'mw-prefs-form' );
1344 $htmlForm->setAutocomplete( 'off' );
1345 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1346 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1347 $htmlForm->setSubmitTooltip( 'preferences-save' );
1348 $htmlForm->setSubmitID( 'prefsubmit' );
1349 $htmlForm->setSubmitCallback( [ 'Preferences', 'tryFormSubmit' ] );
1355 * @param IContextSource $context
1358 static function getTimezoneOptions( IContextSource
$context ) {
1361 $localTZoffset = $context->getConfig()->get( 'LocalTZoffset' );
1362 $timeZoneList = self
::getTimeZoneList( $context->getLanguage() );
1364 $timestamp = MWTimestamp
::getLocalInstance();
1365 // Check that the LocalTZoffset is the same as the local time zone offset
1366 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1367 $timezoneName = $timestamp->getTimezone()->getName();
1368 // Localize timezone
1369 if ( isset( $timeZoneList[$timezoneName] ) ) {
1370 $timezoneName = $timeZoneList[$timezoneName]['name'];
1372 $server_tz_msg = $context->msg(
1373 'timezoneuseserverdefault',
1377 $tzstring = sprintf(
1379 floor( $localTZoffset / 60 ),
1380 abs( $localTZoffset ) %
60
1382 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1384 $opt[$server_tz_msg] = "System|$localTZoffset";
1385 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1386 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1388 foreach ( $timeZoneList as $timeZoneInfo ) {
1389 $region = $timeZoneInfo['region'];
1390 if ( !isset( $opt[$region] ) ) {
1393 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1399 * @param string $value
1400 * @param array $alldata
1403 static function filterIntval( $value, $alldata ) {
1404 return intval( $value );
1409 * @param array $alldata
1412 static function filterTimezoneInput( $tz, $alldata ) {
1413 $data = explode( '|', $tz, 3 );
1414 switch ( $data[0] ) {
1418 if ( count( $data ) === 3 ) {
1419 // Make sure this timezone exists
1421 new DateTimeZone( $data[2] );
1422 // If the constructor didn't throw, we know it's valid
1424 } catch ( Exception
$e ) {
1425 // Not a valid timezone
1430 // If the supplied timezone doesn't exist, fall back to the encoded offset
1431 return 'Offset|' . intval( $tz[1] );
1437 $data = explode( ':', $tz, 2 );
1438 if ( count( $data ) == 2 ) {
1439 $data[0] = intval( $data[0] );
1440 $data[1] = intval( $data[1] );
1441 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1442 if ( $data[0] < 0 ) {
1443 $minDiff = - $minDiff;
1446 $minDiff = intval( $data[0] ) * 60;
1449 # Max is +14:00 and min is -12:00, see:
1450 # https://en.wikipedia.org/wiki/Timezone
1451 $minDiff = min( $minDiff, 840 ); # 14:00
1452 $minDiff = max( $minDiff, -720 ); # -12:00
1453 return 'Offset|' . $minDiff;
1458 * Handle the form submission if everything validated properly
1460 * @param array $formData
1461 * @param PreferencesForm $form
1462 * @return bool|Status|string
1464 static function tryFormSubmit( $formData, $form ) {
1465 $user = $form->getModifiedUser();
1466 $hiddenPrefs = $form->getConfig()->get( 'HiddenPrefs' );
1469 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1470 return Status
::newFatal( 'mypreferencesprotected' );
1474 foreach ( array_keys( $formData ) as $name ) {
1475 if ( isset( self
::$saveFilters[$name] ) ) {
1477 call_user_func( self
::$saveFilters[$name], $formData[$name], $formData );
1481 // Fortunately, the realname field is MUCH simpler
1482 // (not really "private", but still shouldn't be edited without permission)
1484 if ( !in_array( 'realname', $hiddenPrefs )
1485 && $user->isAllowed( 'editmyprivateinfo' )
1486 && array_key_exists( 'realname', $formData )
1488 $realName = $formData['realname'];
1489 $user->setRealName( $realName );
1492 if ( $user->isAllowed( 'editmyoptions' ) ) {
1493 $oldUserOptions = $user->getOptions();
1495 foreach ( self
::$saveBlacklist as $b ) {
1496 unset( $formData[$b] );
1499 # If users have saved a value for a preference which has subsequently been disabled
1500 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1501 # is subsequently re-enabled
1502 foreach ( $hiddenPrefs as $pref ) {
1503 # If the user has not set a non-default value here, the default will be returned
1504 # and subsequently discarded
1505 $formData[$pref] = $user->getOption( $pref, null, true );
1508 // Keep old preferences from interfering due to back-compat code, etc.
1509 $user->resetOptions( 'unused', $form->getContext() );
1511 foreach ( $formData as $key => $value ) {
1512 $user->setOption( $key, $value );
1516 'PreferencesFormPreSave',
1517 [ $formData, $form, $user, &$result, $oldUserOptions ]
1521 MediaWiki\Auth\AuthManager
::callLegacyAuthPlugin( 'updateExternalDB', [ $user ] );
1522 $user->saveSettings();
1528 * @param array $formData
1529 * @param PreferencesForm $form
1532 public static function tryUISubmit( $formData, $form ) {
1533 $res = self
::tryFormSubmit( $formData, $form );
1538 if ( $res === 'eauth' ) {
1539 $urlOptions['eauth'] = 1;
1542 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1544 $url = $form->getTitle()->getFullURL( $urlOptions );
1546 $context = $form->getContext();
1547 // Set session data for the success message
1548 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1550 $context->getOutput()->redirect( $url );
1553 return Status
::newGood();
1557 * Get a list of all time zones
1558 * @param Language $language Language used for the localized names
1559 * @return array A list of all time zones. The system name of the time zone is used as key and
1560 * the value is an array which contains localized name, the timecorrection value used for
1561 * preferences and the region
1564 public static function getTimeZoneList( Language
$language ) {
1565 $identifiers = DateTimeZone
::listIdentifiers();
1566 if ( $identifiers === false ) {
1569 sort( $identifiers );
1572 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1573 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1574 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1575 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1576 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1577 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1578 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1579 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1580 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1581 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1583 asort( $tzRegions );
1587 $now = new DateTime();
1589 foreach ( $identifiers as $identifier ) {
1590 $parts = explode( '/', $identifier, 2 );
1592 // DateTimeZone::listIdentifiers() returns a number of
1593 // backwards-compatibility entries. This filters them out of the
1594 // list presented to the user.
1595 if ( count( $parts ) !== 2 ||
!array_key_exists( $parts[0], $tzRegions ) ) {
1600 $parts[0] = $tzRegions[$parts[0]];
1602 $dateTimeZone = new DateTimeZone( $identifier );
1603 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1605 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1606 $value = "ZoneInfo|$minDiff|$identifier";
1608 $timeZoneList[$identifier] = [
1610 'timecorrection' => $value,
1611 'region' => $parts[0],
1615 return $timeZoneList;
1619 /** Some tweaks to allow js prefs to work */
1620 class PreferencesForm
extends HTMLForm
{
1621 // Override default value from HTMLForm
1622 protected $mSubSectionBeforeFields = false;
1624 private $modifiedUser;
1629 public function setModifiedUser( $user ) {
1630 $this->modifiedUser
= $user;
1636 public function getModifiedUser() {
1637 if ( $this->modifiedUser
=== null ) {
1638 return $this->getUser();
1640 return $this->modifiedUser
;
1645 * Get extra parameters for the query string when redirecting after
1650 public function getExtraSuccessRedirectParameters() {
1655 * @param string $html
1658 function wrapForm( $html ) {
1659 $html = Xml
::tags( 'div', [ 'id' => 'preferences' ], $html );
1661 return parent
::wrapForm( $html );
1667 function getButtons() {
1668 $attrs = [ 'id' => 'mw-prefs-restoreprefs' ];
1670 if ( !$this->getModifiedUser()->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1674 $html = parent
::getButtons();
1676 if ( $this->getModifiedUser()->isAllowed( 'editmyoptions' ) ) {
1677 $t = SpecialPage
::getTitleFor( 'Preferences', 'reset' );
1679 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1680 $html .= "\n" . $linkRenderer->makeLink( $t, $this->msg( 'restoreprefs' )->text(),
1681 Html
::buttonAttributes( $attrs, [ 'mw-ui-quiet' ] ) );
1683 $html = Xml
::tags( 'div', [ 'class' => 'mw-prefs-buttons' ], $html );
1690 * Separate multi-option preferences into multiple preferences, since we
1691 * have to store them separately
1692 * @param array $data
1695 function filterDataForSubmit( $data ) {
1696 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1697 if ( $field instanceof HTMLNestedFilterable
) {
1698 $info = $field->mParams
;
1699 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $fieldname;
1700 foreach ( $field->filterDataForSubmit( $data[$fieldname] ) as $key => $value ) {
1701 $data["$prefix$key"] = $value;
1703 unset( $data[$fieldname] );
1711 * Get the whole body of the form.
1714 function getBody() {
1715 return $this->displaySection( $this->mFieldTree
, '', 'mw-prefsection-' );
1719 * Get the "<legend>" for a given section key. Normally this is the
1720 * prefs-$key message but we'll allow extensions to override it.
1721 * @param string $key
1724 function getLegend( $key ) {
1725 $legend = parent
::getLegend( $key );
1726 Hooks
::run( 'PreferencesGetLegend', [ $this, $key, &$legend ] );
1731 * Get the keys of each top level preference section.
1732 * @return array of section keys
1734 function getPreferenceSections() {
1735 return array_keys( array_filter( $this->mFieldTree
, 'is_array' ) );