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