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