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