Merge "rdbms: add IDatabase::lockForUpdate() convenience method"
[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 if ( !$this->contLang->hasVariants() ) {
448 continue;
449 }
450
451 $variants = $this->contLang->getVariants();
452 $variantArray = [];
453 foreach ( $variants as $v ) {
454 $v = str_replace( '_', '-', strtolower( $v ) );
455 $variantArray[$v] = $lang->getVariantname( $v, false );
456 }
457
458 $options = [];
459 foreach ( $variantArray as $code => $name ) {
460 $display = LanguageCode::bcp47( $code ) . ' - ' . $name;
461 $options[$display] = $code;
462 }
463
464 $defaultPreferences['variant'] = [
465 'label-message' => 'yourvariant',
466 'type' => 'select',
467 'options' => $options,
468 'section' => 'personal/i18n',
469 'help-message' => 'prefs-help-variant',
470 ];
471 } else {
472 $defaultPreferences["variant-$langCode"] = [
473 'type' => 'api',
474 ];
475 }
476 }
477 }
478
479 // Stuff from Language::getExtraUserToggles()
480 // FIXME is this dead code? $extraUserToggles doesn't seem to be defined for any language
481 $toggles = $this->contLang->getExtraUserToggles();
482
483 foreach ( $toggles as $toggle ) {
484 $defaultPreferences[$toggle] = [
485 'type' => 'toggle',
486 'section' => 'personal/i18n',
487 'label-message' => "tog-$toggle",
488 ];
489 }
490
491 // show a preview of the old signature first
492 $oldsigWikiText = MediaWikiServices::getInstance()->getParser()->preSaveTransform(
493 '~~~',
494 $context->getTitle(),
495 $user,
496 ParserOptions::newFromContext( $context )
497 );
498 $oldsigHTML = $context->getOutput()->parseInline( $oldsigWikiText, true, true );
499 $defaultPreferences['oldsig'] = [
500 'type' => 'info',
501 'raw' => true,
502 'label-message' => 'tog-oldsig',
503 'default' => $oldsigHTML,
504 'section' => 'personal/signature',
505 ];
506 $defaultPreferences['nickname'] = [
507 'type' => $this->authManager->allowsPropertyChange( 'nickname' ) ? 'text' : 'info',
508 'maxlength' => $this->config->get( 'MaxSigChars' ),
509 'label-message' => 'yournick',
510 'validation-callback' => function ( $signature, $alldata, HTMLForm $form ) {
511 return $this->validateSignature( $signature, $alldata, $form );
512 },
513 'section' => 'personal/signature',
514 'filter-callback' => function ( $signature, array $alldata, HTMLForm $form ) {
515 return $this->cleanSignature( $signature, $alldata, $form );
516 },
517 ];
518 $defaultPreferences['fancysig'] = [
519 'type' => 'toggle',
520 'label-message' => 'tog-fancysig',
521 // show general help about signature at the bottom of the section
522 'help-message' => 'prefs-help-signature',
523 'section' => 'personal/signature'
524 ];
525
526 # # Email stuff
527
528 if ( $this->config->get( 'EnableEmail' ) ) {
529 if ( $canViewPrivateInfo ) {
530 $helpMessages[] = $this->config->get( 'EmailConfirmToEdit' )
531 ? 'prefs-help-email-required'
532 : 'prefs-help-email';
533
534 if ( $this->config->get( 'EnableUserEmail' ) ) {
535 // additional messages when users can send email to each other
536 $helpMessages[] = 'prefs-help-email-others';
537 }
538
539 $emailAddress = $user->getEmail() ? htmlspecialchars( $user->getEmail() ) : '';
540 if ( $canEditPrivateInfo && $this->authManager->allowsPropertyChange( 'emailaddress' ) ) {
541 if ( $oouiEnabled ) {
542 $link = new \OOUI\ButtonWidget( [
543 'href' => SpecialPage::getTitleFor( 'ChangeEmail' )->getLinkURL( [
544 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText()
545 ] ),
546 'label' =>
547 $context->msg( $user->getEmail() ? 'prefs-changeemail' : 'prefs-setemail' )->text(),
548 ] );
549
550 $emailAddress .= $emailAddress == '' ? $link : ( '<br />' . $link );
551 } else {
552 $link = $this->linkRenderer->makeLink(
553 SpecialPage::getTitleFor( 'ChangeEmail' ),
554 $context->msg( $user->getEmail() ? 'prefs-changeemail' : 'prefs-setemail' )->text(),
555 [],
556 [ 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText() ] );
557
558 $emailAddress .= $emailAddress == '' ? $link : (
559 $context->msg( 'word-separator' )->escaped()
560 . $context->msg( 'parentheses' )->rawParams( $link )->escaped()
561 );
562 }
563 }
564
565 $defaultPreferences['emailaddress'] = [
566 'type' => 'info',
567 'raw' => true,
568 'default' => $emailAddress,
569 'label-message' => 'youremail',
570 'section' => 'personal/email',
571 'help-messages' => $helpMessages,
572 # 'cssclass' chosen below
573 ];
574 }
575
576 $disableEmailPrefs = false;
577
578 if ( $this->config->get( 'EmailAuthentication' ) ) {
579 $emailauthenticationclass = 'mw-email-not-authenticated';
580 if ( $user->getEmail() ) {
581 if ( $user->getEmailAuthenticationTimestamp() ) {
582 // date and time are separate parameters to facilitate localisation.
583 // $time is kept for backward compat reasons.
584 // 'emailauthenticated' is also used in SpecialConfirmemail.php
585 $displayUser = $context->getUser();
586 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
587 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
588 $d = $lang->userDate( $emailTimestamp, $displayUser );
589 $t = $lang->userTime( $emailTimestamp, $displayUser );
590 $emailauthenticated = $context->msg( 'emailauthenticated',
591 $time, $d, $t )->parse() . '<br />';
592 $disableEmailPrefs = false;
593 $emailauthenticationclass = 'mw-email-authenticated';
594 } else {
595 $disableEmailPrefs = true;
596 if ( $oouiEnabled ) {
597 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
598 new \OOUI\ButtonWidget( [
599 'href' => SpecialPage::getTitleFor( 'Confirmemail' )->getLinkURL(),
600 'label' => $context->msg( 'emailconfirmlink' )->text(),
601 ] );
602 } else {
603 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
604 $this->linkRenderer->makeKnownLink(
605 SpecialPage::getTitleFor( 'Confirmemail' ),
606 $context->msg( 'emailconfirmlink' )->text()
607 ) . '<br />';
608 }
609 $emailauthenticationclass = "mw-email-not-authenticated";
610 }
611 } else {
612 $disableEmailPrefs = true;
613 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
614 $emailauthenticationclass = 'mw-email-none';
615 }
616
617 if ( $canViewPrivateInfo ) {
618 $defaultPreferences['emailauthentication'] = [
619 'type' => 'info',
620 'raw' => true,
621 'section' => 'personal/email',
622 'label-message' => 'prefs-emailconfirm-label',
623 'default' => $emailauthenticated,
624 # Apply the same CSS class used on the input to the message:
625 'cssclass' => $emailauthenticationclass,
626 ];
627 }
628 }
629
630 if ( $this->config->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
631 $defaultPreferences['disablemail'] = [
632 'id' => 'wpAllowEmail',
633 'type' => 'toggle',
634 'invert' => true,
635 'section' => 'personal/email',
636 'label-message' => 'allowemail',
637 'disabled' => $disableEmailPrefs,
638 ];
639
640 $defaultPreferences['email-allow-new-users'] = [
641 'id' => 'wpAllowEmailFromNewUsers',
642 'type' => 'toggle',
643 'section' => 'personal/email',
644 'label-message' => 'email-allow-new-users-label',
645 'disabled' => $disableEmailPrefs,
646 ];
647
648 $defaultPreferences['ccmeonemails'] = [
649 'type' => 'toggle',
650 'section' => 'personal/email',
651 'label-message' => 'tog-ccmeonemails',
652 'disabled' => $disableEmailPrefs,
653 ];
654
655 if ( $this->config->get( 'EnableUserEmailBlacklist' ) ) {
656 $lookup = CentralIdLookup::factory();
657 $ids = $user->getOption( 'email-blacklist', [] );
658 $names = $ids ? $lookup->namesFromCentralIds( $ids, $user ) : [];
659
660 $defaultPreferences['email-blacklist'] = [
661 'type' => 'usersmultiselect',
662 'label-message' => 'email-blacklist-label',
663 'section' => 'personal/email',
664 'default' => implode( "\n", $names ),
665 'disabled' => $disableEmailPrefs,
666 ];
667 }
668 }
669
670 if ( $this->config->get( 'EnotifWatchlist' ) ) {
671 $defaultPreferences['enotifwatchlistpages'] = [
672 'type' => 'toggle',
673 'section' => 'personal/email',
674 'label-message' => 'tog-enotifwatchlistpages',
675 'disabled' => $disableEmailPrefs,
676 ];
677 }
678 if ( $this->config->get( 'EnotifUserTalk' ) ) {
679 $defaultPreferences['enotifusertalkpages'] = [
680 'type' => 'toggle',
681 'section' => 'personal/email',
682 'label-message' => 'tog-enotifusertalkpages',
683 'disabled' => $disableEmailPrefs,
684 ];
685 }
686 if ( $this->config->get( 'EnotifUserTalk' ) || $this->config->get( 'EnotifWatchlist' ) ) {
687 if ( $this->config->get( 'EnotifMinorEdits' ) ) {
688 $defaultPreferences['enotifminoredits'] = [
689 'type' => 'toggle',
690 'section' => 'personal/email',
691 'label-message' => 'tog-enotifminoredits',
692 'disabled' => $disableEmailPrefs,
693 ];
694 }
695
696 if ( $this->config->get( 'EnotifRevealEditorAddress' ) ) {
697 $defaultPreferences['enotifrevealaddr'] = [
698 'type' => 'toggle',
699 'section' => 'personal/email',
700 'label-message' => 'tog-enotifrevealaddr',
701 'disabled' => $disableEmailPrefs,
702 ];
703 }
704 }
705 }
706 }
707
708 /**
709 * @param User $user
710 * @param IContextSource $context
711 * @param array &$defaultPreferences
712 * @return void
713 */
714 protected function skinPreferences( User $user, IContextSource $context, &$defaultPreferences ) {
715 # # Skin #####################################
716
717 // Skin selector, if there is at least one valid skin
718 $skinOptions = $this->generateSkinOptions( $user, $context );
719 if ( $skinOptions ) {
720 $defaultPreferences['skin'] = [
721 'type' => 'radio',
722 'options' => $skinOptions,
723 'section' => 'rendering/skin',
724 ];
725 }
726
727 $allowUserCss = $this->config->get( 'AllowUserCss' );
728 $allowUserJs = $this->config->get( 'AllowUserJs' );
729 # Create links to user CSS/JS pages for all skins
730 # This code is basically copied from generateSkinOptions(). It'd
731 # be nice to somehow merge this back in there to avoid redundancy.
732 if ( $allowUserCss || $allowUserJs ) {
733 $linkTools = [];
734 $userName = $user->getName();
735
736 if ( $allowUserCss ) {
737 $cssPage = Title::makeTitleSafe( NS_USER, $userName . '/common.css' );
738 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
739 $linkTools[] = $this->linkRenderer->makeLink( $cssPage, $cssLinkText );
740 }
741
742 if ( $allowUserJs ) {
743 $jsPage = Title::makeTitleSafe( NS_USER, $userName . '/common.js' );
744 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
745 $linkTools[] = $this->linkRenderer->makeLink( $jsPage, $jsLinkText );
746 }
747
748 $defaultPreferences['commoncssjs'] = [
749 'type' => 'info',
750 'raw' => true,
751 'default' => $context->getLanguage()->pipeList( $linkTools ),
752 'label-message' => 'prefs-common-config',
753 'section' => 'rendering/skin',
754 ];
755 }
756 }
757
758 /**
759 * @param IContextSource $context
760 * @param array &$defaultPreferences
761 */
762 protected function filesPreferences( IContextSource $context, &$defaultPreferences ) {
763 # # Files #####################################
764 $defaultPreferences['imagesize'] = [
765 'type' => 'select',
766 'options' => $this->getImageSizes( $context ),
767 'label-message' => 'imagemaxsize',
768 'section' => 'rendering/files',
769 ];
770 $defaultPreferences['thumbsize'] = [
771 'type' => 'select',
772 'options' => $this->getThumbSizes( $context ),
773 'label-message' => 'thumbsize',
774 'section' => 'rendering/files',
775 ];
776 }
777
778 /**
779 * @param User $user
780 * @param IContextSource $context
781 * @param array &$defaultPreferences
782 * @return void
783 */
784 protected function datetimePreferences( $user, IContextSource $context, &$defaultPreferences ) {
785 # # Date and time #####################################
786 $dateOptions = $this->getDateOptions( $context );
787 if ( $dateOptions ) {
788 $defaultPreferences['date'] = [
789 'type' => 'radio',
790 'options' => $dateOptions,
791 'section' => 'rendering/dateformat',
792 ];
793 }
794
795 // Info
796 $now = wfTimestampNow();
797 $lang = $context->getLanguage();
798 $nowlocal = Xml::element( 'span', [ 'id' => 'wpLocalTime' ],
799 $lang->userTime( $now, $user ) );
800 $nowserver = $lang->userTime( $now, $user,
801 [ 'format' => false, 'timecorrection' => false ] ) .
802 Html::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 + (int)substr( $now, 10, 2 ) );
803
804 $defaultPreferences['nowserver'] = [
805 'type' => 'info',
806 'raw' => 1,
807 'label-message' => 'servertime',
808 'default' => $nowserver,
809 'section' => 'rendering/timeoffset',
810 ];
811
812 $defaultPreferences['nowlocal'] = [
813 'type' => 'info',
814 'raw' => 1,
815 'label-message' => 'localtime',
816 'default' => $nowlocal,
817 'section' => 'rendering/timeoffset',
818 ];
819
820 // Grab existing pref.
821 $tzOffset = $user->getOption( 'timecorrection' );
822 $tz = explode( '|', $tzOffset, 3 );
823
824 $tzOptions = $this->getTimezoneOptions( $context );
825
826 $tzSetting = $tzOffset;
827 if ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
828 !in_array( $tzOffset, HTMLFormField::flattenOptions( $tzOptions ) )
829 ) {
830 // Timezone offset can vary with DST
831 try {
832 $userTZ = new DateTimeZone( $tz[2] );
833 $minDiff = floor( $userTZ->getOffset( new DateTime( 'now' ) ) / 60 );
834 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
835 } catch ( Exception $e ) {
836 // User has an invalid time zone set. Fall back to just using the offset
837 $tz[0] = 'Offset';
838 }
839 }
840 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
841 $minDiff = $tz[1];
842 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) % 60 );
843 }
844
845 $defaultPreferences['timecorrection'] = [
846 'class' => \HTMLSelectOrOtherField::class,
847 'label-message' => 'timezonelegend',
848 'options' => $tzOptions,
849 'default' => $tzSetting,
850 'size' => 20,
851 'section' => 'rendering/timeoffset',
852 'id' => 'wpTimeCorrection',
853 ];
854 }
855
856 /**
857 * @param MessageLocalizer $l10n
858 * @param array &$defaultPreferences
859 */
860 protected function renderingPreferences( MessageLocalizer $l10n, &$defaultPreferences ) {
861 # # Diffs ####################################
862 $defaultPreferences['diffonly'] = [
863 'type' => 'toggle',
864 'section' => 'rendering/diffs',
865 'label-message' => 'tog-diffonly',
866 ];
867 $defaultPreferences['norollbackdiff'] = [
868 'type' => 'toggle',
869 'section' => 'rendering/diffs',
870 'label-message' => 'tog-norollbackdiff',
871 ];
872
873 # # Page Rendering ##############################
874 if ( $this->config->get( 'AllowUserCssPrefs' ) ) {
875 $defaultPreferences['underline'] = [
876 'type' => 'select',
877 'options' => [
878 $l10n->msg( 'underline-never' )->text() => 0,
879 $l10n->msg( 'underline-always' )->text() => 1,
880 $l10n->msg( 'underline-default' )->text() => 2,
881 ],
882 'label-message' => 'tog-underline',
883 'section' => 'rendering/advancedrendering',
884 ];
885 }
886
887 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
888 $stubThresholdOptions = [ $l10n->msg( 'stub-threshold-disabled' )->text() => 0 ];
889 foreach ( $stubThresholdValues as $value ) {
890 $stubThresholdOptions[$l10n->msg( 'size-bytes', $value )->text()] = $value;
891 }
892
893 $defaultPreferences['stubthreshold'] = [
894 'type' => 'select',
895 'section' => 'rendering/advancedrendering',
896 'options' => $stubThresholdOptions,
897 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
898 'label-raw' => $l10n->msg( 'stub-threshold' )->rawParams(
899 '<a href="#" class="stub">' .
900 $l10n->msg( 'stub-threshold-sample-link' )->parse() .
901 '</a>' )->parse(),
902 ];
903
904 $defaultPreferences['showhiddencats'] = [
905 'type' => 'toggle',
906 'section' => 'rendering/advancedrendering',
907 'label-message' => 'tog-showhiddencats'
908 ];
909
910 $defaultPreferences['numberheadings'] = [
911 'type' => 'toggle',
912 'section' => 'rendering/advancedrendering',
913 'label-message' => 'tog-numberheadings',
914 ];
915 }
916
917 /**
918 * @param User $user
919 * @param MessageLocalizer $l10n
920 * @param array &$defaultPreferences
921 */
922 protected function editingPreferences( User $user, MessageLocalizer $l10n, &$defaultPreferences ) {
923 # # Editing #####################################
924 $defaultPreferences['editsectiononrightclick'] = [
925 'type' => 'toggle',
926 'section' => 'editing/advancedediting',
927 'label-message' => 'tog-editsectiononrightclick',
928 ];
929 $defaultPreferences['editondblclick'] = [
930 'type' => 'toggle',
931 'section' => 'editing/advancedediting',
932 'label-message' => 'tog-editondblclick',
933 ];
934
935 if ( $this->config->get( 'AllowUserCssPrefs' ) ) {
936 $defaultPreferences['editfont'] = [
937 'type' => 'select',
938 'section' => 'editing/editor',
939 'label-message' => 'editfont-style',
940 'options' => [
941 $l10n->msg( 'editfont-monospace' )->text() => 'monospace',
942 $l10n->msg( 'editfont-sansserif' )->text() => 'sans-serif',
943 $l10n->msg( 'editfont-serif' )->text() => 'serif',
944 ]
945 ];
946 }
947
948 if ( $user->isAllowed( 'minoredit' ) ) {
949 $defaultPreferences['minordefault'] = [
950 'type' => 'toggle',
951 'section' => 'editing/editor',
952 'label-message' => 'tog-minordefault',
953 ];
954 }
955
956 $defaultPreferences['forceeditsummary'] = [
957 'type' => 'toggle',
958 'section' => 'editing/editor',
959 'label-message' => 'tog-forceeditsummary',
960 ];
961 $defaultPreferences['useeditwarning'] = [
962 'type' => 'toggle',
963 'section' => 'editing/editor',
964 'label-message' => 'tog-useeditwarning',
965 ];
966 $defaultPreferences['showtoolbar'] = [
967 'type' => 'toggle',
968 'section' => 'editing/editor',
969 'label-message' => 'tog-showtoolbar',
970 ];
971
972 $defaultPreferences['previewonfirst'] = [
973 'type' => 'toggle',
974 'section' => 'editing/preview',
975 'label-message' => 'tog-previewonfirst',
976 ];
977 $defaultPreferences['previewontop'] = [
978 'type' => 'toggle',
979 'section' => 'editing/preview',
980 'label-message' => 'tog-previewontop',
981 ];
982 $defaultPreferences['uselivepreview'] = [
983 'type' => 'toggle',
984 'section' => 'editing/preview',
985 'label-message' => 'tog-uselivepreview',
986 ];
987 }
988
989 /**
990 * @param User $user
991 * @param MessageLocalizer $l10n
992 * @param array &$defaultPreferences
993 */
994 protected function rcPreferences( User $user, MessageLocalizer $l10n, &$defaultPreferences ) {
995 $rcMaxAge = $this->config->get( 'RCMaxAge' );
996 # # RecentChanges #####################################
997 $defaultPreferences['rcdays'] = [
998 'type' => 'float',
999 'label-message' => 'recentchangesdays',
1000 'section' => 'rc/displayrc',
1001 'min' => 1,
1002 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
1003 'help' => $l10n->msg( 'recentchangesdays-max' )->numParams(
1004 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
1005 ];
1006 $defaultPreferences['rclimit'] = [
1007 'type' => 'int',
1008 'min' => 0,
1009 'max' => 1000,
1010 'label-message' => 'recentchangescount',
1011 'help-message' => 'prefs-help-recentchangescount',
1012 'section' => 'rc/displayrc',
1013 ];
1014 $defaultPreferences['usenewrc'] = [
1015 'type' => 'toggle',
1016 'label-message' => 'tog-usenewrc',
1017 'section' => 'rc/advancedrc',
1018 ];
1019 $defaultPreferences['hideminor'] = [
1020 'type' => 'toggle',
1021 'label-message' => 'tog-hideminor',
1022 'section' => 'rc/advancedrc',
1023 ];
1024 $defaultPreferences['rcfilters-rc-collapsed'] = [
1025 'type' => 'api',
1026 ];
1027 $defaultPreferences['rcfilters-wl-collapsed'] = [
1028 'type' => 'api',
1029 ];
1030 $defaultPreferences['rcfilters-saved-queries'] = [
1031 'type' => 'api',
1032 ];
1033 $defaultPreferences['rcfilters-wl-saved-queries'] = [
1034 'type' => 'api',
1035 ];
1036 // Override RCFilters preferences for RecentChanges 'limit'
1037 $defaultPreferences['rcfilters-limit'] = [
1038 'type' => 'api',
1039 ];
1040 $defaultPreferences['rcfilters-saved-queries-versionbackup'] = [
1041 'type' => 'api',
1042 ];
1043 $defaultPreferences['rcfilters-wl-saved-queries-versionbackup'] = [
1044 'type' => 'api',
1045 ];
1046
1047 if ( $this->config->get( 'RCWatchCategoryMembership' ) ) {
1048 $defaultPreferences['hidecategorization'] = [
1049 'type' => 'toggle',
1050 'label-message' => 'tog-hidecategorization',
1051 'section' => 'rc/advancedrc',
1052 ];
1053 }
1054
1055 if ( $user->useRCPatrol() ) {
1056 $defaultPreferences['hidepatrolled'] = [
1057 'type' => 'toggle',
1058 'section' => 'rc/advancedrc',
1059 'label-message' => 'tog-hidepatrolled',
1060 ];
1061 }
1062
1063 if ( $user->useNPPatrol() ) {
1064 $defaultPreferences['newpageshidepatrolled'] = [
1065 'type' => 'toggle',
1066 'section' => 'rc/advancedrc',
1067 'label-message' => 'tog-newpageshidepatrolled',
1068 ];
1069 }
1070
1071 if ( $this->config->get( 'RCShowWatchingUsers' ) ) {
1072 $defaultPreferences['shownumberswatching'] = [
1073 'type' => 'toggle',
1074 'section' => 'rc/advancedrc',
1075 'label-message' => 'tog-shownumberswatching',
1076 ];
1077 }
1078
1079 if ( $this->config->get( 'StructuredChangeFiltersShowPreference' ) ) {
1080 $defaultPreferences['rcenhancedfilters-disable'] = [
1081 'type' => 'toggle',
1082 'section' => 'rc/optoutrc',
1083 'label-message' => 'rcfilters-preference-label',
1084 'help-message' => 'rcfilters-preference-help',
1085 ];
1086 }
1087 }
1088
1089 /**
1090 * @param User $user
1091 * @param IContextSource $context
1092 * @param array &$defaultPreferences
1093 */
1094 protected function watchlistPreferences(
1095 User $user, IContextSource $context, &$defaultPreferences
1096 ) {
1097 $oouiEnabled = SpecialPreferences::isOouiEnabled( $context );
1098
1099 $watchlistdaysMax = ceil( $this->config->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1100
1101 # # Watchlist #####################################
1102 if ( $user->isAllowed( 'editmywatchlist' ) ) {
1103 $editWatchlistLinks = '';
1104 $editWatchlistLinksOld = [];
1105 $editWatchlistModes = [
1106 'edit' => [ 'subpage' => false, 'flags' => [] ],
1107 'raw' => [ 'subpage' => 'raw', 'flags' => [] ],
1108 'clear' => [ 'subpage' => 'clear', 'flags' => [ 'destructive' ] ],
1109 ];
1110 foreach ( $editWatchlistModes as $mode => $options ) {
1111 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1112 if ( $oouiEnabled ) {
1113 $editWatchlistLinks .=
1114 new \OOUI\ButtonWidget( [
1115 'href' => SpecialPage::getTitleFor( 'EditWatchlist', $options['subpage'] )->getLinkURL(),
1116 'flags' => $options[ 'flags' ],
1117 'label' => new \OOUI\HtmlSnippet(
1118 $context->msg( "prefs-editwatchlist-{$mode}" )->parse()
1119 ),
1120 ] );
1121 } else {
1122 $editWatchlistLinksOld[] = $this->linkRenderer->makeKnownLink(
1123 SpecialPage::getTitleFor( 'EditWatchlist', $options['subpage'] ),
1124 new HtmlArmor( $context->msg( "prefs-editwatchlist-{$mode}" )->parse() )
1125 );
1126 }
1127 }
1128
1129 $defaultPreferences['editwatchlist'] = [
1130 'type' => 'info',
1131 'raw' => true,
1132 'default' => $oouiEnabled ?
1133 $editWatchlistLinks :
1134 $context->getLanguage()->pipeList( $editWatchlistLinksOld ),
1135 'label-message' => 'prefs-editwatchlist-label',
1136 'section' => 'watchlist/editwatchlist',
1137 ];
1138 }
1139
1140 $defaultPreferences['watchlistdays'] = [
1141 'type' => 'float',
1142 'min' => 0,
1143 'max' => $watchlistdaysMax,
1144 'section' => 'watchlist/displaywatchlist',
1145 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1146 $watchlistdaysMax )->escaped(),
1147 'label-message' => 'prefs-watchlist-days',
1148 ];
1149 $defaultPreferences['wllimit'] = [
1150 'type' => 'int',
1151 'min' => 0,
1152 'max' => 1000,
1153 'label-message' => 'prefs-watchlist-edits',
1154 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1155 'section' => 'watchlist/displaywatchlist',
1156 ];
1157 $defaultPreferences['extendwatchlist'] = [
1158 'type' => 'toggle',
1159 'section' => 'watchlist/advancedwatchlist',
1160 'label-message' => 'tog-extendwatchlist',
1161 ];
1162 $defaultPreferences['watchlisthideminor'] = [
1163 'type' => 'toggle',
1164 'section' => 'watchlist/advancedwatchlist',
1165 'label-message' => 'tog-watchlisthideminor',
1166 ];
1167 $defaultPreferences['watchlisthidebots'] = [
1168 'type' => 'toggle',
1169 'section' => 'watchlist/advancedwatchlist',
1170 'label-message' => 'tog-watchlisthidebots',
1171 ];
1172 $defaultPreferences['watchlisthideown'] = [
1173 'type' => 'toggle',
1174 'section' => 'watchlist/advancedwatchlist',
1175 'label-message' => 'tog-watchlisthideown',
1176 ];
1177 $defaultPreferences['watchlisthideanons'] = [
1178 'type' => 'toggle',
1179 'section' => 'watchlist/advancedwatchlist',
1180 'label-message' => 'tog-watchlisthideanons',
1181 ];
1182 $defaultPreferences['watchlisthideliu'] = [
1183 'type' => 'toggle',
1184 'section' => 'watchlist/advancedwatchlist',
1185 'label-message' => 'tog-watchlisthideliu',
1186 ];
1187
1188 if ( !\SpecialWatchlist::checkStructuredFilterUiEnabled(
1189 $this->config,
1190 $user
1191 ) ) {
1192 $defaultPreferences['watchlistreloadautomatically'] = [
1193 'type' => 'toggle',
1194 'section' => 'watchlist/advancedwatchlist',
1195 'label-message' => 'tog-watchlistreloadautomatically',
1196 ];
1197 }
1198
1199 $defaultPreferences['watchlistunwatchlinks'] = [
1200 'type' => 'toggle',
1201 'section' => 'watchlist/advancedwatchlist',
1202 'label-message' => 'tog-watchlistunwatchlinks',
1203 ];
1204
1205 if ( $this->config->get( 'RCWatchCategoryMembership' ) ) {
1206 $defaultPreferences['watchlisthidecategorization'] = [
1207 'type' => 'toggle',
1208 'section' => 'watchlist/advancedwatchlist',
1209 'label-message' => 'tog-watchlisthidecategorization',
1210 ];
1211 }
1212
1213 if ( $user->useRCPatrol() ) {
1214 $defaultPreferences['watchlisthidepatrolled'] = [
1215 'type' => 'toggle',
1216 'section' => 'watchlist/advancedwatchlist',
1217 'label-message' => 'tog-watchlisthidepatrolled',
1218 ];
1219 }
1220
1221 $watchTypes = [
1222 'edit' => 'watchdefault',
1223 'move' => 'watchmoves',
1224 'delete' => 'watchdeletion'
1225 ];
1226
1227 // Kinda hacky
1228 if ( $user->isAllowed( 'createpage' ) || $user->isAllowed( 'createtalk' ) ) {
1229 $watchTypes['read'] = 'watchcreations';
1230 }
1231
1232 if ( $user->isAllowed( 'rollback' ) ) {
1233 $watchTypes['rollback'] = 'watchrollback';
1234 }
1235
1236 if ( $user->isAllowed( 'upload' ) ) {
1237 $watchTypes['upload'] = 'watchuploads';
1238 }
1239
1240 foreach ( $watchTypes as $action => $pref ) {
1241 if ( $user->isAllowed( $action ) ) {
1242 // Messages:
1243 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1244 // tog-watchrollback
1245 $defaultPreferences[$pref] = [
1246 'type' => 'toggle',
1247 'section' => 'watchlist/advancedwatchlist',
1248 'label-message' => "tog-$pref",
1249 ];
1250 }
1251 }
1252
1253 $defaultPreferences['watchlisttoken'] = [
1254 'type' => 'api',
1255 ];
1256
1257 if ( $oouiEnabled ) {
1258 $tokenButton = new \OOUI\ButtonWidget( [
1259 'href' => SpecialPage::getTitleFor( 'ResetTokens' )->getLinkURL( [
1260 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText()
1261 ] ),
1262 'label' => $context->msg( 'prefs-watchlist-managetokens' )->text(),
1263 ] );
1264 $defaultPreferences['watchlisttoken-info'] = [
1265 'type' => 'info',
1266 'section' => 'watchlist/tokenwatchlist',
1267 'label-message' => 'prefs-watchlist-token',
1268 'help-message' => 'prefs-help-tokenmanagement',
1269 'raw' => true,
1270 'default' => (string)$tokenButton,
1271 ];
1272 } else {
1273 $defaultPreferences['watchlisttoken-info'] = [
1274 'type' => 'info',
1275 'section' => 'watchlist/tokenwatchlist',
1276 'label-message' => 'prefs-watchlist-token',
1277 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1278 'help-message' => 'prefs-help-watchlist-token2',
1279 ];
1280 }
1281
1282 if ( $this->config->get( 'StructuredChangeFiltersShowWatchlistPreference' ) ) {
1283 $defaultPreferences['wlenhancedfilters-disable'] = [
1284 'type' => 'toggle',
1285 'section' => 'watchlist/optoutwatchlist',
1286 'label-message' => 'rcfilters-watchlist-preference-label',
1287 'help-message' => 'rcfilters-watchlist-preference-help',
1288 ];
1289 }
1290 }
1291
1292 /**
1293 * @param array &$defaultPreferences
1294 */
1295 protected function searchPreferences( &$defaultPreferences ) {
1296 foreach ( MWNamespace::getValidNamespaces() as $n ) {
1297 $defaultPreferences['searchNs' . $n] = [
1298 'type' => 'api',
1299 ];
1300 }
1301 }
1302
1303 /**
1304 * @param User $user The User object
1305 * @param IContextSource $context
1306 * @return array Text/links to display as key; $skinkey as value
1307 */
1308 protected function generateSkinOptions( User $user, IContextSource $context ) {
1309 $ret = [];
1310
1311 $mptitle = Title::newMainPage();
1312 $previewtext = $context->msg( 'skin-preview' )->escaped();
1313
1314 # Only show skins that aren't disabled in $wgSkipSkins
1315 $validSkinNames = Skin::getAllowedSkins();
1316
1317 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1318 $msg = $context->msg( "skinname-{$skinkey}" );
1319 if ( $msg->exists() ) {
1320 $skinname = htmlspecialchars( $msg->text() );
1321 }
1322 }
1323
1324 $defaultSkin = $this->config->get( 'DefaultSkin' );
1325 $allowUserCss = $this->config->get( 'AllowUserCss' );
1326 $allowUserJs = $this->config->get( 'AllowUserJs' );
1327
1328 # Sort by the internal name, so that the ordering is the same for each display language,
1329 # especially if some skin names are translated to use a different alphabet and some are not.
1330 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1331 # Display the default first in the list by comparing it as lesser than any other.
1332 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1333 return -1;
1334 }
1335 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1336 return 1;
1337 }
1338 return strcasecmp( $a, $b );
1339 } );
1340
1341 $foundDefault = false;
1342 foreach ( $validSkinNames as $skinkey => $sn ) {
1343 $linkTools = [];
1344
1345 # Mark the default skin
1346 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1347 $linkTools[] = $context->msg( 'default' )->escaped();
1348 $foundDefault = true;
1349 }
1350
1351 # Create preview link
1352 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1353 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1354
1355 # Create links to user CSS/JS pages
1356 if ( $allowUserCss ) {
1357 $cssPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.css' );
1358 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
1359 $linkTools[] = $this->linkRenderer->makeLink( $cssPage, $cssLinkText );
1360 }
1361
1362 if ( $allowUserJs ) {
1363 $jsPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.js' );
1364 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
1365 $linkTools[] = $this->linkRenderer->makeLink( $jsPage, $jsLinkText );
1366 }
1367
1368 $display = $sn . ' ' . $context->msg( 'parentheses' )
1369 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1370 ->escaped();
1371 $ret[$display] = $skinkey;
1372 }
1373
1374 if ( !$foundDefault ) {
1375 // If the default skin is not available, things are going to break horribly because the
1376 // default value for skin selector will not be a valid value. Let's just not show it then.
1377 return [];
1378 }
1379
1380 return $ret;
1381 }
1382
1383 /**
1384 * @param IContextSource $context
1385 * @return array
1386 */
1387 protected function getDateOptions( IContextSource $context ) {
1388 $lang = $context->getLanguage();
1389 $dateopts = $lang->getDatePreferences();
1390
1391 $ret = [];
1392
1393 if ( $dateopts ) {
1394 if ( !in_array( 'default', $dateopts ) ) {
1395 $dateopts[] = 'default'; // Make sure default is always valid T21237
1396 }
1397
1398 // FIXME KLUGE: site default might not be valid for user language
1399 global $wgDefaultUserOptions;
1400 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1401 $wgDefaultUserOptions['date'] = 'default';
1402 }
1403
1404 $epoch = wfTimestampNow();
1405 foreach ( $dateopts as $key ) {
1406 if ( $key == 'default' ) {
1407 $formatted = $context->msg( 'datedefault' )->escaped();
1408 } else {
1409 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1410 }
1411 $ret[$formatted] = $key;
1412 }
1413 }
1414 return $ret;
1415 }
1416
1417 /**
1418 * @param MessageLocalizer $l10n
1419 * @return array
1420 */
1421 protected function getImageSizes( MessageLocalizer $l10n ) {
1422 $ret = [];
1423 $pixels = $l10n->msg( 'unit-pixel' )->text();
1424
1425 foreach ( $this->config->get( 'ImageLimits' ) as $index => $limits ) {
1426 // Note: A left-to-right marker (U+200E) is inserted, see T144386
1427 $display = "{$limits[0]}\u{200E}×{$limits[1]}$pixels";
1428 $ret[$display] = $index;
1429 }
1430
1431 return $ret;
1432 }
1433
1434 /**
1435 * @param MessageLocalizer $l10n
1436 * @return array
1437 */
1438 protected function getThumbSizes( MessageLocalizer $l10n ) {
1439 $ret = [];
1440 $pixels = $l10n->msg( 'unit-pixel' )->text();
1441
1442 foreach ( $this->config->get( 'ThumbLimits' ) as $index => $size ) {
1443 $display = $size . $pixels;
1444 $ret[$display] = $index;
1445 }
1446
1447 return $ret;
1448 }
1449
1450 /**
1451 * @param string $signature
1452 * @param array $alldata
1453 * @param HTMLForm $form
1454 * @return bool|string
1455 */
1456 protected function validateSignature( $signature, $alldata, HTMLForm $form ) {
1457 $maxSigChars = $this->config->get( 'MaxSigChars' );
1458 if ( mb_strlen( $signature ) > $maxSigChars ) {
1459 return Xml::element( 'span', [ 'class' => 'error' ],
1460 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1461 } elseif ( isset( $alldata['fancysig'] ) &&
1462 $alldata['fancysig'] &&
1463 MediaWikiServices::getInstance()->getParser()->validateSig( $signature ) === false
1464 ) {
1465 return Xml::element(
1466 'span',
1467 [ 'class' => 'error' ],
1468 $form->msg( 'badsig' )->text()
1469 );
1470 } else {
1471 return true;
1472 }
1473 }
1474
1475 /**
1476 * @param string $signature
1477 * @param array $alldata
1478 * @param HTMLForm $form
1479 * @return string
1480 */
1481 protected function cleanSignature( $signature, $alldata, HTMLForm $form ) {
1482 $parser = MediaWikiServices::getInstance()->getParser();
1483 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1484 $signature = $parser->cleanSig( $signature );
1485 } else {
1486 // When no fancy sig used, make sure ~{3,5} get removed.
1487 $signature = Parser::cleanSigInSig( $signature );
1488 }
1489
1490 return $signature;
1491 }
1492
1493 /**
1494 * @param User $user
1495 * @param IContextSource $context
1496 * @param string $formClass
1497 * @param array $remove Array of items to remove
1498 * @return HTMLForm
1499 */
1500 public function getForm(
1501 User $user,
1502 IContextSource $context,
1503 $formClass = PreferencesFormLegacy::class,
1504 array $remove = []
1505 ) {
1506 if ( SpecialPreferences::isOouiEnabled( $context ) ) {
1507 // We use ButtonWidgets in some of the getPreferences() functions
1508 $context->getOutput()->enableOOUI();
1509 }
1510
1511 $formDescriptor = $this->getFormDescriptor( $user, $context );
1512 if ( count( $remove ) ) {
1513 $removeKeys = array_flip( $remove );
1514 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1515 }
1516
1517 // Remove type=api preferences. They are not intended for rendering in the form.
1518 foreach ( $formDescriptor as $name => $info ) {
1519 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1520 unset( $formDescriptor[$name] );
1521 }
1522 }
1523
1524 /**
1525 * @var $htmlForm HTMLForm
1526 */
1527 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1528
1529 $htmlForm->setModifiedUser( $user );
1530 $htmlForm->setId( 'mw-prefs-form' );
1531 $htmlForm->setAutocomplete( 'off' );
1532 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1533 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1534 $htmlForm->setSubmitTooltip( 'preferences-save' );
1535 $htmlForm->setSubmitID( 'prefcontrol' );
1536 $htmlForm->setSubmitCallback( function ( array $formData, HTMLForm $form ) {
1537 return $this->submitForm( $formData, $form );
1538 } );
1539
1540 return $htmlForm;
1541 }
1542
1543 /**
1544 * @param IContextSource $context
1545 * @return array
1546 */
1547 protected function getTimezoneOptions( IContextSource $context ) {
1548 $opt = [];
1549
1550 $localTZoffset = $this->config->get( 'LocalTZoffset' );
1551 $timeZoneList = $this->getTimeZoneList( $context->getLanguage() );
1552
1553 $timestamp = MWTimestamp::getLocalInstance();
1554 // Check that the LocalTZoffset is the same as the local time zone offset
1555 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1556 $timezoneName = $timestamp->getTimezone()->getName();
1557 // Localize timezone
1558 if ( isset( $timeZoneList[$timezoneName] ) ) {
1559 $timezoneName = $timeZoneList[$timezoneName]['name'];
1560 }
1561 $server_tz_msg = $context->msg(
1562 'timezoneuseserverdefault',
1563 $timezoneName
1564 )->text();
1565 } else {
1566 $tzstring = sprintf(
1567 '%+03d:%02d',
1568 floor( $localTZoffset / 60 ),
1569 abs( $localTZoffset ) % 60
1570 );
1571 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1572 }
1573 $opt[$server_tz_msg] = "System|$localTZoffset";
1574 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1575 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1576
1577 foreach ( $timeZoneList as $timeZoneInfo ) {
1578 $region = $timeZoneInfo['region'];
1579 if ( !isset( $opt[$region] ) ) {
1580 $opt[$region] = [];
1581 }
1582 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1583 }
1584 return $opt;
1585 }
1586
1587 /**
1588 * @param string $tz
1589 * @param array $alldata
1590 * @return string
1591 */
1592 protected function filterTimezoneInput( $tz, array $alldata ) {
1593 $data = explode( '|', $tz, 3 );
1594 switch ( $data[0] ) {
1595 case 'ZoneInfo':
1596 $valid = false;
1597
1598 if ( count( $data ) === 3 ) {
1599 // Make sure this timezone exists
1600 try {
1601 new DateTimeZone( $data[2] );
1602 // If the constructor didn't throw, we know it's valid
1603 $valid = true;
1604 } catch ( Exception $e ) {
1605 // Not a valid timezone
1606 }
1607 }
1608
1609 if ( !$valid ) {
1610 // If the supplied timezone doesn't exist, fall back to the encoded offset
1611 return 'Offset|' . intval( $tz[1] );
1612 }
1613 return $tz;
1614 case 'System':
1615 return $tz;
1616 default:
1617 $data = explode( ':', $tz, 2 );
1618 if ( count( $data ) == 2 ) {
1619 $data[0] = intval( $data[0] );
1620 $data[1] = intval( $data[1] );
1621 $minDiff = abs( $data[0] ) * 60 + $data[1];
1622 if ( $data[0] < 0 ) {
1623 $minDiff = - $minDiff;
1624 }
1625 } else {
1626 $minDiff = intval( $data[0] ) * 60;
1627 }
1628
1629 # Max is +14:00 and min is -12:00, see:
1630 # https://en.wikipedia.org/wiki/Timezone
1631 $minDiff = min( $minDiff, 840 ); # 14:00
1632 $minDiff = max( $minDiff, -720 ); # -12:00
1633 return 'Offset|' . $minDiff;
1634 }
1635 }
1636
1637 /**
1638 * Handle the form submission if everything validated properly
1639 *
1640 * @param array $formData
1641 * @param HTMLForm $form
1642 * @return bool|Status|string
1643 */
1644 protected function saveFormData( $formData, HTMLForm $form ) {
1645 $user = $form->getModifiedUser();
1646 $hiddenPrefs = $this->config->get( 'HiddenPrefs' );
1647 $result = true;
1648
1649 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1650 return Status::newFatal( 'mypreferencesprotected' );
1651 }
1652
1653 // Filter input
1654 foreach ( array_keys( $formData ) as $name ) {
1655 $filters = $this->getSaveFilters();
1656 if ( isset( $filters[$name] ) ) {
1657 $formData[$name] = call_user_func( $filters[$name], $formData[$name], $formData );
1658 }
1659 }
1660
1661 // Fortunately, the realname field is MUCH simpler
1662 // (not really "private", but still shouldn't be edited without permission)
1663
1664 if ( !in_array( 'realname', $hiddenPrefs )
1665 && $user->isAllowed( 'editmyprivateinfo' )
1666 && array_key_exists( 'realname', $formData )
1667 ) {
1668 $realName = $formData['realname'];
1669 $user->setRealName( $realName );
1670 }
1671
1672 if ( $user->isAllowed( 'editmyoptions' ) ) {
1673 $oldUserOptions = $user->getOptions();
1674
1675 foreach ( $this->getSaveBlacklist() as $b ) {
1676 unset( $formData[$b] );
1677 }
1678
1679 # If users have saved a value for a preference which has subsequently been disabled
1680 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1681 # is subsequently re-enabled
1682 foreach ( $hiddenPrefs as $pref ) {
1683 # If the user has not set a non-default value here, the default will be returned
1684 # and subsequently discarded
1685 $formData[$pref] = $user->getOption( $pref, null, true );
1686 }
1687
1688 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1689 if (
1690 isset( $formData['rclimit'] ) &&
1691 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1692 ) {
1693 $formData['rcfilters-limit'] = $formData['rclimit'];
1694 }
1695
1696 // Keep old preferences from interfering due to back-compat code, etc.
1697 $user->resetOptions( 'unused', $form->getContext() );
1698
1699 foreach ( $formData as $key => $value ) {
1700 $user->setOption( $key, $value );
1701 }
1702
1703 Hooks::run(
1704 'PreferencesFormPreSave',
1705 [ $formData, $form, $user, &$result, $oldUserOptions ]
1706 );
1707 }
1708
1709 AuthManager::callLegacyAuthPlugin( 'updateExternalDB', [ $user ] );
1710 $user->saveSettings();
1711
1712 return $result;
1713 }
1714
1715 /**
1716 * DO NOT USE. Temporary function to punch hole for the Preferences class.
1717 *
1718 * @deprecated since 1.31, its inception
1719 *
1720 * @param array $formData
1721 * @param HTMLForm $form
1722 * @return bool|Status|string
1723 */
1724 public function legacySaveFormData( $formData, HTMLForm $form ) {
1725 return $this->saveFormData( $formData, $form );
1726 }
1727
1728 /**
1729 * Save the form data and reload the page
1730 *
1731 * @param array $formData
1732 * @param HTMLForm $form
1733 * @return Status
1734 */
1735 protected function submitForm( array $formData, HTMLForm $form ) {
1736 $res = $this->saveFormData( $formData, $form );
1737
1738 if ( $res === true ) {
1739 $context = $form->getContext();
1740 $urlOptions = [];
1741
1742 if ( $res === 'eauth' ) {
1743 $urlOptions['eauth'] = 1;
1744 }
1745
1746 if (
1747 $context->getRequest()->getFuzzyBool( 'ooui' ) !==
1748 $context->getConfig()->get( 'OOUIPreferences' )
1749 ) {
1750 $urlOptions[ 'ooui' ] = $context->getRequest()->getFuzzyBool( 'ooui' ) ? 1 : 0;
1751 }
1752
1753 $urlOptions += $form->getExtraSuccessRedirectParameters();
1754
1755 $url = $form->getTitle()->getFullURL( $urlOptions );
1756
1757 // Set session data for the success message
1758 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1759
1760 $context->getOutput()->redirect( $url );
1761 }
1762
1763 return ( $res === true ? Status::newGood() : $res );
1764 }
1765
1766 /**
1767 * DO NOT USE. Temporary function to punch hole for the Preferences class.
1768 *
1769 * @deprecated since 1.31, its inception
1770 *
1771 * @param array $formData
1772 * @param HTMLForm $form
1773 * @return Status
1774 */
1775 public function legacySubmitForm( array $formData, HTMLForm $form ) {
1776 return $this->submitForm( $formData, $form );
1777 }
1778
1779 /**
1780 * Get a list of all time zones
1781 * @param Language $language Language used for the localized names
1782 * @return array A list of all time zones. The system name of the time zone is used as key and
1783 * the value is an array which contains localized name, the timecorrection value used for
1784 * preferences and the region
1785 * @since 1.26
1786 */
1787 protected function getTimeZoneList( Language $language ) {
1788 $identifiers = DateTimeZone::listIdentifiers();
1789 if ( $identifiers === false ) {
1790 return [];
1791 }
1792 sort( $identifiers );
1793
1794 $tzRegions = [
1795 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1796 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1797 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1798 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1799 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1800 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1801 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1802 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1803 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1804 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1805 ];
1806 asort( $tzRegions );
1807
1808 $timeZoneList = [];
1809
1810 $now = new DateTime();
1811
1812 foreach ( $identifiers as $identifier ) {
1813 $parts = explode( '/', $identifier, 2 );
1814
1815 // DateTimeZone::listIdentifiers() returns a number of
1816 // backwards-compatibility entries. This filters them out of the
1817 // list presented to the user.
1818 if ( count( $parts ) !== 2 || !array_key_exists( $parts[0], $tzRegions ) ) {
1819 continue;
1820 }
1821
1822 // Localize region
1823 $parts[0] = $tzRegions[$parts[0]];
1824
1825 $dateTimeZone = new DateTimeZone( $identifier );
1826 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1827
1828 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1829 $value = "ZoneInfo|$minDiff|$identifier";
1830
1831 $timeZoneList[$identifier] = [
1832 'name' => $display,
1833 'timecorrection' => $value,
1834 'region' => $parts[0],
1835 ];
1836 }
1837
1838 return $timeZoneList;
1839 }
1840 }