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