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