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