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