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