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