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