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