* Added FileRepo::SKIP_LOCKING constant and made storeBatch() check it.
[lhc/web/wiklou.git] / includes / Preferences.php
1 <?php
2 /**
3 * We're now using the HTMLForm object with some customisation to generate the
4 * Preferences form. This object handles generic submission, CSRF protection,
5 * layout and other logic in a reusable manner. We subclass it as a PreferencesForm
6 * to make some minor customisations.
7 *
8 * In order to generate the form, the HTMLForm object needs an array structure
9 * detailing the form fields available, and that's what this class is for. Each
10 * element of the array is a basic property-list, including the type of field,
11 * the label it is to be given in the form, callbacks for validation and
12 * 'filtering', and other pertinent information. Note that the 'default' field
13 * is named for generic forms, and does not represent the preference's default
14 * (which is stored in $wgDefaultUserOptions), but the default for the form
15 * field, which should be whatever the user has set for that preference. There
16 * is no need to override it unless you have some special storage logic (for
17 * instance, those not presently stored as options, but which are best set from
18 * the user preferences view).
19 *
20 * Field types are implemented as subclasses of the generic HTMLFormField
21 * object, and typically implement at least getInputHTML, which generates the
22 * HTML for the input field to be placed in the table.
23 *
24 * Once fields have been retrieved and validated, submission logic is handed
25 * over to the tryUISubmit static method of this class.
26 */
27
28 class Preferences {
29 static $defaultPreferences = null;
30 static $saveFilters = array(
31 'timecorrection' => array( 'Preferences', 'filterTimezoneInput' ),
32 'cols' => array( 'Preferences', 'filterIntval' ),
33 'rows' => array( 'Preferences', 'filterIntval' ),
34 'rclimit' => array( 'Preferences', 'filterIntval' ),
35 'wllimit' => array( 'Preferences', 'filterIntval' ),
36 'searchlimit' => array( 'Preferences', 'filterIntval' ),
37 );
38
39 /**
40 * @throws MWException
41 * @param $user User
42 * @param $context IContextSource
43 * @return array|null
44 */
45 static function getPreferences( $user, IContextSource $context ) {
46 if ( self::$defaultPreferences ) {
47 return self::$defaultPreferences;
48 }
49
50 $defaultPreferences = array();
51
52 self::profilePreferences( $user, $context, $defaultPreferences );
53 self::skinPreferences( $user, $context, $defaultPreferences );
54 self::filesPreferences( $user, $context, $defaultPreferences );
55 self::datetimePreferences( $user, $context, $defaultPreferences );
56 self::renderingPreferences( $user, $context, $defaultPreferences );
57 self::editingPreferences( $user, $context, $defaultPreferences );
58 self::rcPreferences( $user, $context, $defaultPreferences );
59 self::watchlistPreferences( $user, $context, $defaultPreferences );
60 self::searchPreferences( $user, $context, $defaultPreferences );
61 self::miscPreferences( $user, $context, $defaultPreferences );
62
63 wfRunHooks( 'GetPreferences', array( $user, &$defaultPreferences ) );
64
65 ## Remove preferences that wikis don't want to use
66 global $wgHiddenPrefs;
67 foreach ( $wgHiddenPrefs as $pref ) {
68 if ( isset( $defaultPreferences[$pref] ) ) {
69 unset( $defaultPreferences[$pref] );
70 }
71 }
72
73 ## Prod in defaults from the user
74 foreach ( $defaultPreferences as $name => &$info ) {
75 $prefFromUser = self::getOptionFromUser( $name, $info, $user );
76 $field = HTMLForm::loadInputFromParameters( $name, $info ); // For validation
77 $defaultOptions = User::getDefaultOptions();
78 $globalDefault = isset( $defaultOptions[$name] )
79 ? $defaultOptions[$name]
80 : null;
81
82 // If it validates, set it as the default
83 if ( isset( $info['default'] ) ) {
84 // Already set, no problem
85 continue;
86 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
87 $field->validate( $prefFromUser, $user->mOptions ) === true ) {
88 $info['default'] = $prefFromUser;
89 } elseif ( $field->validate( $globalDefault, $user->mOptions ) === true ) {
90 $info['default'] = $globalDefault;
91 } else {
92 throw new MWException( "Global default '$globalDefault' is invalid for field $name" );
93 }
94 }
95
96 self::$defaultPreferences = $defaultPreferences;
97
98 return $defaultPreferences;
99 }
100
101 /**
102 * Pull option from a user account. Handles stuff like array-type preferences.
103 *
104 * @param $name
105 * @param $info
106 * @param $user User
107 * @return array|String
108 */
109 static function getOptionFromUser( $name, $info, $user ) {
110 $val = $user->getOption( $name );
111
112 // Handling for array-type preferences
113 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
114 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
115 $options = HTMLFormField::flattenOptions( $info['options'] );
116 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
117 $val = array();
118
119 foreach ( $options as $value ) {
120 if ( $user->getOption( "$prefix$value" ) ) {
121 $val[] = $value;
122 }
123 }
124 }
125
126 return $val;
127 }
128
129 /**
130 * @param $user User
131 * @param $context IContextSource
132 * @param $defaultPreferences
133 * @return void
134 */
135 static function profilePreferences( $user, IContextSource $context, &$defaultPreferences ) {
136 global $wgAuth, $wgContLang, $wgParser, $wgCookieExpiration, $wgLanguageCode,
137 $wgDisableTitleConversion, $wgDisableLangConversion, $wgMaxSigChars,
138 $wgEnableEmail, $wgEmailConfirmToEdit, $wgEnableUserEmail, $wgEmailAuthentication,
139 $wgEnotifWatchlist, $wgEnotifUserTalk, $wgEnotifRevealEditorAddress;
140
141 ## User info #####################################
142 // Information panel
143 $defaultPreferences['username'] = array(
144 'type' => 'info',
145 'label-message' => 'username',
146 'default' => $user->getName(),
147 'section' => 'personal/info',
148 );
149
150 $defaultPreferences['userid'] = array(
151 'type' => 'info',
152 'label-message' => 'uid',
153 'default' => $user->getId(),
154 'section' => 'personal/info',
155 );
156
157 # Get groups to which the user belongs
158 $userEffectiveGroups = $user->getEffectiveGroups();
159 $userGroups = $userMembers = array();
160 foreach ( $userEffectiveGroups as $ueg ) {
161 if ( $ueg == '*' ) {
162 // Skip the default * group, seems useless here
163 continue;
164 }
165 $groupName = User::getGroupName( $ueg );
166 $userGroups[] = User::makeGroupLinkHTML( $ueg, $groupName );
167
168 $memberName = User::getGroupMember( $ueg, $user->getName() );
169 $userMembers[] = User::makeGroupLinkHTML( $ueg, $memberName );
170 }
171 asort( $userGroups );
172 asort( $userMembers );
173
174 $lang = $context->getLanguage();
175
176 $defaultPreferences['usergroups'] = array(
177 'type' => 'info',
178 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
179 count( $userGroups ) )->parse(),
180 'default' => $context->msg( 'prefs-memberingroups-type',
181 $lang->commaList( $userGroups ),
182 $lang->commaList( $userMembers )
183 )->plain(),
184 'raw' => true,
185 'section' => 'personal/info',
186 );
187
188 $defaultPreferences['editcount'] = array(
189 'type' => 'info',
190 'label-message' => 'prefs-edits',
191 'default' => $lang->formatNum( $user->getEditCount() ),
192 'section' => 'personal/info',
193 );
194
195 if ( $user->getRegistration() ) {
196 $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['highlightbroken'] = array(
642 'type' => 'toggle',
643 'section' => 'rendering/advancedrendering',
644 'label' => $context->msg( 'tog-highlightbroken' )->text(), // Raw HTML
645 );
646 $defaultPreferences['showtoc'] = array(
647 'type' => 'toggle',
648 'section' => 'rendering/advancedrendering',
649 'label-message' => 'tog-showtoc',
650 );
651 }
652 $defaultPreferences['nocache'] = array(
653 'type' => 'toggle',
654 'label-message' => 'tog-nocache',
655 'section' => 'rendering/advancedrendering',
656 );
657 $defaultPreferences['showhiddencats'] = array(
658 'type' => 'toggle',
659 'section' => 'rendering/advancedrendering',
660 'label-message' => 'tog-showhiddencats'
661 );
662 $defaultPreferences['showjumplinks'] = array(
663 'type' => 'toggle',
664 'section' => 'rendering/advancedrendering',
665 'label-message' => 'tog-showjumplinks',
666 );
667
668 if ( $wgAllowUserCssPrefs ) {
669 $defaultPreferences['justify'] = array(
670 'type' => 'toggle',
671 'section' => 'rendering/advancedrendering',
672 'label-message' => 'tog-justify',
673 );
674 }
675
676 $defaultPreferences['numberheadings'] = array(
677 'type' => 'toggle',
678 'section' => 'rendering/advancedrendering',
679 'label-message' => 'tog-numberheadings',
680 );
681 }
682
683 /**
684 * @param $user User
685 * @param $context IContextSource
686 * @param $defaultPreferences Array
687 */
688 static function editingPreferences( $user, IContextSource $context, &$defaultPreferences ) {
689 global $wgUseExternalEditor, $wgAllowUserCssPrefs;
690
691 ## Editing #####################################
692 $defaultPreferences['cols'] = array(
693 'type' => 'int',
694 'label-message' => 'columns',
695 'section' => 'editing/textboxsize',
696 'min' => 4,
697 'max' => 1000,
698 );
699 $defaultPreferences['rows'] = array(
700 'type' => 'int',
701 'label-message' => 'rows',
702 'section' => 'editing/textboxsize',
703 'min' => 4,
704 'max' => 1000,
705 );
706
707 if ( $wgAllowUserCssPrefs ) {
708 $defaultPreferences['editfont'] = array(
709 'type' => 'select',
710 'section' => 'editing/advancedediting',
711 'label-message' => 'editfont-style',
712 'options' => array(
713 $context->msg( 'editfont-default' )->text() => 'default',
714 $context->msg( 'editfont-monospace' )->text() => 'monospace',
715 $context->msg( 'editfont-sansserif' )->text() => 'sans-serif',
716 $context->msg( 'editfont-serif' )->text() => 'serif',
717 )
718 );
719 }
720 $defaultPreferences['previewontop'] = array(
721 'type' => 'toggle',
722 'section' => 'editing/advancedediting',
723 'label-message' => 'tog-previewontop',
724 );
725 $defaultPreferences['previewonfirst'] = array(
726 'type' => 'toggle',
727 'section' => 'editing/advancedediting',
728 'label-message' => 'tog-previewonfirst',
729 );
730
731 if ( $wgAllowUserCssPrefs ) {
732 $defaultPreferences['editsection'] = array(
733 'type' => 'toggle',
734 'section' => 'editing/advancedediting',
735 'label-message' => 'tog-editsection',
736 );
737 }
738 $defaultPreferences['editsectiononrightclick'] = array(
739 'type' => 'toggle',
740 'section' => 'editing/advancedediting',
741 'label-message' => 'tog-editsectiononrightclick',
742 );
743 $defaultPreferences['editondblclick'] = array(
744 'type' => 'toggle',
745 'section' => 'editing/advancedediting',
746 'label-message' => 'tog-editondblclick',
747 );
748 $defaultPreferences['showtoolbar'] = array(
749 'type' => 'toggle',
750 'section' => 'editing/advancedediting',
751 'label-message' => 'tog-showtoolbar',
752 );
753
754 if ( $user->isAllowed( 'minoredit' ) ) {
755 $defaultPreferences['minordefault'] = array(
756 'type' => 'toggle',
757 'section' => 'editing/advancedediting',
758 'label-message' => 'tog-minordefault',
759 );
760 }
761
762 if ( $wgUseExternalEditor ) {
763 $defaultPreferences['externaleditor'] = array(
764 'type' => 'toggle',
765 'section' => 'editing/advancedediting',
766 'label-message' => 'tog-externaleditor',
767 );
768 $defaultPreferences['externaldiff'] = array(
769 'type' => 'toggle',
770 'section' => 'editing/advancedediting',
771 'label-message' => 'tog-externaldiff',
772 );
773 }
774
775 $defaultPreferences['forceeditsummary'] = array(
776 'type' => 'toggle',
777 'section' => 'editing/advancedediting',
778 'label-message' => 'tog-forceeditsummary',
779 );
780
781
782 $defaultPreferences['uselivepreview'] = array(
783 'type' => 'toggle',
784 'section' => 'editing/advancedediting',
785 'label-message' => 'tog-uselivepreview',
786 );
787 }
788
789 /**
790 * @param $user User
791 * @param $context IContextSource
792 * @param $defaultPreferences Array
793 */
794 static function rcPreferences( $user, IContextSource $context, &$defaultPreferences ) {
795 global $wgRCMaxAge, $wgRCShowWatchingUsers;
796
797 ## RecentChanges #####################################
798 $defaultPreferences['rcdays'] = array(
799 'type' => 'float',
800 'label-message' => 'recentchangesdays',
801 'section' => 'rc/displayrc',
802 'min' => 1,
803 'max' => ceil( $wgRCMaxAge / ( 3600 * 24 ) ),
804 'help' => $context->msg( 'recentchangesdays-max' )->numParams(
805 ceil( $wgRCMaxAge / ( 3600 * 24 ) ) )->text()
806 );
807 $defaultPreferences['rclimit'] = array(
808 'type' => 'int',
809 'label-message' => 'recentchangescount',
810 'help-message' => 'prefs-help-recentchangescount',
811 'section' => 'rc/displayrc',
812 );
813 $defaultPreferences['usenewrc'] = array(
814 'type' => 'toggle',
815 'label-message' => 'tog-usenewrc',
816 'section' => 'rc/advancedrc',
817 );
818 $defaultPreferences['hideminor'] = array(
819 'type' => 'toggle',
820 'label-message' => 'tog-hideminor',
821 'section' => 'rc/advancedrc',
822 );
823
824 if ( $user->useRCPatrol() ) {
825 $defaultPreferences['hidepatrolled'] = array(
826 'type' => 'toggle',
827 'section' => 'rc/advancedrc',
828 'label-message' => 'tog-hidepatrolled',
829 );
830 $defaultPreferences['newpageshidepatrolled'] = array(
831 'type' => 'toggle',
832 'section' => 'rc/advancedrc',
833 'label-message' => 'tog-newpageshidepatrolled',
834 );
835 }
836
837 if ( $wgRCShowWatchingUsers ) {
838 $defaultPreferences['shownumberswatching'] = array(
839 'type' => 'toggle',
840 'section' => 'rc/advancedrc',
841 'label-message' => 'tog-shownumberswatching',
842 );
843 }
844 }
845
846 /**
847 * @param $user User
848 * @param $context IContextSource
849 * @param $defaultPreferences
850 */
851 static function watchlistPreferences( $user, IContextSource $context, &$defaultPreferences ) {
852 global $wgUseRCPatrol, $wgEnableAPI;
853
854 ## Watchlist #####################################
855 $defaultPreferences['watchlistdays'] = array(
856 'type' => 'float',
857 'min' => 0,
858 'max' => 7,
859 'section' => 'watchlist/displaywatchlist',
860 'help' => $context->msg( 'prefs-watchlist-days-max' )->escaped(),
861 'label-message' => 'prefs-watchlist-days',
862 );
863 $defaultPreferences['wllimit'] = array(
864 'type' => 'int',
865 'min' => 0,
866 'max' => 1000,
867 'label-message' => 'prefs-watchlist-edits',
868 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
869 'section' => 'watchlist/displaywatchlist',
870 );
871 $defaultPreferences['extendwatchlist'] = array(
872 'type' => 'toggle',
873 'section' => 'watchlist/advancedwatchlist',
874 'label-message' => 'tog-extendwatchlist',
875 );
876 $defaultPreferences['watchlisthideminor'] = array(
877 'type' => 'toggle',
878 'section' => 'watchlist/advancedwatchlist',
879 'label-message' => 'tog-watchlisthideminor',
880 );
881 $defaultPreferences['watchlisthidebots'] = array(
882 'type' => 'toggle',
883 'section' => 'watchlist/advancedwatchlist',
884 'label-message' => 'tog-watchlisthidebots',
885 );
886 $defaultPreferences['watchlisthideown'] = array(
887 'type' => 'toggle',
888 'section' => 'watchlist/advancedwatchlist',
889 'label-message' => 'tog-watchlisthideown',
890 );
891 $defaultPreferences['watchlisthideanons'] = array(
892 'type' => 'toggle',
893 'section' => 'watchlist/advancedwatchlist',
894 'label-message' => 'tog-watchlisthideanons',
895 );
896 $defaultPreferences['watchlisthideliu'] = array(
897 'type' => 'toggle',
898 'section' => 'watchlist/advancedwatchlist',
899 'label-message' => 'tog-watchlisthideliu',
900 );
901
902 if ( $wgUseRCPatrol ) {
903 $defaultPreferences['watchlisthidepatrolled'] = array(
904 'type' => 'toggle',
905 'section' => 'watchlist/advancedwatchlist',
906 'label-message' => 'tog-watchlisthidepatrolled',
907 );
908 }
909
910 if ( $wgEnableAPI ) {
911 # Some random gibberish as a proposed default
912 $hash = sha1( mt_rand() . microtime( true ) );
913
914 $defaultPreferences['watchlisttoken'] = array(
915 'type' => 'text',
916 'section' => 'watchlist/advancedwatchlist',
917 'label-message' => 'prefs-watchlist-token',
918 'help' => $context->msg( 'prefs-help-watchlist-token', $hash )->escaped()
919 );
920 }
921
922 $watchTypes = array(
923 'edit' => 'watchdefault',
924 'move' => 'watchmoves',
925 'delete' => 'watchdeletion'
926 );
927
928 // Kinda hacky
929 if ( $user->isAllowed( 'createpage' ) || $user->isAllowed( 'createtalk' ) ) {
930 $watchTypes['read'] = 'watchcreations';
931 }
932
933 foreach ( $watchTypes as $action => $pref ) {
934 if ( $user->isAllowed( $action ) ) {
935 $defaultPreferences[$pref] = array(
936 'type' => 'toggle',
937 'section' => 'watchlist/advancedwatchlist',
938 'label-message' => "tog-$pref",
939 );
940 }
941 }
942 }
943
944 /**
945 * @param $user User
946 * @param $context IContextSource
947 * @param $defaultPreferences Array
948 */
949 static function searchPreferences( $user, IContextSource $context, &$defaultPreferences ) {
950 global $wgContLang, $wgEnableMWSuggest, $wgVectorUseSimpleSearch;
951
952 ## Search #####################################
953 $defaultPreferences['searchlimit'] = array(
954 'type' => 'int',
955 'label-message' => 'resultsperpage',
956 'section' => 'searchoptions/displaysearchoptions',
957 'min' => 0,
958 );
959
960 if ( $wgEnableMWSuggest ) {
961 $defaultPreferences['disablesuggest'] = array(
962 'type' => 'toggle',
963 'label-message' => 'mwsuggest-disable',
964 'section' => 'searchoptions/displaysearchoptions',
965 );
966 }
967
968 if ( $wgVectorUseSimpleSearch ) {
969 $defaultPreferences['vector-simplesearch'] = array(
970 'type' => 'toggle',
971 'label-message' => 'vector-simplesearch-preference',
972 'section' => 'searchoptions/displaysearchoptions'
973 );
974 }
975
976 $defaultPreferences['searcheverything'] = array(
977 'type' => 'toggle',
978 'label-message' => 'searcheverything-enable',
979 'section' => 'searchoptions/advancedsearchoptions',
980 );
981
982 $nsOptions = array();
983
984 foreach ( $wgContLang->getNamespaces() as $ns => $name ) {
985 if ( $ns < 0 ) {
986 continue;
987 }
988
989 $displayNs = str_replace( '_', ' ', $name );
990
991 if ( !$displayNs ) {
992 $displayNs = $context->msg( 'blanknamespace' )->text();
993 }
994
995 $displayNs = htmlspecialchars( $displayNs );
996 $nsOptions[$displayNs] = $ns;
997 }
998
999 $defaultPreferences['searchnamespaces'] = array(
1000 'type' => 'multiselect',
1001 'label-message' => 'defaultns',
1002 'options' => $nsOptions,
1003 'section' => 'searchoptions/advancedsearchoptions',
1004 'prefix' => 'searchNs',
1005 );
1006 }
1007
1008 /**
1009 * @param $user User
1010 * @param $context IContextSource
1011 * @param $defaultPreferences Array
1012 */
1013 static function miscPreferences( $user, IContextSource $context, &$defaultPreferences ) {
1014 global $wgContLang;
1015
1016 ## Misc #####################################
1017 $defaultPreferences['diffonly'] = array(
1018 'type' => 'toggle',
1019 'section' => 'misc/diffs',
1020 'label-message' => 'tog-diffonly',
1021 );
1022 $defaultPreferences['norollbackdiff'] = array(
1023 'type' => 'toggle',
1024 'section' => 'misc/diffs',
1025 'label-message' => 'tog-norollbackdiff',
1026 );
1027
1028 // Stuff from Language::getExtraUserToggles()
1029 $toggles = $wgContLang->getExtraUserToggles();
1030
1031 foreach ( $toggles as $toggle ) {
1032 $defaultPreferences[$toggle] = array(
1033 'type' => 'toggle',
1034 'section' => 'personal/i18n',
1035 'label-message' => "tog-$toggle",
1036 );
1037 }
1038 }
1039
1040 /**
1041 * @param $user User The User object
1042 * @param $context IContextSource
1043 * @return Array: text/links to display as key; $skinkey as value
1044 */
1045 static function generateSkinOptions( $user, IContextSource $context ) {
1046 global $wgDefaultSkin, $wgAllowUserCss, $wgAllowUserJs;
1047 $ret = array();
1048
1049 $mptitle = Title::newMainPage();
1050 $previewtext = $context->msg( 'skin-preview' )->text();
1051
1052 # Only show members of Skin::getSkinNames() rather than
1053 # $skinNames (skins is all skin names from Language.php)
1054 $validSkinNames = Skin::getUsableSkins();
1055
1056 # Sort by UI skin name. First though need to update validSkinNames as sometimes
1057 # the skinkey & UI skinname differ (e.g. "standard" skinkey is "Classic" in the UI).
1058 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1059 $msg = $context->msg( "skinname-{$skinkey}" );
1060 if ( $msg->exists() ) {
1061 $skinname = htmlspecialchars( $msg->text() );
1062 }
1063 }
1064 asort( $validSkinNames );
1065
1066 foreach ( $validSkinNames as $skinkey => $sn ) {
1067 $linkTools = array();
1068
1069 # Mark the default skin
1070 if ( $skinkey == $wgDefaultSkin ) {
1071 $linkTools[] = $context->msg( 'default' )->escaped();
1072 }
1073
1074 # Create preview link
1075 $mplink = htmlspecialchars( $mptitle->getLocalURL( "useskin=$skinkey" ) );
1076 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1077
1078 # Create links to user CSS/JS pages
1079 if ( $wgAllowUserCss ) {
1080 $cssPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.css' );
1081 $linkTools[] = Linker::link( $cssPage, $context->msg( 'prefs-custom-css' )->escaped() );
1082 }
1083
1084 if ( $wgAllowUserJs ) {
1085 $jsPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.js' );
1086 $linkTools[] = Linker::link( $jsPage, $context->msg( 'prefs-custom-js' )->escaped() );
1087 }
1088
1089 $display = $sn . ' ' . $context->msg( 'parentheses', $context->getLanguage()->pipeList( $linkTools ) )->text();
1090 $ret[$display] = $skinkey;
1091 }
1092
1093 return $ret;
1094 }
1095
1096 /**
1097 * @param $context IContextSource
1098 * @return array
1099 */
1100 static function getDateOptions( IContextSource $context ) {
1101 $lang = $context->getLanguage();
1102 $dateopts = $lang->getDatePreferences();
1103
1104 $ret = array();
1105
1106 if ( $dateopts ) {
1107 if ( !in_array( 'default', $dateopts ) ) {
1108 $dateopts[] = 'default'; // Make sure default is always valid
1109 // Bug 19237
1110 }
1111
1112 // KLUGE: site default might not be valid for user language
1113 global $wgDefaultUserOptions;
1114 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1115 $wgDefaultUserOptions['date'] = 'default';
1116 }
1117
1118 $epoch = wfTimestampNow();
1119 foreach ( $dateopts as $key ) {
1120 if ( $key == 'default' ) {
1121 $formatted = $context->msg( 'datedefault' )->escaped();
1122 } else {
1123 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1124 }
1125 $ret[$formatted] = $key;
1126 }
1127 }
1128 return $ret;
1129 }
1130
1131 /**
1132 * @param $context IContextSource
1133 * @return array
1134 */
1135 static function getImageSizes( IContextSource $context ) {
1136 global $wgImageLimits;
1137
1138 $ret = array();
1139 $pixels = $context->msg( 'unit-pixel' )->text();
1140
1141 foreach ( $wgImageLimits as $index => $limits ) {
1142 $display = "{$limits[0]}×{$limits[1]}" . $pixels;
1143 $ret[$display] = $index;
1144 }
1145
1146 return $ret;
1147 }
1148
1149 /**
1150 * @param $context IContextSource
1151 * @return array
1152 */
1153 static function getThumbSizes( IContextSource $context ) {
1154 global $wgThumbLimits;
1155
1156 $ret = array();
1157 $pixels = $context->msg( 'unit-pixel' )->text();
1158
1159 foreach ( $wgThumbLimits as $index => $size ) {
1160 $display = $size . $pixels;
1161 $ret[$display] = $index;
1162 }
1163
1164 return $ret;
1165 }
1166
1167 /**
1168 * @param $signature string
1169 * @param $alldata array
1170 * @param $form HTMLForm
1171 * @return bool|string
1172 */
1173 static function validateSignature( $signature, $alldata, $form ) {
1174 global $wgParser, $wgMaxSigChars;
1175 if ( mb_strlen( $signature ) > $wgMaxSigChars ) {
1176 return Xml::element( 'span', array( 'class' => 'error' ),
1177 $form->msg( 'badsiglength' )->numParams( $wgMaxSigChars )->text() );
1178 } elseif ( isset( $alldata['fancysig'] ) &&
1179 $alldata['fancysig'] &&
1180 false === $wgParser->validateSig( $signature ) ) {
1181 return Xml::element( 'span', array( 'class' => 'error' ), $form->msg( 'badsig' )->text() );
1182 } else {
1183 return true;
1184 }
1185 }
1186
1187 /**
1188 * @param $signature string
1189 * @param $alldata array
1190 * @param $form HTMLForm
1191 * @return string
1192 */
1193 static function cleanSignature( $signature, $alldata, $form ) {
1194 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1195 global $wgParser;
1196 $signature = $wgParser->cleanSig( $signature );
1197 } else {
1198 // When no fancy sig used, make sure ~{3,5} get removed.
1199 $signature = Parser::cleanSigInSig( $signature );
1200 }
1201
1202 return $signature;
1203 }
1204
1205 /**
1206 * @param $user User
1207 * @param $context IContextSource
1208 * @param $formClass string
1209 * @param $remove Array: array of items to remove
1210 * @return HtmlForm
1211 */
1212 static function getFormObject( $user, IContextSource $context, $formClass = 'PreferencesForm', array $remove = array() ) {
1213 $formDescriptor = Preferences::getPreferences( $user, $context );
1214 if ( count( $remove ) ) {
1215 $removeKeys = array_flip( $remove );
1216 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1217 }
1218 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1219
1220 $htmlForm->setModifiedUser( $user );
1221 $htmlForm->setId( 'mw-prefs-form' );
1222 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1223 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1224 $htmlForm->setSubmitTooltip( 'preferences-save' );
1225 $htmlForm->setSubmitID( 'prefsubmit' );
1226 $htmlForm->setSubmitCallback( array( 'Preferences', 'tryFormSubmit' ) );
1227
1228 return $htmlForm;
1229 }
1230
1231 /**
1232 * @return array
1233 */
1234 static function getTimezoneOptions( IContextSource $context ) {
1235 $opt = array();
1236
1237 global $wgLocalTZoffset, $wgLocaltimezone;
1238 // Check that $wgLocalTZoffset is the same as $wgLocaltimezone
1239 if ( $wgLocalTZoffset == date( 'Z' ) / 60 ) {
1240 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $wgLocaltimezone )->text();
1241 } else {
1242 $tzstring = sprintf( '%+03d:%02d', floor( $wgLocalTZoffset / 60 ), abs( $wgLocalTZoffset ) % 60 );
1243 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1244 }
1245 $opt[$server_tz_msg] = "System|$wgLocalTZoffset";
1246 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1247 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1248
1249 if ( function_exists( 'timezone_identifiers_list' ) ) {
1250 # Read timezone list
1251 $tzs = timezone_identifiers_list();
1252 sort( $tzs );
1253
1254 $tzRegions = array();
1255 $tzRegions['Africa'] = $context->msg( 'timezoneregion-africa' )->text();
1256 $tzRegions['America'] = $context->msg( 'timezoneregion-america' )->text();
1257 $tzRegions['Antarctica'] = $context->msg( 'timezoneregion-antarctica' )->text();
1258 $tzRegions['Arctic'] = $context->msg( 'timezoneregion-arctic' )->text();
1259 $tzRegions['Asia'] = $context->msg( 'timezoneregion-asia' )->text();
1260 $tzRegions['Atlantic'] = $context->msg( 'timezoneregion-atlantic' )->text();
1261 $tzRegions['Australia'] = $context->msg( 'timezoneregion-australia' )->text();
1262 $tzRegions['Europe'] = $context->msg( 'timezoneregion-europe' )->text();
1263 $tzRegions['Indian'] = $context->msg( 'timezoneregion-indian' )->text();
1264 $tzRegions['Pacific'] = $context->msg( 'timezoneregion-pacific' )->text();
1265 asort( $tzRegions );
1266
1267 $prefill = array_fill_keys( array_values( $tzRegions ), array() );
1268 $opt = array_merge( $opt, $prefill );
1269
1270 $now = date_create( 'now' );
1271
1272 foreach ( $tzs as $tz ) {
1273 $z = explode( '/', $tz, 2 );
1274
1275 # timezone_identifiers_list() returns a number of
1276 # backwards-compatibility entries. This filters them out of the
1277 # list presented to the user.
1278 if ( count( $z ) != 2 || !array_key_exists( $z[0], $tzRegions ) ) {
1279 continue;
1280 }
1281
1282 # Localize region
1283 $z[0] = $tzRegions[$z[0]];
1284
1285 $minDiff = floor( timezone_offset_get( timezone_open( $tz ), $now ) / 60 );
1286
1287 $display = str_replace( '_', ' ', $z[0] . '/' . $z[1] );
1288 $value = "ZoneInfo|$minDiff|$tz";
1289
1290 $opt[$z[0]][$display] = $value;
1291 }
1292 }
1293 return $opt;
1294 }
1295
1296 /**
1297 * @param $value
1298 * @param $alldata
1299 * @return int
1300 */
1301 static function filterIntval( $value, $alldata ){
1302 return intval( $value );
1303 }
1304
1305 /**
1306 * @param $tz
1307 * @param $alldata
1308 * @return string
1309 */
1310 static function filterTimezoneInput( $tz, $alldata ) {
1311 $data = explode( '|', $tz, 3 );
1312 switch ( $data[0] ) {
1313 case 'ZoneInfo':
1314 case 'System':
1315 return $tz;
1316 default:
1317 $data = explode( ':', $tz, 2 );
1318 if ( count( $data ) == 2 ) {
1319 $data[0] = intval( $data[0] );
1320 $data[1] = intval( $data[1] );
1321 $minDiff = abs( $data[0] ) * 60 + $data[1];
1322 if ( $data[0] < 0 ) $minDiff = - $minDiff;
1323 } else {
1324 $minDiff = intval( $data[0] ) * 60;
1325 }
1326
1327 # Max is +14:00 and min is -12:00, see:
1328 # http://en.wikipedia.org/wiki/Timezone
1329 $minDiff = min( $minDiff, 840 ); # 14:00
1330 $minDiff = max( $minDiff, - 720 ); # -12:00
1331 return 'Offset|' . $minDiff;
1332 }
1333 }
1334
1335 /**
1336 * @param $formData
1337 * @param $form HTMLForm
1338 * @param $entryPoint string
1339 * @return bool|Status|string
1340 */
1341 static function tryFormSubmit( $formData, $form, $entryPoint = 'internal' ) {
1342 global $wgHiddenPrefs;
1343
1344 $user = $form->getModifiedUser();
1345 $result = true;
1346
1347 // Filter input
1348 foreach ( array_keys( $formData ) as $name ) {
1349 if ( isset( self::$saveFilters[$name] ) ) {
1350 $formData[$name] =
1351 call_user_func( self::$saveFilters[$name], $formData[$name], $formData );
1352 }
1353 }
1354
1355 // Stuff that shouldn't be saved as a preference.
1356 $saveBlacklist = array(
1357 'realname',
1358 'emailaddress',
1359 );
1360
1361 // Fortunately, the realname field is MUCH simpler
1362 if ( !in_array( 'realname', $wgHiddenPrefs ) ) {
1363 $realName = $formData['realname'];
1364 $user->setRealName( $realName );
1365 }
1366
1367 foreach ( $saveBlacklist as $b ) {
1368 unset( $formData[$b] );
1369 }
1370
1371 # If users have saved a value for a preference which has subsequently been disabled
1372 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1373 # is subsequently re-enabled
1374 # TODO: maintenance script to actually delete these
1375 foreach( $wgHiddenPrefs as $pref ){
1376 # If the user has not set a non-default value here, the default will be returned
1377 # and subsequently discarded
1378 $formData[$pref] = $user->getOption( $pref, null, true );
1379 }
1380
1381 // Keeps old preferences from interfering due to back-compat
1382 // code, etc.
1383 $user->resetOptions();
1384
1385 foreach ( $formData as $key => $value ) {
1386 $user->setOption( $key, $value );
1387 }
1388
1389 $user->saveSettings();
1390
1391 return $result;
1392 }
1393
1394 /**
1395 * @param $formData
1396 * @return Status
1397 */
1398 public static function tryUISubmit( $formData, $form ) {
1399 $res = self::tryFormSubmit( $formData, $form, 'ui' );
1400
1401 if ( $res ) {
1402 $urlOptions = array( 'success' => 1 );
1403
1404 if ( $res === 'eauth' ) {
1405 $urlOptions['eauth'] = 1;
1406 }
1407
1408 $urlOptions += $form->getExtraSuccessRedirectParameters();
1409
1410 $url = $form->getTitle()->getFullURL( $urlOptions );
1411
1412 $form->getContext()->getOutput()->redirect( $url );
1413 }
1414
1415 return Status::newGood();
1416 }
1417
1418 /**
1419 * Try to set a user's email address.
1420 * This does *not* try to validate the address.
1421 * Caller is responsible for checking $wgAuth.
1422 * @param $user User
1423 * @param $newaddr string New email address
1424 * @return Array (true on success or Status on failure, info string)
1425 */
1426 public static function trySetUserEmail( User $user, $newaddr ) {
1427 global $wgEnableEmail, $wgEmailAuthentication;
1428 $info = ''; // none
1429
1430 if ( $wgEnableEmail ) {
1431 $oldaddr = $user->getEmail();
1432 if ( ( $newaddr != '' ) && ( $newaddr != $oldaddr ) ) {
1433 # The user has supplied a new email address on the login page
1434 # new behaviour: set this new emailaddr from login-page into user database record
1435 $user->setEmail( $newaddr );
1436 if ( $wgEmailAuthentication ) {
1437 # Mail a temporary password to the dirty address.
1438 # User can come back through the confirmation URL to re-enable email.
1439 $type = $oldaddr != '' ? 'changed' : 'set';
1440 $result = $user->sendConfirmationMail( $type );
1441 if ( !$result->isGood() ) {
1442 return array( $result, 'mailerror' );
1443 }
1444 $info = 'eauth';
1445 }
1446 } elseif ( $newaddr != $oldaddr ) { // if the address is the same, don't change it
1447 $user->setEmail( $newaddr );
1448 }
1449 if ( $oldaddr != $newaddr ) {
1450 wfRunHooks( 'PrefsEmailAudit', array( $user, $oldaddr, $newaddr ) );
1451 }
1452 }
1453
1454 return array( true, $info );
1455 }
1456
1457 /**
1458 * @param $user User
1459 * @return array
1460 */
1461 public static function loadOldSearchNs( $user ) {
1462 $searchableNamespaces = SearchEngine::searchableNamespaces();
1463 // Back compat with old format
1464 $arr = array();
1465
1466 foreach ( $searchableNamespaces as $ns => $name ) {
1467 if ( $user->getOption( 'searchNs' . $ns ) ) {
1468 $arr[] = $ns;
1469 }
1470 }
1471
1472 return $arr;
1473 }
1474 }
1475
1476 /** Some tweaks to allow js prefs to work */
1477 class PreferencesForm extends HTMLForm {
1478 // Override default value from HTMLForm
1479 protected $mSubSectionBeforeFields = false;
1480
1481 private $modifiedUser;
1482
1483 public function setModifiedUser( $user ) {
1484 $this->modifiedUser = $user;
1485 }
1486
1487 public function getModifiedUser() {
1488 if ( $this->modifiedUser === null ) {
1489 return $this->getUser();
1490 } else {
1491 return $this->modifiedUser;
1492 }
1493 }
1494
1495 /**
1496 * Get extra parameters for the query string when redirecting after
1497 * successful save.
1498 *
1499 * @return array()
1500 */
1501 public function getExtraSuccessRedirectParameters() {
1502 return array();
1503 }
1504
1505 /**
1506 * @param $html string
1507 * @return String
1508 */
1509 function wrapForm( $html ) {
1510 $html = Xml::tags( 'div', array( 'id' => 'preferences' ), $html );
1511
1512 return parent::wrapForm( $html );
1513 }
1514
1515 /**
1516 * @return String
1517 */
1518 function getButtons() {
1519 $html = parent::getButtons();
1520
1521 $t = SpecialPage::getTitleFor( 'Preferences', 'reset' );
1522
1523 $html .= "\n" . Linker::link( $t, $this->msg( 'restoreprefs' )->escaped() );
1524
1525 $html = Xml::tags( 'div', array( 'class' => 'mw-prefs-buttons' ), $html );
1526
1527 return $html;
1528 }
1529
1530 /**
1531 * @param $data array
1532 * @return array
1533 */
1534 function filterDataForSubmit( $data ) {
1535 // Support for separating MultiSelect preferences into multiple preferences
1536 // Due to lack of array support.
1537 foreach ( $this->mFlatFields as $fieldname => $field ) {
1538 $info = $field->mParams;
1539 if ( $field instanceof HTMLMultiSelectField ) {
1540 $options = HTMLFormField::flattenOptions( $info['options'] );
1541 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $fieldname;
1542
1543 foreach ( $options as $opt ) {
1544 $data["$prefix$opt"] = in_array( $opt, $data[$fieldname] );
1545 }
1546
1547 unset( $data[$fieldname] );
1548 }
1549 }
1550
1551 return $data;
1552 }
1553 /**
1554 * Get the whole body of the form.
1555 */
1556 function getBody() {
1557 return $this->displaySection( $this->mFieldTree, '', 'mw-prefsection-' );
1558 }
1559
1560 /**
1561 * Get the <legend> for a given section key. Normally this is the
1562 * prefs-$key message but we'll allow extensions to override it.
1563 */
1564 function getLegend( $key ) {
1565 $legend = parent::getLegend( $key );
1566 wfRunHooks( 'PreferencesGetLegend', array( $this, $key, &$legend ) );
1567 return $legend;
1568 }
1569 }