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