PHPSessionHandler: Implement SessionHandlerInterface
[mediawiki.git] / includes / Preferences.php
blob5f37e3f75d2454dd8f54eb2cada9c4b58ac23ef0
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
23 /**
24 * We're now using the HTMLForm object with some customisation to generate the
25 * Preferences form. This object handles generic submission, CSRF protection,
26 * layout and other logic in a reusable manner. We subclass it as a PreferencesForm
27 * to make some minor customisations.
29 * In order to generate the form, the HTMLForm object needs an array structure
30 * detailing the form fields available, and that's what this class is for. Each
31 * element of the array is a basic property-list, including the type of field,
32 * the label it is to be given in the form, callbacks for validation and
33 * 'filtering', and other pertinent information. Note that the 'default' field
34 * is named for generic forms, and does not represent the preference's default
35 * (which is stored in $wgDefaultUserOptions), but the default for the form
36 * field, which should be whatever the user has set for that preference. There
37 * is no need to override it unless you have some special storage logic (for
38 * instance, those not presently stored as options, but which are best set from
39 * the user preferences view).
41 * Field types are implemented as subclasses of the generic HTMLFormField
42 * object, and typically implement at least getInputHTML, which generates the
43 * HTML for the input field to be placed in the table.
45 * Once fields have been retrieved and validated, submission logic is handed
46 * over to the tryUISubmit static method of this class.
48 class Preferences {
49 /** @var array */
50 protected static $defaultPreferences = null;
52 /** @var array */
53 protected static $saveFilters = array(
54 'timecorrection' => array( 'Preferences', 'filterTimezoneInput' ),
55 'cols' => array( 'Preferences', 'filterIntval' ),
56 'rows' => array( 'Preferences', 'filterIntval' ),
57 'rclimit' => array( 'Preferences', 'filterIntval' ),
58 'wllimit' => array( 'Preferences', 'filterIntval' ),
59 'searchlimit' => array( 'Preferences', 'filterIntval' ),
62 // Stuff that shouldn't be saved as a preference.
63 private static $saveBlacklist = array(
64 'realname',
65 'emailaddress',
68 /**
69 * @return array
71 static function getSaveBlacklist() {
72 return self::$saveBlacklist;
75 /**
76 * @throws MWException
77 * @param User $user
78 * @param IContextSource $context
79 * @return array|null
81 static function getPreferences( $user, IContextSource $context ) {
82 if ( self::$defaultPreferences ) {
83 return self::$defaultPreferences;
86 $defaultPreferences = array();
88 self::profilePreferences( $user, $context, $defaultPreferences );
89 self::skinPreferences( $user, $context, $defaultPreferences );
90 self::datetimePreferences( $user, $context, $defaultPreferences );
91 self::filesPreferences( $user, $context, $defaultPreferences );
92 self::renderingPreferences( $user, $context, $defaultPreferences );
93 self::editingPreferences( $user, $context, $defaultPreferences );
94 self::rcPreferences( $user, $context, $defaultPreferences );
95 self::watchlistPreferences( $user, $context, $defaultPreferences );
96 self::searchPreferences( $user, $context, $defaultPreferences );
97 self::miscPreferences( $user, $context, $defaultPreferences );
99 Hooks::run( 'GetPreferences', array( $user, &$defaultPreferences ) );
101 self::loadPreferenceValues( $user, $context, $defaultPreferences );
102 self::$defaultPreferences = $defaultPreferences;
103 return $defaultPreferences;
107 * Loads existing values for a given array of preferences
108 * @throws MWException
109 * @param User $user
110 * @param IContextSource $context
111 * @param array $defaultPreferences Array to load values for
112 * @return array|null
114 static function loadPreferenceValues( $user, $context, &$defaultPreferences ) {
115 # # Remove preferences that wikis don't want to use
116 foreach ( $context->getConfig()->get( 'HiddenPrefs' ) as $pref ) {
117 if ( isset( $defaultPreferences[$pref] ) ) {
118 unset( $defaultPreferences[$pref] );
122 # # Make sure that form fields have their parent set. See bug 41337.
123 $dummyForm = new HTMLForm( array(), $context );
125 $disable = !$user->isAllowed( 'editmyoptions' );
127 $defaultOptions = User::getDefaultOptions();
128 # # Prod in defaults from the user
129 foreach ( $defaultPreferences as $name => &$info ) {
130 $prefFromUser = self::getOptionFromUser( $name, $info, $user );
131 if ( $disable && !in_array( $name, self::$saveBlacklist ) ) {
132 $info['disabled'] = 'disabled';
134 $field = HTMLForm::loadInputFromParameters( $name, $info, $dummyForm ); // For validation
135 $globalDefault = isset( $defaultOptions[$name] )
136 ? $defaultOptions[$name]
137 : null;
139 // If it validates, set it as the default
140 if ( isset( $info['default'] ) ) {
141 // Already set, no problem
142 continue;
143 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
144 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
145 $info['default'] = $prefFromUser;
146 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
147 $info['default'] = $globalDefault;
148 } else {
149 throw new MWException( "Global default '$globalDefault' is invalid for field $name" );
153 return $defaultPreferences;
157 * Pull option from a user account. Handles stuff like array-type preferences.
159 * @param string $name
160 * @param array $info
161 * @param User $user
162 * @return array|string
164 static function getOptionFromUser( $name, $info, $user ) {
165 $val = $user->getOption( $name );
167 // Handling for multiselect preferences
168 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
169 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
170 $options = HTMLFormField::flattenOptions( $info['options'] );
171 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
172 $val = array();
174 foreach ( $options as $value ) {
175 if ( $user->getOption( "$prefix$value" ) ) {
176 $val[] = $value;
181 // Handling for checkmatrix preferences
182 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
183 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
184 $columns = HTMLFormField::flattenOptions( $info['columns'] );
185 $rows = HTMLFormField::flattenOptions( $info['rows'] );
186 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
187 $val = array();
189 foreach ( $columns as $column ) {
190 foreach ( $rows as $row ) {
191 if ( $user->getOption( "$prefix$column-$row" ) ) {
192 $val[] = "$column-$row";
198 return $val;
202 * @param User $user
203 * @param IContextSource $context
204 * @param array $defaultPreferences
205 * @return void
207 static function profilePreferences( $user, IContextSource $context, &$defaultPreferences ) {
208 global $wgAuth, $wgContLang, $wgParser;
210 $config = $context->getConfig();
211 // retrieving user name for GENDER and misc.
212 $userName = $user->getName();
214 # # User info #####################################
215 // Information panel
216 $defaultPreferences['username'] = array(
217 'type' => 'info',
218 'label-message' => array( 'username', $userName ),
219 'default' => $userName,
220 'section' => 'personal/info',
223 # Get groups to which the user belongs
224 $userEffectiveGroups = $user->getEffectiveGroups();
225 $userGroups = $userMembers = array();
226 foreach ( $userEffectiveGroups as $ueg ) {
227 if ( $ueg == '*' ) {
228 // Skip the default * group, seems useless here
229 continue;
231 $groupName = User::getGroupName( $ueg );
232 $userGroups[] = User::makeGroupLinkHTML( $ueg, $groupName );
234 $memberName = User::getGroupMember( $ueg, $userName );
235 $userMembers[] = User::makeGroupLinkHTML( $ueg, $memberName );
237 asort( $userGroups );
238 asort( $userMembers );
240 $lang = $context->getLanguage();
242 $defaultPreferences['usergroups'] = array(
243 'type' => 'info',
244 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
245 count( $userGroups ) )->params( $userName )->parse(),
246 'default' => $context->msg( 'prefs-memberingroups-type' )
247 ->rawParams( $lang->commaList( $userGroups ), $lang->commaList( $userMembers ) )
248 ->escaped(),
249 'raw' => true,
250 'section' => 'personal/info',
253 $editCount = Linker::link( SpecialPage::getTitleFor( "Contributions", $userName ),
254 $lang->formatNum( $user->getEditCount() ) );
256 $defaultPreferences['editcount'] = array(
257 'type' => 'info',
258 'raw' => true,
259 'label-message' => 'prefs-edits',
260 'default' => $editCount,
261 'section' => 'personal/info',
264 if ( $user->getRegistration() ) {
265 $displayUser = $context->getUser();
266 $userRegistration = $user->getRegistration();
267 $defaultPreferences['registrationdate'] = array(
268 'type' => 'info',
269 'label-message' => 'prefs-registration',
270 'default' => $context->msg(
271 'prefs-registration-date-time',
272 $lang->userTimeAndDate( $userRegistration, $displayUser ),
273 $lang->userDate( $userRegistration, $displayUser ),
274 $lang->userTime( $userRegistration, $displayUser )
275 )->parse(),
276 'section' => 'personal/info',
280 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
281 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
283 // Actually changeable stuff
284 $defaultPreferences['realname'] = array(
285 // (not really "private", but still shouldn't be edited without permission)
286 'type' => $canEditPrivateInfo && $wgAuth->allowPropChange( 'realname' ) ? 'text' : 'info',
287 'default' => $user->getRealName(),
288 'section' => 'personal/info',
289 'label-message' => 'yourrealname',
290 'help-message' => 'prefs-help-realname',
293 if ( $canEditPrivateInfo && $wgAuth->allowPasswordChange() ) {
294 $link = Linker::link( SpecialPage::getTitleFor( 'ChangePassword' ),
295 $context->msg( 'prefs-resetpass' )->escaped(), array(),
296 array( 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText() ) );
298 $defaultPreferences['password'] = array(
299 'type' => 'info',
300 'raw' => true,
301 'default' => $link,
302 'label-message' => 'yourpassword',
303 'section' => 'personal/info',
306 // Only show prefershttps if secure login is turned on
307 if ( $config->get( 'SecureLogin' ) && wfCanIPUseHTTPS( $context->getRequest()->getIP() ) ) {
308 $defaultPreferences['prefershttps'] = array(
309 'type' => 'toggle',
310 'label-message' => 'tog-prefershttps',
311 'help-message' => 'prefs-help-prefershttps',
312 'section' => 'personal/info'
316 // Language
317 $languages = Language::fetchLanguageNames( null, 'mw' );
318 $languageCode = $config->get( 'LanguageCode' );
319 if ( !array_key_exists( $languageCode, $languages ) ) {
320 $languages[$languageCode] = $languageCode;
322 ksort( $languages );
324 $options = array();
325 foreach ( $languages as $code => $name ) {
326 $display = wfBCP47( $code ) . ' - ' . $name;
327 $options[$display] = $code;
329 $defaultPreferences['language'] = array(
330 'type' => 'select',
331 'section' => 'personal/i18n',
332 'options' => $options,
333 'label-message' => 'yourlanguage',
336 $defaultPreferences['gender'] = array(
337 'type' => 'radio',
338 'section' => 'personal/i18n',
339 'options' => array(
340 $context->msg( 'parentheses' )
341 ->params( $context->msg( 'gender-unknown' )->plain() )
342 ->escaped() => 'unknown',
343 $context->msg( 'gender-female' )->escaped() => 'female',
344 $context->msg( 'gender-male' )->escaped() => 'male',
346 'label-message' => 'yourgender',
347 'help-message' => 'prefs-help-gender',
350 // see if there are multiple language variants to choose from
351 if ( !$config->get( 'DisableLangConversion' ) ) {
352 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
353 if ( $langCode == $wgContLang->getCode() ) {
354 $variants = $wgContLang->getVariants();
356 if ( count( $variants ) <= 1 ) {
357 continue;
360 $variantArray = array();
361 foreach ( $variants as $v ) {
362 $v = str_replace( '_', '-', strtolower( $v ) );
363 $variantArray[$v] = $lang->getVariantname( $v, false );
366 $options = array();
367 foreach ( $variantArray as $code => $name ) {
368 $display = wfBCP47( $code ) . ' - ' . $name;
369 $options[$display] = $code;
372 $defaultPreferences['variant'] = array(
373 'label-message' => 'yourvariant',
374 'type' => 'select',
375 'options' => $options,
376 'section' => 'personal/i18n',
377 'help-message' => 'prefs-help-variant',
379 } else {
380 $defaultPreferences["variant-$langCode"] = array(
381 'type' => 'api',
387 // Stuff from Language::getExtraUserToggles()
388 // FIXME is this dead code? $extraUserToggles doesn't seem to be defined for any language
389 $toggles = $wgContLang->getExtraUserToggles();
391 foreach ( $toggles as $toggle ) {
392 $defaultPreferences[$toggle] = array(
393 'type' => 'toggle',
394 'section' => 'personal/i18n',
395 'label-message' => "tog-$toggle",
399 // show a preview of the old signature first
400 $oldsigWikiText = $wgParser->preSaveTransform(
401 '~~~',
402 $context->getTitle(),
403 $user,
404 ParserOptions::newFromContext( $context )
406 $oldsigHTML = $context->getOutput()->parseInline( $oldsigWikiText, true, true );
407 $defaultPreferences['oldsig'] = array(
408 'type' => 'info',
409 'raw' => true,
410 'label-message' => 'tog-oldsig',
411 'default' => $oldsigHTML,
412 'section' => 'personal/signature',
414 $defaultPreferences['nickname'] = array(
415 'type' => $wgAuth->allowPropChange( 'nickname' ) ? 'text' : 'info',
416 'maxlength' => $config->get( 'MaxSigChars' ),
417 'label-message' => 'yournick',
418 'validation-callback' => array( 'Preferences', 'validateSignature' ),
419 'section' => 'personal/signature',
420 'filter-callback' => array( 'Preferences', 'cleanSignature' ),
422 $defaultPreferences['fancysig'] = array(
423 'type' => 'toggle',
424 'label-message' => 'tog-fancysig',
425 // show general help about signature at the bottom of the section
426 'help-message' => 'prefs-help-signature',
427 'section' => 'personal/signature'
430 # # Email stuff
432 if ( $config->get( 'EnableEmail' ) ) {
433 if ( $canViewPrivateInfo ) {
434 $helpMessages[] = $config->get( 'EmailConfirmToEdit' )
435 ? 'prefs-help-email-required'
436 : 'prefs-help-email';
438 if ( $config->get( 'EnableUserEmail' ) ) {
439 // additional messages when users can send email to each other
440 $helpMessages[] = 'prefs-help-email-others';
443 $emailAddress = $user->getEmail() ? htmlspecialchars( $user->getEmail() ) : '';
444 if ( $canEditPrivateInfo && $wgAuth->allowPropChange( 'emailaddress' ) ) {
445 $link = Linker::link(
446 SpecialPage::getTitleFor( 'ChangeEmail' ),
447 $context->msg( $user->getEmail() ? 'prefs-changeemail' : 'prefs-setemail' )->escaped(),
448 array(),
449 array( 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText() ) );
451 $emailAddress .= $emailAddress == '' ? $link : (
452 $context->msg( 'word-separator' )->escaped()
453 . $context->msg( 'parentheses' )->rawParams( $link )->escaped()
457 $defaultPreferences['emailaddress'] = array(
458 'type' => 'info',
459 'raw' => true,
460 'default' => $emailAddress,
461 'label-message' => 'youremail',
462 'section' => 'personal/email',
463 'help-messages' => $helpMessages,
464 # 'cssclass' chosen below
468 $disableEmailPrefs = false;
470 if ( $config->get( 'EmailAuthentication' ) ) {
471 $emailauthenticationclass = 'mw-email-not-authenticated';
472 if ( $user->getEmail() ) {
473 if ( $user->getEmailAuthenticationTimestamp() ) {
474 // date and time are separate parameters to facilitate localisation.
475 // $time is kept for backward compat reasons.
476 // 'emailauthenticated' is also used in SpecialConfirmemail.php
477 $displayUser = $context->getUser();
478 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
479 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
480 $d = $lang->userDate( $emailTimestamp, $displayUser );
481 $t = $lang->userTime( $emailTimestamp, $displayUser );
482 $emailauthenticated = $context->msg( 'emailauthenticated',
483 $time, $d, $t )->parse() . '<br />';
484 $disableEmailPrefs = false;
485 $emailauthenticationclass = 'mw-email-authenticated';
486 } else {
487 $disableEmailPrefs = true;
488 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
489 Linker::linkKnown(
490 SpecialPage::getTitleFor( 'Confirmemail' ),
491 $context->msg( 'emailconfirmlink' )->escaped()
492 ) . '<br />';
493 $emailauthenticationclass = "mw-email-not-authenticated";
495 } else {
496 $disableEmailPrefs = true;
497 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
498 $emailauthenticationclass = 'mw-email-none';
501 if ( $canViewPrivateInfo ) {
502 $defaultPreferences['emailauthentication'] = array(
503 'type' => 'info',
504 'raw' => true,
505 'section' => 'personal/email',
506 'label-message' => 'prefs-emailconfirm-label',
507 'default' => $emailauthenticated,
508 # Apply the same CSS class used on the input to the message:
509 'cssclass' => $emailauthenticationclass,
514 if ( $config->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
515 $defaultPreferences['disablemail'] = array(
516 'type' => 'toggle',
517 'invert' => true,
518 'section' => 'personal/email',
519 'label-message' => 'allowemail',
520 'disabled' => $disableEmailPrefs,
522 $defaultPreferences['ccmeonemails'] = array(
523 'type' => 'toggle',
524 'section' => 'personal/email',
525 'label-message' => 'tog-ccmeonemails',
526 'disabled' => $disableEmailPrefs,
530 if ( $config->get( 'EnotifWatchlist' ) ) {
531 $defaultPreferences['enotifwatchlistpages'] = array(
532 'type' => 'toggle',
533 'section' => 'personal/email',
534 'label-message' => 'tog-enotifwatchlistpages',
535 'disabled' => $disableEmailPrefs,
538 if ( $config->get( 'EnotifUserTalk' ) ) {
539 $defaultPreferences['enotifusertalkpages'] = array(
540 'type' => 'toggle',
541 'section' => 'personal/email',
542 'label-message' => 'tog-enotifusertalkpages',
543 'disabled' => $disableEmailPrefs,
546 if ( $config->get( 'EnotifUserTalk' ) || $config->get( 'EnotifWatchlist' ) ) {
547 $defaultPreferences['enotifminoredits'] = array(
548 'type' => 'toggle',
549 'section' => 'personal/email',
550 'label-message' => 'tog-enotifminoredits',
551 'disabled' => $disableEmailPrefs,
554 if ( $config->get( 'EnotifRevealEditorAddress' ) ) {
555 $defaultPreferences['enotifrevealaddr'] = array(
556 'type' => 'toggle',
557 'section' => 'personal/email',
558 'label-message' => 'tog-enotifrevealaddr',
559 'disabled' => $disableEmailPrefs,
567 * @param User $user
568 * @param IContextSource $context
569 * @param array $defaultPreferences
570 * @return void
572 static function skinPreferences( $user, IContextSource $context, &$defaultPreferences ) {
573 # # Skin #####################################
575 // Skin selector, if there is at least one valid skin
576 $skinOptions = self::generateSkinOptions( $user, $context );
577 if ( $skinOptions ) {
578 $defaultPreferences['skin'] = array(
579 'type' => 'radio',
580 'options' => $skinOptions,
581 'label' => '&#160;',
582 'section' => 'rendering/skin',
586 $config = $context->getConfig();
587 $allowUserCss = $config->get( 'AllowUserCss' );
588 $allowUserJs = $config->get( 'AllowUserJs' );
589 # Create links to user CSS/JS pages for all skins
590 # This code is basically copied from generateSkinOptions(). It'd
591 # be nice to somehow merge this back in there to avoid redundancy.
592 if ( $allowUserCss || $allowUserJs ) {
593 $linkTools = array();
594 $userName = $user->getName();
596 if ( $allowUserCss ) {
597 $cssPage = Title::makeTitleSafe( NS_USER, $userName . '/common.css' );
598 $linkTools[] = Linker::link( $cssPage, $context->msg( 'prefs-custom-css' )->escaped() );
601 if ( $allowUserJs ) {
602 $jsPage = Title::makeTitleSafe( NS_USER, $userName . '/common.js' );
603 $linkTools[] = Linker::link( $jsPage, $context->msg( 'prefs-custom-js' )->escaped() );
606 $defaultPreferences['commoncssjs'] = array(
607 'type' => 'info',
608 'raw' => true,
609 'default' => $context->getLanguage()->pipeList( $linkTools ),
610 'label-message' => 'prefs-common-css-js',
611 'section' => 'rendering/skin',
617 * @param User $user
618 * @param IContextSource $context
619 * @param array $defaultPreferences
621 static function filesPreferences( $user, IContextSource $context, &$defaultPreferences ) {
622 # # Files #####################################
623 $defaultPreferences['imagesize'] = array(
624 'type' => 'select',
625 'options' => self::getImageSizes( $context ),
626 'label-message' => 'imagemaxsize',
627 'section' => 'rendering/files',
629 $defaultPreferences['thumbsize'] = array(
630 'type' => 'select',
631 'options' => self::getThumbSizes( $context ),
632 'label-message' => 'thumbsize',
633 'section' => 'rendering/files',
638 * @param User $user
639 * @param IContextSource $context
640 * @param array $defaultPreferences
641 * @return void
643 static function datetimePreferences( $user, IContextSource $context, &$defaultPreferences ) {
644 # # Date and time #####################################
645 $dateOptions = self::getDateOptions( $context );
646 if ( $dateOptions ) {
647 $defaultPreferences['date'] = array(
648 'type' => 'radio',
649 'options' => $dateOptions,
650 'label' => '&#160;',
651 'section' => 'rendering/dateformat',
655 // Info
656 $now = wfTimestampNow();
657 $lang = $context->getLanguage();
658 $nowlocal = Xml::element( 'span', array( 'id' => 'wpLocalTime' ),
659 $lang->userTime( $now, $user ) );
660 $nowserver = $lang->userTime( $now, $user,
661 array( 'format' => false, 'timecorrection' => false ) ) .
662 Html::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 + (int)substr( $now, 10, 2 ) );
664 $defaultPreferences['nowserver'] = array(
665 'type' => 'info',
666 'raw' => 1,
667 'label-message' => 'servertime',
668 'default' => $nowserver,
669 'section' => 'rendering/timeoffset',
672 $defaultPreferences['nowlocal'] = array(
673 'type' => 'info',
674 'raw' => 1,
675 'label-message' => 'localtime',
676 'default' => $nowlocal,
677 'section' => 'rendering/timeoffset',
680 // Grab existing pref.
681 $tzOffset = $user->getOption( 'timecorrection' );
682 $tz = explode( '|', $tzOffset, 3 );
684 $tzOptions = self::getTimezoneOptions( $context );
686 $tzSetting = $tzOffset;
687 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
688 $minDiff = $tz[1];
689 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) % 60 );
690 } elseif ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
691 !in_array( $tzOffset, HTMLFormField::flattenOptions( $tzOptions ) )
693 # Timezone offset can vary with DST
694 $userTZ = timezone_open( $tz[2] );
695 if ( $userTZ !== false ) {
696 $minDiff = floor( timezone_offset_get( $userTZ, date_create( 'now' ) ) / 60 );
697 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
701 $defaultPreferences['timecorrection'] = array(
702 'class' => 'HTMLSelectOrOtherField',
703 'label-message' => 'timezonelegend',
704 'options' => $tzOptions,
705 'default' => $tzSetting,
706 'size' => 20,
707 'section' => 'rendering/timeoffset',
712 * @param User $user
713 * @param IContextSource $context
714 * @param array $defaultPreferences
716 static function renderingPreferences( $user, IContextSource $context, &$defaultPreferences ) {
717 # # Diffs ####################################
718 $defaultPreferences['diffonly'] = array(
719 'type' => 'toggle',
720 'section' => 'rendering/diffs',
721 'label-message' => 'tog-diffonly',
723 $defaultPreferences['norollbackdiff'] = array(
724 'type' => 'toggle',
725 'section' => 'rendering/diffs',
726 'label-message' => 'tog-norollbackdiff',
729 # # Page Rendering ##############################
730 if ( $context->getConfig()->get( 'AllowUserCssPrefs' ) ) {
731 $defaultPreferences['underline'] = array(
732 'type' => 'select',
733 'options' => array(
734 $context->msg( 'underline-never' )->text() => 0,
735 $context->msg( 'underline-always' )->text() => 1,
736 $context->msg( 'underline-default' )->text() => 2,
738 'label-message' => 'tog-underline',
739 'section' => 'rendering/advancedrendering',
743 $stubThresholdValues = array( 50, 100, 500, 1000, 2000, 5000, 10000 );
744 $stubThresholdOptions = array( $context->msg( 'stub-threshold-disabled' )->text() => 0 );
745 foreach ( $stubThresholdValues as $value ) {
746 $stubThresholdOptions[$context->msg( 'size-bytes', $value )->text()] = $value;
749 $defaultPreferences['stubthreshold'] = array(
750 'type' => 'select',
751 'section' => 'rendering/advancedrendering',
752 'options' => $stubThresholdOptions,
753 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
754 'label-raw' => $context->msg( 'stub-threshold' )->rawParams(
755 '<a href="#" class="stub">' .
756 $context->msg( 'stub-threshold-sample-link' )->parse() .
757 '</a>' )->parse(),
760 $defaultPreferences['showhiddencats'] = array(
761 'type' => 'toggle',
762 'section' => 'rendering/advancedrendering',
763 'label-message' => 'tog-showhiddencats'
766 $defaultPreferences['numberheadings'] = array(
767 'type' => 'toggle',
768 'section' => 'rendering/advancedrendering',
769 'label-message' => 'tog-numberheadings',
774 * @param User $user
775 * @param IContextSource $context
776 * @param array $defaultPreferences
778 static function editingPreferences( $user, IContextSource $context, &$defaultPreferences ) {
779 # # Editing #####################################
780 $defaultPreferences['editsectiononrightclick'] = array(
781 'type' => 'toggle',
782 'section' => 'editing/advancedediting',
783 'label-message' => 'tog-editsectiononrightclick',
785 $defaultPreferences['editondblclick'] = array(
786 'type' => 'toggle',
787 'section' => 'editing/advancedediting',
788 'label-message' => 'tog-editondblclick',
791 if ( $context->getConfig()->get( 'AllowUserCssPrefs' ) ) {
792 $defaultPreferences['editfont'] = array(
793 'type' => 'select',
794 'section' => 'editing/editor',
795 'label-message' => 'editfont-style',
796 'options' => array(
797 $context->msg( 'editfont-default' )->text() => 'default',
798 $context->msg( 'editfont-monospace' )->text() => 'monospace',
799 $context->msg( 'editfont-sansserif' )->text() => 'sans-serif',
800 $context->msg( 'editfont-serif' )->text() => 'serif',
804 $defaultPreferences['cols'] = array(
805 'type' => 'int',
806 'label-message' => 'columns',
807 'section' => 'editing/editor',
808 'min' => 4,
809 'max' => 1000,
811 $defaultPreferences['rows'] = array(
812 'type' => 'int',
813 'label-message' => 'rows',
814 'section' => 'editing/editor',
815 'min' => 4,
816 'max' => 1000,
818 if ( $user->isAllowed( 'minoredit' ) ) {
819 $defaultPreferences['minordefault'] = array(
820 'type' => 'toggle',
821 'section' => 'editing/editor',
822 'label-message' => 'tog-minordefault',
825 $defaultPreferences['forceeditsummary'] = array(
826 'type' => 'toggle',
827 'section' => 'editing/editor',
828 'label-message' => 'tog-forceeditsummary',
830 $defaultPreferences['useeditwarning'] = array(
831 'type' => 'toggle',
832 'section' => 'editing/editor',
833 'label-message' => 'tog-useeditwarning',
835 $defaultPreferences['showtoolbar'] = array(
836 'type' => 'toggle',
837 'section' => 'editing/editor',
838 'label-message' => 'tog-showtoolbar',
841 $defaultPreferences['previewonfirst'] = array(
842 'type' => 'toggle',
843 'section' => 'editing/preview',
844 'label-message' => 'tog-previewonfirst',
846 $defaultPreferences['previewontop'] = array(
847 'type' => 'toggle',
848 'section' => 'editing/preview',
849 'label-message' => 'tog-previewontop',
851 $defaultPreferences['uselivepreview'] = array(
852 'type' => 'toggle',
853 'section' => 'editing/preview',
854 'label-message' => 'tog-uselivepreview',
860 * @param User $user
861 * @param IContextSource $context
862 * @param array $defaultPreferences
864 static function rcPreferences( $user, IContextSource $context, &$defaultPreferences ) {
865 $config = $context->getConfig();
866 $rcMaxAge = $config->get( 'RCMaxAge' );
867 # # RecentChanges #####################################
868 $defaultPreferences['rcdays'] = array(
869 'type' => 'float',
870 'label-message' => 'recentchangesdays',
871 'section' => 'rc/displayrc',
872 'min' => 1,
873 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
874 'help' => $context->msg( 'recentchangesdays-max' )->numParams(
875 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
877 $defaultPreferences['rclimit'] = array(
878 'type' => 'int',
879 'label-message' => 'recentchangescount',
880 'help-message' => 'prefs-help-recentchangescount',
881 'section' => 'rc/displayrc',
883 $defaultPreferences['usenewrc'] = array(
884 'type' => 'toggle',
885 'label-message' => 'tog-usenewrc',
886 'section' => 'rc/advancedrc',
888 $defaultPreferences['hideminor'] = array(
889 'type' => 'toggle',
890 'label-message' => 'tog-hideminor',
891 'section' => 'rc/advancedrc',
894 if ( $config->get( 'RCWatchCategoryMembership' ) ) {
895 $defaultPreferences['hidecategorization'] = array(
896 'type' => 'toggle',
897 'label-message' => 'tog-hidecategorization',
898 'section' => 'rc/advancedrc',
902 if ( $user->useRCPatrol() ) {
903 $defaultPreferences['hidepatrolled'] = array(
904 'type' => 'toggle',
905 'section' => 'rc/advancedrc',
906 'label-message' => 'tog-hidepatrolled',
910 if ( $user->useNPPatrol() ) {
911 $defaultPreferences['newpageshidepatrolled'] = array(
912 'type' => 'toggle',
913 'section' => 'rc/advancedrc',
914 'label-message' => 'tog-newpageshidepatrolled',
918 if ( $config->get( 'RCShowWatchingUsers' ) ) {
919 $defaultPreferences['shownumberswatching'] = array(
920 'type' => 'toggle',
921 'section' => 'rc/advancedrc',
922 'label-message' => 'tog-shownumberswatching',
928 * @param User $user
929 * @param IContextSource $context
930 * @param array $defaultPreferences
932 static function watchlistPreferences( $user, IContextSource $context, &$defaultPreferences ) {
933 $config = $context->getConfig();
934 $watchlistdaysMax = ceil( $config->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
936 # # Watchlist #####################################
937 if ( $user->isAllowed( 'editmywatchlist' ) ) {
938 $editWatchlistLinks = array();
939 $editWatchlistModes = array(
940 'edit' => array( 'EditWatchlist', false ),
941 'raw' => array( 'EditWatchlist', 'raw' ),
942 'clear' => array( 'EditWatchlist', 'clear' ),
944 foreach ( $editWatchlistModes as $editWatchlistMode => $mode ) {
945 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
946 $editWatchlistLinks[] = Linker::linkKnown(
947 SpecialPage::getTitleFor( $mode[0], $mode[1] ),
948 $context->msg( "prefs-editwatchlist-{$editWatchlistMode}" )->parse()
952 $defaultPreferences['editwatchlist'] = array(
953 'type' => 'info',
954 'raw' => true,
955 'default' => $context->getLanguage()->pipeList( $editWatchlistLinks ),
956 'label-message' => 'prefs-editwatchlist-label',
957 'section' => 'watchlist/editwatchlist',
961 $defaultPreferences['watchlistdays'] = array(
962 'type' => 'float',
963 'min' => 0,
964 'max' => $watchlistdaysMax,
965 'section' => 'watchlist/displaywatchlist',
966 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
967 $watchlistdaysMax )->escaped(),
968 'label-message' => 'prefs-watchlist-days',
970 $defaultPreferences['wllimit'] = array(
971 'type' => 'int',
972 'min' => 0,
973 'max' => 1000,
974 'label-message' => 'prefs-watchlist-edits',
975 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
976 'section' => 'watchlist/displaywatchlist',
978 $defaultPreferences['extendwatchlist'] = array(
979 'type' => 'toggle',
980 'section' => 'watchlist/advancedwatchlist',
981 'label-message' => 'tog-extendwatchlist',
983 $defaultPreferences['watchlisthideminor'] = array(
984 'type' => 'toggle',
985 'section' => 'watchlist/advancedwatchlist',
986 'label-message' => 'tog-watchlisthideminor',
988 $defaultPreferences['watchlisthidebots'] = array(
989 'type' => 'toggle',
990 'section' => 'watchlist/advancedwatchlist',
991 'label-message' => 'tog-watchlisthidebots',
993 $defaultPreferences['watchlisthideown'] = array(
994 'type' => 'toggle',
995 'section' => 'watchlist/advancedwatchlist',
996 'label-message' => 'tog-watchlisthideown',
998 $defaultPreferences['watchlisthideanons'] = array(
999 'type' => 'toggle',
1000 'section' => 'watchlist/advancedwatchlist',
1001 'label-message' => 'tog-watchlisthideanons',
1003 $defaultPreferences['watchlisthideliu'] = array(
1004 'type' => 'toggle',
1005 'section' => 'watchlist/advancedwatchlist',
1006 'label-message' => 'tog-watchlisthideliu',
1008 $defaultPreferences['watchlistreloadautomatically'] = array(
1009 'type' => 'toggle',
1010 'section' => 'watchlist/advancedwatchlist',
1011 'label-message' => 'tog-watchlistreloadautomatically',
1014 if ( $config->get( 'RCWatchCategoryMembership' ) ) {
1015 $defaultPreferences['watchlisthidecategorization'] = array(
1016 'type' => 'toggle',
1017 'section' => 'watchlist/advancedwatchlist',
1018 'label-message' => 'tog-watchlisthidecategorization',
1022 if ( $user->useRCPatrol() ) {
1023 $defaultPreferences['watchlisthidepatrolled'] = array(
1024 'type' => 'toggle',
1025 'section' => 'watchlist/advancedwatchlist',
1026 'label-message' => 'tog-watchlisthidepatrolled',
1030 $watchTypes = array(
1031 'edit' => 'watchdefault',
1032 'move' => 'watchmoves',
1033 'delete' => 'watchdeletion'
1036 // Kinda hacky
1037 if ( $user->isAllowed( 'createpage' ) || $user->isAllowed( 'createtalk' ) ) {
1038 $watchTypes['read'] = 'watchcreations';
1041 if ( $user->isAllowed( 'rollback' ) ) {
1042 $watchTypes['rollback'] = 'watchrollback';
1045 foreach ( $watchTypes as $action => $pref ) {
1046 if ( $user->isAllowed( $action ) ) {
1047 // Messages:
1048 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations
1049 // tog-watchrollback
1050 $defaultPreferences[$pref] = array(
1051 'type' => 'toggle',
1052 'section' => 'watchlist/advancedwatchlist',
1053 'label-message' => "tog-$pref",
1058 if ( $config->get( 'EnableAPI' ) ) {
1059 $defaultPreferences['watchlisttoken'] = array(
1060 'type' => 'api',
1062 $defaultPreferences['watchlisttoken-info'] = array(
1063 'type' => 'info',
1064 'section' => 'watchlist/tokenwatchlist',
1065 'label-message' => 'prefs-watchlist-token',
1066 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1067 'help-message' => 'prefs-help-watchlist-token2',
1073 * @param User $user
1074 * @param IContextSource $context
1075 * @param array $defaultPreferences
1077 static function searchPreferences( $user, IContextSource $context, &$defaultPreferences ) {
1078 foreach ( MWNamespace::getValidNamespaces() as $n ) {
1079 $defaultPreferences['searchNs' . $n] = array(
1080 'type' => 'api',
1086 * Dummy, kept for backwards-compatibility.
1088 static function miscPreferences( $user, IContextSource $context, &$defaultPreferences ) {
1092 * @param User $user The User object
1093 * @param IContextSource $context
1094 * @return array Text/links to display as key; $skinkey as value
1096 static function generateSkinOptions( $user, IContextSource $context ) {
1097 $ret = array();
1099 $mptitle = Title::newMainPage();
1100 $previewtext = $context->msg( 'skin-preview' )->escaped();
1102 # Only show skins that aren't disabled in $wgSkipSkins
1103 $validSkinNames = Skin::getAllowedSkins();
1105 # Sort by UI skin name. First though need to update validSkinNames as sometimes
1106 # the skinkey & UI skinname differ (e.g. "standard" skinkey is "Classic" in the UI).
1107 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1108 $msg = $context->msg( "skinname-{$skinkey}" );
1109 if ( $msg->exists() ) {
1110 $skinname = htmlspecialchars( $msg->text() );
1113 asort( $validSkinNames );
1115 $config = $context->getConfig();
1116 $defaultSkin = $config->get( 'DefaultSkin' );
1117 $allowUserCss = $config->get( 'AllowUserCss' );
1118 $allowUserJs = $config->get( 'AllowUserJs' );
1120 $foundDefault = false;
1121 foreach ( $validSkinNames as $skinkey => $sn ) {
1122 $linkTools = array();
1124 # Mark the default skin
1125 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1126 $linkTools[] = $context->msg( 'default' )->escaped();
1127 $foundDefault = true;
1130 # Create preview link
1131 $mplink = htmlspecialchars( $mptitle->getLocalURL( array( 'useskin' => $skinkey ) ) );
1132 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1134 # Create links to user CSS/JS pages
1135 if ( $allowUserCss ) {
1136 $cssPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.css' );
1137 $linkTools[] = Linker::link( $cssPage, $context->msg( 'prefs-custom-css' )->escaped() );
1140 if ( $allowUserJs ) {
1141 $jsPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.js' );
1142 $linkTools[] = Linker::link( $jsPage, $context->msg( 'prefs-custom-js' )->escaped() );
1145 $display = $sn . ' ' . $context->msg( 'parentheses' )
1146 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1147 ->escaped();
1148 $ret[$display] = $skinkey;
1151 if ( !$foundDefault ) {
1152 // If the default skin is not available, things are going to break horribly because the
1153 // default value for skin selector will not be a valid value. Let's just not show it then.
1154 return array();
1157 return $ret;
1161 * @param IContextSource $context
1162 * @return array
1164 static function getDateOptions( IContextSource $context ) {
1165 $lang = $context->getLanguage();
1166 $dateopts = $lang->getDatePreferences();
1168 $ret = array();
1170 if ( $dateopts ) {
1171 if ( !in_array( 'default', $dateopts ) ) {
1172 $dateopts[] = 'default'; // Make sure default is always valid
1173 // Bug 19237
1176 // FIXME KLUGE: site default might not be valid for user language
1177 global $wgDefaultUserOptions;
1178 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1179 $wgDefaultUserOptions['date'] = 'default';
1182 $epoch = wfTimestampNow();
1183 foreach ( $dateopts as $key ) {
1184 if ( $key == 'default' ) {
1185 $formatted = $context->msg( 'datedefault' )->escaped();
1186 } else {
1187 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1189 $ret[$formatted] = $key;
1192 return $ret;
1196 * @param IContextSource $context
1197 * @return array
1199 static function getImageSizes( IContextSource $context ) {
1200 $ret = array();
1201 $pixels = $context->msg( 'unit-pixel' )->text();
1203 foreach ( $context->getConfig()->get( 'ImageLimits' ) as $index => $limits ) {
1204 $display = "{$limits[0]}×{$limits[1]}" . $pixels;
1205 $ret[$display] = $index;
1208 return $ret;
1212 * @param IContextSource $context
1213 * @return array
1215 static function getThumbSizes( IContextSource $context ) {
1216 $ret = array();
1217 $pixels = $context->msg( 'unit-pixel' )->text();
1219 foreach ( $context->getConfig()->get( 'ThumbLimits' ) as $index => $size ) {
1220 $display = $size . $pixels;
1221 $ret[$display] = $index;
1224 return $ret;
1228 * @param string $signature
1229 * @param array $alldata
1230 * @param HTMLForm $form
1231 * @return bool|string
1233 static function validateSignature( $signature, $alldata, $form ) {
1234 global $wgParser;
1235 $maxSigChars = $form->getConfig()->get( 'MaxSigChars' );
1236 if ( mb_strlen( $signature ) > $maxSigChars ) {
1237 return Xml::element( 'span', array( 'class' => 'error' ),
1238 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1239 } elseif ( isset( $alldata['fancysig'] ) &&
1240 $alldata['fancysig'] &&
1241 $wgParser->validateSig( $signature ) === false
1243 return Xml::element(
1244 'span',
1245 array( 'class' => 'error' ),
1246 $form->msg( 'badsig' )->text()
1248 } else {
1249 return true;
1254 * @param string $signature
1255 * @param array $alldata
1256 * @param HTMLForm $form
1257 * @return string
1259 static function cleanSignature( $signature, $alldata, $form ) {
1260 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1261 global $wgParser;
1262 $signature = $wgParser->cleanSig( $signature );
1263 } else {
1264 // When no fancy sig used, make sure ~{3,5} get removed.
1265 $signature = Parser::cleanSigInSig( $signature );
1268 return $signature;
1272 * @param User $user
1273 * @param IContextSource $context
1274 * @param string $formClass
1275 * @param array $remove Array of items to remove
1276 * @return PreferencesForm|HtmlForm
1278 static function getFormObject(
1279 $user,
1280 IContextSource $context,
1281 $formClass = 'PreferencesForm',
1282 array $remove = array()
1284 $formDescriptor = Preferences::getPreferences( $user, $context );
1285 if ( count( $remove ) ) {
1286 $removeKeys = array_flip( $remove );
1287 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1290 // Remove type=api preferences. They are not intended for rendering in the form.
1291 foreach ( $formDescriptor as $name => $info ) {
1292 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1293 unset( $formDescriptor[$name] );
1298 * @var $htmlForm PreferencesForm
1300 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1302 $htmlForm->setModifiedUser( $user );
1303 $htmlForm->setId( 'mw-prefs-form' );
1304 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1305 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1306 $htmlForm->setSubmitTooltip( 'preferences-save' );
1307 $htmlForm->setSubmitID( 'prefsubmit' );
1308 $htmlForm->setSubmitCallback( array( 'Preferences', 'tryFormSubmit' ) );
1310 return $htmlForm;
1314 * @param IContextSource $context
1315 * @return array
1317 static function getTimezoneOptions( IContextSource $context ) {
1318 $opt = array();
1320 $localTZoffset = $context->getConfig()->get( 'LocalTZoffset' );
1321 $timeZoneList = self::getTimeZoneList( $context->getLanguage() );
1323 $timestamp = MWTimestamp::getLocalInstance();
1324 // Check that the LocalTZoffset is the same as the local time zone offset
1325 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1326 $timezoneName = $timestamp->getTimezone()->getName();
1327 // Localize timezone
1328 if ( isset( $timeZoneList[$timezoneName] ) ) {
1329 $timezoneName = $timeZoneList[$timezoneName]['name'];
1331 $server_tz_msg = $context->msg(
1332 'timezoneuseserverdefault',
1333 $timezoneName
1334 )->text();
1335 } else {
1336 $tzstring = sprintf(
1337 '%+03d:%02d',
1338 floor( $localTZoffset / 60 ),
1339 abs( $localTZoffset ) % 60
1341 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1343 $opt[$server_tz_msg] = "System|$localTZoffset";
1344 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1345 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1347 foreach ( $timeZoneList as $timeZoneInfo ) {
1348 $region = $timeZoneInfo['region'];
1349 if ( !isset( $opt[$region] ) ) {
1350 $opt[$region] = array();
1352 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1354 return $opt;
1358 * @param string $value
1359 * @param array $alldata
1360 * @return int
1362 static function filterIntval( $value, $alldata ) {
1363 return intval( $value );
1367 * @param string $tz
1368 * @param array $alldata
1369 * @return string
1371 static function filterTimezoneInput( $tz, $alldata ) {
1372 $data = explode( '|', $tz, 3 );
1373 switch ( $data[0] ) {
1374 case 'ZoneInfo':
1375 case 'System':
1376 return $tz;
1377 default:
1378 $data = explode( ':', $tz, 2 );
1379 if ( count( $data ) == 2 ) {
1380 $data[0] = intval( $data[0] );
1381 $data[1] = intval( $data[1] );
1382 $minDiff = abs( $data[0] ) * 60 + $data[1];
1383 if ( $data[0] < 0 ) {
1384 $minDiff = - $minDiff;
1386 } else {
1387 $minDiff = intval( $data[0] ) * 60;
1390 # Max is +14:00 and min is -12:00, see:
1391 # https://en.wikipedia.org/wiki/Timezone
1392 $minDiff = min( $minDiff, 840 ); # 14:00
1393 $minDiff = max( $minDiff, - 720 ); # -12:00
1394 return 'Offset|' . $minDiff;
1399 * Handle the form submission if everything validated properly
1401 * @param array $formData
1402 * @param PreferencesForm $form
1403 * @return bool|Status|string
1405 static function tryFormSubmit( $formData, $form ) {
1406 global $wgAuth;
1408 $user = $form->getModifiedUser();
1409 $hiddenPrefs = $form->getConfig()->get( 'HiddenPrefs' );
1410 $result = true;
1412 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1413 return Status::newFatal( 'mypreferencesprotected' );
1416 // Filter input
1417 foreach ( array_keys( $formData ) as $name ) {
1418 if ( isset( self::$saveFilters[$name] ) ) {
1419 $formData[$name] =
1420 call_user_func( self::$saveFilters[$name], $formData[$name], $formData );
1424 // Fortunately, the realname field is MUCH simpler
1425 // (not really "private", but still shouldn't be edited without permission)
1426 if ( !in_array( 'realname', $hiddenPrefs )
1427 && $user->isAllowed( 'editmyprivateinfo' )
1428 && array_key_exists( 'realname', $formData )
1430 $realName = $formData['realname'];
1431 $user->setRealName( $realName );
1434 if ( $user->isAllowed( 'editmyoptions' ) ) {
1435 foreach ( self::$saveBlacklist as $b ) {
1436 unset( $formData[$b] );
1439 # If users have saved a value for a preference which has subsequently been disabled
1440 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1441 # is subsequently re-enabled
1442 foreach ( $hiddenPrefs as $pref ) {
1443 # If the user has not set a non-default value here, the default will be returned
1444 # and subsequently discarded
1445 $formData[$pref] = $user->getOption( $pref, null, true );
1448 // Keep old preferences from interfering due to back-compat code, etc.
1449 $user->resetOptions( 'unused', $form->getContext() );
1451 foreach ( $formData as $key => $value ) {
1452 $user->setOption( $key, $value );
1455 Hooks::run( 'PreferencesFormPreSave', array( $formData, $form, $user, &$result ) );
1458 $wgAuth->updateExternalDB( $user );
1459 $user->saveSettings();
1461 return $result;
1465 * @param array $formData
1466 * @param PreferencesForm $form
1467 * @return Status
1469 public static function tryUISubmit( $formData, $form ) {
1470 $res = self::tryFormSubmit( $formData, $form );
1472 if ( $res ) {
1473 $urlOptions = array();
1475 if ( $res === 'eauth' ) {
1476 $urlOptions['eauth'] = 1;
1479 $urlOptions += $form->getExtraSuccessRedirectParameters();
1481 $url = $form->getTitle()->getFullURL( $urlOptions );
1483 $context = $form->getContext();
1484 // Set session data for the success message
1485 $context->getRequest()->setSessionData( 'specialPreferencesSaveSuccess', 1 );
1487 $context->getOutput()->redirect( $url );
1490 return Status::newGood();
1494 * Get a list of all time zones
1495 * @param Language $language Language used for the localized names
1496 * @return array A list of all time zones. The system name of the time zone is used as key and
1497 * the value is an array which contains localized name, the timecorrection value used for
1498 * preferences and the region
1499 * @since 1.26
1501 public static function getTimeZoneList( Language $language ) {
1502 $identifiers = DateTimeZone::listIdentifiers();
1503 if ( $identifiers === false ) {
1504 return array();
1506 sort( $identifiers );
1508 $tzRegions = array(
1509 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1510 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1511 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1512 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1513 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1514 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1515 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1516 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1517 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1518 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1520 asort( $tzRegions );
1522 $timeZoneList = array();
1524 $now = new DateTime();
1526 foreach ( $identifiers as $identifier ) {
1527 $parts = explode( '/', $identifier, 2 );
1529 // DateTimeZone::listIdentifiers() returns a number of
1530 // backwards-compatibility entries. This filters them out of the
1531 // list presented to the user.
1532 if ( count( $parts ) !== 2 || !array_key_exists( $parts[0], $tzRegions ) ) {
1533 continue;
1536 // Localize region
1537 $parts[0] = $tzRegions[$parts[0]];
1539 $dateTimeZone = new DateTimeZone( $identifier );
1540 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1542 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1543 $value = "ZoneInfo|$minDiff|$identifier";
1545 $timeZoneList[$identifier] = array(
1546 'name' => $display,
1547 'timecorrection' => $value,
1548 'region' => $parts[0],
1552 return $timeZoneList;
1556 /** Some tweaks to allow js prefs to work */
1557 class PreferencesForm extends HTMLForm {
1558 // Override default value from HTMLForm
1559 protected $mSubSectionBeforeFields = false;
1561 private $modifiedUser;
1564 * @param User $user
1566 public function setModifiedUser( $user ) {
1567 $this->modifiedUser = $user;
1571 * @return User
1573 public function getModifiedUser() {
1574 if ( $this->modifiedUser === null ) {
1575 return $this->getUser();
1576 } else {
1577 return $this->modifiedUser;
1582 * Get extra parameters for the query string when redirecting after
1583 * successful save.
1585 * @return array()
1587 public function getExtraSuccessRedirectParameters() {
1588 return array();
1592 * @param string $html
1593 * @return string
1595 function wrapForm( $html ) {
1596 $html = Xml::tags( 'div', array( 'id' => 'preferences' ), $html );
1598 return parent::wrapForm( $html );
1602 * @return string
1604 function getButtons() {
1606 $attrs = array( 'id' => 'mw-prefs-restoreprefs' );
1608 if ( !$this->getModifiedUser()->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1609 return '';
1612 $html = parent::getButtons();
1614 if ( $this->getModifiedUser()->isAllowed( 'editmyoptions' ) ) {
1615 $t = SpecialPage::getTitleFor( 'Preferences', 'reset' );
1617 $html .= "\n" . Linker::link( $t, $this->msg( 'restoreprefs' )->escaped(),
1618 Html::buttonAttributes( $attrs, array( 'mw-ui-quiet' ) ) );
1620 $html = Xml::tags( 'div', array( 'class' => 'mw-prefs-buttons' ), $html );
1623 return $html;
1627 * Separate multi-option preferences into multiple preferences, since we
1628 * have to store them separately
1629 * @param array $data
1630 * @return array
1632 function filterDataForSubmit( $data ) {
1633 foreach ( $this->mFlatFields as $fieldname => $field ) {
1634 if ( $field instanceof HTMLNestedFilterable ) {
1635 $info = $field->mParams;
1636 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $fieldname;
1637 foreach ( $field->filterDataForSubmit( $data[$fieldname] ) as $key => $value ) {
1638 $data["$prefix$key"] = $value;
1640 unset( $data[$fieldname] );
1644 return $data;
1648 * Get the whole body of the form.
1649 * @return string
1651 function getBody() {
1652 return $this->displaySection( $this->mFieldTree, '', 'mw-prefsection-' );
1656 * Get the "<legend>" for a given section key. Normally this is the
1657 * prefs-$key message but we'll allow extensions to override it.
1658 * @param string $key
1659 * @return string
1661 function getLegend( $key ) {
1662 $legend = parent::getLegend( $key );
1663 Hooks::run( 'PreferencesGetLegend', array( $this, $key, &$legend ) );
1664 return $legend;
1668 * Get the keys of each top level preference section.
1669 * @return array of section keys
1671 function getPreferenceSections() {
1672 return array_keys( array_filter( $this->mFieldTree, 'is_array' ) );