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