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