DatabaseMysqlBase visibility cleanups
[mediawiki.git] / includes / Preferences.php
blob9f8c06b9bf964c6aea4b1d259ee8810557fcff8d
1 <?php
2 /**
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
20 * @file
22 use MediaWiki\Auth\AuthManager;
23 use MediaWiki\Auth\PasswordAuthenticationRequest;
25 /**
26 * We're now using the HTMLForm object with some customisation to generate the
27 * Preferences form. This object handles generic submission, CSRF protection,
28 * layout and other logic in a reusable manner. We subclass it as a PreferencesForm
29 * to make some minor customisations.
31 * In order to generate the form, the HTMLForm object needs an array structure
32 * detailing the form fields available, and that's what this class is for. Each
33 * element of the array is a basic property-list, including the type of field,
34 * the label it is to be given in the form, callbacks for validation and
35 * 'filtering', and other pertinent information. Note that the 'default' field
36 * is named for generic forms, and does not represent the preference's default
37 * (which is stored in $wgDefaultUserOptions), but the default for the form
38 * field, which should be whatever the user has set for that preference. There
39 * is no need to override it unless you have some special storage logic (for
40 * instance, those not presently stored as options, but which are best set from
41 * the user preferences view).
43 * Field types are implemented as subclasses of the generic HTMLFormField
44 * object, and typically implement at least getInputHTML, which generates the
45 * HTML for the input field to be placed in the table.
47 * Once fields have been retrieved and validated, submission logic is handed
48 * over to the tryUISubmit static method of this class.
50 class Preferences {
51 /** @var array */
52 protected static $defaultPreferences = null;
54 /** @var array */
55 protected static $saveFilters = [
56 'timecorrection' => [ 'Preferences', 'filterTimezoneInput' ],
57 'cols' => [ 'Preferences', 'filterIntval' ],
58 'rows' => [ 'Preferences', 'filterIntval' ],
59 'rclimit' => [ 'Preferences', 'filterIntval' ],
60 'wllimit' => [ 'Preferences', 'filterIntval' ],
61 'searchlimit' => [ 'Preferences', 'filterIntval' ],
64 // Stuff that shouldn't be saved as a preference.
65 private static $saveBlacklist = [
66 'realname',
67 'emailaddress',
70 /**
71 * @return array
73 static function getSaveBlacklist() {
74 return self::$saveBlacklist;
77 /**
78 * @throws MWException
79 * @param User $user
80 * @param IContextSource $context
81 * @return array|null
83 static function getPreferences( $user, IContextSource $context ) {
84 if ( self::$defaultPreferences ) {
85 return self::$defaultPreferences;
88 $defaultPreferences = [];
90 self::profilePreferences( $user, $context, $defaultPreferences );
91 self::skinPreferences( $user, $context, $defaultPreferences );
92 self::datetimePreferences( $user, $context, $defaultPreferences );
93 self::filesPreferences( $user, $context, $defaultPreferences );
94 self::renderingPreferences( $user, $context, $defaultPreferences );
95 self::editingPreferences( $user, $context, $defaultPreferences );
96 self::rcPreferences( $user, $context, $defaultPreferences );
97 self::watchlistPreferences( $user, $context, $defaultPreferences );
98 self::searchPreferences( $user, $context, $defaultPreferences );
99 self::miscPreferences( $user, $context, $defaultPreferences );
101 Hooks::run( 'GetPreferences', [ $user, &$defaultPreferences ] );
103 self::loadPreferenceValues( $user, $context, $defaultPreferences );
104 self::$defaultPreferences = $defaultPreferences;
105 return $defaultPreferences;
109 * Loads existing values for a given array of preferences
110 * @throws MWException
111 * @param User $user
112 * @param IContextSource $context
113 * @param array $defaultPreferences Array to load values for
114 * @return array|null
116 static function loadPreferenceValues( $user, $context, &$defaultPreferences ) {
117 # # Remove preferences that wikis don't want to use
118 foreach ( $context->getConfig()->get( 'HiddenPrefs' ) as $pref ) {
119 if ( isset( $defaultPreferences[$pref] ) ) {
120 unset( $defaultPreferences[$pref] );
124 # # Make sure that form fields have their parent set. See bug 41337.
125 $dummyForm = new HTMLForm( [], $context );
127 $disable = !$user->isAllowed( 'editmyoptions' );
129 $defaultOptions = User::getDefaultOptions();
130 # # Prod in defaults from the user
131 foreach ( $defaultPreferences as $name => &$info ) {
132 $prefFromUser = self::getOptionFromUser( $name, $info, $user );
133 if ( $disable && !in_array( $name, self::$saveBlacklist ) ) {
134 $info['disabled'] = 'disabled';
136 $field = HTMLForm::loadInputFromParameters( $name, $info, $dummyForm ); // For validation
137 $globalDefault = isset( $defaultOptions[$name] )
138 ? $defaultOptions[$name]
139 : null;
141 // If it validates, set it as the default
142 if ( isset( $info['default'] ) ) {
143 // Already set, no problem
144 continue;
145 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
146 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
147 $info['default'] = $prefFromUser;
148 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
149 $info['default'] = $globalDefault;
150 } else {
151 throw new MWException( "Global default '$globalDefault' is invalid for field $name" );
155 return $defaultPreferences;
159 * Pull option from a user account. Handles stuff like array-type preferences.
161 * @param string $name
162 * @param array $info
163 * @param User $user
164 * @return array|string
166 static function getOptionFromUser( $name, $info, $user ) {
167 $val = $user->getOption( $name );
169 // Handling for multiselect preferences
170 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
171 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
172 $options = HTMLFormField::flattenOptions( $info['options'] );
173 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
174 $val = [];
176 foreach ( $options as $value ) {
177 if ( $user->getOption( "$prefix$value" ) ) {
178 $val[] = $value;
183 // Handling for checkmatrix preferences
184 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
185 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
186 $columns = HTMLFormField::flattenOptions( $info['columns'] );
187 $rows = HTMLFormField::flattenOptions( $info['rows'] );
188 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
189 $val = [];
191 foreach ( $columns as $column ) {
192 foreach ( $rows as $row ) {
193 if ( $user->getOption( "$prefix$column-$row" ) ) {
194 $val[] = "$column-$row";
200 return $val;
204 * @param User $user
205 * @param IContextSource $context
206 * @param array $defaultPreferences
207 * @return void
209 static function profilePreferences( $user, IContextSource $context, &$defaultPreferences ) {
210 global $wgContLang, $wgParser;
212 $authManager = AuthManager::singleton();
213 $config = $context->getConfig();
214 // retrieving user name for GENDER and misc.
215 $userName = $user->getName();
217 # # User info #####################################
218 // Information panel
219 $defaultPreferences['username'] = [
220 'type' => 'info',
221 'label-message' => [ 'username', $userName ],
222 'default' => $userName,
223 'section' => 'personal/info',
226 # Get groups to which the user belongs
227 $userEffectiveGroups = $user->getEffectiveGroups();
228 $userGroups = $userMembers = [];
229 foreach ( $userEffectiveGroups as $ueg ) {
230 if ( $ueg == '*' ) {
231 // Skip the default * group, seems useless here
232 continue;
234 $groupName = User::getGroupName( $ueg );
235 $userGroups[] = User::makeGroupLinkHTML( $ueg, $groupName );
237 $memberName = User::getGroupMember( $ueg, $userName );
238 $userMembers[] = User::makeGroupLinkHTML( $ueg, $memberName );
240 asort( $userGroups );
241 asort( $userMembers );
243 $lang = $context->getLanguage();
245 $defaultPreferences['usergroups'] = [
246 'type' => 'info',
247 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
248 count( $userGroups ) )->params( $userName )->parse(),
249 'default' => $context->msg( 'prefs-memberingroups-type' )
250 ->rawParams( $lang->commaList( $userGroups ), $lang->commaList( $userMembers ) )
251 ->escaped(),
252 'raw' => true,
253 'section' => 'personal/info',
256 $editCount = Linker::link( SpecialPage::getTitleFor( "Contributions", $userName ),
257 $lang->formatNum( $user->getEditCount() ) );
259 $defaultPreferences['editcount'] = [
260 'type' => 'info',
261 'raw' => true,
262 'label-message' => 'prefs-edits',
263 'default' => $editCount,
264 'section' => 'personal/info',
267 if ( $user->getRegistration() ) {
268 $displayUser = $context->getUser();
269 $userRegistration = $user->getRegistration();
270 $defaultPreferences['registrationdate'] = [
271 'type' => 'info',
272 'label-message' => 'prefs-registration',
273 'default' => $context->msg(
274 'prefs-registration-date-time',
275 $lang->userTimeAndDate( $userRegistration, $displayUser ),
276 $lang->userDate( $userRegistration, $displayUser ),
277 $lang->userTime( $userRegistration, $displayUser )
278 )->parse(),
279 'section' => 'personal/info',
283 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
284 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
286 // Actually changeable stuff
287 $defaultPreferences['realname'] = [
288 // (not really "private", but still shouldn't be edited without permission)
289 'type' => $canEditPrivateInfo && $authManager->allowsPropertyChange( 'realname' )
290 ? 'text' : 'info',
291 'default' => $user->getRealName(),
292 'section' => 'personal/info',
293 'label-message' => 'yourrealname',
294 'help-message' => 'prefs-help-realname',
297 if ( $canEditPrivateInfo && $authManager->allowsAuthenticationDataChange(
298 new PasswordAuthenticationRequest(), false )->isGood()
300 $link = Linker::link( SpecialPage::getTitleFor( 'ChangePassword' ),
301 $context->msg( 'prefs-resetpass' )->escaped(), [],
302 [ 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText() ] );
304 $defaultPreferences['password'] = [
305 'type' => 'info',
306 'raw' => true,
307 'default' => $link,
308 'label-message' => 'yourpassword',
309 'section' => 'personal/info',
312 // Only show prefershttps if secure login is turned on
313 if ( $config->get( 'SecureLogin' ) && wfCanIPUseHTTPS( $context->getRequest()->getIP() ) ) {
314 $defaultPreferences['prefershttps'] = [
315 'type' => 'toggle',
316 'label-message' => 'tog-prefershttps',
317 'help-message' => 'prefs-help-prefershttps',
318 'section' => 'personal/info'
322 // Language
323 $languages = Language::fetchLanguageNames( null, 'mw' );
324 $languageCode = $config->get( 'LanguageCode' );
325 if ( !array_key_exists( $languageCode, $languages ) ) {
326 $languages[$languageCode] = $languageCode;
328 ksort( $languages );
330 $options = [];
331 foreach ( $languages as $code => $name ) {
332 $display = wfBCP47( $code ) . ' - ' . $name;
333 $options[$display] = $code;
335 $defaultPreferences['language'] = [
336 'type' => 'select',
337 'section' => 'personal/i18n',
338 'options' => $options,
339 'label-message' => 'yourlanguage',
342 $defaultPreferences['gender'] = [
343 'type' => 'radio',
344 'section' => 'personal/i18n',
345 'options' => [
346 $context->msg( 'parentheses' )
347 ->params( $context->msg( 'gender-unknown' )->plain() )
348 ->escaped() => 'unknown',
349 $context->msg( 'gender-female' )->escaped() => 'female',
350 $context->msg( 'gender-male' )->escaped() => 'male',
352 'label-message' => 'yourgender',
353 'help-message' => 'prefs-help-gender',
356 // see if there are multiple language variants to choose from
357 if ( !$config->get( 'DisableLangConversion' ) ) {
358 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
359 if ( $langCode == $wgContLang->getCode() ) {
360 $variants = $wgContLang->getVariants();
362 if ( count( $variants ) <= 1 ) {
363 continue;
366 $variantArray = [];
367 foreach ( $variants as $v ) {
368 $v = str_replace( '_', '-', strtolower( $v ) );
369 $variantArray[$v] = $lang->getVariantname( $v, false );
372 $options = [];
373 foreach ( $variantArray as $code => $name ) {
374 $display = wfBCP47( $code ) . ' - ' . $name;
375 $options[$display] = $code;
378 $defaultPreferences['variant'] = [
379 'label-message' => 'yourvariant',
380 'type' => 'select',
381 'options' => $options,
382 'section' => 'personal/i18n',
383 'help-message' => 'prefs-help-variant',
385 } else {
386 $defaultPreferences["variant-$langCode"] = [
387 'type' => 'api',
393 // Stuff from Language::getExtraUserToggles()
394 // FIXME is this dead code? $extraUserToggles doesn't seem to be defined for any language
395 $toggles = $wgContLang->getExtraUserToggles();
397 foreach ( $toggles as $toggle ) {
398 $defaultPreferences[$toggle] = [
399 'type' => 'toggle',
400 'section' => 'personal/i18n',
401 'label-message' => "tog-$toggle",
405 // show a preview of the old signature first
406 $oldsigWikiText = $wgParser->preSaveTransform(
407 '~~~',
408 $context->getTitle(),
409 $user,
410 ParserOptions::newFromContext( $context )
412 $oldsigHTML = $context->getOutput()->parseInline( $oldsigWikiText, true, true );
413 $defaultPreferences['oldsig'] = [
414 'type' => 'info',
415 'raw' => true,
416 'label-message' => 'tog-oldsig',
417 'default' => $oldsigHTML,
418 'section' => 'personal/signature',
420 $defaultPreferences['nickname'] = [
421 'type' => $authManager->allowsPropertyChange( 'nickname' ) ? 'text' : 'info',
422 'maxlength' => $config->get( 'MaxSigChars' ),
423 'label-message' => 'yournick',
424 'validation-callback' => [ 'Preferences', 'validateSignature' ],
425 'section' => 'personal/signature',
426 'filter-callback' => [ 'Preferences', 'cleanSignature' ],
428 $defaultPreferences['fancysig'] = [
429 'type' => 'toggle',
430 'label-message' => 'tog-fancysig',
431 // show general help about signature at the bottom of the section
432 'help-message' => 'prefs-help-signature',
433 'section' => 'personal/signature'
436 # # Email stuff
438 if ( $config->get( 'EnableEmail' ) ) {
439 if ( $canViewPrivateInfo ) {
440 $helpMessages[] = $config->get( 'EmailConfirmToEdit' )
441 ? 'prefs-help-email-required'
442 : 'prefs-help-email';
444 if ( $config->get( 'EnableUserEmail' ) ) {
445 // additional messages when users can send email to each other
446 $helpMessages[] = 'prefs-help-email-others';
449 $emailAddress = $user->getEmail() ? htmlspecialchars( $user->getEmail() ) : '';
450 if ( $canEditPrivateInfo && $authManager->allowsPropertyChange( 'emailaddress' ) ) {
451 $link = Linker::link(
452 SpecialPage::getTitleFor( 'ChangeEmail' ),
453 $context->msg( $user->getEmail() ? 'prefs-changeemail' : 'prefs-setemail' )->escaped(),
455 [ 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText() ] );
457 $emailAddress .= $emailAddress == '' ? $link : (
458 $context->msg( 'word-separator' )->escaped()
459 . $context->msg( 'parentheses' )->rawParams( $link )->escaped()
463 $defaultPreferences['emailaddress'] = [
464 'type' => 'info',
465 'raw' => true,
466 'default' => $emailAddress,
467 'label-message' => 'youremail',
468 'section' => 'personal/email',
469 'help-messages' => $helpMessages,
470 # 'cssclass' chosen below
474 $disableEmailPrefs = false;
476 if ( $config->get( 'EmailAuthentication' ) ) {
477 $emailauthenticationclass = 'mw-email-not-authenticated';
478 if ( $user->getEmail() ) {
479 if ( $user->getEmailAuthenticationTimestamp() ) {
480 // date and time are separate parameters to facilitate localisation.
481 // $time is kept for backward compat reasons.
482 // 'emailauthenticated' is also used in SpecialConfirmemail.php
483 $displayUser = $context->getUser();
484 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
485 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
486 $d = $lang->userDate( $emailTimestamp, $displayUser );
487 $t = $lang->userTime( $emailTimestamp, $displayUser );
488 $emailauthenticated = $context->msg( 'emailauthenticated',
489 $time, $d, $t )->parse() . '<br />';
490 $disableEmailPrefs = false;
491 $emailauthenticationclass = 'mw-email-authenticated';
492 } else {
493 $disableEmailPrefs = true;
494 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
495 Linker::linkKnown(
496 SpecialPage::getTitleFor( 'Confirmemail' ),
497 $context->msg( 'emailconfirmlink' )->escaped()
498 ) . '<br />';
499 $emailauthenticationclass = "mw-email-not-authenticated";
501 } else {
502 $disableEmailPrefs = true;
503 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
504 $emailauthenticationclass = 'mw-email-none';
507 if ( $canViewPrivateInfo ) {
508 $defaultPreferences['emailauthentication'] = [
509 'type' => 'info',
510 'raw' => true,
511 'section' => 'personal/email',
512 'label-message' => 'prefs-emailconfirm-label',
513 'default' => $emailauthenticated,
514 # Apply the same CSS class used on the input to the message:
515 'cssclass' => $emailauthenticationclass,
520 if ( $config->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
521 $defaultPreferences['disablemail'] = [
522 'type' => 'toggle',
523 'invert' => true,
524 'section' => 'personal/email',
525 'label-message' => 'allowemail',
526 'disabled' => $disableEmailPrefs,
528 $defaultPreferences['ccmeonemails'] = [
529 'type' => 'toggle',
530 'section' => 'personal/email',
531 'label-message' => 'tog-ccmeonemails',
532 'disabled' => $disableEmailPrefs,
536 if ( $config->get( 'EnotifWatchlist' ) ) {
537 $defaultPreferences['enotifwatchlistpages'] = [
538 'type' => 'toggle',
539 'section' => 'personal/email',
540 'label-message' => 'tog-enotifwatchlistpages',
541 'disabled' => $disableEmailPrefs,
544 if ( $config->get( 'EnotifUserTalk' ) ) {
545 $defaultPreferences['enotifusertalkpages'] = [
546 'type' => 'toggle',
547 'section' => 'personal/email',
548 'label-message' => 'tog-enotifusertalkpages',
549 'disabled' => $disableEmailPrefs,
552 if ( $config->get( 'EnotifUserTalk' ) || $config->get( 'EnotifWatchlist' ) ) {
553 if ( $config->get( 'EnotifMinorEdits' ) ) {
554 $defaultPreferences['enotifminoredits'] = [
555 'type' => 'toggle',
556 'section' => 'personal/email',
557 'label-message' => 'tog-enotifminoredits',
558 'disabled' => $disableEmailPrefs,
562 if ( $config->get( 'EnotifRevealEditorAddress' ) ) {
563 $defaultPreferences['enotifrevealaddr'] = [
564 'type' => 'toggle',
565 'section' => 'personal/email',
566 'label-message' => 'tog-enotifrevealaddr',
567 'disabled' => $disableEmailPrefs,
575 * @param User $user
576 * @param IContextSource $context
577 * @param array $defaultPreferences
578 * @return void
580 static function skinPreferences( $user, IContextSource $context, &$defaultPreferences ) {
581 # # Skin #####################################
583 // Skin selector, if there is at least one valid skin
584 $skinOptions = self::generateSkinOptions( $user, $context );
585 if ( $skinOptions ) {
586 $defaultPreferences['skin'] = [
587 'type' => 'radio',
588 'options' => $skinOptions,
589 'label' => '&#160;',
590 'section' => 'rendering/skin',
594 $config = $context->getConfig();
595 $allowUserCss = $config->get( 'AllowUserCss' );
596 $allowUserJs = $config->get( 'AllowUserJs' );
597 # Create links to user CSS/JS pages for all skins
598 # This code is basically copied from generateSkinOptions(). It'd
599 # be nice to somehow merge this back in there to avoid redundancy.
600 if ( $allowUserCss || $allowUserJs ) {
601 $linkTools = [];
602 $userName = $user->getName();
604 if ( $allowUserCss ) {
605 $cssPage = Title::makeTitleSafe( NS_USER, $userName . '/common.css' );
606 $linkTools[] = Linker::link( $cssPage, $context->msg( 'prefs-custom-css' )->escaped() );
609 if ( $allowUserJs ) {
610 $jsPage = Title::makeTitleSafe( NS_USER, $userName . '/common.js' );
611 $linkTools[] = Linker::link( $jsPage, $context->msg( 'prefs-custom-js' )->escaped() );
614 $defaultPreferences['commoncssjs'] = [
615 'type' => 'info',
616 'raw' => true,
617 'default' => $context->getLanguage()->pipeList( $linkTools ),
618 'label-message' => 'prefs-common-css-js',
619 'section' => 'rendering/skin',
625 * @param User $user
626 * @param IContextSource $context
627 * @param array $defaultPreferences
629 static function filesPreferences( $user, IContextSource $context, &$defaultPreferences ) {
630 # # Files #####################################
631 $defaultPreferences['imagesize'] = [
632 'type' => 'select',
633 'options' => self::getImageSizes( $context ),
634 'label-message' => 'imagemaxsize',
635 'section' => 'rendering/files',
637 $defaultPreferences['thumbsize'] = [
638 'type' => 'select',
639 'options' => self::getThumbSizes( $context ),
640 'label-message' => 'thumbsize',
641 'section' => 'rendering/files',
646 * @param User $user
647 * @param IContextSource $context
648 * @param array $defaultPreferences
649 * @return void
651 static function datetimePreferences( $user, IContextSource $context, &$defaultPreferences ) {
652 # # Date and time #####################################
653 $dateOptions = self::getDateOptions( $context );
654 if ( $dateOptions ) {
655 $defaultPreferences['date'] = [
656 'type' => 'radio',
657 'options' => $dateOptions,
658 'label' => '&#160;',
659 'section' => 'rendering/dateformat',
663 // Info
664 $now = wfTimestampNow();
665 $lang = $context->getLanguage();
666 $nowlocal = Xml::element( 'span', [ 'id' => 'wpLocalTime' ],
667 $lang->userTime( $now, $user ) );
668 $nowserver = $lang->userTime( $now, $user,
669 [ 'format' => false, 'timecorrection' => false ] ) .
670 Html::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 + (int)substr( $now, 10, 2 ) );
672 $defaultPreferences['nowserver'] = [
673 'type' => 'info',
674 'raw' => 1,
675 'label-message' => 'servertime',
676 'default' => $nowserver,
677 'section' => 'rendering/timeoffset',
680 $defaultPreferences['nowlocal'] = [
681 'type' => 'info',
682 'raw' => 1,
683 'label-message' => 'localtime',
684 'default' => $nowlocal,
685 'section' => 'rendering/timeoffset',
688 // Grab existing pref.
689 $tzOffset = $user->getOption( 'timecorrection' );
690 $tz = explode( '|', $tzOffset, 3 );
692 $tzOptions = self::getTimezoneOptions( $context );
694 $tzSetting = $tzOffset;
695 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
696 $minDiff = $tz[1];
697 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) % 60 );
698 } elseif ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
699 !in_array( $tzOffset, HTMLFormField::flattenOptions( $tzOptions ) )
701 # Timezone offset can vary with DST
702 $userTZ = timezone_open( $tz[2] );
703 if ( $userTZ !== false ) {
704 $minDiff = floor( timezone_offset_get( $userTZ, date_create( 'now' ) ) / 60 );
705 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
709 $defaultPreferences['timecorrection'] = [
710 'class' => 'HTMLSelectOrOtherField',
711 'label-message' => 'timezonelegend',
712 'options' => $tzOptions,
713 'default' => $tzSetting,
714 'size' => 20,
715 'section' => 'rendering/timeoffset',
720 * @param User $user
721 * @param IContextSource $context
722 * @param array $defaultPreferences
724 static function renderingPreferences( $user, IContextSource $context, &$defaultPreferences ) {
725 # # Diffs ####################################
726 $defaultPreferences['diffonly'] = [
727 'type' => 'toggle',
728 'section' => 'rendering/diffs',
729 'label-message' => 'tog-diffonly',
731 $defaultPreferences['norollbackdiff'] = [
732 'type' => 'toggle',
733 'section' => 'rendering/diffs',
734 'label-message' => 'tog-norollbackdiff',
737 # # Page Rendering ##############################
738 if ( $context->getConfig()->get( 'AllowUserCssPrefs' ) ) {
739 $defaultPreferences['underline'] = [
740 'type' => 'select',
741 'options' => [
742 $context->msg( 'underline-never' )->text() => 0,
743 $context->msg( 'underline-always' )->text() => 1,
744 $context->msg( 'underline-default' )->text() => 2,
746 'label-message' => 'tog-underline',
747 'section' => 'rendering/advancedrendering',
751 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
752 $stubThresholdOptions = [ $context->msg( 'stub-threshold-disabled' )->text() => 0 ];
753 foreach ( $stubThresholdValues as $value ) {
754 $stubThresholdOptions[$context->msg( 'size-bytes', $value )->text()] = $value;
757 $defaultPreferences['stubthreshold'] = [
758 'type' => 'select',
759 'section' => 'rendering/advancedrendering',
760 'options' => $stubThresholdOptions,
761 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
762 'label-raw' => $context->msg( 'stub-threshold' )->rawParams(
763 '<a href="#" class="stub">' .
764 $context->msg( 'stub-threshold-sample-link' )->parse() .
765 '</a>' )->parse(),
768 $defaultPreferences['showhiddencats'] = [
769 'type' => 'toggle',
770 'section' => 'rendering/advancedrendering',
771 'label-message' => 'tog-showhiddencats'
774 $defaultPreferences['numberheadings'] = [
775 'type' => 'toggle',
776 'section' => 'rendering/advancedrendering',
777 'label-message' => 'tog-numberheadings',
782 * @param User $user
783 * @param IContextSource $context
784 * @param array $defaultPreferences
786 static function editingPreferences( $user, IContextSource $context, &$defaultPreferences ) {
787 # # Editing #####################################
788 $defaultPreferences['editsectiononrightclick'] = [
789 'type' => 'toggle',
790 'section' => 'editing/advancedediting',
791 'label-message' => 'tog-editsectiononrightclick',
793 $defaultPreferences['editondblclick'] = [
794 'type' => 'toggle',
795 'section' => 'editing/advancedediting',
796 'label-message' => 'tog-editondblclick',
799 if ( $context->getConfig()->get( 'AllowUserCssPrefs' ) ) {
800 $defaultPreferences['editfont'] = [
801 'type' => 'select',
802 'section' => 'editing/editor',
803 'label-message' => 'editfont-style',
804 'options' => [
805 $context->msg( 'editfont-default' )->text() => 'default',
806 $context->msg( 'editfont-monospace' )->text() => 'monospace',
807 $context->msg( 'editfont-sansserif' )->text() => 'sans-serif',
808 $context->msg( 'editfont-serif' )->text() => 'serif',
812 $defaultPreferences['cols'] = [
813 'type' => 'int',
814 'label-message' => 'columns',
815 'section' => 'editing/editor',
816 'min' => 4,
817 'max' => 1000,
819 $defaultPreferences['rows'] = [
820 'type' => 'int',
821 'label-message' => 'rows',
822 'section' => 'editing/editor',
823 'min' => 4,
824 'max' => 1000,
826 if ( $user->isAllowed( 'minoredit' ) ) {
827 $defaultPreferences['minordefault'] = [
828 'type' => 'toggle',
829 'section' => 'editing/editor',
830 'label-message' => 'tog-minordefault',
833 $defaultPreferences['forceeditsummary'] = [
834 'type' => 'toggle',
835 'section' => 'editing/editor',
836 'label-message' => 'tog-forceeditsummary',
838 $defaultPreferences['useeditwarning'] = [
839 'type' => 'toggle',
840 'section' => 'editing/editor',
841 'label-message' => 'tog-useeditwarning',
843 $defaultPreferences['showtoolbar'] = [
844 'type' => 'toggle',
845 'section' => 'editing/editor',
846 'label-message' => 'tog-showtoolbar',
849 $defaultPreferences['previewonfirst'] = [
850 'type' => 'toggle',
851 'section' => 'editing/preview',
852 'label-message' => 'tog-previewonfirst',
854 $defaultPreferences['previewontop'] = [
855 'type' => 'toggle',
856 'section' => 'editing/preview',
857 'label-message' => 'tog-previewontop',
859 $defaultPreferences['uselivepreview'] = [
860 'type' => 'toggle',
861 'section' => 'editing/preview',
862 'label-message' => 'tog-uselivepreview',
868 * @param User $user
869 * @param IContextSource $context
870 * @param array $defaultPreferences
872 static function rcPreferences( $user, IContextSource $context, &$defaultPreferences ) {
873 $config = $context->getConfig();
874 $rcMaxAge = $config->get( 'RCMaxAge' );
875 # # RecentChanges #####################################
876 $defaultPreferences['rcdays'] = [
877 'type' => 'float',
878 'label-message' => 'recentchangesdays',
879 'section' => 'rc/displayrc',
880 'min' => 1,
881 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
882 'help' => $context->msg( 'recentchangesdays-max' )->numParams(
883 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
885 $defaultPreferences['rclimit'] = [
886 'type' => 'int',
887 'label-message' => 'recentchangescount',
888 'help-message' => 'prefs-help-recentchangescount',
889 'section' => 'rc/displayrc',
891 $defaultPreferences['usenewrc'] = [
892 'type' => 'toggle',
893 'label-message' => 'tog-usenewrc',
894 'section' => 'rc/advancedrc',
896 $defaultPreferences['hideminor'] = [
897 'type' => 'toggle',
898 'label-message' => 'tog-hideminor',
899 'section' => 'rc/advancedrc',
902 if ( $config->get( 'RCWatchCategoryMembership' ) ) {
903 $defaultPreferences['hidecategorization'] = [
904 'type' => 'toggle',
905 'label-message' => 'tog-hidecategorization',
906 'section' => 'rc/advancedrc',
910 if ( $user->useRCPatrol() ) {
911 $defaultPreferences['hidepatrolled'] = [
912 'type' => 'toggle',
913 'section' => 'rc/advancedrc',
914 'label-message' => 'tog-hidepatrolled',
918 if ( $user->useNPPatrol() ) {
919 $defaultPreferences['newpageshidepatrolled'] = [
920 'type' => 'toggle',
921 'section' => 'rc/advancedrc',
922 'label-message' => 'tog-newpageshidepatrolled',
926 if ( $config->get( 'RCShowWatchingUsers' ) ) {
927 $defaultPreferences['shownumberswatching'] = [
928 'type' => 'toggle',
929 'section' => 'rc/advancedrc',
930 'label-message' => 'tog-shownumberswatching',
936 * @param User $user
937 * @param IContextSource $context
938 * @param array $defaultPreferences
940 static function watchlistPreferences( $user, IContextSource $context, &$defaultPreferences ) {
941 $config = $context->getConfig();
942 $watchlistdaysMax = ceil( $config->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
944 # # Watchlist #####################################
945 if ( $user->isAllowed( 'editmywatchlist' ) ) {
946 $editWatchlistLinks = [];
947 $editWatchlistModes = [
948 'edit' => [ 'EditWatchlist', false ],
949 'raw' => [ 'EditWatchlist', 'raw' ],
950 'clear' => [ 'EditWatchlist', 'clear' ],
952 foreach ( $editWatchlistModes as $editWatchlistMode => $mode ) {
953 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
954 $editWatchlistLinks[] = Linker::linkKnown(
955 SpecialPage::getTitleFor( $mode[0], $mode[1] ),
956 $context->msg( "prefs-editwatchlist-{$editWatchlistMode}" )->parse()
960 $defaultPreferences['editwatchlist'] = [
961 'type' => 'info',
962 'raw' => true,
963 'default' => $context->getLanguage()->pipeList( $editWatchlistLinks ),
964 'label-message' => 'prefs-editwatchlist-label',
965 'section' => 'watchlist/editwatchlist',
969 $defaultPreferences['watchlistdays'] = [
970 'type' => 'float',
971 'min' => 0,
972 'max' => $watchlistdaysMax,
973 'section' => 'watchlist/displaywatchlist',
974 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
975 $watchlistdaysMax )->escaped(),
976 'label-message' => 'prefs-watchlist-days',
978 $defaultPreferences['wllimit'] = [
979 'type' => 'int',
980 'min' => 0,
981 'max' => 1000,
982 'label-message' => 'prefs-watchlist-edits',
983 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
984 'section' => 'watchlist/displaywatchlist',
986 $defaultPreferences['extendwatchlist'] = [
987 'type' => 'toggle',
988 'section' => 'watchlist/advancedwatchlist',
989 'label-message' => 'tog-extendwatchlist',
991 $defaultPreferences['watchlisthideminor'] = [
992 'type' => 'toggle',
993 'section' => 'watchlist/advancedwatchlist',
994 'label-message' => 'tog-watchlisthideminor',
996 $defaultPreferences['watchlisthidebots'] = [
997 'type' => 'toggle',
998 'section' => 'watchlist/advancedwatchlist',
999 'label-message' => 'tog-watchlisthidebots',
1001 $defaultPreferences['watchlisthideown'] = [
1002 'type' => 'toggle',
1003 'section' => 'watchlist/advancedwatchlist',
1004 'label-message' => 'tog-watchlisthideown',
1006 $defaultPreferences['watchlisthideanons'] = [
1007 'type' => 'toggle',
1008 'section' => 'watchlist/advancedwatchlist',
1009 'label-message' => 'tog-watchlisthideanons',
1011 $defaultPreferences['watchlisthideliu'] = [
1012 'type' => 'toggle',
1013 'section' => 'watchlist/advancedwatchlist',
1014 'label-message' => 'tog-watchlisthideliu',
1016 $defaultPreferences['watchlistreloadautomatically'] = [
1017 'type' => 'toggle',
1018 'section' => 'watchlist/advancedwatchlist',
1019 'label-message' => 'tog-watchlistreloadautomatically',
1022 if ( $config->get( 'RCWatchCategoryMembership' ) ) {
1023 $defaultPreferences['watchlisthidecategorization'] = [
1024 'type' => 'toggle',
1025 'section' => 'watchlist/advancedwatchlist',
1026 'label-message' => 'tog-watchlisthidecategorization',
1030 if ( $user->useRCPatrol() ) {
1031 $defaultPreferences['watchlisthidepatrolled'] = [
1032 'type' => 'toggle',
1033 'section' => 'watchlist/advancedwatchlist',
1034 'label-message' => 'tog-watchlisthidepatrolled',
1038 $watchTypes = [
1039 'edit' => 'watchdefault',
1040 'move' => 'watchmoves',
1041 'delete' => 'watchdeletion'
1044 // Kinda hacky
1045 if ( $user->isAllowed( 'createpage' ) || $user->isAllowed( 'createtalk' ) ) {
1046 $watchTypes['read'] = 'watchcreations';
1049 if ( $user->isAllowed( 'rollback' ) ) {
1050 $watchTypes['rollback'] = 'watchrollback';
1053 if ( $user->isAllowed( 'upload' ) ) {
1054 $watchTypes['upload'] = 'watchuploads';
1057 foreach ( $watchTypes as $action => $pref ) {
1058 if ( $user->isAllowed( $action ) ) {
1059 // Messages:
1060 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1061 // tog-watchrollback
1062 $defaultPreferences[$pref] = [
1063 'type' => 'toggle',
1064 'section' => 'watchlist/advancedwatchlist',
1065 'label-message' => "tog-$pref",
1070 if ( $config->get( 'EnableAPI' ) ) {
1071 $defaultPreferences['watchlisttoken'] = [
1072 'type' => 'api',
1074 $defaultPreferences['watchlisttoken-info'] = [
1075 'type' => 'info',
1076 'section' => 'watchlist/tokenwatchlist',
1077 'label-message' => 'prefs-watchlist-token',
1078 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1079 'help-message' => 'prefs-help-watchlist-token2',
1085 * @param User $user
1086 * @param IContextSource $context
1087 * @param array $defaultPreferences
1089 static function searchPreferences( $user, IContextSource $context, &$defaultPreferences ) {
1090 foreach ( MWNamespace::getValidNamespaces() as $n ) {
1091 $defaultPreferences['searchNs' . $n] = [
1092 'type' => 'api',
1098 * Dummy, kept for backwards-compatibility.
1100 static function miscPreferences( $user, IContextSource $context, &$defaultPreferences ) {
1104 * @param User $user The User object
1105 * @param IContextSource $context
1106 * @return array Text/links to display as key; $skinkey as value
1108 static function generateSkinOptions( $user, IContextSource $context ) {
1109 $ret = [];
1111 $mptitle = Title::newMainPage();
1112 $previewtext = $context->msg( 'skin-preview' )->escaped();
1114 # Only show skins that aren't disabled in $wgSkipSkins
1115 $validSkinNames = Skin::getAllowedSkins();
1117 # Sort by UI skin name. First though need to update validSkinNames as sometimes
1118 # the skinkey & UI skinname differ (e.g. "standard" skinkey is "Classic" in the UI).
1119 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1120 $msg = $context->msg( "skinname-{$skinkey}" );
1121 if ( $msg->exists() ) {
1122 $skinname = htmlspecialchars( $msg->text() );
1125 asort( $validSkinNames );
1127 $config = $context->getConfig();
1128 $defaultSkin = $config->get( 'DefaultSkin' );
1129 $allowUserCss = $config->get( 'AllowUserCss' );
1130 $allowUserJs = $config->get( 'AllowUserJs' );
1132 $foundDefault = false;
1133 foreach ( $validSkinNames as $skinkey => $sn ) {
1134 $linkTools = [];
1136 # Mark the default skin
1137 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1138 $linkTools[] = $context->msg( 'default' )->escaped();
1139 $foundDefault = true;
1142 # Create preview link
1143 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1144 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1146 # Create links to user CSS/JS pages
1147 if ( $allowUserCss ) {
1148 $cssPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.css' );
1149 $linkTools[] = Linker::link( $cssPage, $context->msg( 'prefs-custom-css' )->escaped() );
1152 if ( $allowUserJs ) {
1153 $jsPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.js' );
1154 $linkTools[] = Linker::link( $jsPage, $context->msg( 'prefs-custom-js' )->escaped() );
1157 $display = $sn . ' ' . $context->msg( 'parentheses' )
1158 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1159 ->escaped();
1160 $ret[$display] = $skinkey;
1163 if ( !$foundDefault ) {
1164 // If the default skin is not available, things are going to break horribly because the
1165 // default value for skin selector will not be a valid value. Let's just not show it then.
1166 return [];
1169 return $ret;
1173 * @param IContextSource $context
1174 * @return array
1176 static function getDateOptions( IContextSource $context ) {
1177 $lang = $context->getLanguage();
1178 $dateopts = $lang->getDatePreferences();
1180 $ret = [];
1182 if ( $dateopts ) {
1183 if ( !in_array( 'default', $dateopts ) ) {
1184 $dateopts[] = 'default'; // Make sure default is always valid
1185 // Bug 19237
1188 // FIXME KLUGE: site default might not be valid for user language
1189 global $wgDefaultUserOptions;
1190 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1191 $wgDefaultUserOptions['date'] = 'default';
1194 $epoch = wfTimestampNow();
1195 foreach ( $dateopts as $key ) {
1196 if ( $key == 'default' ) {
1197 $formatted = $context->msg( 'datedefault' )->escaped();
1198 } else {
1199 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1201 $ret[$formatted] = $key;
1204 return $ret;
1208 * @param IContextSource $context
1209 * @return array
1211 static function getImageSizes( IContextSource $context ) {
1212 $ret = [];
1213 $pixels = $context->msg( 'unit-pixel' )->text();
1215 foreach ( $context->getConfig()->get( 'ImageLimits' ) as $index => $limits ) {
1216 $display = "{$limits[0]}×{$limits[1]}" . $pixels;
1217 $ret[$display] = $index;
1220 return $ret;
1224 * @param IContextSource $context
1225 * @return array
1227 static function getThumbSizes( IContextSource $context ) {
1228 $ret = [];
1229 $pixels = $context->msg( 'unit-pixel' )->text();
1231 foreach ( $context->getConfig()->get( 'ThumbLimits' ) as $index => $size ) {
1232 $display = $size . $pixels;
1233 $ret[$display] = $index;
1236 return $ret;
1240 * @param string $signature
1241 * @param array $alldata
1242 * @param HTMLForm $form
1243 * @return bool|string
1245 static function validateSignature( $signature, $alldata, $form ) {
1246 global $wgParser;
1247 $maxSigChars = $form->getConfig()->get( 'MaxSigChars' );
1248 if ( mb_strlen( $signature ) > $maxSigChars ) {
1249 return Xml::element( 'span', [ 'class' => 'error' ],
1250 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1251 } elseif ( isset( $alldata['fancysig'] ) &&
1252 $alldata['fancysig'] &&
1253 $wgParser->validateSig( $signature ) === false
1255 return Xml::element(
1256 'span',
1257 [ 'class' => 'error' ],
1258 $form->msg( 'badsig' )->text()
1260 } else {
1261 return true;
1266 * @param string $signature
1267 * @param array $alldata
1268 * @param HTMLForm $form
1269 * @return string
1271 static function cleanSignature( $signature, $alldata, $form ) {
1272 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1273 global $wgParser;
1274 $signature = $wgParser->cleanSig( $signature );
1275 } else {
1276 // When no fancy sig used, make sure ~{3,5} get removed.
1277 $signature = Parser::cleanSigInSig( $signature );
1280 return $signature;
1284 * @param User $user
1285 * @param IContextSource $context
1286 * @param string $formClass
1287 * @param array $remove Array of items to remove
1288 * @return PreferencesForm|HtmlForm
1290 static function getFormObject(
1291 $user,
1292 IContextSource $context,
1293 $formClass = 'PreferencesForm',
1294 array $remove = []
1296 $formDescriptor = Preferences::getPreferences( $user, $context );
1297 if ( count( $remove ) ) {
1298 $removeKeys = array_flip( $remove );
1299 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1302 // Remove type=api preferences. They are not intended for rendering in the form.
1303 foreach ( $formDescriptor as $name => $info ) {
1304 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1305 unset( $formDescriptor[$name] );
1310 * @var $htmlForm PreferencesForm
1312 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1314 $htmlForm->setModifiedUser( $user );
1315 $htmlForm->setId( 'mw-prefs-form' );
1316 $htmlForm->setAutocomplete( 'off' );
1317 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1318 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1319 $htmlForm->setSubmitTooltip( 'preferences-save' );
1320 $htmlForm->setSubmitID( 'prefsubmit' );
1321 $htmlForm->setSubmitCallback( [ 'Preferences', 'tryFormSubmit' ] );
1323 return $htmlForm;
1327 * @param IContextSource $context
1328 * @return array
1330 static function getTimezoneOptions( IContextSource $context ) {
1331 $opt = [];
1333 $localTZoffset = $context->getConfig()->get( 'LocalTZoffset' );
1334 $timeZoneList = self::getTimeZoneList( $context->getLanguage() );
1336 $timestamp = MWTimestamp::getLocalInstance();
1337 // Check that the LocalTZoffset is the same as the local time zone offset
1338 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1339 $timezoneName = $timestamp->getTimezone()->getName();
1340 // Localize timezone
1341 if ( isset( $timeZoneList[$timezoneName] ) ) {
1342 $timezoneName = $timeZoneList[$timezoneName]['name'];
1344 $server_tz_msg = $context->msg(
1345 'timezoneuseserverdefault',
1346 $timezoneName
1347 )->text();
1348 } else {
1349 $tzstring = sprintf(
1350 '%+03d:%02d',
1351 floor( $localTZoffset / 60 ),
1352 abs( $localTZoffset ) % 60
1354 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1356 $opt[$server_tz_msg] = "System|$localTZoffset";
1357 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1358 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1360 foreach ( $timeZoneList as $timeZoneInfo ) {
1361 $region = $timeZoneInfo['region'];
1362 if ( !isset( $opt[$region] ) ) {
1363 $opt[$region] = [];
1365 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1367 return $opt;
1371 * @param string $value
1372 * @param array $alldata
1373 * @return int
1375 static function filterIntval( $value, $alldata ) {
1376 return intval( $value );
1380 * @param string $tz
1381 * @param array $alldata
1382 * @return string
1384 static function filterTimezoneInput( $tz, $alldata ) {
1385 $data = explode( '|', $tz, 3 );
1386 switch ( $data[0] ) {
1387 case 'ZoneInfo':
1388 case 'System':
1389 return $tz;
1390 default:
1391 $data = explode( ':', $tz, 2 );
1392 if ( count( $data ) == 2 ) {
1393 $data[0] = intval( $data[0] );
1394 $data[1] = intval( $data[1] );
1395 $minDiff = abs( $data[0] ) * 60 + $data[1];
1396 if ( $data[0] < 0 ) {
1397 $minDiff = - $minDiff;
1399 } else {
1400 $minDiff = intval( $data[0] ) * 60;
1403 # Max is +14:00 and min is -12:00, see:
1404 # https://en.wikipedia.org/wiki/Timezone
1405 $minDiff = min( $minDiff, 840 ); # 14:00
1406 $minDiff = max( $minDiff, - 720 ); # -12:00
1407 return 'Offset|' . $minDiff;
1412 * Handle the form submission if everything validated properly
1414 * @param array $formData
1415 * @param PreferencesForm $form
1416 * @return bool|Status|string
1418 static function tryFormSubmit( $formData, $form ) {
1419 $user = $form->getModifiedUser();
1420 $hiddenPrefs = $form->getConfig()->get( 'HiddenPrefs' );
1421 $result = true;
1423 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1424 return Status::newFatal( 'mypreferencesprotected' );
1427 // Filter input
1428 foreach ( array_keys( $formData ) as $name ) {
1429 if ( isset( self::$saveFilters[$name] ) ) {
1430 $formData[$name] =
1431 call_user_func( self::$saveFilters[$name], $formData[$name], $formData );
1435 // Fortunately, the realname field is MUCH simpler
1436 // (not really "private", but still shouldn't be edited without permission)
1438 if ( !in_array( 'realname', $hiddenPrefs )
1439 && $user->isAllowed( 'editmyprivateinfo' )
1440 && array_key_exists( 'realname', $formData )
1442 $realName = $formData['realname'];
1443 $user->setRealName( $realName );
1446 if ( $user->isAllowed( 'editmyoptions' ) ) {
1447 foreach ( self::$saveBlacklist as $b ) {
1448 unset( $formData[$b] );
1451 # If users have saved a value for a preference which has subsequently been disabled
1452 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1453 # is subsequently re-enabled
1454 foreach ( $hiddenPrefs as $pref ) {
1455 # If the user has not set a non-default value here, the default will be returned
1456 # and subsequently discarded
1457 $formData[$pref] = $user->getOption( $pref, null, true );
1460 // Keep old preferences from interfering due to back-compat code, etc.
1461 $user->resetOptions( 'unused', $form->getContext() );
1463 foreach ( $formData as $key => $value ) {
1464 $user->setOption( $key, $value );
1467 Hooks::run( 'PreferencesFormPreSave', [ $formData, $form, $user, &$result ] );
1470 MediaWiki\Auth\AuthManager::callLegacyAuthPlugin( 'updateExternalDB', [ $user ] );
1471 $user->saveSettings();
1473 return $result;
1477 * @param array $formData
1478 * @param PreferencesForm $form
1479 * @return Status
1481 public static function tryUISubmit( $formData, $form ) {
1482 $res = self::tryFormSubmit( $formData, $form );
1484 if ( $res ) {
1485 $urlOptions = [];
1487 if ( $res === 'eauth' ) {
1488 $urlOptions['eauth'] = 1;
1491 $urlOptions += $form->getExtraSuccessRedirectParameters();
1493 $url = $form->getTitle()->getFullURL( $urlOptions );
1495 $context = $form->getContext();
1496 // Set session data for the success message
1497 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1499 $context->getOutput()->redirect( $url );
1502 return Status::newGood();
1506 * Get a list of all time zones
1507 * @param Language $language Language used for the localized names
1508 * @return array A list of all time zones. The system name of the time zone is used as key and
1509 * the value is an array which contains localized name, the timecorrection value used for
1510 * preferences and the region
1511 * @since 1.26
1513 public static function getTimeZoneList( Language $language ) {
1514 $identifiers = DateTimeZone::listIdentifiers();
1515 if ( $identifiers === false ) {
1516 return [];
1518 sort( $identifiers );
1520 $tzRegions = [
1521 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1522 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1523 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1524 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1525 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1526 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1527 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1528 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1529 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1530 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1532 asort( $tzRegions );
1534 $timeZoneList = [];
1536 $now = new DateTime();
1538 foreach ( $identifiers as $identifier ) {
1539 $parts = explode( '/', $identifier, 2 );
1541 // DateTimeZone::listIdentifiers() returns a number of
1542 // backwards-compatibility entries. This filters them out of the
1543 // list presented to the user.
1544 if ( count( $parts ) !== 2 || !array_key_exists( $parts[0], $tzRegions ) ) {
1545 continue;
1548 // Localize region
1549 $parts[0] = $tzRegions[$parts[0]];
1551 $dateTimeZone = new DateTimeZone( $identifier );
1552 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1554 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1555 $value = "ZoneInfo|$minDiff|$identifier";
1557 $timeZoneList[$identifier] = [
1558 'name' => $display,
1559 'timecorrection' => $value,
1560 'region' => $parts[0],
1564 return $timeZoneList;
1568 /** Some tweaks to allow js prefs to work */
1569 class PreferencesForm extends HTMLForm {
1570 // Override default value from HTMLForm
1571 protected $mSubSectionBeforeFields = false;
1573 private $modifiedUser;
1576 * @param User $user
1578 public function setModifiedUser( $user ) {
1579 $this->modifiedUser = $user;
1583 * @return User
1585 public function getModifiedUser() {
1586 if ( $this->modifiedUser === null ) {
1587 return $this->getUser();
1588 } else {
1589 return $this->modifiedUser;
1594 * Get extra parameters for the query string when redirecting after
1595 * successful save.
1597 * @return array
1599 public function getExtraSuccessRedirectParameters() {
1600 return [];
1604 * @param string $html
1605 * @return string
1607 function wrapForm( $html ) {
1608 $html = Xml::tags( 'div', [ 'id' => 'preferences' ], $html );
1610 return parent::wrapForm( $html );
1614 * @return string
1616 function getButtons() {
1618 $attrs = [ 'id' => 'mw-prefs-restoreprefs' ];
1620 if ( !$this->getModifiedUser()->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1621 return '';
1624 $html = parent::getButtons();
1626 if ( $this->getModifiedUser()->isAllowed( 'editmyoptions' ) ) {
1627 $t = SpecialPage::getTitleFor( 'Preferences', 'reset' );
1629 $html .= "\n" . Linker::link( $t, $this->msg( 'restoreprefs' )->escaped(),
1630 Html::buttonAttributes( $attrs, [ 'mw-ui-quiet' ] ) );
1632 $html = Xml::tags( 'div', [ 'class' => 'mw-prefs-buttons' ], $html );
1635 return $html;
1639 * Separate multi-option preferences into multiple preferences, since we
1640 * have to store them separately
1641 * @param array $data
1642 * @return array
1644 function filterDataForSubmit( $data ) {
1645 foreach ( $this->mFlatFields as $fieldname => $field ) {
1646 if ( $field instanceof HTMLNestedFilterable ) {
1647 $info = $field->mParams;
1648 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $fieldname;
1649 foreach ( $field->filterDataForSubmit( $data[$fieldname] ) as $key => $value ) {
1650 $data["$prefix$key"] = $value;
1652 unset( $data[$fieldname] );
1656 return $data;
1660 * Get the whole body of the form.
1661 * @return string
1663 function getBody() {
1664 return $this->displaySection( $this->mFieldTree, '', 'mw-prefsection-' );
1668 * Get the "<legend>" for a given section key. Normally this is the
1669 * prefs-$key message but we'll allow extensions to override it.
1670 * @param string $key
1671 * @return string
1673 function getLegend( $key ) {
1674 $legend = parent::getLegend( $key );
1675 Hooks::run( 'PreferencesGetLegend', [ $this, $key, &$legend ] );
1676 return $legend;
1680 * Get the keys of each top level preference section.
1681 * @return array of section keys
1683 function getPreferenceSections() {
1684 return array_keys( array_filter( $this->mFieldTree, 'is_array' ) );