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