Merge "rdbms: make * consistently act like in select/insertSelect methods"
[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 $defaultPreferences['rcenhancedfilters-disable'] = [
1064 'type' => 'toggle',
1065 'section' => 'rc/optoutrc',
1066 'label-message' => 'rcfilters-preference-label',
1067 'help-message' => 'rcfilters-preference-help',
1068 ];
1069 }
1070
1071 /**
1072 * @param User $user
1073 * @param IContextSource $context
1074 * @param array &$defaultPreferences
1075 */
1076 protected function watchlistPreferences(
1077 User $user, IContextSource $context, &$defaultPreferences
1078 ) {
1079 $oouiEnabled = SpecialPreferences::isOouiEnabled( $context );
1080
1081 $watchlistdaysMax = ceil( $this->config->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1082
1083 # # Watchlist #####################################
1084 if ( $user->isAllowed( 'editmywatchlist' ) ) {
1085 $editWatchlistLinks = '';
1086 $editWatchlistLinksOld = [];
1087 $editWatchlistModes = [
1088 'edit' => [ 'subpage' => false, 'flags' => [] ],
1089 'raw' => [ 'subpage' => 'raw', 'flags' => [] ],
1090 'clear' => [ 'subpage' => 'clear', 'flags' => [ 'destructive' ] ],
1091 ];
1092 foreach ( $editWatchlistModes as $mode => $options ) {
1093 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1094 if ( $oouiEnabled ) {
1095 $editWatchlistLinks .=
1096 new \OOUI\ButtonWidget( [
1097 'href' => SpecialPage::getTitleFor( 'EditWatchlist', $options['subpage'] )->getLinkURL(),
1098 'flags' => $options[ 'flags' ],
1099 'label' => new \OOUI\HtmlSnippet(
1100 $context->msg( "prefs-editwatchlist-{$mode}" )->parse()
1101 ),
1102 ] );
1103 } else {
1104 $editWatchlistLinksOld[] = $this->linkRenderer->makeKnownLink(
1105 SpecialPage::getTitleFor( 'EditWatchlist', $options['subpage'] ),
1106 new HtmlArmor( $context->msg( "prefs-editwatchlist-{$mode}" )->parse() )
1107 );
1108 }
1109 }
1110
1111 $defaultPreferences['editwatchlist'] = [
1112 'type' => 'info',
1113 'raw' => true,
1114 'default' => $oouiEnabled ?
1115 $editWatchlistLinks :
1116 $context->getLanguage()->pipeList( $editWatchlistLinksOld ),
1117 'label-message' => 'prefs-editwatchlist-label',
1118 'section' => 'watchlist/editwatchlist',
1119 ];
1120 }
1121
1122 $defaultPreferences['watchlistdays'] = [
1123 'type' => 'float',
1124 'min' => 1 / 24,
1125 'max' => $watchlistdaysMax,
1126 'section' => 'watchlist/displaywatchlist',
1127 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1128 $watchlistdaysMax )->escaped(),
1129 'label-message' => 'prefs-watchlist-days',
1130 ];
1131 $defaultPreferences['wllimit'] = [
1132 'type' => 'int',
1133 'min' => 1,
1134 'max' => 1000,
1135 'label-message' => 'prefs-watchlist-edits',
1136 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1137 'section' => 'watchlist/displaywatchlist',
1138 'filter' => IntvalFilter::class,
1139 ];
1140 $defaultPreferences['extendwatchlist'] = [
1141 'type' => 'toggle',
1142 'section' => 'watchlist/advancedwatchlist',
1143 'label-message' => 'tog-extendwatchlist',
1144 ];
1145 $defaultPreferences['watchlisthideminor'] = [
1146 'type' => 'toggle',
1147 'section' => 'watchlist/advancedwatchlist',
1148 'label-message' => 'tog-watchlisthideminor',
1149 ];
1150 $defaultPreferences['watchlisthidebots'] = [
1151 'type' => 'toggle',
1152 'section' => 'watchlist/advancedwatchlist',
1153 'label-message' => 'tog-watchlisthidebots',
1154 ];
1155 $defaultPreferences['watchlisthideown'] = [
1156 'type' => 'toggle',
1157 'section' => 'watchlist/advancedwatchlist',
1158 'label-message' => 'tog-watchlisthideown',
1159 ];
1160 $defaultPreferences['watchlisthideanons'] = [
1161 'type' => 'toggle',
1162 'section' => 'watchlist/advancedwatchlist',
1163 'label-message' => 'tog-watchlisthideanons',
1164 ];
1165 $defaultPreferences['watchlisthideliu'] = [
1166 'type' => 'toggle',
1167 'section' => 'watchlist/advancedwatchlist',
1168 'label-message' => 'tog-watchlisthideliu',
1169 ];
1170
1171 if ( !\SpecialWatchlist::checkStructuredFilterUiEnabled(
1172 $this->config,
1173 $user
1174 ) ) {
1175 $defaultPreferences['watchlistreloadautomatically'] = [
1176 'type' => 'toggle',
1177 'section' => 'watchlist/advancedwatchlist',
1178 'label-message' => 'tog-watchlistreloadautomatically',
1179 ];
1180 }
1181
1182 $defaultPreferences['watchlistunwatchlinks'] = [
1183 'type' => 'toggle',
1184 'section' => 'watchlist/advancedwatchlist',
1185 'label-message' => 'tog-watchlistunwatchlinks',
1186 ];
1187
1188 if ( $this->config->get( 'RCWatchCategoryMembership' ) ) {
1189 $defaultPreferences['watchlisthidecategorization'] = [
1190 'type' => 'toggle',
1191 'section' => 'watchlist/advancedwatchlist',
1192 'label-message' => 'tog-watchlisthidecategorization',
1193 ];
1194 }
1195
1196 if ( $user->useRCPatrol() ) {
1197 $defaultPreferences['watchlisthidepatrolled'] = [
1198 'type' => 'toggle',
1199 'section' => 'watchlist/advancedwatchlist',
1200 'label-message' => 'tog-watchlisthidepatrolled',
1201 ];
1202 }
1203
1204 $watchTypes = [
1205 'edit' => 'watchdefault',
1206 'move' => 'watchmoves',
1207 'delete' => 'watchdeletion'
1208 ];
1209
1210 // Kinda hacky
1211 if ( $user->isAllowed( 'createpage' ) || $user->isAllowed( 'createtalk' ) ) {
1212 $watchTypes['read'] = 'watchcreations';
1213 }
1214
1215 if ( $user->isAllowed( 'rollback' ) ) {
1216 $watchTypes['rollback'] = 'watchrollback';
1217 }
1218
1219 if ( $user->isAllowed( 'upload' ) ) {
1220 $watchTypes['upload'] = 'watchuploads';
1221 }
1222
1223 foreach ( $watchTypes as $action => $pref ) {
1224 if ( $user->isAllowed( $action ) ) {
1225 // Messages:
1226 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1227 // tog-watchrollback
1228 $defaultPreferences[$pref] = [
1229 'type' => 'toggle',
1230 'section' => 'watchlist/advancedwatchlist',
1231 'label-message' => "tog-$pref",
1232 ];
1233 }
1234 }
1235
1236 $defaultPreferences['watchlisttoken'] = [
1237 'type' => 'api',
1238 ];
1239
1240 if ( $oouiEnabled ) {
1241 $tokenButton = new \OOUI\ButtonWidget( [
1242 'href' => SpecialPage::getTitleFor( 'ResetTokens' )->getLinkURL( [
1243 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText()
1244 ] ),
1245 'label' => $context->msg( 'prefs-watchlist-managetokens' )->text(),
1246 ] );
1247 $defaultPreferences['watchlisttoken-info'] = [
1248 'type' => 'info',
1249 'section' => 'watchlist/tokenwatchlist',
1250 'label-message' => 'prefs-watchlist-token',
1251 'help-message' => 'prefs-help-tokenmanagement',
1252 'raw' => true,
1253 'default' => (string)$tokenButton,
1254 ];
1255 } else {
1256 $defaultPreferences['watchlisttoken-info'] = [
1257 'type' => 'info',
1258 'section' => 'watchlist/tokenwatchlist',
1259 'label-message' => 'prefs-watchlist-token',
1260 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1261 'help-message' => 'prefs-help-watchlist-token2',
1262 ];
1263 }
1264
1265 $defaultPreferences['wlenhancedfilters-disable'] = [
1266 'type' => 'toggle',
1267 'section' => 'watchlist/optoutwatchlist',
1268 'label-message' => 'rcfilters-watchlist-preference-label',
1269 'help-message' => 'rcfilters-watchlist-preference-help',
1270 ];
1271 }
1272
1273 /**
1274 * @param array &$defaultPreferences
1275 */
1276 protected function searchPreferences( &$defaultPreferences ) {
1277 foreach ( MWNamespace::getValidNamespaces() as $n ) {
1278 $defaultPreferences['searchNs' . $n] = [
1279 'type' => 'api',
1280 ];
1281 }
1282 }
1283
1284 /**
1285 * @param User $user The User object
1286 * @param IContextSource $context
1287 * @return array Text/links to display as key; $skinkey as value
1288 */
1289 protected function generateSkinOptions( User $user, IContextSource $context ) {
1290 $ret = [];
1291
1292 $mptitle = Title::newMainPage();
1293 $previewtext = $context->msg( 'skin-preview' )->escaped();
1294
1295 # Only show skins that aren't disabled in $wgSkipSkins
1296 $validSkinNames = Skin::getAllowedSkins();
1297
1298 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1299 $msg = $context->msg( "skinname-{$skinkey}" );
1300 if ( $msg->exists() ) {
1301 $skinname = htmlspecialchars( $msg->text() );
1302 }
1303 }
1304
1305 $defaultSkin = $this->config->get( 'DefaultSkin' );
1306 $allowUserCss = $this->config->get( 'AllowUserCss' );
1307 $allowUserJs = $this->config->get( 'AllowUserJs' );
1308
1309 # Sort by the internal name, so that the ordering is the same for each display language,
1310 # especially if some skin names are translated to use a different alphabet and some are not.
1311 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1312 # Display the default first in the list by comparing it as lesser than any other.
1313 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1314 return -1;
1315 }
1316 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1317 return 1;
1318 }
1319 return strcasecmp( $a, $b );
1320 } );
1321
1322 $foundDefault = false;
1323 foreach ( $validSkinNames as $skinkey => $sn ) {
1324 $linkTools = [];
1325
1326 # Mark the default skin
1327 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1328 $linkTools[] = $context->msg( 'default' )->escaped();
1329 $foundDefault = true;
1330 }
1331
1332 # Create preview link
1333 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1334 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1335
1336 # Create links to user CSS/JS pages
1337 if ( $allowUserCss ) {
1338 $cssPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.css' );
1339 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
1340 $linkTools[] = $this->linkRenderer->makeLink( $cssPage, $cssLinkText );
1341 }
1342
1343 if ( $allowUserJs ) {
1344 $jsPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.js' );
1345 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
1346 $linkTools[] = $this->linkRenderer->makeLink( $jsPage, $jsLinkText );
1347 }
1348
1349 $display = $sn . ' ' . $context->msg( 'parentheses' )
1350 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1351 ->escaped();
1352 $ret[$display] = $skinkey;
1353 }
1354
1355 if ( !$foundDefault ) {
1356 // If the default skin is not available, things are going to break horribly because the
1357 // default value for skin selector will not be a valid value. Let's just not show it then.
1358 return [];
1359 }
1360
1361 return $ret;
1362 }
1363
1364 /**
1365 * @param IContextSource $context
1366 * @return array
1367 */
1368 protected function getDateOptions( IContextSource $context ) {
1369 $lang = $context->getLanguage();
1370 $dateopts = $lang->getDatePreferences();
1371
1372 $ret = [];
1373
1374 if ( $dateopts ) {
1375 if ( !in_array( 'default', $dateopts ) ) {
1376 $dateopts[] = 'default'; // Make sure default is always valid T21237
1377 }
1378
1379 // FIXME KLUGE: site default might not be valid for user language
1380 global $wgDefaultUserOptions;
1381 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1382 $wgDefaultUserOptions['date'] = 'default';
1383 }
1384
1385 $epoch = wfTimestampNow();
1386 foreach ( $dateopts as $key ) {
1387 if ( $key == 'default' ) {
1388 $formatted = $context->msg( 'datedefault' )->escaped();
1389 } else {
1390 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1391 }
1392 $ret[$formatted] = $key;
1393 }
1394 }
1395 return $ret;
1396 }
1397
1398 /**
1399 * @param MessageLocalizer $l10n
1400 * @return array
1401 */
1402 protected function getImageSizes( MessageLocalizer $l10n ) {
1403 $ret = [];
1404 $pixels = $l10n->msg( 'unit-pixel' )->text();
1405
1406 foreach ( $this->config->get( 'ImageLimits' ) as $index => $limits ) {
1407 // Note: A left-to-right marker (U+200E) is inserted, see T144386
1408 $display = "{$limits[0]}\u{200E}×{$limits[1]}$pixels";
1409 $ret[$display] = $index;
1410 }
1411
1412 return $ret;
1413 }
1414
1415 /**
1416 * @param MessageLocalizer $l10n
1417 * @return array
1418 */
1419 protected function getThumbSizes( MessageLocalizer $l10n ) {
1420 $ret = [];
1421 $pixels = $l10n->msg( 'unit-pixel' )->text();
1422
1423 foreach ( $this->config->get( 'ThumbLimits' ) as $index => $size ) {
1424 $display = $size . $pixels;
1425 $ret[$display] = $index;
1426 }
1427
1428 return $ret;
1429 }
1430
1431 /**
1432 * @param string $signature
1433 * @param array $alldata
1434 * @param HTMLForm $form
1435 * @return bool|string
1436 */
1437 protected function validateSignature( $signature, $alldata, HTMLForm $form ) {
1438 $maxSigChars = $this->config->get( 'MaxSigChars' );
1439 if ( mb_strlen( $signature ) > $maxSigChars ) {
1440 return Xml::element( 'span', [ 'class' => 'error' ],
1441 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1442 } elseif ( isset( $alldata['fancysig'] ) &&
1443 $alldata['fancysig'] &&
1444 MediaWikiServices::getInstance()->getParser()->validateSig( $signature ) === false
1445 ) {
1446 return Xml::element(
1447 'span',
1448 [ 'class' => 'error' ],
1449 $form->msg( 'badsig' )->text()
1450 );
1451 } else {
1452 return true;
1453 }
1454 }
1455
1456 /**
1457 * @param string $signature
1458 * @param array $alldata
1459 * @param HTMLForm $form
1460 * @return string
1461 */
1462 protected function cleanSignature( $signature, $alldata, HTMLForm $form ) {
1463 $parser = MediaWikiServices::getInstance()->getParser();
1464 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1465 $signature = $parser->cleanSig( $signature );
1466 } else {
1467 // When no fancy sig used, make sure ~{3,5} get removed.
1468 $signature = Parser::cleanSigInSig( $signature );
1469 }
1470
1471 return $signature;
1472 }
1473
1474 /**
1475 * @param User $user
1476 * @param IContextSource $context
1477 * @param string $formClass
1478 * @param array $remove Array of items to remove
1479 * @return HTMLForm
1480 */
1481 public function getForm(
1482 User $user,
1483 IContextSource $context,
1484 $formClass = PreferencesFormLegacy::class,
1485 array $remove = []
1486 ) {
1487 if ( SpecialPreferences::isOouiEnabled( $context ) ) {
1488 // We use ButtonWidgets in some of the getPreferences() functions
1489 $context->getOutput()->enableOOUI();
1490 }
1491
1492 $formDescriptor = $this->getFormDescriptor( $user, $context );
1493 if ( count( $remove ) ) {
1494 $removeKeys = array_flip( $remove );
1495 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1496 }
1497
1498 // Remove type=api preferences. They are not intended for rendering in the form.
1499 foreach ( $formDescriptor as $name => $info ) {
1500 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1501 unset( $formDescriptor[$name] );
1502 }
1503 }
1504
1505 /**
1506 * @var $htmlForm HTMLForm
1507 */
1508 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1509
1510 $htmlForm->setModifiedUser( $user );
1511 $htmlForm->setId( 'mw-prefs-form' );
1512 $htmlForm->setAutocomplete( 'off' );
1513 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1514 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1515 $htmlForm->setSubmitTooltip( 'preferences-save' );
1516 $htmlForm->setSubmitID( 'prefcontrol' );
1517 $htmlForm->setSubmitCallback(
1518 function ( array $formData, HTMLForm $form ) use ( $formDescriptor ) {
1519 return $this->submitForm( $formData, $form, $formDescriptor );
1520 }
1521 );
1522
1523 return $htmlForm;
1524 }
1525
1526 /**
1527 * @param IContextSource $context
1528 * @return array
1529 */
1530 protected function getTimezoneOptions( IContextSource $context ) {
1531 $opt = [];
1532
1533 $localTZoffset = $this->config->get( 'LocalTZoffset' );
1534 $timeZoneList = $this->getTimeZoneList( $context->getLanguage() );
1535
1536 $timestamp = MWTimestamp::getLocalInstance();
1537 // Check that the LocalTZoffset is the same as the local time zone offset
1538 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1539 $timezoneName = $timestamp->getTimezone()->getName();
1540 // Localize timezone
1541 if ( isset( $timeZoneList[$timezoneName] ) ) {
1542 $timezoneName = $timeZoneList[$timezoneName]['name'];
1543 }
1544 $server_tz_msg = $context->msg(
1545 'timezoneuseserverdefault',
1546 $timezoneName
1547 )->text();
1548 } else {
1549 $tzstring = sprintf(
1550 '%+03d:%02d',
1551 floor( $localTZoffset / 60 ),
1552 abs( $localTZoffset ) % 60
1553 );
1554 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1555 }
1556 $opt[$server_tz_msg] = "System|$localTZoffset";
1557 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1558 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1559
1560 foreach ( $timeZoneList as $timeZoneInfo ) {
1561 $region = $timeZoneInfo['region'];
1562 if ( !isset( $opt[$region] ) ) {
1563 $opt[$region] = [];
1564 }
1565 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1566 }
1567 return $opt;
1568 }
1569
1570 /**
1571 * Handle the form submission if everything validated properly
1572 *
1573 * @param array $formData
1574 * @param HTMLForm $form
1575 * @param array[] $formDescriptor
1576 * @return bool|Status|string
1577 */
1578 protected function saveFormData( $formData, HTMLForm $form, array $formDescriptor ) {
1579 /** @var \User $user */
1580 $user = $form->getModifiedUser();
1581 $hiddenPrefs = $this->config->get( 'HiddenPrefs' );
1582 $result = true;
1583
1584 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1585 return Status::newFatal( 'mypreferencesprotected' );
1586 }
1587
1588 // Filter input
1589 $this->applyFilters( $formData, $formDescriptor, 'filterFromForm' );
1590
1591 // Fortunately, the realname field is MUCH simpler
1592 // (not really "private", but still shouldn't be edited without permission)
1593
1594 if ( !in_array( 'realname', $hiddenPrefs )
1595 && $user->isAllowed( 'editmyprivateinfo' )
1596 && array_key_exists( 'realname', $formData )
1597 ) {
1598 $realName = $formData['realname'];
1599 $user->setRealName( $realName );
1600 }
1601
1602 if ( $user->isAllowed( 'editmyoptions' ) ) {
1603 $oldUserOptions = $user->getOptions();
1604
1605 foreach ( $this->getSaveBlacklist() as $b ) {
1606 unset( $formData[$b] );
1607 }
1608
1609 # If users have saved a value for a preference which has subsequently been disabled
1610 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1611 # is subsequently re-enabled
1612 foreach ( $hiddenPrefs as $pref ) {
1613 # If the user has not set a non-default value here, the default will be returned
1614 # and subsequently discarded
1615 $formData[$pref] = $user->getOption( $pref, null, true );
1616 }
1617
1618 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1619 if (
1620 isset( $formData['rclimit'] ) &&
1621 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1622 ) {
1623 $formData['rcfilters-limit'] = $formData['rclimit'];
1624 }
1625
1626 // Keep old preferences from interfering due to back-compat code, etc.
1627 $user->resetOptions( 'unused', $form->getContext() );
1628
1629 foreach ( $formData as $key => $value ) {
1630 $user->setOption( $key, $value );
1631 }
1632
1633 Hooks::run(
1634 'PreferencesFormPreSave',
1635 [ $formData, $form, $user, &$result, $oldUserOptions ]
1636 );
1637 }
1638
1639 AuthManager::callLegacyAuthPlugin( 'updateExternalDB', [ $user ] );
1640 $user->saveSettings();
1641
1642 return $result;
1643 }
1644
1645 /**
1646 * Applies filters to preferences either before or after form usage
1647 *
1648 * @param array &$preferences
1649 * @param array $formDescriptor
1650 * @param string $verb Name of the filter method to call, either 'filterFromForm' or
1651 * 'filterForForm'
1652 */
1653 protected function applyFilters( array &$preferences, array $formDescriptor, $verb ) {
1654 foreach ( $formDescriptor as $preference => $desc ) {
1655 if ( !isset( $desc['filter'] ) || !isset( $preferences[$preference] ) ) {
1656 continue;
1657 }
1658 $filterDesc = $desc['filter'];
1659 if ( $filterDesc instanceof Filter ) {
1660 $filter = $filterDesc;
1661 } elseif ( class_exists( $filterDesc ) ) {
1662 $filter = new $filterDesc();
1663 } elseif ( is_callable( $filterDesc ) ) {
1664 $filter = $filterDesc();
1665 } else {
1666 throw new UnexpectedValueException(
1667 "Unrecognized filter type for preference '$preference'"
1668 );
1669 }
1670 $preferences[$preference] = $filter->$verb( $preferences[$preference] );
1671 }
1672 }
1673
1674 /**
1675 * Save the form data and reload the page
1676 *
1677 * @param array $formData
1678 * @param HTMLForm $form
1679 * @param array $formDescriptor
1680 * @return Status
1681 */
1682 protected function submitForm( array $formData, HTMLForm $form, array $formDescriptor ) {
1683 $res = $this->saveFormData( $formData, $form, $formDescriptor );
1684
1685 if ( $res === true ) {
1686 $context = $form->getContext();
1687 $urlOptions = [];
1688
1689 if ( $res === 'eauth' ) {
1690 $urlOptions['eauth'] = 1;
1691 }
1692
1693 if (
1694 $context->getRequest()->getFuzzyBool( 'ooui' ) !==
1695 $context->getConfig()->get( 'OOUIPreferences' )
1696 ) {
1697 $urlOptions[ 'ooui' ] = $context->getRequest()->getFuzzyBool( 'ooui' ) ? 1 : 0;
1698 }
1699
1700 $urlOptions += $form->getExtraSuccessRedirectParameters();
1701
1702 $url = $form->getTitle()->getFullURL( $urlOptions );
1703
1704 // Set session data for the success message
1705 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1706
1707 $context->getOutput()->redirect( $url );
1708 }
1709
1710 return ( $res === true ? Status::newGood() : $res );
1711 }
1712
1713 /**
1714 * Get a list of all time zones
1715 * @param Language $language Language used for the localized names
1716 * @return array A list of all time zones. The system name of the time zone is used as key and
1717 * the value is an array which contains localized name, the timecorrection value used for
1718 * preferences and the region
1719 * @since 1.26
1720 */
1721 protected function getTimeZoneList( Language $language ) {
1722 $identifiers = DateTimeZone::listIdentifiers();
1723 if ( $identifiers === false ) {
1724 return [];
1725 }
1726 sort( $identifiers );
1727
1728 $tzRegions = [
1729 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1730 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1731 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1732 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1733 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1734 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1735 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1736 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1737 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1738 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1739 ];
1740 asort( $tzRegions );
1741
1742 $timeZoneList = [];
1743
1744 $now = new DateTime();
1745
1746 foreach ( $identifiers as $identifier ) {
1747 $parts = explode( '/', $identifier, 2 );
1748
1749 // DateTimeZone::listIdentifiers() returns a number of
1750 // backwards-compatibility entries. This filters them out of the
1751 // list presented to the user.
1752 if ( count( $parts ) !== 2 || !array_key_exists( $parts[0], $tzRegions ) ) {
1753 continue;
1754 }
1755
1756 // Localize region
1757 $parts[0] = $tzRegions[$parts[0]];
1758
1759 $dateTimeZone = new DateTimeZone( $identifier );
1760 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1761
1762 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1763 $value = "ZoneInfo|$minDiff|$identifier";
1764
1765 $timeZoneList[$identifier] = [
1766 'name' => $display,
1767 'timecorrection' => $value,
1768 'region' => $parts[0],
1769 ];
1770 }
1771
1772 return $timeZoneList;
1773 }
1774 }