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