Merge "Correct $specialPageAliases for sa.wiki"
[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, 'mwfile' );
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-rc-collapsed'] = [
1026 'type' => 'api',
1027 ];
1028 $defaultPreferences['rcfilters-wl-collapsed'] = [
1029 'type' => 'api',
1030 ];
1031 $defaultPreferences['rcfilters-saved-queries'] = [
1032 'type' => 'api',
1033 ];
1034 $defaultPreferences['rcfilters-wl-saved-queries'] = [
1035 'type' => 'api',
1036 ];
1037 // Override RCFilters preferences for RecentChanges 'limit'
1038 $defaultPreferences['rcfilters-limit'] = [
1039 'type' => 'api',
1040 ];
1041 $defaultPreferences['rcfilters-saved-queries-versionbackup'] = [
1042 'type' => 'api',
1043 ];
1044 $defaultPreferences['rcfilters-wl-saved-queries-versionbackup'] = [
1045 'type' => 'api',
1046 ];
1047
1048 if ( $this->config->get( 'RCWatchCategoryMembership' ) ) {
1049 $defaultPreferences['hidecategorization'] = [
1050 'type' => 'toggle',
1051 'label-message' => 'tog-hidecategorization',
1052 'section' => 'rc/advancedrc',
1053 ];
1054 }
1055
1056 if ( $user->useRCPatrol() ) {
1057 $defaultPreferences['hidepatrolled'] = [
1058 'type' => 'toggle',
1059 'section' => 'rc/advancedrc',
1060 'label-message' => 'tog-hidepatrolled',
1061 ];
1062 }
1063
1064 if ( $user->useNPPatrol() ) {
1065 $defaultPreferences['newpageshidepatrolled'] = [
1066 'type' => 'toggle',
1067 'section' => 'rc/advancedrc',
1068 'label-message' => 'tog-newpageshidepatrolled',
1069 ];
1070 }
1071
1072 if ( $this->config->get( 'RCShowWatchingUsers' ) ) {
1073 $defaultPreferences['shownumberswatching'] = [
1074 'type' => 'toggle',
1075 'section' => 'rc/advancedrc',
1076 'label-message' => 'tog-shownumberswatching',
1077 ];
1078 }
1079
1080 if ( $this->config->get( 'StructuredChangeFiltersShowPreference' ) ) {
1081 $defaultPreferences['rcenhancedfilters-disable'] = [
1082 'type' => 'toggle',
1083 'section' => 'rc/opt-out',
1084 'label-message' => 'rcfilters-preference-label',
1085 'help-message' => 'rcfilters-preference-help',
1086 ];
1087 }
1088 }
1089
1090 /**
1091 * @param User $user
1092 * @param IContextSource $context
1093 * @param array &$defaultPreferences
1094 */
1095 protected function watchlistPreferences(
1096 User $user, IContextSource $context, &$defaultPreferences
1097 ) {
1098 $oouiEnabled = SpecialPreferences::isOouiEnabled( $context );
1099
1100 $watchlistdaysMax = ceil( $this->config->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1101
1102 # # Watchlist #####################################
1103 if ( $user->isAllowed( 'editmywatchlist' ) ) {
1104 $editWatchlistLinks = '';
1105 $editWatchlistLinksOld = [];
1106 $editWatchlistModes = [
1107 'edit' => [ 'subpage' => false, 'flags' => [] ],
1108 'raw' => [ 'subpage' => 'raw', 'flags' => [] ],
1109 'clear' => [ 'subpage' => 'clear', 'flags' => [ 'destructive' ] ],
1110 ];
1111 foreach ( $editWatchlistModes as $mode => $options ) {
1112 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1113 if ( $oouiEnabled ) {
1114 $editWatchlistLinks .=
1115 new \OOUI\ButtonWidget( [
1116 'href' => SpecialPage::getTitleFor( 'EditWatchlist', $options['subpage'] )->getLinkURL(),
1117 'flags' => $options[ 'flags' ],
1118 'label' => new \OOUI\HtmlSnippet(
1119 $context->msg( "prefs-editwatchlist-{$mode}" )->parse()
1120 ),
1121 ] );
1122 } else {
1123 $editWatchlistLinksOld[] = $this->linkRenderer->makeKnownLink(
1124 SpecialPage::getTitleFor( 'EditWatchlist', $options['subpage'] ),
1125 new HtmlArmor( $context->msg( "prefs-editwatchlist-{$mode}" )->parse() )
1126 );
1127 }
1128 }
1129
1130 $defaultPreferences['editwatchlist'] = [
1131 'type' => 'info',
1132 'raw' => true,
1133 'default' => $oouiEnabled ?
1134 $editWatchlistLinks :
1135 $context->getLanguage()->pipeList( $editWatchlistLinksOld ),
1136 'label-message' => 'prefs-editwatchlist-label',
1137 'section' => 'watchlist/editwatchlist',
1138 ];
1139 }
1140
1141 $defaultPreferences['watchlistdays'] = [
1142 'type' => 'float',
1143 'min' => 0,
1144 'max' => $watchlistdaysMax,
1145 'section' => 'watchlist/displaywatchlist',
1146 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1147 $watchlistdaysMax )->escaped(),
1148 'label-message' => 'prefs-watchlist-days',
1149 ];
1150 $defaultPreferences['wllimit'] = [
1151 'type' => 'int',
1152 'min' => 0,
1153 'max' => 1000,
1154 'label-message' => 'prefs-watchlist-edits',
1155 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1156 'section' => 'watchlist/displaywatchlist',
1157 ];
1158 $defaultPreferences['extendwatchlist'] = [
1159 'type' => 'toggle',
1160 'section' => 'watchlist/advancedwatchlist',
1161 'label-message' => 'tog-extendwatchlist',
1162 ];
1163 $defaultPreferences['watchlisthideminor'] = [
1164 'type' => 'toggle',
1165 'section' => 'watchlist/advancedwatchlist',
1166 'label-message' => 'tog-watchlisthideminor',
1167 ];
1168 $defaultPreferences['watchlisthidebots'] = [
1169 'type' => 'toggle',
1170 'section' => 'watchlist/advancedwatchlist',
1171 'label-message' => 'tog-watchlisthidebots',
1172 ];
1173 $defaultPreferences['watchlisthideown'] = [
1174 'type' => 'toggle',
1175 'section' => 'watchlist/advancedwatchlist',
1176 'label-message' => 'tog-watchlisthideown',
1177 ];
1178 $defaultPreferences['watchlisthideanons'] = [
1179 'type' => 'toggle',
1180 'section' => 'watchlist/advancedwatchlist',
1181 'label-message' => 'tog-watchlisthideanons',
1182 ];
1183 $defaultPreferences['watchlisthideliu'] = [
1184 'type' => 'toggle',
1185 'section' => 'watchlist/advancedwatchlist',
1186 'label-message' => 'tog-watchlisthideliu',
1187 ];
1188
1189 if ( !\SpecialWatchlist::checkStructuredFilterUiEnabled(
1190 $this->config,
1191 $user
1192 ) ) {
1193 $defaultPreferences['watchlistreloadautomatically'] = [
1194 'type' => 'toggle',
1195 'section' => 'watchlist/advancedwatchlist',
1196 'label-message' => 'tog-watchlistreloadautomatically',
1197 ];
1198 }
1199
1200 $defaultPreferences['watchlistunwatchlinks'] = [
1201 'type' => 'toggle',
1202 'section' => 'watchlist/advancedwatchlist',
1203 'label-message' => 'tog-watchlistunwatchlinks',
1204 ];
1205
1206 if ( $this->config->get( 'RCWatchCategoryMembership' ) ) {
1207 $defaultPreferences['watchlisthidecategorization'] = [
1208 'type' => 'toggle',
1209 'section' => 'watchlist/advancedwatchlist',
1210 'label-message' => 'tog-watchlisthidecategorization',
1211 ];
1212 }
1213
1214 if ( $user->useRCPatrol() ) {
1215 $defaultPreferences['watchlisthidepatrolled'] = [
1216 'type' => 'toggle',
1217 'section' => 'watchlist/advancedwatchlist',
1218 'label-message' => 'tog-watchlisthidepatrolled',
1219 ];
1220 }
1221
1222 $watchTypes = [
1223 'edit' => 'watchdefault',
1224 'move' => 'watchmoves',
1225 'delete' => 'watchdeletion'
1226 ];
1227
1228 // Kinda hacky
1229 if ( $user->isAllowed( 'createpage' ) || $user->isAllowed( 'createtalk' ) ) {
1230 $watchTypes['read'] = 'watchcreations';
1231 }
1232
1233 if ( $user->isAllowed( 'rollback' ) ) {
1234 $watchTypes['rollback'] = 'watchrollback';
1235 }
1236
1237 if ( $user->isAllowed( 'upload' ) ) {
1238 $watchTypes['upload'] = 'watchuploads';
1239 }
1240
1241 foreach ( $watchTypes as $action => $pref ) {
1242 if ( $user->isAllowed( $action ) ) {
1243 // Messages:
1244 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1245 // tog-watchrollback
1246 $defaultPreferences[$pref] = [
1247 'type' => 'toggle',
1248 'section' => 'watchlist/advancedwatchlist',
1249 'label-message' => "tog-$pref",
1250 ];
1251 }
1252 }
1253
1254 $defaultPreferences['watchlisttoken'] = [
1255 'type' => 'api',
1256 ];
1257
1258 if ( $oouiEnabled ) {
1259 $tokenButton = new \OOUI\ButtonWidget( [
1260 'href' => SpecialPage::getTitleFor( 'ResetTokens' )->getLinkURL( [
1261 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText()
1262 ] ),
1263 'label' => $context->msg( 'prefs-watchlist-managetokens' )->text(),
1264 ] );
1265 $defaultPreferences['watchlisttoken-info'] = [
1266 'type' => 'info',
1267 'section' => 'watchlist/tokenwatchlist',
1268 'label-message' => 'prefs-watchlist-token',
1269 'help-message' => 'prefs-help-tokenmanagement',
1270 'raw' => true,
1271 'default' => (string)$tokenButton,
1272 ];
1273 } else {
1274 $defaultPreferences['watchlisttoken-info'] = [
1275 'type' => 'info',
1276 'section' => 'watchlist/tokenwatchlist',
1277 'label-message' => 'prefs-watchlist-token',
1278 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1279 'help-message' => 'prefs-help-watchlist-token2',
1280 ];
1281 }
1282
1283 if ( $this->config->get( 'StructuredChangeFiltersShowWatchlistPreference' ) ) {
1284 $defaultPreferences['wlenhancedfilters-disable'] = [
1285 'type' => 'toggle',
1286 'section' => 'watchlist/opt-out',
1287 'label-message' => 'rcfilters-watchlist-preference-label',
1288 'help-message' => 'rcfilters-watchlist-preference-help',
1289 ];
1290 }
1291 }
1292
1293 /**
1294 * @param array &$defaultPreferences
1295 */
1296 protected function searchPreferences( &$defaultPreferences ) {
1297 foreach ( MWNamespace::getValidNamespaces() as $n ) {
1298 $defaultPreferences['searchNs' . $n] = [
1299 'type' => 'api',
1300 ];
1301 }
1302 }
1303
1304 /**
1305 * @param User $user The User object
1306 * @param IContextSource $context
1307 * @return array Text/links to display as key; $skinkey as value
1308 */
1309 protected function generateSkinOptions( User $user, IContextSource $context ) {
1310 $ret = [];
1311
1312 $mptitle = Title::newMainPage();
1313 $previewtext = $context->msg( 'skin-preview' )->escaped();
1314
1315 # Only show skins that aren't disabled in $wgSkipSkins
1316 $validSkinNames = Skin::getAllowedSkins();
1317
1318 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1319 $msg = $context->msg( "skinname-{$skinkey}" );
1320 if ( $msg->exists() ) {
1321 $skinname = htmlspecialchars( $msg->text() );
1322 }
1323 }
1324
1325 $defaultSkin = $this->config->get( 'DefaultSkin' );
1326 $allowUserCss = $this->config->get( 'AllowUserCss' );
1327 $allowUserJs = $this->config->get( 'AllowUserJs' );
1328
1329 # Sort by the internal name, so that the ordering is the same for each display language,
1330 # especially if some skin names are translated to use a different alphabet and some are not.
1331 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1332 # Display the default first in the list by comparing it as lesser than any other.
1333 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1334 return -1;
1335 }
1336 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1337 return 1;
1338 }
1339 return strcasecmp( $a, $b );
1340 } );
1341
1342 $foundDefault = false;
1343 foreach ( $validSkinNames as $skinkey => $sn ) {
1344 $linkTools = [];
1345
1346 # Mark the default skin
1347 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1348 $linkTools[] = $context->msg( 'default' )->escaped();
1349 $foundDefault = true;
1350 }
1351
1352 # Create preview link
1353 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1354 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1355
1356 # Create links to user CSS/JS pages
1357 if ( $allowUserCss ) {
1358 $cssPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.css' );
1359 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
1360 $linkTools[] = $this->linkRenderer->makeLink( $cssPage, $cssLinkText );
1361 }
1362
1363 if ( $allowUserJs ) {
1364 $jsPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.js' );
1365 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
1366 $linkTools[] = $this->linkRenderer->makeLink( $jsPage, $jsLinkText );
1367 }
1368
1369 $display = $sn . ' ' . $context->msg( 'parentheses' )
1370 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1371 ->escaped();
1372 $ret[$display] = $skinkey;
1373 }
1374
1375 if ( !$foundDefault ) {
1376 // If the default skin is not available, things are going to break horribly because the
1377 // default value for skin selector will not be a valid value. Let's just not show it then.
1378 return [];
1379 }
1380
1381 return $ret;
1382 }
1383
1384 /**
1385 * @param IContextSource $context
1386 * @return array
1387 */
1388 protected function getDateOptions( IContextSource $context ) {
1389 $lang = $context->getLanguage();
1390 $dateopts = $lang->getDatePreferences();
1391
1392 $ret = [];
1393
1394 if ( $dateopts ) {
1395 if ( !in_array( 'default', $dateopts ) ) {
1396 $dateopts[] = 'default'; // Make sure default is always valid T21237
1397 }
1398
1399 // FIXME KLUGE: site default might not be valid for user language
1400 global $wgDefaultUserOptions;
1401 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1402 $wgDefaultUserOptions['date'] = 'default';
1403 }
1404
1405 $epoch = wfTimestampNow();
1406 foreach ( $dateopts as $key ) {
1407 if ( $key == 'default' ) {
1408 $formatted = $context->msg( 'datedefault' )->escaped();
1409 } else {
1410 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1411 }
1412 $ret[$formatted] = $key;
1413 }
1414 }
1415 return $ret;
1416 }
1417
1418 /**
1419 * @param MessageLocalizer $l10n
1420 * @return array
1421 */
1422 protected function getImageSizes( MessageLocalizer $l10n ) {
1423 $ret = [];
1424 $pixels = $l10n->msg( 'unit-pixel' )->text();
1425
1426 foreach ( $this->config->get( 'ImageLimits' ) as $index => $limits ) {
1427 // Note: A left-to-right marker (U+200E) is inserted, see T144386
1428 $display = "{$limits[0]}\u{200E}×{$limits[1]}$pixels";
1429 $ret[$display] = $index;
1430 }
1431
1432 return $ret;
1433 }
1434
1435 /**
1436 * @param MessageLocalizer $l10n
1437 * @return array
1438 */
1439 protected function getThumbSizes( MessageLocalizer $l10n ) {
1440 $ret = [];
1441 $pixels = $l10n->msg( 'unit-pixel' )->text();
1442
1443 foreach ( $this->config->get( 'ThumbLimits' ) as $index => $size ) {
1444 $display = $size . $pixels;
1445 $ret[$display] = $index;
1446 }
1447
1448 return $ret;
1449 }
1450
1451 /**
1452 * @param string $signature
1453 * @param array $alldata
1454 * @param HTMLForm $form
1455 * @return bool|string
1456 */
1457 protected function validateSignature( $signature, $alldata, HTMLForm $form ) {
1458 $maxSigChars = $this->config->get( 'MaxSigChars' );
1459 if ( mb_strlen( $signature ) > $maxSigChars ) {
1460 return Xml::element( 'span', [ 'class' => 'error' ],
1461 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1462 } elseif ( isset( $alldata['fancysig'] ) &&
1463 $alldata['fancysig'] &&
1464 MediaWikiServices::getInstance()->getParser()->validateSig( $signature ) === false
1465 ) {
1466 return Xml::element(
1467 'span',
1468 [ 'class' => 'error' ],
1469 $form->msg( 'badsig' )->text()
1470 );
1471 } else {
1472 return true;
1473 }
1474 }
1475
1476 /**
1477 * @param string $signature
1478 * @param array $alldata
1479 * @param HTMLForm $form
1480 * @return string
1481 */
1482 protected function cleanSignature( $signature, $alldata, HTMLForm $form ) {
1483 $parser = MediaWikiServices::getInstance()->getParser();
1484 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1485 $signature = $parser->cleanSig( $signature );
1486 } else {
1487 // When no fancy sig used, make sure ~{3,5} get removed.
1488 $signature = Parser::cleanSigInSig( $signature );
1489 }
1490
1491 return $signature;
1492 }
1493
1494 /**
1495 * @param User $user
1496 * @param IContextSource $context
1497 * @param string $formClass
1498 * @param array $remove Array of items to remove
1499 * @return HTMLForm
1500 */
1501 public function getForm(
1502 User $user,
1503 IContextSource $context,
1504 $formClass = PreferencesFormLegacy::class,
1505 array $remove = []
1506 ) {
1507 if ( SpecialPreferences::isOouiEnabled( $context ) ) {
1508 // We use ButtonWidgets in some of the getPreferences() functions
1509 $context->getOutput()->enableOOUI();
1510 }
1511
1512 $formDescriptor = $this->getFormDescriptor( $user, $context );
1513 if ( count( $remove ) ) {
1514 $removeKeys = array_flip( $remove );
1515 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1516 }
1517
1518 // Remove type=api preferences. They are not intended for rendering in the form.
1519 foreach ( $formDescriptor as $name => $info ) {
1520 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1521 unset( $formDescriptor[$name] );
1522 }
1523 }
1524
1525 /**
1526 * @var $htmlForm HTMLForm
1527 */
1528 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1529
1530 $htmlForm->setModifiedUser( $user );
1531 $htmlForm->setId( 'mw-prefs-form' );
1532 $htmlForm->setAutocomplete( 'off' );
1533 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1534 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1535 $htmlForm->setSubmitTooltip( 'preferences-save' );
1536 $htmlForm->setSubmitID( 'prefcontrol' );
1537 $htmlForm->setSubmitCallback( function ( array $formData, HTMLForm $form ) {
1538 return $this->submitForm( $formData, $form );
1539 } );
1540
1541 return $htmlForm;
1542 }
1543
1544 /**
1545 * @param IContextSource $context
1546 * @return array
1547 */
1548 protected function getTimezoneOptions( IContextSource $context ) {
1549 $opt = [];
1550
1551 $localTZoffset = $this->config->get( 'LocalTZoffset' );
1552 $timeZoneList = $this->getTimeZoneList( $context->getLanguage() );
1553
1554 $timestamp = MWTimestamp::getLocalInstance();
1555 // Check that the LocalTZoffset is the same as the local time zone offset
1556 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1557 $timezoneName = $timestamp->getTimezone()->getName();
1558 // Localize timezone
1559 if ( isset( $timeZoneList[$timezoneName] ) ) {
1560 $timezoneName = $timeZoneList[$timezoneName]['name'];
1561 }
1562 $server_tz_msg = $context->msg(
1563 'timezoneuseserverdefault',
1564 $timezoneName
1565 )->text();
1566 } else {
1567 $tzstring = sprintf(
1568 '%+03d:%02d',
1569 floor( $localTZoffset / 60 ),
1570 abs( $localTZoffset ) % 60
1571 );
1572 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1573 }
1574 $opt[$server_tz_msg] = "System|$localTZoffset";
1575 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1576 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1577
1578 foreach ( $timeZoneList as $timeZoneInfo ) {
1579 $region = $timeZoneInfo['region'];
1580 if ( !isset( $opt[$region] ) ) {
1581 $opt[$region] = [];
1582 }
1583 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1584 }
1585 return $opt;
1586 }
1587
1588 /**
1589 * @param string $tz
1590 * @param array $alldata
1591 * @return string
1592 */
1593 protected function filterTimezoneInput( $tz, array $alldata ) {
1594 $data = explode( '|', $tz, 3 );
1595 switch ( $data[0] ) {
1596 case 'ZoneInfo':
1597 $valid = false;
1598
1599 if ( count( $data ) === 3 ) {
1600 // Make sure this timezone exists
1601 try {
1602 new DateTimeZone( $data[2] );
1603 // If the constructor didn't throw, we know it's valid
1604 $valid = true;
1605 } catch ( Exception $e ) {
1606 // Not a valid timezone
1607 }
1608 }
1609
1610 if ( !$valid ) {
1611 // If the supplied timezone doesn't exist, fall back to the encoded offset
1612 return 'Offset|' . intval( $tz[1] );
1613 }
1614 return $tz;
1615 case 'System':
1616 return $tz;
1617 default:
1618 $data = explode( ':', $tz, 2 );
1619 if ( count( $data ) == 2 ) {
1620 $data[0] = intval( $data[0] );
1621 $data[1] = intval( $data[1] );
1622 $minDiff = abs( $data[0] ) * 60 + $data[1];
1623 if ( $data[0] < 0 ) {
1624 $minDiff = - $minDiff;
1625 }
1626 } else {
1627 $minDiff = intval( $data[0] ) * 60;
1628 }
1629
1630 # Max is +14:00 and min is -12:00, see:
1631 # https://en.wikipedia.org/wiki/Timezone
1632 $minDiff = min( $minDiff, 840 ); # 14:00
1633 $minDiff = max( $minDiff, -720 ); # -12:00
1634 return 'Offset|' . $minDiff;
1635 }
1636 }
1637
1638 /**
1639 * Handle the form submission if everything validated properly
1640 *
1641 * @param array $formData
1642 * @param HTMLForm $form
1643 * @return bool|Status|string
1644 */
1645 protected function saveFormData( $formData, HTMLForm $form ) {
1646 $user = $form->getModifiedUser();
1647 $hiddenPrefs = $this->config->get( 'HiddenPrefs' );
1648 $result = true;
1649
1650 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1651 return Status::newFatal( 'mypreferencesprotected' );
1652 }
1653
1654 // Filter input
1655 foreach ( array_keys( $formData ) as $name ) {
1656 $filters = $this->getSaveFilters();
1657 if ( isset( $filters[$name] ) ) {
1658 $formData[$name] = call_user_func( $filters[$name], $formData[$name], $formData );
1659 }
1660 }
1661
1662 // Fortunately, the realname field is MUCH simpler
1663 // (not really "private", but still shouldn't be edited without permission)
1664
1665 if ( !in_array( 'realname', $hiddenPrefs )
1666 && $user->isAllowed( 'editmyprivateinfo' )
1667 && array_key_exists( 'realname', $formData )
1668 ) {
1669 $realName = $formData['realname'];
1670 $user->setRealName( $realName );
1671 }
1672
1673 if ( $user->isAllowed( 'editmyoptions' ) ) {
1674 $oldUserOptions = $user->getOptions();
1675
1676 foreach ( $this->getSaveBlacklist() as $b ) {
1677 unset( $formData[$b] );
1678 }
1679
1680 # If users have saved a value for a preference which has subsequently been disabled
1681 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1682 # is subsequently re-enabled
1683 foreach ( $hiddenPrefs as $pref ) {
1684 # If the user has not set a non-default value here, the default will be returned
1685 # and subsequently discarded
1686 $formData[$pref] = $user->getOption( $pref, null, true );
1687 }
1688
1689 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1690 if (
1691 isset( $formData['rclimit'] ) &&
1692 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1693 ) {
1694 $formData['rcfilters-limit'] = $formData['rclimit'];
1695 }
1696
1697 // Keep old preferences from interfering due to back-compat code, etc.
1698 $user->resetOptions( 'unused', $form->getContext() );
1699
1700 foreach ( $formData as $key => $value ) {
1701 $user->setOption( $key, $value );
1702 }
1703
1704 Hooks::run(
1705 'PreferencesFormPreSave',
1706 [ $formData, $form, $user, &$result, $oldUserOptions ]
1707 );
1708 }
1709
1710 AuthManager::callLegacyAuthPlugin( 'updateExternalDB', [ $user ] );
1711 $user->saveSettings();
1712
1713 return $result;
1714 }
1715
1716 /**
1717 * DO NOT USE. Temporary function to punch hole for the Preferences class.
1718 *
1719 * @deprecated since 1.31, its inception
1720 *
1721 * @param array $formData
1722 * @param HTMLForm $form
1723 * @return bool|Status|string
1724 */
1725 public function legacySaveFormData( $formData, HTMLForm $form ) {
1726 return $this->saveFormData( $formData, $form );
1727 }
1728
1729 /**
1730 * Save the form data and reload the page
1731 *
1732 * @param array $formData
1733 * @param HTMLForm $form
1734 * @return Status
1735 */
1736 protected function submitForm( array $formData, HTMLForm $form ) {
1737 $res = $this->saveFormData( $formData, $form );
1738
1739 if ( $res === true ) {
1740 $context = $form->getContext();
1741 $urlOptions = [];
1742
1743 if ( $res === 'eauth' ) {
1744 $urlOptions['eauth'] = 1;
1745 }
1746
1747 if (
1748 $context->getRequest()->getFuzzyBool( 'ooui' ) !==
1749 $context->getConfig()->get( 'OOUIPreferences' )
1750 ) {
1751 $urlOptions[ 'ooui' ] = $context->getRequest()->getFuzzyBool( 'ooui' ) ? 1 : 0;
1752 }
1753
1754 $urlOptions += $form->getExtraSuccessRedirectParameters();
1755
1756 $url = $form->getTitle()->getFullURL( $urlOptions );
1757
1758 // Set session data for the success message
1759 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1760
1761 $context->getOutput()->redirect( $url );
1762 }
1763
1764 return ( $res === true ? Status::newGood() : $res );
1765 }
1766
1767 /**
1768 * DO NOT USE. Temporary function to punch hole for the Preferences class.
1769 *
1770 * @deprecated since 1.31, its inception
1771 *
1772 * @param array $formData
1773 * @param HTMLForm $form
1774 * @return Status
1775 */
1776 public function legacySubmitForm( array $formData, HTMLForm $form ) {
1777 return $this->submitForm( $formData, $form );
1778 }
1779
1780 /**
1781 * Get a list of all time zones
1782 * @param Language $language Language used for the localized names
1783 * @return array A list of all time zones. The system name of the time zone is used as key and
1784 * the value is an array which contains localized name, the timecorrection value used for
1785 * preferences and the region
1786 * @since 1.26
1787 */
1788 protected function getTimeZoneList( Language $language ) {
1789 $identifiers = DateTimeZone::listIdentifiers();
1790 if ( $identifiers === false ) {
1791 return [];
1792 }
1793 sort( $identifiers );
1794
1795 $tzRegions = [
1796 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1797 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1798 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1799 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1800 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1801 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1802 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1803 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1804 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1805 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1806 ];
1807 asort( $tzRegions );
1808
1809 $timeZoneList = [];
1810
1811 $now = new DateTime();
1812
1813 foreach ( $identifiers as $identifier ) {
1814 $parts = explode( '/', $identifier, 2 );
1815
1816 // DateTimeZone::listIdentifiers() returns a number of
1817 // backwards-compatibility entries. This filters them out of the
1818 // list presented to the user.
1819 if ( count( $parts ) !== 2 || !array_key_exists( $parts[0], $tzRegions ) ) {
1820 continue;
1821 }
1822
1823 // Localize region
1824 $parts[0] = $tzRegions[$parts[0]];
1825
1826 $dateTimeZone = new DateTimeZone( $identifier );
1827 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1828
1829 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1830 $value = "ZoneInfo|$minDiff|$identifier";
1831
1832 $timeZoneList[$identifier] = [
1833 'name' => $display,
1834 'timecorrection' => $value,
1835 'region' => $parts[0],
1836 ];
1837 }
1838
1839 return $timeZoneList;
1840 }
1841 }