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