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