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