Fix hook situation for Skin::doEditSectionLink
[mediawiki.git] / includes / Preferences.php
blob40c3a2b888d632e10735fba33d6c74bd70602d09
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 ## Prod in defaults from the user
128 foreach ( $defaultPreferences as $name => &$info ) {
129 $prefFromUser = self::getOptionFromUser( $name, $info, $user );
130 if ( $disable && !in_array( $name, self::$saveBlacklist ) ) {
131 $info['disabled'] = 'disabled';
133 $field = HTMLForm::loadInputFromParameters( $name, $info, $dummyForm ); // For validation
134 $defaultOptions = User::getDefaultOptions();
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,
511 $defaultPreferences['emailaddress']['cssclass'] = $emailauthenticationclass;
515 if ( $config->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
516 $defaultPreferences['disablemail'] = array(
517 'type' => 'toggle',
518 'invert' => true,
519 'section' => 'personal/email',
520 'label-message' => 'allowemail',
521 'disabled' => $disableEmailPrefs,
523 $defaultPreferences['ccmeonemails'] = array(
524 'type' => 'toggle',
525 'section' => 'personal/email',
526 'label-message' => 'tog-ccmeonemails',
527 'disabled' => $disableEmailPrefs,
531 if ( $config->get( 'EnotifWatchlist' ) ) {
532 $defaultPreferences['enotifwatchlistpages'] = array(
533 'type' => 'toggle',
534 'section' => 'personal/email',
535 'label-message' => 'tog-enotifwatchlistpages',
536 'disabled' => $disableEmailPrefs,
539 if ( $config->get( 'EnotifUserTalk' ) ) {
540 $defaultPreferences['enotifusertalkpages'] = array(
541 'type' => 'toggle',
542 'section' => 'personal/email',
543 'label-message' => 'tog-enotifusertalkpages',
544 'disabled' => $disableEmailPrefs,
547 if ( $config->get( 'EnotifUserTalk' ) || $config->get( 'EnotifWatchlist' ) ) {
548 $defaultPreferences['enotifminoredits'] = array(
549 'type' => 'toggle',
550 'section' => 'personal/email',
551 'label-message' => 'tog-enotifminoredits',
552 'disabled' => $disableEmailPrefs,
555 if ( $config->get( 'EnotifRevealEditorAddress' ) ) {
556 $defaultPreferences['enotifrevealaddr'] = array(
557 'type' => 'toggle',
558 'section' => 'personal/email',
559 'label-message' => 'tog-enotifrevealaddr',
560 'disabled' => $disableEmailPrefs,
568 * @param User $user
569 * @param IContextSource $context
570 * @param array $defaultPreferences
571 * @return void
573 static function skinPreferences( $user, IContextSource $context, &$defaultPreferences ) {
574 ## Skin #####################################
576 // Skin selector, if there is at least one valid skin
577 $skinOptions = self::generateSkinOptions( $user, $context );
578 if ( $skinOptions ) {
579 $defaultPreferences['skin'] = array(
580 'type' => 'radio',
581 'options' => $skinOptions,
582 'label' => '&#160;',
583 'section' => 'rendering/skin',
587 $config = $context->getConfig();
588 $allowUserCss = $config->get( 'AllowUserCss' );
589 $allowUserJs = $config->get( 'AllowUserJs' );
590 # Create links to user CSS/JS pages for all skins
591 # This code is basically copied from generateSkinOptions(). It'd
592 # be nice to somehow merge this back in there to avoid redundancy.
593 if ( $allowUserCss || $allowUserJs ) {
594 $linkTools = array();
595 $userName = $user->getName();
597 if ( $allowUserCss ) {
598 $cssPage = Title::makeTitleSafe( NS_USER, $userName . '/common.css' );
599 $linkTools[] = Linker::link( $cssPage, $context->msg( 'prefs-custom-css' )->escaped() );
602 if ( $allowUserJs ) {
603 $jsPage = Title::makeTitleSafe( NS_USER, $userName . '/common.js' );
604 $linkTools[] = Linker::link( $jsPage, $context->msg( 'prefs-custom-js' )->escaped() );
607 $defaultPreferences['commoncssjs'] = array(
608 'type' => 'info',
609 'raw' => true,
610 'default' => $context->getLanguage()->pipeList( $linkTools ),
611 'label-message' => 'prefs-common-css-js',
612 'section' => 'rendering/skin',
618 * @param User $user
619 * @param IContextSource $context
620 * @param array $defaultPreferences
622 static function filesPreferences( $user, IContextSource $context, &$defaultPreferences ) {
623 ## Files #####################################
624 $defaultPreferences['imagesize'] = array(
625 'type' => 'select',
626 'options' => self::getImageSizes( $context ),
627 'label-message' => 'imagemaxsize',
628 'section' => 'rendering/files',
630 $defaultPreferences['thumbsize'] = array(
631 'type' => 'select',
632 'options' => self::getThumbSizes( $context ),
633 'label-message' => 'thumbsize',
634 'section' => 'rendering/files',
639 * @param User $user
640 * @param IContextSource $context
641 * @param array $defaultPreferences
642 * @return void
644 static function datetimePreferences( $user, IContextSource $context, &$defaultPreferences ) {
645 ## Date and time #####################################
646 $dateOptions = self::getDateOptions( $context );
647 if ( $dateOptions ) {
648 $defaultPreferences['date'] = array(
649 'type' => 'radio',
650 'options' => $dateOptions,
651 'label' => '&#160;',
652 'section' => 'rendering/dateformat',
656 // Info
657 $now = wfTimestampNow();
658 $lang = $context->getLanguage();
659 $nowlocal = Xml::element( 'span', array( 'id' => 'wpLocalTime' ),
660 $lang->time( $now, true ) );
661 $nowserver = $lang->time( $now, 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 'label-raw' => $context->msg( 'stub-threshold' )->text(), // Raw HTML message. Yay?
756 $defaultPreferences['showhiddencats'] = array(
757 'type' => 'toggle',
758 'section' => 'rendering/advancedrendering',
759 'label-message' => 'tog-showhiddencats'
762 $defaultPreferences['numberheadings'] = array(
763 'type' => 'toggle',
764 'section' => 'rendering/advancedrendering',
765 'label-message' => 'tog-numberheadings',
770 * @param User $user
771 * @param IContextSource $context
772 * @param array $defaultPreferences
774 static function editingPreferences( $user, IContextSource $context, &$defaultPreferences ) {
775 ## Editing #####################################
776 $defaultPreferences['editsectiononrightclick'] = array(
777 'type' => 'toggle',
778 'section' => 'editing/advancedediting',
779 'label-message' => 'tog-editsectiononrightclick',
781 $defaultPreferences['editondblclick'] = array(
782 'type' => 'toggle',
783 'section' => 'editing/advancedediting',
784 'label-message' => 'tog-editondblclick',
787 if ( $context->getConfig()->get( 'AllowUserCssPrefs' ) ) {
788 $defaultPreferences['editfont'] = array(
789 'type' => 'select',
790 'section' => 'editing/editor',
791 'label-message' => 'editfont-style',
792 'options' => array(
793 $context->msg( 'editfont-default' )->text() => 'default',
794 $context->msg( 'editfont-monospace' )->text() => 'monospace',
795 $context->msg( 'editfont-sansserif' )->text() => 'sans-serif',
796 $context->msg( 'editfont-serif' )->text() => 'serif',
800 $defaultPreferences['cols'] = array(
801 'type' => 'int',
802 'label-message' => 'columns',
803 'section' => 'editing/editor',
804 'min' => 4,
805 'max' => 1000,
807 $defaultPreferences['rows'] = array(
808 'type' => 'int',
809 'label-message' => 'rows',
810 'section' => 'editing/editor',
811 'min' => 4,
812 'max' => 1000,
814 if ( $user->isAllowed( 'minoredit' ) ) {
815 $defaultPreferences['minordefault'] = array(
816 'type' => 'toggle',
817 'section' => 'editing/editor',
818 'label-message' => 'tog-minordefault',
821 $defaultPreferences['forceeditsummary'] = array(
822 'type' => 'toggle',
823 'section' => 'editing/editor',
824 'label-message' => 'tog-forceeditsummary',
826 $defaultPreferences['useeditwarning'] = array(
827 'type' => 'toggle',
828 'section' => 'editing/editor',
829 'label-message' => 'tog-useeditwarning',
831 $defaultPreferences['showtoolbar'] = array(
832 'type' => 'toggle',
833 'section' => 'editing/editor',
834 'label-message' => 'tog-showtoolbar',
837 $defaultPreferences['previewonfirst'] = array(
838 'type' => 'toggle',
839 'section' => 'editing/preview',
840 'label-message' => 'tog-previewonfirst',
842 $defaultPreferences['previewontop'] = array(
843 'type' => 'toggle',
844 'section' => 'editing/preview',
845 'label-message' => 'tog-previewontop',
847 $defaultPreferences['uselivepreview'] = array(
848 'type' => 'toggle',
849 'section' => 'editing/preview',
850 'label-message' => 'tog-uselivepreview',
856 * @param User $user
857 * @param IContextSource $context
858 * @param array $defaultPreferences
860 static function rcPreferences( $user, IContextSource $context, &$defaultPreferences ) {
861 $config = $context->getConfig();
862 $rcMaxAge = $config->get( 'RCMaxAge' );
863 ## RecentChanges #####################################
864 $defaultPreferences['rcdays'] = array(
865 'type' => 'float',
866 'label-message' => 'recentchangesdays',
867 'section' => 'rc/displayrc',
868 'min' => 1,
869 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
870 'help' => $context->msg( 'recentchangesdays-max' )->numParams(
871 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
873 $defaultPreferences['rclimit'] = array(
874 'type' => 'int',
875 'label-message' => 'recentchangescount',
876 'help-message' => 'prefs-help-recentchangescount',
877 'section' => 'rc/displayrc',
879 $defaultPreferences['usenewrc'] = array(
880 'type' => 'toggle',
881 'label-message' => 'tog-usenewrc',
882 'section' => 'rc/advancedrc',
884 $defaultPreferences['hideminor'] = array(
885 'type' => 'toggle',
886 'label-message' => 'tog-hideminor',
887 'section' => 'rc/advancedrc',
890 if ( $user->useRCPatrol() ) {
891 $defaultPreferences['hidepatrolled'] = array(
892 'type' => 'toggle',
893 'section' => 'rc/advancedrc',
894 'label-message' => 'tog-hidepatrolled',
898 if ( $user->useNPPatrol() ) {
899 $defaultPreferences['newpageshidepatrolled'] = array(
900 'type' => 'toggle',
901 'section' => 'rc/advancedrc',
902 'label-message' => 'tog-newpageshidepatrolled',
906 if ( $config->get( 'RCShowWatchingUsers' ) ) {
907 $defaultPreferences['shownumberswatching'] = array(
908 'type' => 'toggle',
909 'section' => 'rc/advancedrc',
910 'label-message' => 'tog-shownumberswatching',
916 * @param User $user
917 * @param IContextSource $context
918 * @param array $defaultPreferences
920 static function watchlistPreferences( $user, IContextSource $context, &$defaultPreferences ) {
921 $config = $context->getConfig();
922 $watchlistdaysMax = ceil( $config->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
924 ## Watchlist #####################################
925 if ( $user->isAllowed( 'editmywatchlist' ) ) {
926 $editWatchlistLinks = array();
927 $editWatchlistModes = array(
928 'edit' => array( 'EditWatchlist', false ),
929 'raw' => array( 'EditWatchlist', 'raw' ),
930 'clear' => array( 'EditWatchlist', 'clear' ),
932 foreach ( $editWatchlistModes as $editWatchlistMode => $mode ) {
933 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
934 $editWatchlistLinks[] = Linker::linkKnown(
935 SpecialPage::getTitleFor( $mode[0], $mode[1] ),
936 $context->msg( "prefs-editwatchlist-{$editWatchlistMode}" )->parse()
940 $defaultPreferences['editwatchlist'] = array(
941 'type' => 'info',
942 'raw' => true,
943 'default' => $context->getLanguage()->pipeList( $editWatchlistLinks ),
944 'label-message' => 'prefs-editwatchlist-label',
945 'section' => 'watchlist/editwatchlist',
949 $defaultPreferences['watchlistdays'] = array(
950 'type' => 'float',
951 'min' => 0,
952 'max' => $watchlistdaysMax,
953 'section' => 'watchlist/displaywatchlist',
954 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
955 $watchlistdaysMax )->escaped(),
956 'label-message' => 'prefs-watchlist-days',
958 $defaultPreferences['wllimit'] = array(
959 'type' => 'int',
960 'min' => 0,
961 'max' => 1000,
962 'label-message' => 'prefs-watchlist-edits',
963 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
964 'section' => 'watchlist/displaywatchlist',
966 $defaultPreferences['extendwatchlist'] = array(
967 'type' => 'toggle',
968 'section' => 'watchlist/advancedwatchlist',
969 'label-message' => 'tog-extendwatchlist',
971 $defaultPreferences['watchlisthideminor'] = array(
972 'type' => 'toggle',
973 'section' => 'watchlist/advancedwatchlist',
974 'label-message' => 'tog-watchlisthideminor',
976 $defaultPreferences['watchlisthidebots'] = array(
977 'type' => 'toggle',
978 'section' => 'watchlist/advancedwatchlist',
979 'label-message' => 'tog-watchlisthidebots',
981 $defaultPreferences['watchlisthideown'] = array(
982 'type' => 'toggle',
983 'section' => 'watchlist/advancedwatchlist',
984 'label-message' => 'tog-watchlisthideown',
986 $defaultPreferences['watchlisthideanons'] = array(
987 'type' => 'toggle',
988 'section' => 'watchlist/advancedwatchlist',
989 'label-message' => 'tog-watchlisthideanons',
991 $defaultPreferences['watchlisthideliu'] = array(
992 'type' => 'toggle',
993 'section' => 'watchlist/advancedwatchlist',
994 'label-message' => 'tog-watchlisthideliu',
997 if ( $user->useRCPatrol() ) {
998 $defaultPreferences['watchlisthidepatrolled'] = array(
999 'type' => 'toggle',
1000 'section' => 'watchlist/advancedwatchlist',
1001 'label-message' => 'tog-watchlisthidepatrolled',
1005 $watchTypes = array(
1006 'edit' => 'watchdefault',
1007 'move' => 'watchmoves',
1008 'delete' => 'watchdeletion'
1011 // Kinda hacky
1012 if ( $user->isAllowed( 'createpage' ) || $user->isAllowed( 'createtalk' ) ) {
1013 $watchTypes['read'] = 'watchcreations';
1016 if ( $user->isAllowed( 'rollback' ) ) {
1017 $watchTypes['rollback'] = 'watchrollback';
1020 foreach ( $watchTypes as $action => $pref ) {
1021 if ( $user->isAllowed( $action ) ) {
1022 // Messages:
1023 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations
1024 // tog-watchrollback
1025 $defaultPreferences[$pref] = array(
1026 'type' => 'toggle',
1027 'section' => 'watchlist/advancedwatchlist',
1028 'label-message' => "tog-$pref",
1033 if ( $config->get( 'EnableAPI' ) ) {
1034 $defaultPreferences['watchlisttoken'] = array(
1035 'type' => 'api',
1037 $defaultPreferences['watchlisttoken-info'] = array(
1038 'type' => 'info',
1039 'section' => 'watchlist/tokenwatchlist',
1040 'label-message' => 'prefs-watchlist-token',
1041 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1042 'help-message' => 'prefs-help-watchlist-token2',
1048 * @param User $user
1049 * @param IContextSource $context
1050 * @param array $defaultPreferences
1052 static function searchPreferences( $user, IContextSource $context, &$defaultPreferences ) {
1053 foreach ( MWNamespace::getValidNamespaces() as $n ) {
1054 $defaultPreferences['searchNs' . $n] = array(
1055 'type' => 'api',
1061 * Dummy, kept for backwards-compatibility.
1063 static function miscPreferences( $user, IContextSource $context, &$defaultPreferences ) {
1067 * @param User $user The User object
1068 * @param IContextSource $context
1069 * @return array Text/links to display as key; $skinkey as value
1071 static function generateSkinOptions( $user, IContextSource $context ) {
1072 $ret = array();
1074 $mptitle = Title::newMainPage();
1075 $previewtext = $context->msg( 'skin-preview' )->escaped();
1077 # Only show skins that aren't disabled in $wgSkipSkins
1078 $validSkinNames = Skin::getAllowedSkins();
1080 # Sort by UI skin name. First though need to update validSkinNames as sometimes
1081 # the skinkey & UI skinname differ (e.g. "standard" skinkey is "Classic" in the UI).
1082 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1083 $msg = $context->msg( "skinname-{$skinkey}" );
1084 if ( $msg->exists() ) {
1085 $skinname = htmlspecialchars( $msg->text() );
1088 asort( $validSkinNames );
1090 $config = $context->getConfig();
1091 $defaultSkin = $config->get( 'DefaultSkin' );
1092 $allowUserCss = $config->get( 'AllowUserCss' );
1093 $allowUserJs = $config->get( 'AllowUserJs' );
1095 $foundDefault = false;
1096 foreach ( $validSkinNames as $skinkey => $sn ) {
1097 $linkTools = array();
1099 # Mark the default skin
1100 if ( $skinkey == $defaultSkin ) {
1101 $linkTools[] = $context->msg( 'default' )->escaped();
1102 $foundDefault = true;
1105 # Create preview link
1106 $mplink = htmlspecialchars( $mptitle->getLocalURL( array( 'useskin' => $skinkey ) ) );
1107 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1109 # Create links to user CSS/JS pages
1110 if ( $allowUserCss ) {
1111 $cssPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.css' );
1112 $linkTools[] = Linker::link( $cssPage, $context->msg( 'prefs-custom-css' )->escaped() );
1115 if ( $allowUserJs ) {
1116 $jsPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.js' );
1117 $linkTools[] = Linker::link( $jsPage, $context->msg( 'prefs-custom-js' )->escaped() );
1120 $display = $sn . ' ' . $context->msg( 'parentheses' )
1121 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1122 ->escaped();
1123 $ret[$display] = $skinkey;
1126 if ( !$foundDefault ) {
1127 // If the default skin is not available, things are going to break horribly because the
1128 // default value for skin selector will not be a valid value. Let's just not show it then.
1129 return array();
1132 return $ret;
1136 * @param IContextSource $context
1137 * @return array
1139 static function getDateOptions( IContextSource $context ) {
1140 $lang = $context->getLanguage();
1141 $dateopts = $lang->getDatePreferences();
1143 $ret = array();
1145 if ( $dateopts ) {
1146 if ( !in_array( 'default', $dateopts ) ) {
1147 $dateopts[] = 'default'; // Make sure default is always valid
1148 // Bug 19237
1151 // FIXME KLUGE: site default might not be valid for user language
1152 global $wgDefaultUserOptions;
1153 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1154 $wgDefaultUserOptions['date'] = 'default';
1157 $epoch = wfTimestampNow();
1158 foreach ( $dateopts as $key ) {
1159 if ( $key == 'default' ) {
1160 $formatted = $context->msg( 'datedefault' )->escaped();
1161 } else {
1162 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1164 $ret[$formatted] = $key;
1167 return $ret;
1171 * @param IContextSource $context
1172 * @return array
1174 static function getImageSizes( IContextSource $context ) {
1175 $ret = array();
1176 $pixels = $context->msg( 'unit-pixel' )->text();
1178 foreach ( $context->getConfig()->get( 'ImageLimits' ) as $index => $limits ) {
1179 $display = "{$limits[0]}×{$limits[1]}" . $pixels;
1180 $ret[$display] = $index;
1183 return $ret;
1187 * @param IContextSource $context
1188 * @return array
1190 static function getThumbSizes( IContextSource $context ) {
1191 $ret = array();
1192 $pixels = $context->msg( 'unit-pixel' )->text();
1194 foreach ( $context->getConfig()->get( 'ThumbLimits' ) as $index => $size ) {
1195 $display = $size . $pixels;
1196 $ret[$display] = $index;
1199 return $ret;
1203 * @param string $signature
1204 * @param array $alldata
1205 * @param HTMLForm $form
1206 * @return bool|string
1208 static function validateSignature( $signature, $alldata, $form ) {
1209 global $wgParser;
1210 $maxSigChars = $form->getConfig()->get( 'MaxSigChars' );
1211 if ( mb_strlen( $signature ) > $maxSigChars ) {
1212 return Xml::element( 'span', array( 'class' => 'error' ),
1213 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1214 } elseif ( isset( $alldata['fancysig'] ) &&
1215 $alldata['fancysig'] &&
1216 $wgParser->validateSig( $signature ) === false
1218 return Xml::element(
1219 'span',
1220 array( 'class' => 'error' ),
1221 $form->msg( 'badsig' )->text()
1223 } else {
1224 return true;
1229 * @param string $signature
1230 * @param array $alldata
1231 * @param HTMLForm $form
1232 * @return string
1234 static function cleanSignature( $signature, $alldata, $form ) {
1235 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1236 global $wgParser;
1237 $signature = $wgParser->cleanSig( $signature );
1238 } else {
1239 // When no fancy sig used, make sure ~{3,5} get removed.
1240 $signature = Parser::cleanSigInSig( $signature );
1243 return $signature;
1247 * @param User $user
1248 * @param IContextSource $context
1249 * @param string $formClass
1250 * @param array $remove Array of items to remove
1251 * @return HtmlForm
1253 static function getFormObject(
1254 $user,
1255 IContextSource $context,
1256 $formClass = 'PreferencesForm',
1257 array $remove = array()
1259 $formDescriptor = Preferences::getPreferences( $user, $context );
1260 if ( count( $remove ) ) {
1261 $removeKeys = array_flip( $remove );
1262 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1265 // Remove type=api preferences. They are not intended for rendering in the form.
1266 foreach ( $formDescriptor as $name => $info ) {
1267 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1268 unset( $formDescriptor[$name] );
1273 * @var $htmlForm PreferencesForm
1275 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1277 $htmlForm->setModifiedUser( $user );
1278 $htmlForm->setId( 'mw-prefs-form' );
1279 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1280 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1281 $htmlForm->setSubmitTooltip( 'preferences-save' );
1282 $htmlForm->setSubmitID( 'prefsubmit' );
1283 $htmlForm->setSubmitCallback( array( 'Preferences', 'tryFormSubmit' ) );
1285 return $htmlForm;
1289 * @param IContextSource $context
1290 * @return array
1292 static function getTimezoneOptions( IContextSource $context ) {
1293 $opt = array();
1295 $localTZoffset = $context->getConfig()->get( 'LocalTZoffset' );
1296 $timestamp = MWTimestamp::getLocalInstance();
1297 // Check that the LocalTZoffset is the same as the local time zone offset
1298 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1299 $server_tz_msg = $context->msg(
1300 'timezoneuseserverdefault',
1301 $timestamp->getTimezone()->getName()
1302 )->text();
1303 } else {
1304 $tzstring = sprintf(
1305 '%+03d:%02d',
1306 floor( $localTZoffset / 60 ),
1307 abs( $localTZoffset ) % 60
1309 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1311 $opt[$server_tz_msg] = "System|$localTZoffset";
1312 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1313 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1315 if ( function_exists( 'timezone_identifiers_list' ) ) {
1316 # Read timezone list
1317 $tzs = timezone_identifiers_list();
1318 sort( $tzs );
1320 $tzRegions = array();
1321 $tzRegions['Africa'] = $context->msg( 'timezoneregion-africa' )->text();
1322 $tzRegions['America'] = $context->msg( 'timezoneregion-america' )->text();
1323 $tzRegions['Antarctica'] = $context->msg( 'timezoneregion-antarctica' )->text();
1324 $tzRegions['Arctic'] = $context->msg( 'timezoneregion-arctic' )->text();
1325 $tzRegions['Asia'] = $context->msg( 'timezoneregion-asia' )->text();
1326 $tzRegions['Atlantic'] = $context->msg( 'timezoneregion-atlantic' )->text();
1327 $tzRegions['Australia'] = $context->msg( 'timezoneregion-australia' )->text();
1328 $tzRegions['Europe'] = $context->msg( 'timezoneregion-europe' )->text();
1329 $tzRegions['Indian'] = $context->msg( 'timezoneregion-indian' )->text();
1330 $tzRegions['Pacific'] = $context->msg( 'timezoneregion-pacific' )->text();
1331 asort( $tzRegions );
1333 $prefill = array_fill_keys( array_values( $tzRegions ), array() );
1334 $opt = array_merge( $opt, $prefill );
1336 $now = date_create( 'now' );
1338 foreach ( $tzs as $tz ) {
1339 $z = explode( '/', $tz, 2 );
1341 # timezone_identifiers_list() returns a number of
1342 # backwards-compatibility entries. This filters them out of the
1343 # list presented to the user.
1344 if ( count( $z ) != 2 || !array_key_exists( $z[0], $tzRegions ) ) {
1345 continue;
1348 # Localize region
1349 $z[0] = $tzRegions[$z[0]];
1351 $minDiff = floor( timezone_offset_get( timezone_open( $tz ), $now ) / 60 );
1353 $display = str_replace( '_', ' ', $z[0] . '/' . $z[1] );
1354 $value = "ZoneInfo|$minDiff|$tz";
1356 $opt[$z[0]][$display] = $value;
1359 return $opt;
1363 * @param string $value
1364 * @param array $alldata
1365 * @return int
1367 static function filterIntval( $value, $alldata ) {
1368 return intval( $value );
1372 * @param string $tz
1373 * @param array $alldata
1374 * @return string
1376 static function filterTimezoneInput( $tz, $alldata ) {
1377 $data = explode( '|', $tz, 3 );
1378 switch ( $data[0] ) {
1379 case 'ZoneInfo':
1380 case 'System':
1381 return $tz;
1382 default:
1383 $data = explode( ':', $tz, 2 );
1384 if ( count( $data ) == 2 ) {
1385 $data[0] = intval( $data[0] );
1386 $data[1] = intval( $data[1] );
1387 $minDiff = abs( $data[0] ) * 60 + $data[1];
1388 if ( $data[0] < 0 ) {
1389 $minDiff = - $minDiff;
1391 } else {
1392 $minDiff = intval( $data[0] ) * 60;
1395 # Max is +14:00 and min is -12:00, see:
1396 # http://en.wikipedia.org/wiki/Timezone
1397 $minDiff = min( $minDiff, 840 ); # 14:00
1398 $minDiff = max( $minDiff, - 720 ); # -12:00
1399 return 'Offset|' . $minDiff;
1404 * Handle the form submission if everything validated properly
1406 * @param array $formData
1407 * @param PreferencesForm $form
1408 * @return bool|Status|string
1410 static function tryFormSubmit( $formData, $form ) {
1411 global $wgAuth;
1413 $user = $form->getModifiedUser();
1414 $hiddenPrefs = $form->getConfig()->get( 'HiddenPrefs' );
1415 $result = true;
1417 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1418 return Status::newFatal( 'mypreferencesprotected' );
1421 // Filter input
1422 foreach ( array_keys( $formData ) as $name ) {
1423 if ( isset( self::$saveFilters[$name] ) ) {
1424 $formData[$name] =
1425 call_user_func( self::$saveFilters[$name], $formData[$name], $formData );
1429 // Fortunately, the realname field is MUCH simpler
1430 // (not really "private", but still shouldn't be edited without permission)
1431 if ( !in_array( 'realname', $hiddenPrefs )
1432 && $user->isAllowed( 'editmyprivateinfo' )
1433 && array_key_exists( 'realname', $formData )
1435 $realName = $formData['realname'];
1436 $user->setRealName( $realName );
1439 if ( $user->isAllowed( 'editmyoptions' ) ) {
1440 foreach ( self::$saveBlacklist as $b ) {
1441 unset( $formData[$b] );
1444 # If users have saved a value for a preference which has subsequently been disabled
1445 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1446 # is subsequently re-enabled
1447 foreach ( $hiddenPrefs as $pref ) {
1448 # If the user has not set a non-default value here, the default will be returned
1449 # and subsequently discarded
1450 $formData[$pref] = $user->getOption( $pref, null, true );
1453 // Keep old preferences from interfering due to back-compat code, etc.
1454 $user->resetOptions( 'unused', $form->getContext() );
1456 foreach ( $formData as $key => $value ) {
1457 $user->setOption( $key, $value );
1460 Hooks::run( 'PreferencesFormPreSave', array( $formData, $form, $user, &$result ) );
1461 $user->saveSettings();
1464 $wgAuth->updateExternalDB( $user );
1466 return $result;
1470 * @param array $formData
1471 * @param PreferencesForm $form
1472 * @return Status
1474 public static function tryUISubmit( $formData, $form ) {
1475 $res = self::tryFormSubmit( $formData, $form );
1477 if ( $res ) {
1478 $urlOptions = array( 'success' => 1 );
1480 if ( $res === 'eauth' ) {
1481 $urlOptions['eauth'] = 1;
1484 $urlOptions += $form->getExtraSuccessRedirectParameters();
1486 $url = $form->getTitle()->getFullURL( $urlOptions );
1488 $form->getContext()->getOutput()->redirect( $url );
1491 return Status::newGood();
1495 /** Some tweaks to allow js prefs to work */
1496 class PreferencesForm extends HTMLForm {
1497 // Override default value from HTMLForm
1498 protected $mSubSectionBeforeFields = false;
1500 private $modifiedUser;
1503 * @param User $user
1505 public function setModifiedUser( $user ) {
1506 $this->modifiedUser = $user;
1510 * @return User
1512 public function getModifiedUser() {
1513 if ( $this->modifiedUser === null ) {
1514 return $this->getUser();
1515 } else {
1516 return $this->modifiedUser;
1521 * Get extra parameters for the query string when redirecting after
1522 * successful save.
1524 * @return array()
1526 public function getExtraSuccessRedirectParameters() {
1527 return array();
1531 * @param string $html
1532 * @return string
1534 function wrapForm( $html ) {
1535 $html = Xml::tags( 'div', array( 'id' => 'preferences' ), $html );
1537 return parent::wrapForm( $html );
1541 * @return string
1543 function getButtons() {
1545 $attrs = array( 'id' => 'mw-prefs-restoreprefs' );
1547 if ( !$this->getModifiedUser()->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1548 return '';
1551 $html = parent::getButtons();
1553 if ( $this->getModifiedUser()->isAllowed( 'editmyoptions' ) ) {
1554 $t = SpecialPage::getTitleFor( 'Preferences', 'reset' );
1556 $html .= "\n" . Linker::link( $t, $this->msg( 'restoreprefs' )->escaped(),
1557 Html::buttonAttributes( $attrs, array( 'mw-ui-quiet' ) ) );
1559 $html = Xml::tags( 'div', array( 'class' => 'mw-prefs-buttons' ), $html );
1562 return $html;
1566 * Separate multi-option preferences into multiple preferences, since we
1567 * have to store them separately
1568 * @param array $data
1569 * @return array
1571 function filterDataForSubmit( $data ) {
1572 foreach ( $this->mFlatFields as $fieldname => $field ) {
1573 if ( $field instanceof HTMLNestedFilterable ) {
1574 $info = $field->mParams;
1575 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $fieldname;
1576 foreach ( $field->filterDataForSubmit( $data[$fieldname] ) as $key => $value ) {
1577 $data["$prefix$key"] = $value;
1579 unset( $data[$fieldname] );
1583 return $data;
1587 * Get the whole body of the form.
1588 * @return string
1590 function getBody() {
1591 return $this->displaySection( $this->mFieldTree, '', 'mw-prefsection-' );
1595 * Get the "<legend>" for a given section key. Normally this is the
1596 * prefs-$key message but we'll allow extensions to override it.
1597 * @param string $key
1598 * @return string
1600 function getLegend( $key ) {
1601 $legend = parent::getLegend( $key );
1602 Hooks::run( 'PreferencesGetLegend', array( $this, $key, &$legend ) );
1603 return $legend;