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