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