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