Allow more than one variant set in user preferences.
[lhc/web/wiklou.git] / includes / Preferences.php
1 <?php
2 /**
3 * Form to edit user preferences.
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22
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.
28 *
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).
40 *
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.
44 *
45 * Once fields have been retrieved and validated, submission logic is handed
46 * over to the tryUISubmit static method of this class.
47 */
48 class Preferences {
49 static $defaultPreferences = null;
50 static $saveFilters = array(
51 'timecorrection' => array( 'Preferences', 'filterTimezoneInput' ),
52 'cols' => array( 'Preferences', 'filterIntval' ),
53 'rows' => array( 'Preferences', 'filterIntval' ),
54 'rclimit' => array( 'Preferences', 'filterIntval' ),
55 'wllimit' => array( 'Preferences', 'filterIntval' ),
56 'searchlimit' => array( 'Preferences', 'filterIntval' ),
57 );
58
59 // Stuff that shouldn't be saved as a preference.
60 private static $saveBlacklist = array(
61 'realname',
62 'emailaddress',
63 );
64
65 /**
66 * @throws MWException
67 * @param $user User
68 * @param $context IContextSource
69 * @return array|null
70 */
71 static function getPreferences( $user, IContextSource $context ) {
72 if ( self::$defaultPreferences ) {
73 return self::$defaultPreferences;
74 }
75
76 $defaultPreferences = array();
77
78 self::profilePreferences( $user, $context, $defaultPreferences );
79 self::skinPreferences( $user, $context, $defaultPreferences );
80 self::filesPreferences( $user, $context, $defaultPreferences );
81 self::datetimePreferences( $user, $context, $defaultPreferences );
82 self::renderingPreferences( $user, $context, $defaultPreferences );
83 self::editingPreferences( $user, $context, $defaultPreferences );
84 self::rcPreferences( $user, $context, $defaultPreferences );
85 self::watchlistPreferences( $user, $context, $defaultPreferences );
86 self::searchPreferences( $user, $context, $defaultPreferences );
87 self::miscPreferences( $user, $context, $defaultPreferences );
88
89 wfRunHooks( 'GetPreferences', array( $user, &$defaultPreferences ) );
90
91 ## Remove preferences that wikis don't want to use
92 global $wgHiddenPrefs;
93 foreach ( $wgHiddenPrefs as $pref ) {
94 if ( isset( $defaultPreferences[$pref] ) ) {
95 unset( $defaultPreferences[$pref] );
96 }
97 }
98
99 ## Make sure that form fields have their parent set. See bug 41337.
100 $dummyForm = new HTMLForm( array(), $context );
101
102 $disable = !$user->isAllowed( 'editmyoptions' );
103
104 ## Prod in defaults from the user
105 foreach ( $defaultPreferences as $name => &$info ) {
106 $prefFromUser = self::getOptionFromUser( $name, $info, $user );
107 if ( $disable && !in_array( $name, self::$saveBlacklist ) ) {
108 $info['disabled'] = 'disabled';
109 }
110 $field = HTMLForm::loadInputFromParameters( $name, $info ); // For validation
111 $field->mParent = $dummyForm;
112 $defaultOptions = User::getDefaultOptions();
113 $globalDefault = isset( $defaultOptions[$name] )
114 ? $defaultOptions[$name]
115 : null;
116
117 // If it validates, set it as the default
118 if ( isset( $info['default'] ) ) {
119 // Already set, no problem
120 continue;
121 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
122 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
123 $info['default'] = $prefFromUser;
124 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
125 $info['default'] = $globalDefault;
126 } else {
127 throw new MWException( "Global default '$globalDefault' is invalid for field $name" );
128 }
129 }
130
131 self::$defaultPreferences = $defaultPreferences;
132
133 return $defaultPreferences;
134 }
135
136 /**
137 * Pull option from a user account. Handles stuff like array-type preferences.
138 *
139 * @param $name
140 * @param $info
141 * @param $user User
142 * @return array|String
143 */
144 static function getOptionFromUser( $name, $info, $user ) {
145 $val = $user->getOption( $name );
146
147 // Handling for multiselect preferences
148 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
149 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
150 $options = HTMLFormField::flattenOptions( $info['options'] );
151 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
152 $val = array();
153
154 foreach ( $options as $value ) {
155 if ( $user->getOption( "$prefix$value" ) ) {
156 $val[] = $value;
157 }
158 }
159 }
160
161 // Handling for checkmatrix preferences
162 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
163 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
164 $columns = HTMLFormField::flattenOptions( $info['columns'] );
165 $rows = HTMLFormField::flattenOptions( $info['rows'] );
166 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
167 $val = array();
168
169 foreach ( $columns as $column ) {
170 foreach ( $rows as $row ) {
171 if ( $user->getOption( "$prefix$column-$row" ) ) {
172 $val[] = "$column-$row";
173 }
174 }
175 }
176 }
177
178 return $val;
179 }
180
181 /**
182 * @param $user User
183 * @param $context IContextSource
184 * @param $defaultPreferences
185 * @return void
186 */
187 static function profilePreferences( $user, IContextSource $context, &$defaultPreferences ) {
188 global $wgAuth, $wgContLang, $wgParser, $wgCookieExpiration, $wgLanguageCode,
189 $wgDisableTitleConversion, $wgDisableLangConversion, $wgMaxSigChars,
190 $wgEnableEmail, $wgEmailConfirmToEdit, $wgEnableUserEmail, $wgEmailAuthentication,
191 $wgEnotifWatchlist, $wgEnotifUserTalk, $wgEnotifRevealEditorAddress;
192
193 // retrieving user name for GENDER and misc.
194 $userName = $user->getName();
195
196 ## User info #####################################
197 // Information panel
198 $defaultPreferences['username'] = array(
199 'type' => 'info',
200 'label-message' => array( 'username', $userName ),
201 'default' => $userName,
202 'section' => 'personal/info',
203 );
204
205 $defaultPreferences['userid'] = array(
206 'type' => 'info',
207 'label-message' => array( 'uid', $userName ),
208 'default' => $user->getId(),
209 'section' => 'personal/info',
210 );
211
212 # Get groups to which the user belongs
213 $userEffectiveGroups = $user->getEffectiveGroups();
214 $userGroups = $userMembers = array();
215 foreach ( $userEffectiveGroups as $ueg ) {
216 if ( $ueg == '*' ) {
217 // Skip the default * group, seems useless here
218 continue;
219 }
220 $groupName = User::getGroupName( $ueg );
221 $userGroups[] = User::makeGroupLinkHTML( $ueg, $groupName );
222
223 $memberName = User::getGroupMember( $ueg, $userName );
224 $userMembers[] = User::makeGroupLinkHTML( $ueg, $memberName );
225 }
226 asort( $userGroups );
227 asort( $userMembers );
228
229 $lang = $context->getLanguage();
230
231 $defaultPreferences['usergroups'] = array(
232 'type' => 'info',
233 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
234 count( $userGroups ) )->params( $userName )->parse(),
235 'default' => $context->msg( 'prefs-memberingroups-type',
236 $lang->commaList( $userGroups ),
237 $lang->commaList( $userMembers )
238 )->plain(),
239 'raw' => true,
240 'section' => 'personal/info',
241 );
242
243 $editCount = Linker::link( SpecialPage::getTitleFor( "Contributions", $userName ),
244 $lang->formatNum( $user->getEditCount() ) );
245
246 $defaultPreferences['editcount'] = array(
247 'type' => 'info',
248 'raw' => true,
249 'label-message' => 'prefs-edits',
250 'default' => $editCount,
251 'section' => 'personal/info',
252 );
253
254 if ( $user->getRegistration() ) {
255 $displayUser = $context->getUser();
256 $userRegistration = $user->getRegistration();
257 $defaultPreferences['registrationdate'] = array(
258 'type' => 'info',
259 'label-message' => 'prefs-registration',
260 'default' => $context->msg(
261 'prefs-registration-date-time',
262 $lang->userTimeAndDate( $userRegistration, $displayUser ),
263 $lang->userDate( $userRegistration, $displayUser ),
264 $lang->userTime( $userRegistration, $displayUser )
265 )->parse(),
266 'section' => 'personal/info',
267 );
268 }
269
270 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
271 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
272
273 // Actually changeable stuff
274 $defaultPreferences['realname'] = array(
275 // (not really "private", but still shouldn't be edited without permission)
276 'type' => $canEditPrivateInfo && $wgAuth->allowPropChange( 'realname' ) ? 'text' : 'info',
277 'default' => $user->getRealName(),
278 'section' => 'personal/info',
279 'label-message' => 'yourrealname',
280 'help-message' => 'prefs-help-realname',
281 );
282
283 $defaultPreferences['gender'] = array(
284 'type' => 'select',
285 'section' => 'personal/info',
286 'options' => array(
287 $context->msg( 'gender-male' )->text() => 'male',
288 $context->msg( 'gender-female' )->text() => 'female',
289 $context->msg( 'gender-unknown' )->text() => 'unknown',
290 ),
291 'label-message' => 'yourgender',
292 'help-message' => 'prefs-help-gender',
293 );
294
295 if ( $canEditPrivateInfo && $wgAuth->allowPasswordChange() ) {
296 $link = Linker::link( SpecialPage::getTitleFor( 'ChangePassword' ),
297 $context->msg( 'prefs-resetpass' )->escaped(), array(),
298 array( 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText() ) );
299
300 $defaultPreferences['password'] = array(
301 'type' => 'info',
302 'raw' => true,
303 'default' => $link,
304 'label-message' => 'yourpassword',
305 'section' => 'personal/info',
306 );
307 }
308 if ( $wgCookieExpiration > 0 ) {
309 $defaultPreferences['rememberpassword'] = array(
310 'type' => 'toggle',
311 'label' => $context->msg( 'tog-rememberpassword' )->numParams(
312 ceil( $wgCookieExpiration / ( 3600 * 24 ) ) )->text(),
313 'section' => 'personal/info',
314 );
315 }
316
317 // Language
318 $languages = Language::fetchLanguageNames( null, 'mw' );
319 if ( !array_key_exists( $wgLanguageCode, $languages ) ) {
320 $languages[$wgLanguageCode] = $wgLanguageCode;
321 }
322 ksort( $languages );
323
324 $options = array();
325 foreach ( $languages as $code => $name ) {
326 $display = wfBCP47( $code ) . ' - ' . $name;
327 $options[$display] = $code;
328 }
329 $defaultPreferences['language'] = array(
330 'type' => 'select',
331 'section' => 'personal/i18n',
332 'options' => $options,
333 'label-message' => 'yourlanguage',
334 );
335
336 // see if there are multiple language variants to choose from
337 if ( !$wgDisableLangConversion ) {
338 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
339 if ( $langCode == $wgContLang->getCode() ) {
340 $variants = $wgContLang->getVariants();
341
342 if ( count( $variants ) <= 1 ) {
343 continue;
344 }
345
346 $variantArray = array();
347 foreach ( $variants as $v ) {
348 $v = str_replace( '_', '-', strtolower( $v ) );
349 $variantArray[$v] = $lang->getVariantname( $v, false );
350 }
351
352 $options = array();
353 foreach ( $variantArray as $code => $name ) {
354 $display = wfBCP47( $code ) . ' - ' . $name;
355 $options[$display] = $code;
356 }
357
358 $defaultPreferences['variant'] = array(
359 'label-message' => 'yourvariant',
360 'type' => 'select',
361 'options' => $options,
362 'section' => 'personal/i18n',
363 'help-message' => 'prefs-help-variant',
364 );
365
366 if ( !$wgDisableTitleConversion ) {
367 $defaultPreferences['noconvertlink'] = array(
368 'type' => 'toggle',
369 'section' => 'personal/i18n',
370 'label-message' => 'tog-noconvertlink',
371 );
372 }
373 } else {
374 $defaultPreferences["variant-$langCode"] = array(
375 'type' => 'api',
376 );
377 }
378 }
379 }
380
381 // show a preview of the old signature first
382 $oldsigWikiText = $wgParser->preSaveTransform( "~~~", $context->getTitle(), $user, ParserOptions::newFromContext( $context ) );
383 $oldsigHTML = $context->getOutput()->parseInline( $oldsigWikiText, true, true );
384 $defaultPreferences['oldsig'] = array(
385 'type' => 'info',
386 'raw' => true,
387 'label-message' => 'tog-oldsig',
388 'default' => $oldsigHTML,
389 'section' => 'personal/signature',
390 );
391 $defaultPreferences['nickname'] = array(
392 'type' => $wgAuth->allowPropChange( 'nickname' ) ? 'text' : 'info',
393 'maxlength' => $wgMaxSigChars,
394 'label-message' => 'yournick',
395 'validation-callback' => array( 'Preferences', 'validateSignature' ),
396 'section' => 'personal/signature',
397 'filter-callback' => array( 'Preferences', 'cleanSignature' ),
398 );
399 $defaultPreferences['fancysig'] = array(
400 'type' => 'toggle',
401 'label-message' => 'tog-fancysig',
402 'help-message' => 'prefs-help-signature', // show general help about signature at the bottom of the section
403 'section' => 'personal/signature'
404 );
405
406 ## Email stuff
407
408 if ( $wgEnableEmail ) {
409 if ( $canViewPrivateInfo ) {
410 $helpMessages[] = $wgEmailConfirmToEdit
411 ? 'prefs-help-email-required'
412 : 'prefs-help-email';
413
414 if ( $wgEnableUserEmail ) {
415 // additional messages when users can send email to each other
416 $helpMessages[] = 'prefs-help-email-others';
417 }
418
419 $emailAddress = $user->getEmail() ? htmlspecialchars( $user->getEmail() ) : '';
420 if ( $canEditPrivateInfo && $wgAuth->allowPropChange( 'emailaddress' ) ) {
421 $link = Linker::link(
422 SpecialPage::getTitleFor( 'ChangeEmail' ),
423 $context->msg( $user->getEmail() ? 'prefs-changeemail' : 'prefs-setemail' )->escaped(),
424 array(),
425 array( 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText() ) );
426
427 $emailAddress .= $emailAddress == '' ? $link : (
428 $context->msg( 'word-separator' )->plain()
429 . $context->msg( 'parentheses' )->rawParams( $link )->plain()
430 );
431 }
432
433 $defaultPreferences['emailaddress'] = array(
434 'type' => 'info',
435 'raw' => true,
436 'default' => $emailAddress,
437 'label-message' => 'youremail',
438 'section' => 'personal/email',
439 'help-messages' => $helpMessages,
440 # 'cssclass' chosen below
441 );
442 }
443
444 $disableEmailPrefs = false;
445
446 if ( $wgEmailAuthentication ) {
447 $emailauthenticationclass = 'mw-email-not-authenticated';
448 if ( $user->getEmail() ) {
449 if ( $user->getEmailAuthenticationTimestamp() ) {
450 // date and time are separate parameters to facilitate localisation.
451 // $time is kept for backward compat reasons.
452 // 'emailauthenticated' is also used in SpecialConfirmemail.php
453 $displayUser = $context->getUser();
454 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
455 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
456 $d = $lang->userDate( $emailTimestamp, $displayUser );
457 $t = $lang->userTime( $emailTimestamp, $displayUser );
458 $emailauthenticated = $context->msg( 'emailauthenticated',
459 $time, $d, $t )->parse() . '<br />';
460 $disableEmailPrefs = false;
461 $emailauthenticationclass = 'mw-email-authenticated';
462 } else {
463 $disableEmailPrefs = true;
464 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
465 Linker::linkKnown(
466 SpecialPage::getTitleFor( 'Confirmemail' ),
467 $context->msg( 'emailconfirmlink' )->escaped()
468 ) . '<br />';
469 $emailauthenticationclass = "mw-email-not-authenticated";
470 }
471 } else {
472 $disableEmailPrefs = true;
473 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
474 $emailauthenticationclass = 'mw-email-none';
475 }
476
477 if ( $canViewPrivateInfo ) {
478 $defaultPreferences['emailauthentication'] = array(
479 'type' => 'info',
480 'raw' => true,
481 'section' => 'personal/email',
482 'label-message' => 'prefs-emailconfirm-label',
483 'default' => $emailauthenticated,
484 # Apply the same CSS class used on the input to the message:
485 'cssclass' => $emailauthenticationclass,
486 );
487 $defaultPreferences['emailaddress']['cssclass'] = $emailauthenticationclass;
488 }
489 }
490
491 if ( $wgEnableUserEmail && $user->isAllowed( 'sendemail' ) ) {
492 $defaultPreferences['disablemail'] = array(
493 'type' => 'toggle',
494 'invert' => true,
495 'section' => 'personal/email',
496 'label-message' => 'allowemail',
497 'disabled' => $disableEmailPrefs,
498 );
499 $defaultPreferences['ccmeonemails'] = array(
500 'type' => 'toggle',
501 'section' => 'personal/email',
502 'label-message' => 'tog-ccmeonemails',
503 'disabled' => $disableEmailPrefs,
504 );
505 }
506
507 if ( $wgEnotifWatchlist ) {
508 $defaultPreferences['enotifwatchlistpages'] = array(
509 'type' => 'toggle',
510 'section' => 'personal/email',
511 'label-message' => 'tog-enotifwatchlistpages',
512 'disabled' => $disableEmailPrefs,
513 );
514 }
515 if ( $wgEnotifUserTalk ) {
516 $defaultPreferences['enotifusertalkpages'] = array(
517 'type' => 'toggle',
518 'section' => 'personal/email',
519 'label-message' => 'tog-enotifusertalkpages',
520 'disabled' => $disableEmailPrefs,
521 );
522 }
523 if ( $wgEnotifUserTalk || $wgEnotifWatchlist ) {
524 $defaultPreferences['enotifminoredits'] = array(
525 'type' => 'toggle',
526 'section' => 'personal/email',
527 'label-message' => 'tog-enotifminoredits',
528 'disabled' => $disableEmailPrefs,
529 );
530
531 if ( $wgEnotifRevealEditorAddress ) {
532 $defaultPreferences['enotifrevealaddr'] = array(
533 'type' => 'toggle',
534 'section' => 'personal/email',
535 'label-message' => 'tog-enotifrevealaddr',
536 'disabled' => $disableEmailPrefs,
537 );
538 }
539 }
540 }
541 }
542
543 /**
544 * @param $user User
545 * @param $context IContextSource
546 * @param $defaultPreferences
547 * @return void
548 */
549 static function skinPreferences( $user, IContextSource $context, &$defaultPreferences ) {
550 ## Skin #####################################
551 global $wgAllowUserCss, $wgAllowUserJs;
552
553 $defaultPreferences['skin'] = array(
554 'type' => 'radio',
555 'options' => self::generateSkinOptions( $user, $context ),
556 'label' => '&#160;',
557 'section' => 'rendering/skin',
558 );
559
560 # Create links to user CSS/JS pages for all skins
561 # This code is basically copied from generateSkinOptions(). It'd
562 # be nice to somehow merge this back in there to avoid redundancy.
563 if ( $wgAllowUserCss || $wgAllowUserJs ) {
564 $linkTools = array();
565 $userName = $user->getName();
566
567 if ( $wgAllowUserCss ) {
568 $cssPage = Title::makeTitleSafe( NS_USER, $userName . '/common.css' );
569 $linkTools[] = Linker::link( $cssPage, $context->msg( 'prefs-custom-css' )->escaped() );
570 }
571
572 if ( $wgAllowUserJs ) {
573 $jsPage = Title::makeTitleSafe( NS_USER, $userName . '/common.js' );
574 $linkTools[] = Linker::link( $jsPage, $context->msg( 'prefs-custom-js' )->escaped() );
575 }
576
577 $defaultPreferences['commoncssjs'] = array(
578 'type' => 'info',
579 'raw' => true,
580 'default' => $context->getLanguage()->pipeList( $linkTools ),
581 'label-message' => 'prefs-common-css-js',
582 'section' => 'rendering/skin',
583 );
584 }
585 }
586
587 /**
588 * @param $user User
589 * @param $context IContextSource
590 * @param $defaultPreferences Array
591 */
592 static function filesPreferences( $user, IContextSource $context, &$defaultPreferences ) {
593 ## Files #####################################
594 $defaultPreferences['imagesize'] = array(
595 'type' => 'select',
596 'options' => self::getImageSizes( $context ),
597 'label-message' => 'imagemaxsize',
598 'section' => 'rendering/files',
599 );
600 $defaultPreferences['thumbsize'] = array(
601 'type' => 'select',
602 'options' => self::getThumbSizes( $context ),
603 'label-message' => 'thumbsize',
604 'section' => 'rendering/files',
605 );
606 }
607
608 /**
609 * @param $user User
610 * @param $context IContextSource
611 * @param $defaultPreferences
612 * @return void
613 */
614 static function datetimePreferences( $user, IContextSource $context, &$defaultPreferences ) {
615 ## Date and time #####################################
616 $dateOptions = self::getDateOptions( $context );
617 if ( $dateOptions ) {
618 $defaultPreferences['date'] = array(
619 'type' => 'radio',
620 'options' => $dateOptions,
621 'label' => '&#160;',
622 'section' => 'datetime/dateformat',
623 );
624 }
625
626 // Info
627 $now = wfTimestampNow();
628 $lang = $context->getLanguage();
629 $nowlocal = Xml::element( 'span', array( 'id' => 'wpLocalTime' ),
630 $lang->time( $now, true ) );
631 $nowserver = $lang->time( $now, false ) .
632 Html::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 + (int)substr( $now, 10, 2 ) );
633
634 $defaultPreferences['nowserver'] = array(
635 'type' => 'info',
636 'raw' => 1,
637 'label-message' => 'servertime',
638 'default' => $nowserver,
639 'section' => 'datetime/timeoffset',
640 );
641
642 $defaultPreferences['nowlocal'] = array(
643 'type' => 'info',
644 'raw' => 1,
645 'label-message' => 'localtime',
646 'default' => $nowlocal,
647 'section' => 'datetime/timeoffset',
648 );
649
650 // Grab existing pref.
651 $tzOffset = $user->getOption( 'timecorrection' );
652 $tz = explode( '|', $tzOffset, 3 );
653
654 $tzOptions = self::getTimezoneOptions( $context );
655
656 $tzSetting = $tzOffset;
657 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
658 $minDiff = $tz[1];
659 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) % 60 );
660 } elseif ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
661 !in_array( $tzOffset, HTMLFormField::flattenOptions( $tzOptions ) ) )
662 {
663 # Timezone offset can vary with DST
664 $userTZ = timezone_open( $tz[2] );
665 if ( $userTZ !== false ) {
666 $minDiff = floor( timezone_offset_get( $userTZ, date_create( 'now' ) ) / 60 );
667 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
668 }
669 }
670
671 $defaultPreferences['timecorrection'] = array(
672 'class' => 'HTMLSelectOrOtherField',
673 'label-message' => 'timezonelegend',
674 'options' => $tzOptions,
675 'default' => $tzSetting,
676 'size' => 20,
677 'section' => 'datetime/timeoffset',
678 );
679 }
680
681 /**
682 * @param $user User
683 * @param $context IContextSource
684 * @param $defaultPreferences Array
685 */
686 static function renderingPreferences( $user, IContextSource $context, &$defaultPreferences ) {
687 ## Page Rendering ##############################
688 global $wgAllowUserCssPrefs;
689 if ( $wgAllowUserCssPrefs ) {
690 $defaultPreferences['underline'] = array(
691 'type' => 'select',
692 'options' => array(
693 $context->msg( 'underline-never' )->text() => 0,
694 $context->msg( 'underline-always' )->text() => 1,
695 $context->msg( 'underline-default' )->text() => 2,
696 ),
697 'label-message' => 'tog-underline',
698 'section' => 'rendering/advancedrendering',
699 );
700 }
701
702 $stubThresholdValues = array( 50, 100, 500, 1000, 2000, 5000, 10000 );
703 $stubThresholdOptions = array( $context->msg( 'stub-threshold-disabled' )->text() => 0 );
704 foreach ( $stubThresholdValues as $value ) {
705 $stubThresholdOptions[$context->msg( 'size-bytes', $value )->text()] = $value;
706 }
707
708 $defaultPreferences['stubthreshold'] = array(
709 'type' => 'selectorother',
710 'section' => 'rendering/advancedrendering',
711 'options' => $stubThresholdOptions,
712 'size' => 20,
713 'label-raw' => $context->msg( 'stub-threshold' )->text(), // Raw HTML message. Yay?
714 );
715
716 if ( $wgAllowUserCssPrefs ) {
717 $defaultPreferences['showtoc'] = array(
718 'type' => 'toggle',
719 'section' => 'rendering/advancedrendering',
720 'label-message' => 'tog-showtoc',
721 );
722 }
723 $defaultPreferences['nocache'] = array(
724 'type' => 'toggle',
725 'label-message' => 'tog-nocache',
726 'section' => 'rendering/advancedrendering',
727 );
728 $defaultPreferences['showhiddencats'] = array(
729 'type' => 'toggle',
730 'section' => 'rendering/advancedrendering',
731 'label-message' => 'tog-showhiddencats'
732 );
733
734 if ( $wgAllowUserCssPrefs ) {
735 $defaultPreferences['justify'] = array(
736 'type' => 'toggle',
737 'section' => 'rendering/advancedrendering',
738 'label-message' => 'tog-justify',
739 );
740 }
741
742 $defaultPreferences['numberheadings'] = array(
743 'type' => 'toggle',
744 'section' => 'rendering/advancedrendering',
745 'label-message' => 'tog-numberheadings',
746 );
747 }
748
749 /**
750 * @param $user User
751 * @param $context IContextSource
752 * @param $defaultPreferences Array
753 */
754 static function editingPreferences( $user, IContextSource $context, &$defaultPreferences ) {
755 global $wgAllowUserCssPrefs;
756
757 ## Editing #####################################
758 if ( $wgAllowUserCssPrefs ) {
759 $defaultPreferences['editsection'] = array(
760 'type' => 'toggle',
761 'section' => 'editing/advancedediting',
762 'label-message' => 'tog-editsection',
763 );
764 }
765 $defaultPreferences['editsectiononrightclick'] = array(
766 'type' => 'toggle',
767 'section' => 'editing/advancedediting',
768 'label-message' => 'tog-editsectiononrightclick',
769 );
770 $defaultPreferences['editondblclick'] = array(
771 'type' => 'toggle',
772 'section' => 'editing/advancedediting',
773 'label-message' => 'tog-editondblclick',
774 );
775
776 if ( $wgAllowUserCssPrefs ) {
777 $defaultPreferences['editfont'] = array(
778 'type' => 'select',
779 'section' => 'editing/editor',
780 'label-message' => 'editfont-style',
781 'options' => array(
782 $context->msg( 'editfont-default' )->text() => 'default',
783 $context->msg( 'editfont-monospace' )->text() => 'monospace',
784 $context->msg( 'editfont-sansserif' )->text() => 'sans-serif',
785 $context->msg( 'editfont-serif' )->text() => 'serif',
786 )
787 );
788 }
789 $defaultPreferences['cols'] = array(
790 'type' => 'int',
791 'label-message' => 'columns',
792 'section' => 'editing/editor',
793 'min' => 4,
794 'max' => 1000,
795 );
796 $defaultPreferences['rows'] = array(
797 'type' => 'int',
798 'label-message' => 'rows',
799 'section' => 'editing/editor',
800 'min' => 4,
801 'max' => 1000,
802 );
803 if ( $user->isAllowed( 'minoredit' ) ) {
804 $defaultPreferences['minordefault'] = array(
805 'type' => 'toggle',
806 'section' => 'editing/editor',
807 'label-message' => 'tog-minordefault',
808 );
809 }
810 $defaultPreferences['forceeditsummary'] = array(
811 'type' => 'toggle',
812 'section' => 'editing/editor',
813 'label-message' => 'tog-forceeditsummary',
814 );
815 $defaultPreferences['useeditwarning'] = array(
816 'type' => 'toggle',
817 'section' => 'editing/editor',
818 'label-message' => 'tog-useeditwarning',
819 );
820 $defaultPreferences['showtoolbar'] = array(
821 'type' => 'toggle',
822 'section' => 'editing/editor',
823 'label-message' => 'tog-showtoolbar',
824 );
825
826 $defaultPreferences['previewonfirst'] = array(
827 'type' => 'toggle',
828 'section' => 'editing/preview',
829 'label-message' => 'tog-previewonfirst',
830 );
831 $defaultPreferences['previewontop'] = array(
832 'type' => 'toggle',
833 'section' => 'editing/preview',
834 'label-message' => 'tog-previewontop',
835 );
836 $defaultPreferences['uselivepreview'] = array(
837 'type' => 'toggle',
838 'section' => 'editing/preview',
839 'label-message' => 'tog-uselivepreview',
840 );
841
842 }
843
844 /**
845 * @param $user User
846 * @param $context IContextSource
847 * @param $defaultPreferences Array
848 */
849 static function rcPreferences( $user, IContextSource $context, &$defaultPreferences ) {
850 global $wgRCMaxAge, $wgRCShowWatchingUsers;
851
852 ## RecentChanges #####################################
853 $defaultPreferences['rcdays'] = array(
854 'type' => 'float',
855 'label-message' => 'recentchangesdays',
856 'section' => 'rc/displayrc',
857 'min' => 1,
858 'max' => ceil( $wgRCMaxAge / ( 3600 * 24 ) ),
859 'help' => $context->msg( 'recentchangesdays-max' )->numParams(
860 ceil( $wgRCMaxAge / ( 3600 * 24 ) ) )->text()
861 );
862 $defaultPreferences['rclimit'] = array(
863 'type' => 'int',
864 'label-message' => 'recentchangescount',
865 'help-message' => 'prefs-help-recentchangescount',
866 'section' => 'rc/displayrc',
867 );
868 $defaultPreferences['usenewrc'] = array(
869 'type' => 'toggle',
870 'label-message' => 'tog-usenewrc',
871 'section' => 'rc/advancedrc',
872 );
873 $defaultPreferences['hideminor'] = array(
874 'type' => 'toggle',
875 'label-message' => 'tog-hideminor',
876 'section' => 'rc/advancedrc',
877 );
878
879 if ( $user->useRCPatrol() ) {
880 $defaultPreferences['hidepatrolled'] = array(
881 'type' => 'toggle',
882 'section' => 'rc/advancedrc',
883 'label-message' => 'tog-hidepatrolled',
884 );
885 $defaultPreferences['newpageshidepatrolled'] = array(
886 'type' => 'toggle',
887 'section' => 'rc/advancedrc',
888 'label-message' => 'tog-newpageshidepatrolled',
889 );
890 }
891
892 if ( $wgRCShowWatchingUsers ) {
893 $defaultPreferences['shownumberswatching'] = array(
894 'type' => 'toggle',
895 'section' => 'rc/advancedrc',
896 'label-message' => 'tog-shownumberswatching',
897 );
898 }
899 }
900
901 /**
902 * @param $user User
903 * @param $context IContextSource
904 * @param $defaultPreferences
905 */
906 static function watchlistPreferences( $user, IContextSource $context, &$defaultPreferences ) {
907 global $wgUseRCPatrol, $wgEnableAPI, $wgRCMaxAge;
908
909 $watchlistdaysMax = ceil( $wgRCMaxAge / ( 3600 * 24 ) );
910
911 ## Watchlist #####################################
912 $defaultPreferences['watchlistdays'] = array(
913 'type' => 'float',
914 'min' => 0,
915 'max' => $watchlistdaysMax,
916 'section' => 'watchlist/displaywatchlist',
917 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
918 $watchlistdaysMax )->text(),
919 'label-message' => 'prefs-watchlist-days',
920 );
921 $defaultPreferences['wllimit'] = array(
922 'type' => 'int',
923 'min' => 0,
924 'max' => 1000,
925 'label-message' => 'prefs-watchlist-edits',
926 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
927 'section' => 'watchlist/displaywatchlist',
928 );
929 $defaultPreferences['extendwatchlist'] = array(
930 'type' => 'toggle',
931 'section' => 'watchlist/advancedwatchlist',
932 'label-message' => 'tog-extendwatchlist',
933 );
934 $defaultPreferences['watchlisthideminor'] = array(
935 'type' => 'toggle',
936 'section' => 'watchlist/advancedwatchlist',
937 'label-message' => 'tog-watchlisthideminor',
938 );
939 $defaultPreferences['watchlisthidebots'] = array(
940 'type' => 'toggle',
941 'section' => 'watchlist/advancedwatchlist',
942 'label-message' => 'tog-watchlisthidebots',
943 );
944 $defaultPreferences['watchlisthideown'] = array(
945 'type' => 'toggle',
946 'section' => 'watchlist/advancedwatchlist',
947 'label-message' => 'tog-watchlisthideown',
948 );
949 $defaultPreferences['watchlisthideanons'] = array(
950 'type' => 'toggle',
951 'section' => 'watchlist/advancedwatchlist',
952 'label-message' => 'tog-watchlisthideanons',
953 );
954 $defaultPreferences['watchlisthideliu'] = array(
955 'type' => 'toggle',
956 'section' => 'watchlist/advancedwatchlist',
957 'label-message' => 'tog-watchlisthideliu',
958 );
959
960 if ( $wgUseRCPatrol ) {
961 $defaultPreferences['watchlisthidepatrolled'] = array(
962 'type' => 'toggle',
963 'section' => 'watchlist/advancedwatchlist',
964 'label-message' => 'tog-watchlisthidepatrolled',
965 );
966 }
967
968 $watchTypes = array(
969 'edit' => 'watchdefault',
970 'move' => 'watchmoves',
971 'delete' => 'watchdeletion'
972 );
973
974 // Kinda hacky
975 if ( $user->isAllowed( 'createpage' ) || $user->isAllowed( 'createtalk' ) ) {
976 $watchTypes['read'] = 'watchcreations';
977 }
978
979 foreach ( $watchTypes as $action => $pref ) {
980 if ( $user->isAllowed( $action ) ) {
981 $defaultPreferences[$pref] = array(
982 'type' => 'toggle',
983 'section' => 'watchlist/advancedwatchlist',
984 'label-message' => "tog-$pref",
985 );
986 }
987 }
988
989 if ( $wgEnableAPI ) {
990 $defaultPreferences['watchlisttoken'] = array(
991 'type' => 'api',
992 );
993 $defaultPreferences['watchlisttoken-info'] = array(
994 'type' => 'info',
995 'section' => 'watchlist/tokenwatchlist',
996 'label-message' => 'prefs-watchlist-token',
997 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
998 'help-message' => 'prefs-help-watchlist-token2',
999 );
1000 }
1001 }
1002
1003 /**
1004 * @param $user User
1005 * @param $context IContextSource
1006 * @param $defaultPreferences Array
1007 */
1008 static function searchPreferences( $user, IContextSource $context, &$defaultPreferences ) {
1009 global $wgContLang, $wgVectorUseSimpleSearch;
1010
1011 ## Search #####################################
1012 $defaultPreferences['searchlimit'] = array(
1013 'type' => 'int',
1014 'label-message' => 'resultsperpage',
1015 'section' => 'searchoptions/displaysearchoptions',
1016 'min' => 0,
1017 );
1018
1019 if ( $wgVectorUseSimpleSearch ) {
1020 $defaultPreferences['vector-simplesearch'] = array(
1021 'type' => 'toggle',
1022 'label-message' => 'vector-simplesearch-preference',
1023 'section' => 'searchoptions/displaysearchoptions',
1024 );
1025 }
1026
1027 $defaultPreferences['disablesuggest'] = array(
1028 'type' => 'toggle',
1029 'label-message' => 'mwsuggest-disable',
1030 'section' => 'searchoptions/displaysearchoptions',
1031 );
1032
1033 $defaultPreferences['searcheverything'] = array(
1034 'type' => 'toggle',
1035 'label-message' => 'searcheverything-enable',
1036 'section' => 'searchoptions/advancedsearchoptions',
1037 );
1038
1039 $nsOptions = $wgContLang->getFormattedNamespaces();
1040 $nsOptions[0] = $context->msg( 'blanknamespace' )->text();
1041 foreach ( $nsOptions as $ns => $name ) {
1042 if ( $ns < 0 ) {
1043 unset( $nsOptions[$ns] );
1044 }
1045 }
1046
1047 $defaultPreferences['searchnamespaces'] = array(
1048 'type' => 'multiselect',
1049 'label-message' => 'defaultns',
1050 'options' => array_flip( $nsOptions ),
1051 'section' => 'searchoptions/advancedsearchoptions',
1052 'prefix' => 'searchNs',
1053 );
1054 }
1055
1056 /**
1057 * @param $user User
1058 * @param $context IContextSource
1059 * @param $defaultPreferences Array
1060 */
1061 static function miscPreferences( $user, IContextSource $context, &$defaultPreferences ) {
1062 global $wgContLang;
1063
1064 ## Misc #####################################
1065 $defaultPreferences['diffonly'] = array(
1066 'type' => 'toggle',
1067 'section' => 'misc/diffs',
1068 'label-message' => 'tog-diffonly',
1069 );
1070 $defaultPreferences['norollbackdiff'] = array(
1071 'type' => 'toggle',
1072 'section' => 'misc/diffs',
1073 'label-message' => 'tog-norollbackdiff',
1074 );
1075
1076 // Stuff from Language::getExtraUserToggles()
1077 $toggles = $wgContLang->getExtraUserToggles();
1078
1079 foreach ( $toggles as $toggle ) {
1080 $defaultPreferences[$toggle] = array(
1081 'type' => 'toggle',
1082 'section' => 'personal/i18n',
1083 'label-message' => "tog-$toggle",
1084 );
1085 }
1086 }
1087
1088 /**
1089 * @param $user User The User object
1090 * @param $context IContextSource
1091 * @return Array: text/links to display as key; $skinkey as value
1092 */
1093 static function generateSkinOptions( $user, IContextSource $context ) {
1094 global $wgDefaultSkin, $wgAllowUserCss, $wgAllowUserJs;
1095 $ret = array();
1096
1097 $mptitle = Title::newMainPage();
1098 $previewtext = $context->msg( 'skin-preview' )->text();
1099
1100 # Only show members of Skin::getSkinNames() rather than
1101 # $skinNames (skins is all skin names from Language.php)
1102 $validSkinNames = Skin::getUsableSkins();
1103
1104 # Sort by UI skin name. First though need to update validSkinNames as sometimes
1105 # the skinkey & UI skinname differ (e.g. "standard" skinkey is "Classic" in the UI).
1106 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1107 $msg = $context->msg( "skinname-{$skinkey}" );
1108 if ( $msg->exists() ) {
1109 $skinname = htmlspecialchars( $msg->text() );
1110 }
1111 }
1112 asort( $validSkinNames );
1113
1114 foreach ( $validSkinNames as $skinkey => $sn ) {
1115 $linkTools = array();
1116
1117 # Mark the default skin
1118 if ( $skinkey == $wgDefaultSkin ) {
1119 $linkTools[] = $context->msg( 'default' )->escaped();
1120 }
1121
1122 # Create preview link
1123 $mplink = htmlspecialchars( $mptitle->getLocalURL( array( 'useskin' => $skinkey ) ) );
1124 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1125
1126 # Create links to user CSS/JS pages
1127 if ( $wgAllowUserCss ) {
1128 $cssPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.css' );
1129 $linkTools[] = Linker::link( $cssPage, $context->msg( 'prefs-custom-css' )->escaped() );
1130 }
1131
1132 if ( $wgAllowUserJs ) {
1133 $jsPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.js' );
1134 $linkTools[] = Linker::link( $jsPage, $context->msg( 'prefs-custom-js' )->escaped() );
1135 }
1136
1137 $display = $sn . ' ' . $context->msg( 'parentheses', $context->getLanguage()->pipeList( $linkTools ) )->text();
1138 $ret[$display] = $skinkey;
1139 }
1140
1141 return $ret;
1142 }
1143
1144 /**
1145 * @param $context IContextSource
1146 * @return array
1147 */
1148 static function getDateOptions( IContextSource $context ) {
1149 $lang = $context->getLanguage();
1150 $dateopts = $lang->getDatePreferences();
1151
1152 $ret = array();
1153
1154 if ( $dateopts ) {
1155 if ( !in_array( 'default', $dateopts ) ) {
1156 $dateopts[] = 'default'; // Make sure default is always valid
1157 // Bug 19237
1158 }
1159
1160 // KLUGE: site default might not be valid for user language
1161 global $wgDefaultUserOptions;
1162 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1163 $wgDefaultUserOptions['date'] = 'default';
1164 }
1165
1166 $epoch = wfTimestampNow();
1167 foreach ( $dateopts as $key ) {
1168 if ( $key == 'default' ) {
1169 $formatted = $context->msg( 'datedefault' )->escaped();
1170 } else {
1171 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1172 }
1173 $ret[$formatted] = $key;
1174 }
1175 }
1176 return $ret;
1177 }
1178
1179 /**
1180 * @param $context IContextSource
1181 * @return array
1182 */
1183 static function getImageSizes( IContextSource $context ) {
1184 global $wgImageLimits;
1185
1186 $ret = array();
1187 $pixels = $context->msg( 'unit-pixel' )->text();
1188
1189 foreach ( $wgImageLimits as $index => $limits ) {
1190 $display = "{$limits[0]}×{$limits[1]}" . $pixels;
1191 $ret[$display] = $index;
1192 }
1193
1194 return $ret;
1195 }
1196
1197 /**
1198 * @param $context IContextSource
1199 * @return array
1200 */
1201 static function getThumbSizes( IContextSource $context ) {
1202 global $wgThumbLimits;
1203
1204 $ret = array();
1205 $pixels = $context->msg( 'unit-pixel' )->text();
1206
1207 foreach ( $wgThumbLimits as $index => $size ) {
1208 $display = $size . $pixels;
1209 $ret[$display] = $index;
1210 }
1211
1212 return $ret;
1213 }
1214
1215 /**
1216 * @param $signature string
1217 * @param $alldata array
1218 * @param $form HTMLForm
1219 * @return bool|string
1220 */
1221 static function validateSignature( $signature, $alldata, $form ) {
1222 global $wgParser, $wgMaxSigChars;
1223 if ( mb_strlen( $signature ) > $wgMaxSigChars ) {
1224 return Xml::element( 'span', array( 'class' => 'error' ),
1225 $form->msg( 'badsiglength' )->numParams( $wgMaxSigChars )->text() );
1226 } elseif ( isset( $alldata['fancysig'] ) &&
1227 $alldata['fancysig'] &&
1228 false === $wgParser->validateSig( $signature ) ) {
1229 return Xml::element( 'span', array( 'class' => 'error' ), $form->msg( 'badsig' )->text() );
1230 } else {
1231 return true;
1232 }
1233 }
1234
1235 /**
1236 * @param $signature string
1237 * @param $alldata array
1238 * @param $form HTMLForm
1239 * @return string
1240 */
1241 static function cleanSignature( $signature, $alldata, $form ) {
1242 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1243 global $wgParser;
1244 $signature = $wgParser->cleanSig( $signature );
1245 } else {
1246 // When no fancy sig used, make sure ~{3,5} get removed.
1247 $signature = Parser::cleanSigInSig( $signature );
1248 }
1249
1250 return $signature;
1251 }
1252
1253 /**
1254 * @param $user User
1255 * @param $context IContextSource
1256 * @param $formClass string
1257 * @param array $remove array of items to remove
1258 * @return HtmlForm
1259 */
1260 static function getFormObject( $user, IContextSource $context, $formClass = 'PreferencesForm', array $remove = array() ) {
1261 $formDescriptor = Preferences::getPreferences( $user, $context );
1262 if ( count( $remove ) ) {
1263 $removeKeys = array_flip( $remove );
1264 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1265 }
1266
1267 // Remove type=api preferences. They are not intended for rendering in the form.
1268 foreach ( $formDescriptor as $name => $info ) {
1269 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1270 unset( $formDescriptor[$name] );
1271 }
1272 }
1273
1274 /**
1275 * @var $htmlForm PreferencesForm
1276 */
1277 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1278
1279 $htmlForm->setModifiedUser( $user );
1280 $htmlForm->setId( 'mw-prefs-form' );
1281 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1282 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1283 $htmlForm->setSubmitTooltip( 'preferences-save' );
1284 $htmlForm->setSubmitID( 'prefsubmit' );
1285 $htmlForm->setSubmitCallback( array( 'Preferences', 'tryFormSubmit' ) );
1286
1287 return $htmlForm;
1288 }
1289
1290 /**
1291 * @param $context IContextSource
1292 * @return array
1293 */
1294 static function getTimezoneOptions( IContextSource $context ) {
1295 $opt = array();
1296
1297 global $wgLocalTZoffset;
1298 $timestamp = MWTimestamp::getLocalInstance();
1299 // Check that $wgLocalTZoffset is the same as the local time zone offset
1300 if ( $wgLocalTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1301 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $timestamp->getTimezone()->getName() )->text();
1302 } else {
1303 $tzstring = sprintf( '%+03d:%02d', floor( $wgLocalTZoffset / 60 ), abs( $wgLocalTZoffset ) % 60 );
1304 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1305 }
1306 $opt[$server_tz_msg] = "System|$wgLocalTZoffset";
1307 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1308 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1309
1310 if ( function_exists( 'timezone_identifiers_list' ) ) {
1311 # Read timezone list
1312 $tzs = timezone_identifiers_list();
1313 sort( $tzs );
1314
1315 $tzRegions = array();
1316 $tzRegions['Africa'] = $context->msg( 'timezoneregion-africa' )->text();
1317 $tzRegions['America'] = $context->msg( 'timezoneregion-america' )->text();
1318 $tzRegions['Antarctica'] = $context->msg( 'timezoneregion-antarctica' )->text();
1319 $tzRegions['Arctic'] = $context->msg( 'timezoneregion-arctic' )->text();
1320 $tzRegions['Asia'] = $context->msg( 'timezoneregion-asia' )->text();
1321 $tzRegions['Atlantic'] = $context->msg( 'timezoneregion-atlantic' )->text();
1322 $tzRegions['Australia'] = $context->msg( 'timezoneregion-australia' )->text();
1323 $tzRegions['Europe'] = $context->msg( 'timezoneregion-europe' )->text();
1324 $tzRegions['Indian'] = $context->msg( 'timezoneregion-indian' )->text();
1325 $tzRegions['Pacific'] = $context->msg( 'timezoneregion-pacific' )->text();
1326 asort( $tzRegions );
1327
1328 $prefill = array_fill_keys( array_values( $tzRegions ), array() );
1329 $opt = array_merge( $opt, $prefill );
1330
1331 $now = date_create( 'now' );
1332
1333 foreach ( $tzs as $tz ) {
1334 $z = explode( '/', $tz, 2 );
1335
1336 # timezone_identifiers_list() returns a number of
1337 # backwards-compatibility entries. This filters them out of the
1338 # list presented to the user.
1339 if ( count( $z ) != 2 || !array_key_exists( $z[0], $tzRegions ) ) {
1340 continue;
1341 }
1342
1343 # Localize region
1344 $z[0] = $tzRegions[$z[0]];
1345
1346 $minDiff = floor( timezone_offset_get( timezone_open( $tz ), $now ) / 60 );
1347
1348 $display = str_replace( '_', ' ', $z[0] . '/' . $z[1] );
1349 $value = "ZoneInfo|$minDiff|$tz";
1350
1351 $opt[$z[0]][$display] = $value;
1352 }
1353 }
1354 return $opt;
1355 }
1356
1357 /**
1358 * @param $value
1359 * @param $alldata
1360 * @return int
1361 */
1362 static function filterIntval( $value, $alldata ) {
1363 return intval( $value );
1364 }
1365
1366 /**
1367 * @param $tz
1368 * @param $alldata
1369 * @return string
1370 */
1371 static function filterTimezoneInput( $tz, $alldata ) {
1372 $data = explode( '|', $tz, 3 );
1373 switch ( $data[0] ) {
1374 case 'ZoneInfo':
1375 case 'System':
1376 return $tz;
1377 default:
1378 $data = explode( ':', $tz, 2 );
1379 if ( count( $data ) == 2 ) {
1380 $data[0] = intval( $data[0] );
1381 $data[1] = intval( $data[1] );
1382 $minDiff = abs( $data[0] ) * 60 + $data[1];
1383 if ( $data[0] < 0 ) {
1384 $minDiff = - $minDiff;
1385 }
1386 } else {
1387 $minDiff = intval( $data[0] ) * 60;
1388 }
1389
1390 # Max is +14:00 and min is -12:00, see:
1391 # http://en.wikipedia.org/wiki/Timezone
1392 $minDiff = min( $minDiff, 840 ); # 14:00
1393 $minDiff = max( $minDiff, - 720 ); # -12:00
1394 return 'Offset|' . $minDiff;
1395 }
1396 }
1397
1398 /**
1399 * Handle the form submission if everything validated properly
1400 *
1401 * @param $formData
1402 * @param $form PreferencesForm
1403 * @param $entryPoint string
1404 * @return bool|Status|string
1405 */
1406 static function tryFormSubmit( $formData, $form, $entryPoint = 'internal' ) {
1407 global $wgHiddenPrefs, $wgAuth;
1408
1409 $user = $form->getModifiedUser();
1410 $result = true;
1411
1412 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1413 return Status::newFatal( 'mypreferencesprotected' );
1414 }
1415
1416 // Filter input
1417 foreach ( array_keys( $formData ) as $name ) {
1418 if ( isset( self::$saveFilters[$name] ) ) {
1419 $formData[$name] =
1420 call_user_func( self::$saveFilters[$name], $formData[$name], $formData );
1421 }
1422 }
1423
1424 // Fortunately, the realname field is MUCH simpler
1425 // (not really "private", but still shouldn't be edited without permission)
1426 if ( !in_array( 'realname', $wgHiddenPrefs ) && $user->isAllowed( 'editmyprivateinfo' ) ) {
1427 $realName = $formData['realname'];
1428 $user->setRealName( $realName );
1429 }
1430
1431 if ( $user->isAllowed( 'editmyoptions' ) ) {
1432 foreach ( self::$saveBlacklist as $b ) {
1433 unset( $formData[$b] );
1434 }
1435
1436 # If users have saved a value for a preference which has subsequently been disabled
1437 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1438 # is subsequently re-enabled
1439 # TODO: maintenance script to actually delete these
1440 foreach ( $wgHiddenPrefs as $pref ) {
1441 # If the user has not set a non-default value here, the default will be returned
1442 # and subsequently discarded
1443 $formData[$pref] = $user->getOption( $pref, null, true );
1444 }
1445
1446 // Keep old preferences from interfering due to back-compat code, etc.
1447 $user->resetOptions( 'unused', $form->getContext() );
1448
1449 foreach ( $formData as $key => $value ) {
1450 $user->setOption( $key, $value );
1451 }
1452
1453 $user->saveSettings();
1454 }
1455
1456 $wgAuth->updateExternalDB( $user );
1457
1458 return $result;
1459 }
1460
1461 /**
1462 * @param $formData
1463 * @param $form PreferencesForm
1464 * @return Status
1465 */
1466 public static function tryUISubmit( $formData, $form ) {
1467 $res = self::tryFormSubmit( $formData, $form, 'ui' );
1468
1469 if ( $res ) {
1470 $urlOptions = array( 'success' => 1 );
1471
1472 if ( $res === 'eauth' ) {
1473 $urlOptions['eauth'] = 1;
1474 }
1475
1476 $urlOptions += $form->getExtraSuccessRedirectParameters();
1477
1478 $url = $form->getTitle()->getFullURL( $urlOptions );
1479
1480 $form->getContext()->getOutput()->redirect( $url );
1481 }
1482
1483 return Status::newGood();
1484 }
1485
1486 /**
1487 * Try to set a user's email address.
1488 * This does *not* try to validate the address.
1489 * Caller is responsible for checking $wgAuth and 'editmyprivateinfo'
1490 * right.
1491 *
1492 * @deprecated in 1.20; use User::setEmailWithConfirmation() instead.
1493 * @param $user User
1494 * @param string $newaddr New email address
1495 * @return Array (true on success or Status on failure, info string)
1496 */
1497 public static function trySetUserEmail( User $user, $newaddr ) {
1498 wfDeprecated( __METHOD__, '1.20' );
1499
1500 $result = $user->setEmailWithConfirmation( $newaddr );
1501 if ( $result->isGood() ) {
1502 return array( true, $result->value );
1503 } else {
1504 return array( $result, 'mailerror' );
1505 }
1506 }
1507
1508 /**
1509 * @deprecated in 1.19
1510 * @param $user User
1511 * @return array
1512 */
1513 public static function loadOldSearchNs( $user ) {
1514 wfDeprecated( __METHOD__, '1.19' );
1515
1516 $searchableNamespaces = SearchEngine::searchableNamespaces();
1517 // Back compat with old format
1518 $arr = array();
1519
1520 foreach ( $searchableNamespaces as $ns => $name ) {
1521 if ( $user->getOption( 'searchNs' . $ns ) ) {
1522 $arr[] = $ns;
1523 }
1524 }
1525
1526 return $arr;
1527 }
1528 }
1529
1530 /** Some tweaks to allow js prefs to work */
1531 class PreferencesForm extends HTMLForm {
1532 // Override default value from HTMLForm
1533 protected $mSubSectionBeforeFields = false;
1534
1535 private $modifiedUser;
1536
1537 /**
1538 * @param $user User
1539 */
1540 public function setModifiedUser( $user ) {
1541 $this->modifiedUser = $user;
1542 }
1543
1544 /**
1545 * @return User
1546 */
1547 public function getModifiedUser() {
1548 if ( $this->modifiedUser === null ) {
1549 return $this->getUser();
1550 } else {
1551 return $this->modifiedUser;
1552 }
1553 }
1554
1555 /**
1556 * Get extra parameters for the query string when redirecting after
1557 * successful save.
1558 *
1559 * @return array()
1560 */
1561 public function getExtraSuccessRedirectParameters() {
1562 return array();
1563 }
1564
1565 /**
1566 * @param $html string
1567 * @return String
1568 */
1569 function wrapForm( $html ) {
1570 $html = Xml::tags( 'div', array( 'id' => 'preferences' ), $html );
1571
1572 return parent::wrapForm( $html );
1573 }
1574
1575 /**
1576 * @return String
1577 */
1578 function getButtons() {
1579 if ( !$this->getModifiedUser()->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1580 return '';
1581 }
1582
1583 $html = parent::getButtons();
1584
1585 if ( $this->getModifiedUser()->isAllowed( 'editmyoptions' ) ) {
1586 $t = SpecialPage::getTitleFor( 'Preferences', 'reset' );
1587
1588 $html .= "\n" . Linker::link( $t, $this->msg( 'restoreprefs' )->escaped() );
1589
1590 $html = Xml::tags( 'div', array( 'class' => 'mw-prefs-buttons' ), $html );
1591 }
1592
1593 return $html;
1594 }
1595
1596 /**
1597 * Separate multi-option preferences into multiple preferences, since we
1598 * have to store them separately
1599 * @param $data array
1600 * @return array
1601 */
1602 function filterDataForSubmit( $data ) {
1603 foreach ( $this->mFlatFields as $fieldname => $field ) {
1604 if ( $field instanceof HTMLNestedFilterable ) {
1605 $info = $field->mParams;
1606 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $fieldname;
1607 foreach ( $field->filterDataForSubmit( $data[$fieldname] ) as $key => $value ) {
1608 $data["$prefix$key"] = $value;
1609 }
1610 unset( $data[$fieldname] );
1611 }
1612 }
1613
1614 return $data;
1615 }
1616
1617 /**
1618 * Get the whole body of the form.
1619 * @return string
1620 */
1621 function getBody() {
1622 return $this->displaySection( $this->mFieldTree, '', 'mw-prefsection-' );
1623 }
1624
1625 /**
1626 * Get the "<legend>" for a given section key. Normally this is the
1627 * prefs-$key message but we'll allow extensions to override it.
1628 * @param $key string
1629 * @return string
1630 */
1631 function getLegend( $key ) {
1632 $legend = parent::getLegend( $key );
1633 wfRunHooks( 'PreferencesGetLegend', array( $this, $key, &$legend ) );
1634 return $legend;
1635 }
1636 }