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