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