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
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.
50 protected static $defaultPreferences = null;
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(
71 static function getSaveBlacklist() {
72 return self
::$saveBlacklist;
78 * @param IContextSource $context
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 wfRunHooks( 'GetPreferences', array( $user, &$defaultPreferences ) );
101 ## Remove preferences that wikis don't want to use
102 global $wgHiddenPrefs;
103 foreach ( $wgHiddenPrefs as $pref ) {
104 if ( isset( $defaultPreferences[$pref] ) ) {
105 unset( $defaultPreferences[$pref] );
109 ## Make sure that form fields have their parent set. See bug 41337.
110 $dummyForm = new HTMLForm( array(), $context );
112 $disable = !$user->isAllowed( 'editmyoptions' );
114 ## Prod in defaults from the user
115 foreach ( $defaultPreferences as $name => &$info ) {
116 $prefFromUser = self
::getOptionFromUser( $name, $info, $user );
117 if ( $disable && !in_array( $name, self
::$saveBlacklist ) ) {
118 $info['disabled'] = 'disabled';
120 $field = HTMLForm
::loadInputFromParameters( $name, $info ); // For validation
121 $field->mParent
= $dummyForm;
122 $defaultOptions = User
::getDefaultOptions();
123 $globalDefault = isset( $defaultOptions[$name] )
124 ?
$defaultOptions[$name]
127 // If it validates, set it as the default
128 if ( isset( $info['default'] ) ) {
129 // Already set, no problem
131 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
132 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
133 $info['default'] = $prefFromUser;
134 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
135 $info['default'] = $globalDefault;
137 throw new MWException( "Global default '$globalDefault' is invalid for field $name" );
141 self
::$defaultPreferences = $defaultPreferences;
143 return $defaultPreferences;
147 * Pull option from a user account. Handles stuff like array-type preferences.
149 * @param string $name
152 * @return array|string
154 static function getOptionFromUser( $name, $info, $user ) {
155 $val = $user->getOption( $name );
157 // Handling for multiselect preferences
158 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
159 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
160 $options = HTMLFormField
::flattenOptions( $info['options'] );
161 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
164 foreach ( $options as $value ) {
165 if ( $user->getOption( "$prefix$value" ) ) {
171 // Handling for checkmatrix preferences
172 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
173 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
174 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
175 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
176 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
179 foreach ( $columns as $column ) {
180 foreach ( $rows as $row ) {
181 if ( $user->getOption( "$prefix$column-$row" ) ) {
182 $val[] = "$column-$row";
193 * @param IContextSource $context
194 * @param array $defaultPreferences
197 static function profilePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
198 global $wgAuth, $wgContLang, $wgParser, $wgCookieExpiration, $wgLanguageCode,
199 $wgDisableLangConversion, $wgMaxSigChars,
200 $wgEnableEmail, $wgEmailConfirmToEdit, $wgEnableUserEmail, $wgEmailAuthentication,
201 $wgEnotifWatchlist, $wgEnotifUserTalk, $wgEnotifRevealEditorAddress,
204 // retrieving user name for GENDER and misc.
205 $userName = $user->getName();
207 ## User info #####################################
209 $defaultPreferences['username'] = array(
211 'label-message' => array( 'username', $userName ),
212 'default' => $userName,
213 'section' => 'personal/info',
216 # Get groups to which the user belongs
217 $userEffectiveGroups = $user->getEffectiveGroups();
218 $userGroups = $userMembers = array();
219 foreach ( $userEffectiveGroups as $ueg ) {
221 // Skip the default * group, seems useless here
224 $groupName = User
::getGroupName( $ueg );
225 $userGroups[] = User
::makeGroupLinkHTML( $ueg, $groupName );
227 $memberName = User
::getGroupMember( $ueg, $userName );
228 $userMembers[] = User
::makeGroupLinkHTML( $ueg, $memberName );
230 asort( $userGroups );
231 asort( $userMembers );
233 $lang = $context->getLanguage();
235 $defaultPreferences['usergroups'] = array(
237 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
238 count( $userGroups ) )->params( $userName )->parse(),
239 'default' => $context->msg( 'prefs-memberingroups-type',
240 $lang->commaList( $userGroups ),
241 $lang->commaList( $userMembers )
244 'section' => 'personal/info',
247 $editCount = Linker
::link( SpecialPage
::getTitleFor( "Contributions", $userName ),
248 $lang->formatNum( $user->getEditCount() ) );
250 $defaultPreferences['editcount'] = array(
253 'label-message' => 'prefs-edits',
254 'default' => $editCount,
255 'section' => 'personal/info',
258 if ( $user->getRegistration() ) {
259 $displayUser = $context->getUser();
260 $userRegistration = $user->getRegistration();
261 $defaultPreferences['registrationdate'] = array(
263 'label-message' => 'prefs-registration',
264 'default' => $context->msg(
265 'prefs-registration-date-time',
266 $lang->userTimeAndDate( $userRegistration, $displayUser ),
267 $lang->userDate( $userRegistration, $displayUser ),
268 $lang->userTime( $userRegistration, $displayUser )
270 'section' => 'personal/info',
274 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
275 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
277 // Actually changeable stuff
278 $defaultPreferences['realname'] = array(
279 // (not really "private", but still shouldn't be edited without permission)
280 'type' => $canEditPrivateInfo && $wgAuth->allowPropChange( 'realname' ) ?
'text' : 'info',
281 'default' => $user->getRealName(),
282 'section' => 'personal/info',
283 'label-message' => 'yourrealname',
284 'help-message' => 'prefs-help-realname',
287 if ( $canEditPrivateInfo && $wgAuth->allowPasswordChange() ) {
288 $link = Linker
::link( SpecialPage
::getTitleFor( 'ChangePassword' ),
289 $context->msg( 'prefs-resetpass' )->escaped(), array(),
290 array( 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText() ) );
292 $defaultPreferences['password'] = array(
296 'label-message' => 'yourpassword',
297 'section' => 'personal/info',
300 // Only show prefershttps if secure login is turned on
301 if ( $wgSecureLogin && wfCanIPUseHTTPS( $context->getRequest()->getIP() ) ) {
302 $defaultPreferences['prefershttps'] = array(
304 'label-message' => 'tog-prefershttps',
305 'help-message' => 'prefs-help-prefershttps',
306 'section' => 'personal/info'
311 $languages = Language
::fetchLanguageNames( null, 'mw' );
312 if ( !array_key_exists( $wgLanguageCode, $languages ) ) {
313 $languages[$wgLanguageCode] = $wgLanguageCode;
318 foreach ( $languages as $code => $name ) {
319 $display = wfBCP47( $code ) . ' - ' . $name;
320 $options[$display] = $code;
322 $defaultPreferences['language'] = array(
324 'section' => 'personal/i18n',
325 'options' => $options,
326 'label-message' => 'yourlanguage',
329 $defaultPreferences['gender'] = array(
331 'section' => 'personal/i18n',
333 $context->msg( 'parentheses',
334 $context->msg( 'gender-unknown' )->text()
335 )->text() => 'unknown',
336 $context->msg( 'gender-female' )->text() => 'female',
337 $context->msg( 'gender-male' )->text() => 'male',
339 'label-message' => 'yourgender',
340 'help-message' => 'prefs-help-gender',
343 // see if there are multiple language variants to choose from
344 if ( !$wgDisableLangConversion ) {
345 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
346 if ( $langCode == $wgContLang->getCode() ) {
347 $variants = $wgContLang->getVariants();
349 if ( count( $variants ) <= 1 ) {
353 $variantArray = array();
354 foreach ( $variants as $v ) {
355 $v = str_replace( '_', '-', strtolower( $v ) );
356 $variantArray[$v] = $lang->getVariantname( $v, false );
360 foreach ( $variantArray as $code => $name ) {
361 $display = wfBCP47( $code ) . ' - ' . $name;
362 $options[$display] = $code;
365 $defaultPreferences['variant'] = array(
366 'label-message' => 'yourvariant',
368 'options' => $options,
369 'section' => 'personal/i18n',
370 'help-message' => 'prefs-help-variant',
373 $defaultPreferences["variant-$langCode"] = array(
380 // Stuff from Language::getExtraUserToggles()
381 // FIXME is this dead code? $extraUserToggles doesn't seem to be defined for any language
382 $toggles = $wgContLang->getExtraUserToggles();
384 foreach ( $toggles as $toggle ) {
385 $defaultPreferences[$toggle] = array(
387 'section' => 'personal/i18n',
388 'label-message' => "tog-$toggle",
392 // show a preview of the old signature first
393 $oldsigWikiText = $wgParser->preSaveTransform(
395 $context->getTitle(),
397 ParserOptions
::newFromContext( $context )
399 $oldsigHTML = $context->getOutput()->parseInline( $oldsigWikiText, true, true );
400 $defaultPreferences['oldsig'] = array(
403 'label-message' => 'tog-oldsig',
404 'default' => $oldsigHTML,
405 'section' => 'personal/signature',
407 $defaultPreferences['nickname'] = array(
408 'type' => $wgAuth->allowPropChange( 'nickname' ) ?
'text' : 'info',
409 'maxlength' => $wgMaxSigChars,
410 'label-message' => 'yournick',
411 'validation-callback' => array( 'Preferences', 'validateSignature' ),
412 'section' => 'personal/signature',
413 'filter-callback' => array( 'Preferences', 'cleanSignature' ),
415 $defaultPreferences['fancysig'] = array(
417 'label-message' => 'tog-fancysig',
418 // show general help about signature at the bottom of the section
419 'help-message' => 'prefs-help-signature',
420 'section' => 'personal/signature'
425 if ( $wgEnableEmail ) {
426 if ( $canViewPrivateInfo ) {
427 $helpMessages[] = $wgEmailConfirmToEdit
428 ?
'prefs-help-email-required'
429 : 'prefs-help-email';
431 if ( $wgEnableUserEmail ) {
432 // additional messages when users can send email to each other
433 $helpMessages[] = 'prefs-help-email-others';
436 $emailAddress = $user->getEmail() ?
htmlspecialchars( $user->getEmail() ) : '';
437 if ( $canEditPrivateInfo && $wgAuth->allowPropChange( 'emailaddress' ) ) {
438 $link = Linker
::link(
439 SpecialPage
::getTitleFor( 'ChangeEmail' ),
440 $context->msg( $user->getEmail() ?
'prefs-changeemail' : 'prefs-setemail' )->escaped(),
442 array( 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText() ) );
444 $emailAddress .= $emailAddress == '' ?
$link : (
445 $context->msg( 'word-separator' )->plain()
446 . $context->msg( 'parentheses' )->rawParams( $link )->plain()
450 $defaultPreferences['emailaddress'] = array(
453 'default' => $emailAddress,
454 'label-message' => 'youremail',
455 'section' => 'personal/email',
456 'help-messages' => $helpMessages,
457 # 'cssclass' chosen below
461 $disableEmailPrefs = false;
463 if ( $wgEmailAuthentication ) {
464 $emailauthenticationclass = 'mw-email-not-authenticated';
465 if ( $user->getEmail() ) {
466 if ( $user->getEmailAuthenticationTimestamp() ) {
467 // date and time are separate parameters to facilitate localisation.
468 // $time is kept for backward compat reasons.
469 // 'emailauthenticated' is also used in SpecialConfirmemail.php
470 $displayUser = $context->getUser();
471 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
472 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
473 $d = $lang->userDate( $emailTimestamp, $displayUser );
474 $t = $lang->userTime( $emailTimestamp, $displayUser );
475 $emailauthenticated = $context->msg( 'emailauthenticated',
476 $time, $d, $t )->parse() . '<br />';
477 $disableEmailPrefs = false;
478 $emailauthenticationclass = 'mw-email-authenticated';
480 $disableEmailPrefs = true;
481 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
483 SpecialPage
::getTitleFor( 'Confirmemail' ),
484 $context->msg( 'emailconfirmlink' )->escaped()
486 $emailauthenticationclass = "mw-email-not-authenticated";
489 $disableEmailPrefs = true;
490 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
491 $emailauthenticationclass = 'mw-email-none';
494 if ( $canViewPrivateInfo ) {
495 $defaultPreferences['emailauthentication'] = array(
498 'section' => 'personal/email',
499 'label-message' => 'prefs-emailconfirm-label',
500 'default' => $emailauthenticated,
501 # Apply the same CSS class used on the input to the message:
502 'cssclass' => $emailauthenticationclass,
504 $defaultPreferences['emailaddress']['cssclass'] = $emailauthenticationclass;
508 if ( $wgEnableUserEmail && $user->isAllowed( 'sendemail' ) ) {
509 $defaultPreferences['disablemail'] = array(
512 'section' => 'personal/email',
513 'label-message' => 'allowemail',
514 'disabled' => $disableEmailPrefs,
516 $defaultPreferences['ccmeonemails'] = array(
518 'section' => 'personal/email',
519 'label-message' => 'tog-ccmeonemails',
520 'disabled' => $disableEmailPrefs,
524 if ( $wgEnotifWatchlist ) {
525 $defaultPreferences['enotifwatchlistpages'] = array(
527 'section' => 'personal/email',
528 'label-message' => 'tog-enotifwatchlistpages',
529 'disabled' => $disableEmailPrefs,
532 if ( $wgEnotifUserTalk ) {
533 $defaultPreferences['enotifusertalkpages'] = array(
535 'section' => 'personal/email',
536 'label-message' => 'tog-enotifusertalkpages',
537 'disabled' => $disableEmailPrefs,
540 if ( $wgEnotifUserTalk ||
$wgEnotifWatchlist ) {
541 $defaultPreferences['enotifminoredits'] = array(
543 'section' => 'personal/email',
544 'label-message' => 'tog-enotifminoredits',
545 'disabled' => $disableEmailPrefs,
548 if ( $wgEnotifRevealEditorAddress ) {
549 $defaultPreferences['enotifrevealaddr'] = array(
551 'section' => 'personal/email',
552 'label-message' => 'tog-enotifrevealaddr',
553 'disabled' => $disableEmailPrefs,
562 * @param IContextSource $context
563 * @param array $defaultPreferences
566 static function skinPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
567 ## Skin #####################################
568 global $wgAllowUserCss, $wgAllowUserJs;
570 $defaultPreferences['skin'] = array(
572 'options' => self
::generateSkinOptions( $user, $context ),
574 'section' => 'rendering/skin',
577 # Create links to user CSS/JS pages for all skins
578 # This code is basically copied from generateSkinOptions(). It'd
579 # be nice to somehow merge this back in there to avoid redundancy.
580 if ( $wgAllowUserCss ||
$wgAllowUserJs ) {
581 $linkTools = array();
582 $userName = $user->getName();
584 if ( $wgAllowUserCss ) {
585 $cssPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.css' );
586 $linkTools[] = Linker
::link( $cssPage, $context->msg( 'prefs-custom-css' )->escaped() );
589 if ( $wgAllowUserJs ) {
590 $jsPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.js' );
591 $linkTools[] = Linker
::link( $jsPage, $context->msg( 'prefs-custom-js' )->escaped() );
594 $defaultPreferences['commoncssjs'] = array(
597 'default' => $context->getLanguage()->pipeList( $linkTools ),
598 'label-message' => 'prefs-common-css-js',
599 'section' => 'rendering/skin',
606 * @param IContextSource $context
607 * @param array $defaultPreferences
609 static function filesPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
610 ## Files #####################################
611 $defaultPreferences['imagesize'] = array(
613 'options' => self
::getImageSizes( $context ),
614 'label-message' => 'imagemaxsize',
615 'section' => 'rendering/files',
617 $defaultPreferences['thumbsize'] = array(
619 'options' => self
::getThumbSizes( $context ),
620 'label-message' => 'thumbsize',
621 'section' => 'rendering/files',
627 * @param IContextSource $context
628 * @param array $defaultPreferences
631 static function datetimePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
632 ## Date and time #####################################
633 $dateOptions = self
::getDateOptions( $context );
634 if ( $dateOptions ) {
635 $defaultPreferences['date'] = array(
637 'options' => $dateOptions,
639 'section' => 'rendering/dateformat',
644 $now = wfTimestampNow();
645 $lang = $context->getLanguage();
646 $nowlocal = Xml
::element( 'span', array( 'id' => 'wpLocalTime' ),
647 $lang->time( $now, true ) );
648 $nowserver = $lang->time( $now, false ) .
649 Html
::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 +
(int)substr( $now, 10, 2 ) );
651 $defaultPreferences['nowserver'] = array(
654 'label-message' => 'servertime',
655 'default' => $nowserver,
656 'section' => 'rendering/timeoffset',
659 $defaultPreferences['nowlocal'] = array(
662 'label-message' => 'localtime',
663 'default' => $nowlocal,
664 'section' => 'rendering/timeoffset',
667 // Grab existing pref.
668 $tzOffset = $user->getOption( 'timecorrection' );
669 $tz = explode( '|', $tzOffset, 3 );
671 $tzOptions = self
::getTimezoneOptions( $context );
673 $tzSetting = $tzOffset;
674 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
676 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) %
60 );
677 } elseif ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
678 !in_array( $tzOffset, HTMLFormField
::flattenOptions( $tzOptions ) )
680 # Timezone offset can vary with DST
681 $userTZ = timezone_open( $tz[2] );
682 if ( $userTZ !== false ) {
683 $minDiff = floor( timezone_offset_get( $userTZ, date_create( 'now' ) ) / 60 );
684 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
688 $defaultPreferences['timecorrection'] = array(
689 'class' => 'HTMLSelectOrOtherField',
690 'label-message' => 'timezonelegend',
691 'options' => $tzOptions,
692 'default' => $tzSetting,
694 'section' => 'rendering/timeoffset',
700 * @param IContextSource $context
701 * @param array $defaultPreferences
703 static function renderingPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
704 ## Diffs ####################################
705 $defaultPreferences['diffonly'] = array(
707 'section' => 'rendering/diffs',
708 'label-message' => 'tog-diffonly',
710 $defaultPreferences['norollbackdiff'] = array(
712 'section' => 'rendering/diffs',
713 'label-message' => 'tog-norollbackdiff',
716 ## Page Rendering ##############################
717 global $wgAllowUserCssPrefs;
718 if ( $wgAllowUserCssPrefs ) {
719 $defaultPreferences['underline'] = array(
722 $context->msg( 'underline-never' )->text() => 0,
723 $context->msg( 'underline-always' )->text() => 1,
724 $context->msg( 'underline-default' )->text() => 2,
726 'label-message' => 'tog-underline',
727 'section' => 'rendering/advancedrendering',
731 $stubThresholdValues = array( 50, 100, 500, 1000, 2000, 5000, 10000 );
732 $stubThresholdOptions = array( $context->msg( 'stub-threshold-disabled' )->text() => 0 );
733 foreach ( $stubThresholdValues as $value ) {
734 $stubThresholdOptions[$context->msg( 'size-bytes', $value )->text()] = $value;
737 $defaultPreferences['stubthreshold'] = array(
739 'section' => 'rendering/advancedrendering',
740 'options' => $stubThresholdOptions,
742 'label-raw' => $context->msg( 'stub-threshold' )->text(), // Raw HTML message. Yay?
745 $defaultPreferences['showhiddencats'] = array(
747 'section' => 'rendering/advancedrendering',
748 'label-message' => 'tog-showhiddencats'
751 $defaultPreferences['numberheadings'] = array(
753 'section' => 'rendering/advancedrendering',
754 'label-message' => 'tog-numberheadings',
760 * @param IContextSource $context
761 * @param array $defaultPreferences
763 static function editingPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
764 global $wgAllowUserCssPrefs;
766 ## Editing #####################################
767 $defaultPreferences['editsectiononrightclick'] = array(
769 'section' => 'editing/advancedediting',
770 'label-message' => 'tog-editsectiononrightclick',
772 $defaultPreferences['editondblclick'] = array(
774 'section' => 'editing/advancedediting',
775 'label-message' => 'tog-editondblclick',
778 if ( $wgAllowUserCssPrefs ) {
779 $defaultPreferences['editfont'] = array(
781 'section' => 'editing/editor',
782 'label-message' => 'editfont-style',
784 $context->msg( 'editfont-default' )->text() => 'default',
785 $context->msg( 'editfont-monospace' )->text() => 'monospace',
786 $context->msg( 'editfont-sansserif' )->text() => 'sans-serif',
787 $context->msg( 'editfont-serif' )->text() => 'serif',
791 $defaultPreferences['cols'] = array(
793 'label-message' => 'columns',
794 'section' => 'editing/editor',
798 $defaultPreferences['rows'] = array(
800 'label-message' => 'rows',
801 'section' => 'editing/editor',
805 if ( $user->isAllowed( 'minoredit' ) ) {
806 $defaultPreferences['minordefault'] = array(
808 'section' => 'editing/editor',
809 'label-message' => 'tog-minordefault',
812 $defaultPreferences['forceeditsummary'] = array(
814 'section' => 'editing/editor',
815 'label-message' => 'tog-forceeditsummary',
817 $defaultPreferences['useeditwarning'] = array(
819 'section' => 'editing/editor',
820 'label-message' => 'tog-useeditwarning',
822 $defaultPreferences['showtoolbar'] = array(
824 'section' => 'editing/editor',
825 'label-message' => 'tog-showtoolbar',
828 $defaultPreferences['previewonfirst'] = array(
830 'section' => 'editing/preview',
831 'label-message' => 'tog-previewonfirst',
833 $defaultPreferences['previewontop'] = array(
835 'section' => 'editing/preview',
836 'label-message' => 'tog-previewontop',
838 $defaultPreferences['uselivepreview'] = array(
840 'section' => 'editing/preview',
841 'label-message' => 'tog-uselivepreview',
848 * @param IContextSource $context
849 * @param array $defaultPreferences
851 static function rcPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
852 global $wgRCMaxAge, $wgRCShowWatchingUsers;
854 ## RecentChanges #####################################
855 $defaultPreferences['rcdays'] = array(
857 'label-message' => 'recentchangesdays',
858 'section' => 'rc/displayrc',
860 'max' => ceil( $wgRCMaxAge / ( 3600 * 24 ) ),
861 'help' => $context->msg( 'recentchangesdays-max' )->numParams(
862 ceil( $wgRCMaxAge / ( 3600 * 24 ) ) )->text()
864 $defaultPreferences['rclimit'] = array(
866 'label-message' => 'recentchangescount',
867 'help-message' => 'prefs-help-recentchangescount',
868 'section' => 'rc/displayrc',
870 $defaultPreferences['usenewrc'] = array(
872 'label-message' => 'tog-usenewrc',
873 'section' => 'rc/advancedrc',
875 $defaultPreferences['hideminor'] = array(
877 'label-message' => 'tog-hideminor',
878 'section' => 'rc/advancedrc',
881 if ( $user->useRCPatrol() ) {
882 $defaultPreferences['hidepatrolled'] = array(
884 'section' => 'rc/advancedrc',
885 'label-message' => 'tog-hidepatrolled',
887 $defaultPreferences['newpageshidepatrolled'] = array(
889 'section' => 'rc/advancedrc',
890 'label-message' => 'tog-newpageshidepatrolled',
894 if ( $wgRCShowWatchingUsers ) {
895 $defaultPreferences['shownumberswatching'] = array(
897 'section' => 'rc/advancedrc',
898 'label-message' => 'tog-shownumberswatching',
905 * @param IContextSource $context
906 * @param array $defaultPreferences
908 static function watchlistPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
909 global $wgUseRCPatrol, $wgEnableAPI, $wgRCMaxAge;
911 $watchlistdaysMax = ceil( $wgRCMaxAge / ( 3600 * 24 ) );
913 ## Watchlist #####################################
914 $defaultPreferences['watchlistdays'] = array(
917 'max' => $watchlistdaysMax,
918 'section' => 'watchlist/displaywatchlist',
919 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
920 $watchlistdaysMax )->text(),
921 'label-message' => 'prefs-watchlist-days',
923 $defaultPreferences['wllimit'] = array(
927 'label-message' => 'prefs-watchlist-edits',
928 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
929 'section' => 'watchlist/displaywatchlist',
931 $defaultPreferences['extendwatchlist'] = array(
933 'section' => 'watchlist/advancedwatchlist',
934 'label-message' => 'tog-extendwatchlist',
936 $defaultPreferences['watchlisthideminor'] = array(
938 'section' => 'watchlist/advancedwatchlist',
939 'label-message' => 'tog-watchlisthideminor',
941 $defaultPreferences['watchlisthidebots'] = array(
943 'section' => 'watchlist/advancedwatchlist',
944 'label-message' => 'tog-watchlisthidebots',
946 $defaultPreferences['watchlisthideown'] = array(
948 'section' => 'watchlist/advancedwatchlist',
949 'label-message' => 'tog-watchlisthideown',
951 $defaultPreferences['watchlisthideanons'] = array(
953 'section' => 'watchlist/advancedwatchlist',
954 'label-message' => 'tog-watchlisthideanons',
956 $defaultPreferences['watchlisthideliu'] = array(
958 'section' => 'watchlist/advancedwatchlist',
959 'label-message' => 'tog-watchlisthideliu',
962 if ( $wgUseRCPatrol ) {
963 $defaultPreferences['watchlisthidepatrolled'] = array(
965 'section' => 'watchlist/advancedwatchlist',
966 'label-message' => 'tog-watchlisthidepatrolled',
971 'edit' => 'watchdefault',
972 'move' => 'watchmoves',
973 'delete' => 'watchdeletion'
977 if ( $user->isAllowed( 'createpage' ) ||
$user->isAllowed( 'createtalk' ) ) {
978 $watchTypes['read'] = 'watchcreations';
981 foreach ( $watchTypes as $action => $pref ) {
982 if ( $user->isAllowed( $action ) ) {
984 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations
985 $defaultPreferences[$pref] = array(
987 'section' => 'watchlist/advancedwatchlist',
988 'label-message' => "tog-$pref",
993 if ( $wgEnableAPI ) {
994 $defaultPreferences['watchlisttoken'] = array(
997 $defaultPreferences['watchlisttoken-info'] = array(
999 'section' => 'watchlist/tokenwatchlist',
1000 'label-message' => 'prefs-watchlist-token',
1001 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1002 'help-message' => 'prefs-help-watchlist-token2',
1009 * @param IContextSource $context
1010 * @param array $defaultPreferences
1012 static function searchPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
1013 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
1014 $defaultPreferences[ 'searchNs' . $n ] = array(
1021 * Dummy, kept for backwards-compatibility.
1023 static function miscPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
1027 * @param User $user The User object
1028 * @param IContextSource $context
1029 * @return array Text/links to display as key; $skinkey as value
1031 static function generateSkinOptions( $user, IContextSource
$context ) {
1032 global $wgDefaultSkin, $wgAllowUserCss, $wgAllowUserJs;
1035 $mptitle = Title
::newMainPage();
1036 $previewtext = $context->msg( 'skin-preview' )->text();
1038 # Only show skins that aren't disabled in $wgSkipSkins
1039 $validSkinNames = Skin
::getAllowedSkins();
1041 # Sort by UI skin name. First though need to update validSkinNames as sometimes
1042 # the skinkey & UI skinname differ (e.g. "standard" skinkey is "Classic" in the UI).
1043 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1044 $msg = $context->msg( "skinname-{$skinkey}" );
1045 if ( $msg->exists() ) {
1046 $skinname = htmlspecialchars( $msg->text() );
1049 asort( $validSkinNames );
1051 foreach ( $validSkinNames as $skinkey => $sn ) {
1052 $linkTools = array();
1054 # Mark the default skin
1055 if ( $skinkey == $wgDefaultSkin ) {
1056 $linkTools[] = $context->msg( 'default' )->escaped();
1059 # Create preview link
1060 $mplink = htmlspecialchars( $mptitle->getLocalURL( array( 'useskin' => $skinkey ) ) );
1061 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1063 # Create links to user CSS/JS pages
1064 if ( $wgAllowUserCss ) {
1065 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1066 $linkTools[] = Linker
::link( $cssPage, $context->msg( 'prefs-custom-css' )->escaped() );
1069 if ( $wgAllowUserJs ) {
1070 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1071 $linkTools[] = Linker
::link( $jsPage, $context->msg( 'prefs-custom-js' )->escaped() );
1074 $display = $sn . ' ' . $context->msg(
1076 $context->getLanguage()->pipeList( $linkTools )
1078 $ret[$display] = $skinkey;
1085 * @param IContextSource $context
1088 static function getDateOptions( IContextSource
$context ) {
1089 $lang = $context->getLanguage();
1090 $dateopts = $lang->getDatePreferences();
1095 if ( !in_array( 'default', $dateopts ) ) {
1096 $dateopts[] = 'default'; // Make sure default is always valid
1100 // KLUGE: site default might not be valid for user language
1101 global $wgDefaultUserOptions;
1102 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1103 $wgDefaultUserOptions['date'] = 'default';
1106 $epoch = wfTimestampNow();
1107 foreach ( $dateopts as $key ) {
1108 if ( $key == 'default' ) {
1109 $formatted = $context->msg( 'datedefault' )->escaped();
1111 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1113 $ret[$formatted] = $key;
1120 * @param IContextSource $context
1123 static function getImageSizes( IContextSource
$context ) {
1124 global $wgImageLimits;
1127 $pixels = $context->msg( 'unit-pixel' )->text();
1129 foreach ( $wgImageLimits as $index => $limits ) {
1130 $display = "{$limits[0]}×{$limits[1]}" . $pixels;
1131 $ret[$display] = $index;
1138 * @param IContextSource $context
1141 static function getThumbSizes( IContextSource
$context ) {
1142 global $wgThumbLimits;
1145 $pixels = $context->msg( 'unit-pixel' )->text();
1147 foreach ( $wgThumbLimits as $index => $size ) {
1148 $display = $size . $pixels;
1149 $ret[$display] = $index;
1156 * @param string $signature
1157 * @param array $alldata
1158 * @param HTMLForm $form
1159 * @return bool|string
1161 static function validateSignature( $signature, $alldata, $form ) {
1162 global $wgParser, $wgMaxSigChars;
1163 if ( mb_strlen( $signature ) > $wgMaxSigChars ) {
1164 return Xml
::element( 'span', array( 'class' => 'error' ),
1165 $form->msg( 'badsiglength' )->numParams( $wgMaxSigChars )->text() );
1166 } elseif ( isset( $alldata['fancysig'] ) &&
1167 $alldata['fancysig'] &&
1168 $wgParser->validateSig( $signature ) === false
1170 return Xml
::element(
1172 array( 'class' => 'error' ),
1173 $form->msg( 'badsig' )->text()
1181 * @param string $signature
1182 * @param array $alldata
1183 * @param HTMLForm $form
1186 static function cleanSignature( $signature, $alldata, $form ) {
1187 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1189 $signature = $wgParser->cleanSig( $signature );
1191 // When no fancy sig used, make sure ~{3,5} get removed.
1192 $signature = Parser
::cleanSigInSig( $signature );
1200 * @param IContextSource $context
1201 * @param string $formClass
1202 * @param array $remove Array of items to remove
1205 static function getFormObject(
1207 IContextSource
$context,
1208 $formClass = 'PreferencesForm',
1209 array $remove = array()
1211 $formDescriptor = Preferences
::getPreferences( $user, $context );
1212 if ( count( $remove ) ) {
1213 $removeKeys = array_flip( $remove );
1214 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1217 // Remove type=api preferences. They are not intended for rendering in the form.
1218 foreach ( $formDescriptor as $name => $info ) {
1219 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1220 unset( $formDescriptor[$name] );
1225 * @var $htmlForm PreferencesForm
1227 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1229 $htmlForm->setModifiedUser( $user );
1230 $htmlForm->setId( 'mw-prefs-form' );
1231 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1232 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1233 $htmlForm->setSubmitTooltip( 'preferences-save' );
1234 $htmlForm->setSubmitID( 'prefsubmit' );
1235 $htmlForm->setSubmitCallback( array( 'Preferences', 'tryFormSubmit' ) );
1241 * @param IContextSource $context
1244 static function getTimezoneOptions( IContextSource
$context ) {
1247 global $wgLocalTZoffset;
1248 $timestamp = MWTimestamp
::getLocalInstance();
1249 // Check that $wgLocalTZoffset is the same as the local time zone offset
1250 if ( $wgLocalTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1251 $server_tz_msg = $context->msg(
1252 'timezoneuseserverdefault',
1253 $timestamp->getTimezone()->getName()
1256 $tzstring = sprintf(
1258 floor( $wgLocalTZoffset / 60 ),
1259 abs( $wgLocalTZoffset ) %
60
1261 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1263 $opt[$server_tz_msg] = "System|$wgLocalTZoffset";
1264 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1265 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1267 if ( function_exists( 'timezone_identifiers_list' ) ) {
1268 # Read timezone list
1269 $tzs = timezone_identifiers_list();
1272 $tzRegions = array();
1273 $tzRegions['Africa'] = $context->msg( 'timezoneregion-africa' )->text();
1274 $tzRegions['America'] = $context->msg( 'timezoneregion-america' )->text();
1275 $tzRegions['Antarctica'] = $context->msg( 'timezoneregion-antarctica' )->text();
1276 $tzRegions['Arctic'] = $context->msg( 'timezoneregion-arctic' )->text();
1277 $tzRegions['Asia'] = $context->msg( 'timezoneregion-asia' )->text();
1278 $tzRegions['Atlantic'] = $context->msg( 'timezoneregion-atlantic' )->text();
1279 $tzRegions['Australia'] = $context->msg( 'timezoneregion-australia' )->text();
1280 $tzRegions['Europe'] = $context->msg( 'timezoneregion-europe' )->text();
1281 $tzRegions['Indian'] = $context->msg( 'timezoneregion-indian' )->text();
1282 $tzRegions['Pacific'] = $context->msg( 'timezoneregion-pacific' )->text();
1283 asort( $tzRegions );
1285 $prefill = array_fill_keys( array_values( $tzRegions ), array() );
1286 $opt = array_merge( $opt, $prefill );
1288 $now = date_create( 'now' );
1290 foreach ( $tzs as $tz ) {
1291 $z = explode( '/', $tz, 2 );
1293 # timezone_identifiers_list() returns a number of
1294 # backwards-compatibility entries. This filters them out of the
1295 # list presented to the user.
1296 if ( count( $z ) != 2 ||
!array_key_exists( $z[0], $tzRegions ) ) {
1301 $z[0] = $tzRegions[$z[0]];
1303 $minDiff = floor( timezone_offset_get( timezone_open( $tz ), $now ) / 60 );
1305 $display = str_replace( '_', ' ', $z[0] . '/' . $z[1] );
1306 $value = "ZoneInfo|$minDiff|$tz";
1308 $opt[$z[0]][$display] = $value;
1315 * @param string $value
1316 * @param array $alldata
1319 static function filterIntval( $value, $alldata ) {
1320 return intval( $value );
1325 * @param array $alldata
1328 static function filterTimezoneInput( $tz, $alldata ) {
1329 $data = explode( '|', $tz, 3 );
1330 switch ( $data[0] ) {
1335 $data = explode( ':', $tz, 2 );
1336 if ( count( $data ) == 2 ) {
1337 $data[0] = intval( $data[0] );
1338 $data[1] = intval( $data[1] );
1339 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1340 if ( $data[0] < 0 ) {
1341 $minDiff = - $minDiff;
1344 $minDiff = intval( $data[0] ) * 60;
1347 # Max is +14:00 and min is -12:00, see:
1348 # http://en.wikipedia.org/wiki/Timezone
1349 $minDiff = min( $minDiff, 840 ); # 14:00
1350 $minDiff = max( $minDiff, - 720 ); # -12:00
1351 return 'Offset|' . $minDiff;
1356 * Handle the form submission if everything validated properly
1358 * @param array $formData
1359 * @param PreferencesForm $form
1360 * @return bool|Status|string
1362 static function tryFormSubmit( $formData, $form ) {
1363 global $wgHiddenPrefs, $wgAuth;
1365 $user = $form->getModifiedUser();
1368 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1369 return Status
::newFatal( 'mypreferencesprotected' );
1373 foreach ( array_keys( $formData ) as $name ) {
1374 if ( isset( self
::$saveFilters[$name] ) ) {
1376 call_user_func( self
::$saveFilters[$name], $formData[$name], $formData );
1380 // Fortunately, the realname field is MUCH simpler
1381 // (not really "private", but still shouldn't be edited without permission)
1382 if ( !in_array( 'realname', $wgHiddenPrefs )
1383 && $user->isAllowed( 'editmyprivateinfo' )
1384 && array_key_exists( 'realname', $formData )
1386 $realName = $formData['realname'];
1387 $user->setRealName( $realName );
1390 if ( $user->isAllowed( 'editmyoptions' ) ) {
1391 foreach ( self
::$saveBlacklist as $b ) {
1392 unset( $formData[$b] );
1395 # If users have saved a value for a preference which has subsequently been disabled
1396 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1397 # is subsequently re-enabled
1398 foreach ( $wgHiddenPrefs as $pref ) {
1399 # If the user has not set a non-default value here, the default will be returned
1400 # and subsequently discarded
1401 $formData[$pref] = $user->getOption( $pref, null, true );
1404 // Keep old preferences from interfering due to back-compat code, etc.
1405 $user->resetOptions( 'unused', $form->getContext() );
1407 foreach ( $formData as $key => $value ) {
1408 $user->setOption( $key, $value );
1411 wfRunHooks( 'PreferencesFormPreSave', array( $formData, $form, $user, &$result ) );
1412 $user->saveSettings();
1415 $wgAuth->updateExternalDB( $user );
1421 * @param array $formData
1422 * @param PreferencesForm $form
1425 public static function tryUISubmit( $formData, $form ) {
1426 $res = self
::tryFormSubmit( $formData, $form );
1429 $urlOptions = array( 'success' => 1 );
1431 if ( $res === 'eauth' ) {
1432 $urlOptions['eauth'] = 1;
1435 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1437 $url = $form->getTitle()->getFullURL( $urlOptions );
1439 $form->getContext()->getOutput()->redirect( $url );
1442 return Status
::newGood();
1446 * Try to set a user's email address.
1447 * This does *not* try to validate the address.
1448 * Caller is responsible for checking $wgAuth and 'editmyprivateinfo'
1451 * @deprecated since 1.20; use User::setEmailWithConfirmation() instead.
1453 * @param string $newaddr New email address
1454 * @return array (true on success or Status on failure, info string)
1456 public static function trySetUserEmail( User
$user, $newaddr ) {
1457 wfDeprecated( __METHOD__
, '1.20' );
1459 $result = $user->setEmailWithConfirmation( $newaddr );
1460 if ( $result->isGood() ) {
1461 return array( true, $result->value
);
1463 return array( $result, 'mailerror' );
1468 * @deprecated since 1.19
1472 public static function loadOldSearchNs( $user ) {
1473 wfDeprecated( __METHOD__
, '1.19' );
1475 $searchableNamespaces = SearchEngine
::searchableNamespaces();
1476 // Back compat with old format
1479 foreach ( $searchableNamespaces as $ns => $name ) {
1480 if ( $user->getOption( 'searchNs' . $ns ) ) {
1489 /** Some tweaks to allow js prefs to work */
1490 class PreferencesForm
extends HTMLForm
{
1491 // Override default value from HTMLForm
1492 protected $mSubSectionBeforeFields = false;
1494 private $modifiedUser;
1499 public function setModifiedUser( $user ) {
1500 $this->modifiedUser
= $user;
1506 public function getModifiedUser() {
1507 if ( $this->modifiedUser
=== null ) {
1508 return $this->getUser();
1510 return $this->modifiedUser
;
1515 * Get extra parameters for the query string when redirecting after
1520 public function getExtraSuccessRedirectParameters() {
1525 * @param string $html
1528 function wrapForm( $html ) {
1529 $html = Xml
::tags( 'div', array( 'id' => 'preferences' ), $html );
1531 return parent
::wrapForm( $html );
1537 function getButtons() {
1538 if ( !$this->getModifiedUser()->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1542 $html = parent
::getButtons();
1544 if ( $this->getModifiedUser()->isAllowed( 'editmyoptions' ) ) {
1545 $t = SpecialPage
::getTitleFor( 'Preferences', 'reset' );
1547 $html .= "\n" . Linker
::link( $t, $this->msg( 'restoreprefs' )->escaped() );
1549 $html = Xml
::tags( 'div', array( 'class' => 'mw-prefs-buttons' ), $html );
1556 * Separate multi-option preferences into multiple preferences, since we
1557 * have to store them separately
1558 * @param array $data
1561 function filterDataForSubmit( $data ) {
1562 foreach ( $this->mFlatFields
as $fieldname => $field ) {
1563 if ( $field instanceof HTMLNestedFilterable
) {
1564 $info = $field->mParams
;
1565 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $fieldname;
1566 foreach ( $field->filterDataForSubmit( $data[$fieldname] ) as $key => $value ) {
1567 $data["$prefix$key"] = $value;
1569 unset( $data[$fieldname] );
1577 * Get the whole body of the form.
1580 function getBody() {
1581 return $this->displaySection( $this->mFieldTree
, '', 'mw-prefsection-' );
1585 * Get the "<legend>" for a given section key. Normally this is the
1586 * prefs-$key message but we'll allow extensions to override it.
1587 * @param string $key
1590 function getLegend( $key ) {
1591 $legend = parent
::getLegend( $key );
1592 wfRunHooks( 'PreferencesGetLegend', array( $this, $key, &$legend ) );