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