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