Merge "Do not create new archive file names for old files"
[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( $user, $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 User $user
804 * @param MessageLocalizer $l10n
805 * @param array &$defaultPreferences
806 */
807 protected function renderingPreferences(
808 User $user,
809 MessageLocalizer $l10n,
810 &$defaultPreferences
811 ) {
812 # # Diffs ####################################
813 $defaultPreferences['diffonly'] = [
814 'type' => 'toggle',
815 'section' => 'rendering/diffs',
816 'label-message' => 'tog-diffonly',
817 ];
818 $defaultPreferences['norollbackdiff'] = [
819 'type' => 'toggle',
820 'section' => 'rendering/diffs',
821 'label-message' => 'tog-norollbackdiff',
822 ];
823
824 # # Page Rendering ##############################
825 if ( $this->config->get( 'AllowUserCssPrefs' ) ) {
826 $defaultPreferences['underline'] = [
827 'type' => 'select',
828 'options' => [
829 $l10n->msg( 'underline-never' )->text() => 0,
830 $l10n->msg( 'underline-always' )->text() => 1,
831 $l10n->msg( 'underline-default' )->text() => 2,
832 ],
833 'label-message' => 'tog-underline',
834 'section' => 'rendering/advancedrendering',
835 ];
836 }
837
838 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
839 $stubThresholdOptions = [ $l10n->msg( 'stub-threshold-disabled' )->text() => 0 ];
840 foreach ( $stubThresholdValues as $value ) {
841 $stubThresholdOptions[$l10n->msg( 'size-bytes', $value )->text()] = $value;
842 }
843
844 $defaultPreferences['stubthreshold'] = [
845 'type' => 'select',
846 'section' => 'rendering/advancedrendering',
847 'options' => $stubThresholdOptions,
848 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
849 'label-raw' => $l10n->msg( 'stub-threshold' )->rawParams(
850 '<a class="stub">' .
851 $l10n->msg( 'stub-threshold-sample-link' )->parse() .
852 '</a>' )->parse(),
853 ];
854
855 $defaultPreferences['showhiddencats'] = [
856 'type' => 'toggle',
857 'section' => 'rendering/advancedrendering',
858 'label-message' => 'tog-showhiddencats'
859 ];
860
861 $defaultPreferences['numberheadings'] = [
862 'type' => 'toggle',
863 'section' => 'rendering/advancedrendering',
864 'label-message' => 'tog-numberheadings',
865 ];
866
867 if ( $user->isAllowed( 'rollback' ) ) {
868 $defaultPreferences['showrollbackconfirmation'] = [
869 'type' => 'toggle',
870 'section' => 'rendering/advancedrendering',
871 'label-message' => 'tog-showrollbackconfirmation',
872 ];
873
874 /**
875 * FIXME
876 * Remove temporary help text and references to DisableRollbackConfirmationFeature
877 * after release of rollback feature. See T199534
878 */
879 if ( MediaWikiServices::getInstance()
880 ->getMainConfig()->get( 'DisableRollbackConfirmationFeature' ) ) {
881 $defaultPreferences['showrollbackconfirmation']
882 ['help-message'] = 'tog-showrollbackconfirmation-prerelease-warning';
883 }
884 }
885 }
886
887 /**
888 * @param User $user
889 * @param MessageLocalizer $l10n
890 * @param array &$defaultPreferences
891 */
892 protected function editingPreferences( User $user, MessageLocalizer $l10n, &$defaultPreferences ) {
893 # # Editing #####################################
894 $defaultPreferences['editsectiononrightclick'] = [
895 'type' => 'toggle',
896 'section' => 'editing/advancedediting',
897 'label-message' => 'tog-editsectiononrightclick',
898 ];
899 $defaultPreferences['editondblclick'] = [
900 'type' => 'toggle',
901 'section' => 'editing/advancedediting',
902 'label-message' => 'tog-editondblclick',
903 ];
904
905 if ( $this->config->get( 'AllowUserCssPrefs' ) ) {
906 $defaultPreferences['editfont'] = [
907 'type' => 'select',
908 'section' => 'editing/editor',
909 'label-message' => 'editfont-style',
910 'options' => [
911 $l10n->msg( 'editfont-monospace' )->text() => 'monospace',
912 $l10n->msg( 'editfont-sansserif' )->text() => 'sans-serif',
913 $l10n->msg( 'editfont-serif' )->text() => 'serif',
914 ]
915 ];
916 }
917
918 if ( $user->isAllowed( 'minoredit' ) ) {
919 $defaultPreferences['minordefault'] = [
920 'type' => 'toggle',
921 'section' => 'editing/editor',
922 'label-message' => 'tog-minordefault',
923 ];
924 }
925
926 $defaultPreferences['forceeditsummary'] = [
927 'type' => 'toggle',
928 'section' => 'editing/editor',
929 'label-message' => 'tog-forceeditsummary',
930 ];
931 $defaultPreferences['useeditwarning'] = [
932 'type' => 'toggle',
933 'section' => 'editing/editor',
934 'label-message' => 'tog-useeditwarning',
935 ];
936
937 $defaultPreferences['previewonfirst'] = [
938 'type' => 'toggle',
939 'section' => 'editing/preview',
940 'label-message' => 'tog-previewonfirst',
941 ];
942 $defaultPreferences['previewontop'] = [
943 'type' => 'toggle',
944 'section' => 'editing/preview',
945 'label-message' => 'tog-previewontop',
946 ];
947 $defaultPreferences['uselivepreview'] = [
948 'type' => 'toggle',
949 'section' => 'editing/preview',
950 'label-message' => 'tog-uselivepreview',
951 ];
952 }
953
954 /**
955 * @param User $user
956 * @param MessageLocalizer $l10n
957 * @param array &$defaultPreferences
958 */
959 protected function rcPreferences( User $user, MessageLocalizer $l10n, &$defaultPreferences ) {
960 $rcMaxAge = $this->config->get( 'RCMaxAge' );
961 # # RecentChanges #####################################
962 $defaultPreferences['rcdays'] = [
963 'type' => 'float',
964 'label-message' => 'recentchangesdays',
965 'section' => 'rc/displayrc',
966 'min' => 1 / 24,
967 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
968 'help' => $l10n->msg( 'recentchangesdays-max' )->numParams(
969 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
970 ];
971 $defaultPreferences['rclimit'] = [
972 'type' => 'int',
973 'min' => 1,
974 'max' => 1000,
975 'label-message' => 'recentchangescount',
976 'help-message' => 'prefs-help-recentchangescount',
977 'section' => 'rc/displayrc',
978 'filter' => IntvalFilter::class,
979 ];
980 $defaultPreferences['usenewrc'] = [
981 'type' => 'toggle',
982 'label-message' => 'tog-usenewrc',
983 'section' => 'rc/advancedrc',
984 ];
985 $defaultPreferences['hideminor'] = [
986 'type' => 'toggle',
987 'label-message' => 'tog-hideminor',
988 'section' => 'rc/changesrc',
989 ];
990 $defaultPreferences['rcfilters-rc-collapsed'] = [
991 'type' => 'api',
992 ];
993 $defaultPreferences['rcfilters-wl-collapsed'] = [
994 'type' => 'api',
995 ];
996 $defaultPreferences['rcfilters-saved-queries'] = [
997 'type' => 'api',
998 ];
999 $defaultPreferences['rcfilters-wl-saved-queries'] = [
1000 'type' => 'api',
1001 ];
1002 // Override RCFilters preferences for RecentChanges 'limit'
1003 $defaultPreferences['rcfilters-limit'] = [
1004 'type' => 'api',
1005 ];
1006 $defaultPreferences['rcfilters-saved-queries-versionbackup'] = [
1007 'type' => 'api',
1008 ];
1009 $defaultPreferences['rcfilters-wl-saved-queries-versionbackup'] = [
1010 'type' => 'api',
1011 ];
1012
1013 if ( $this->config->get( 'RCWatchCategoryMembership' ) ) {
1014 $defaultPreferences['hidecategorization'] = [
1015 'type' => 'toggle',
1016 'label-message' => 'tog-hidecategorization',
1017 'section' => 'rc/changesrc',
1018 ];
1019 }
1020
1021 if ( $user->useRCPatrol() ) {
1022 $defaultPreferences['hidepatrolled'] = [
1023 'type' => 'toggle',
1024 'section' => 'rc/changesrc',
1025 'label-message' => 'tog-hidepatrolled',
1026 ];
1027 }
1028
1029 if ( $user->useNPPatrol() ) {
1030 $defaultPreferences['newpageshidepatrolled'] = [
1031 'type' => 'toggle',
1032 'section' => 'rc/changesrc',
1033 'label-message' => 'tog-newpageshidepatrolled',
1034 ];
1035 }
1036
1037 if ( $this->config->get( 'RCShowWatchingUsers' ) ) {
1038 $defaultPreferences['shownumberswatching'] = [
1039 'type' => 'toggle',
1040 'section' => 'rc/advancedrc',
1041 'label-message' => 'tog-shownumberswatching',
1042 ];
1043 }
1044
1045 $defaultPreferences['rcenhancedfilters-disable'] = [
1046 'type' => 'toggle',
1047 'section' => 'rc/advancedrc',
1048 'label-message' => 'rcfilters-preference-label',
1049 'help-message' => 'rcfilters-preference-help',
1050 ];
1051 }
1052
1053 /**
1054 * @param User $user
1055 * @param IContextSource $context
1056 * @param array &$defaultPreferences
1057 */
1058 protected function watchlistPreferences(
1059 User $user, IContextSource $context, &$defaultPreferences
1060 ) {
1061 $watchlistdaysMax = ceil( $this->config->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1062
1063 # # Watchlist #####################################
1064 if ( $user->isAllowed( 'editmywatchlist' ) ) {
1065 $editWatchlistLinks = '';
1066 $editWatchlistLinksOld = [];
1067 $editWatchlistModes = [
1068 'edit' => [ 'subpage' => false, 'flags' => [] ],
1069 'raw' => [ 'subpage' => 'raw', 'flags' => [] ],
1070 'clear' => [ 'subpage' => 'clear', 'flags' => [ 'destructive' ] ],
1071 ];
1072 foreach ( $editWatchlistModes as $mode => $options ) {
1073 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1074 $editWatchlistLinks .=
1075 new \OOUI\ButtonWidget( [
1076 'href' => SpecialPage::getTitleFor( 'EditWatchlist', $options['subpage'] )->getLinkURL(),
1077 'flags' => $options[ 'flags' ],
1078 'label' => new \OOUI\HtmlSnippet(
1079 $context->msg( "prefs-editwatchlist-{$mode}" )->parse()
1080 ),
1081 ] );
1082 }
1083
1084 $defaultPreferences['editwatchlist'] = [
1085 'type' => 'info',
1086 'raw' => true,
1087 'default' => $editWatchlistLinks,
1088 'label-message' => 'prefs-editwatchlist-label',
1089 'section' => 'watchlist/editwatchlist',
1090 ];
1091 }
1092
1093 $defaultPreferences['watchlistdays'] = [
1094 'type' => 'float',
1095 'min' => 1 / 24,
1096 'max' => $watchlistdaysMax,
1097 'section' => 'watchlist/displaywatchlist',
1098 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1099 $watchlistdaysMax )->escaped(),
1100 'label-message' => 'prefs-watchlist-days',
1101 ];
1102 $defaultPreferences['wllimit'] = [
1103 'type' => 'int',
1104 'min' => 1,
1105 'max' => 1000,
1106 'label-message' => 'prefs-watchlist-edits',
1107 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1108 'section' => 'watchlist/displaywatchlist',
1109 'filter' => IntvalFilter::class,
1110 ];
1111 $defaultPreferences['extendwatchlist'] = [
1112 'type' => 'toggle',
1113 'section' => 'watchlist/advancedwatchlist',
1114 'label-message' => 'tog-extendwatchlist',
1115 ];
1116 $defaultPreferences['watchlisthideminor'] = [
1117 'type' => 'toggle',
1118 'section' => 'watchlist/changeswatchlist',
1119 'label-message' => 'tog-watchlisthideminor',
1120 ];
1121 $defaultPreferences['watchlisthidebots'] = [
1122 'type' => 'toggle',
1123 'section' => 'watchlist/changeswatchlist',
1124 'label-message' => 'tog-watchlisthidebots',
1125 ];
1126 $defaultPreferences['watchlisthideown'] = [
1127 'type' => 'toggle',
1128 'section' => 'watchlist/changeswatchlist',
1129 'label-message' => 'tog-watchlisthideown',
1130 ];
1131 $defaultPreferences['watchlisthideanons'] = [
1132 'type' => 'toggle',
1133 'section' => 'watchlist/changeswatchlist',
1134 'label-message' => 'tog-watchlisthideanons',
1135 ];
1136 $defaultPreferences['watchlisthideliu'] = [
1137 'type' => 'toggle',
1138 'section' => 'watchlist/changeswatchlist',
1139 'label-message' => 'tog-watchlisthideliu',
1140 ];
1141
1142 if ( !\SpecialWatchlist::checkStructuredFilterUiEnabled(
1143 $this->config,
1144 $user
1145 ) ) {
1146 $defaultPreferences['watchlistreloadautomatically'] = [
1147 'type' => 'toggle',
1148 'section' => 'watchlist/advancedwatchlist',
1149 'label-message' => 'tog-watchlistreloadautomatically',
1150 ];
1151 }
1152
1153 $defaultPreferences['watchlistunwatchlinks'] = [
1154 'type' => 'toggle',
1155 'section' => 'watchlist/advancedwatchlist',
1156 'label-message' => 'tog-watchlistunwatchlinks',
1157 ];
1158
1159 if ( $this->config->get( 'RCWatchCategoryMembership' ) ) {
1160 $defaultPreferences['watchlisthidecategorization'] = [
1161 'type' => 'toggle',
1162 'section' => 'watchlist/changeswatchlist',
1163 'label-message' => 'tog-watchlisthidecategorization',
1164 ];
1165 }
1166
1167 if ( $user->useRCPatrol() ) {
1168 $defaultPreferences['watchlisthidepatrolled'] = [
1169 'type' => 'toggle',
1170 'section' => 'watchlist/changeswatchlist',
1171 'label-message' => 'tog-watchlisthidepatrolled',
1172 ];
1173 }
1174
1175 $watchTypes = [
1176 'edit' => 'watchdefault',
1177 'move' => 'watchmoves',
1178 'delete' => 'watchdeletion'
1179 ];
1180
1181 // Kinda hacky
1182 if ( $user->isAllowed( 'createpage' ) || $user->isAllowed( 'createtalk' ) ) {
1183 $watchTypes['read'] = 'watchcreations';
1184 }
1185
1186 if ( $user->isAllowed( 'rollback' ) ) {
1187 $watchTypes['rollback'] = 'watchrollback';
1188 }
1189
1190 if ( $user->isAllowed( 'upload' ) ) {
1191 $watchTypes['upload'] = 'watchuploads';
1192 }
1193
1194 foreach ( $watchTypes as $action => $pref ) {
1195 if ( $user->isAllowed( $action ) ) {
1196 // Messages:
1197 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1198 // tog-watchrollback
1199 $defaultPreferences[$pref] = [
1200 'type' => 'toggle',
1201 'section' => 'watchlist/pageswatchlist',
1202 'label-message' => "tog-$pref",
1203 ];
1204 }
1205 }
1206
1207 $defaultPreferences['watchlisttoken'] = [
1208 'type' => 'api',
1209 ];
1210
1211 $tokenButton = new \OOUI\ButtonWidget( [
1212 'href' => SpecialPage::getTitleFor( 'ResetTokens' )->getLinkURL( [
1213 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText()
1214 ] ),
1215 'label' => $context->msg( 'prefs-watchlist-managetokens' )->text(),
1216 ] );
1217 $defaultPreferences['watchlisttoken-info'] = [
1218 'type' => 'info',
1219 'section' => 'watchlist/tokenwatchlist',
1220 'label-message' => 'prefs-watchlist-token',
1221 'help-message' => 'prefs-help-tokenmanagement',
1222 'raw' => true,
1223 'default' => (string)$tokenButton,
1224 ];
1225
1226 $defaultPreferences['wlenhancedfilters-disable'] = [
1227 'type' => 'toggle',
1228 'section' => 'watchlist/advancedwatchlist',
1229 'label-message' => 'rcfilters-watchlist-preference-label',
1230 'help-message' => 'rcfilters-watchlist-preference-help',
1231 ];
1232 }
1233
1234 /**
1235 * @param array &$defaultPreferences
1236 */
1237 protected function searchPreferences( &$defaultPreferences ) {
1238 foreach ( MWNamespace::getValidNamespaces() as $n ) {
1239 $defaultPreferences['searchNs' . $n] = [
1240 'type' => 'api',
1241 ];
1242 }
1243 }
1244
1245 /**
1246 * @param User $user The User object
1247 * @param IContextSource $context
1248 * @return array Text/links to display as key; $skinkey as value
1249 */
1250 protected function generateSkinOptions( User $user, IContextSource $context ) {
1251 $ret = [];
1252
1253 $mptitle = Title::newMainPage();
1254 $previewtext = $context->msg( 'skin-preview' )->escaped();
1255
1256 # Only show skins that aren't disabled in $wgSkipSkins
1257 $validSkinNames = Skin::getAllowedSkins();
1258
1259 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1260 $msg = $context->msg( "skinname-{$skinkey}" );
1261 if ( $msg->exists() ) {
1262 $skinname = htmlspecialchars( $msg->text() );
1263 }
1264 }
1265
1266 $defaultSkin = $this->config->get( 'DefaultSkin' );
1267 $allowUserCss = $this->config->get( 'AllowUserCss' );
1268 $allowUserJs = $this->config->get( 'AllowUserJs' );
1269
1270 # Sort by the internal name, so that the ordering is the same for each display language,
1271 # especially if some skin names are translated to use a different alphabet and some are not.
1272 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1273 # Display the default first in the list by comparing it as lesser than any other.
1274 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1275 return -1;
1276 }
1277 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1278 return 1;
1279 }
1280 return strcasecmp( $a, $b );
1281 } );
1282
1283 $foundDefault = false;
1284 foreach ( $validSkinNames as $skinkey => $sn ) {
1285 $linkTools = [];
1286
1287 # Mark the default skin
1288 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1289 $linkTools[] = $context->msg( 'default' )->escaped();
1290 $foundDefault = true;
1291 }
1292
1293 # Create preview link
1294 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1295 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1296
1297 # Create links to user CSS/JS pages
1298 if ( $allowUserCss ) {
1299 $cssPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.css' );
1300 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
1301 $linkTools[] = $this->linkRenderer->makeLink( $cssPage, $cssLinkText );
1302 }
1303
1304 if ( $allowUserJs ) {
1305 $jsPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.js' );
1306 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
1307 $linkTools[] = $this->linkRenderer->makeLink( $jsPage, $jsLinkText );
1308 }
1309
1310 $display = $sn . ' ' . $context->msg( 'parentheses' )
1311 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1312 ->escaped();
1313 $ret[$display] = $skinkey;
1314 }
1315
1316 if ( !$foundDefault ) {
1317 // If the default skin is not available, things are going to break horribly because the
1318 // default value for skin selector will not be a valid value. Let's just not show it then.
1319 return [];
1320 }
1321
1322 return $ret;
1323 }
1324
1325 /**
1326 * @param IContextSource $context
1327 * @return array
1328 */
1329 protected function getDateOptions( IContextSource $context ) {
1330 $lang = $context->getLanguage();
1331 $dateopts = $lang->getDatePreferences();
1332
1333 $ret = [];
1334
1335 if ( $dateopts ) {
1336 if ( !in_array( 'default', $dateopts ) ) {
1337 $dateopts[] = 'default'; // Make sure default is always valid T21237
1338 }
1339
1340 // FIXME KLUGE: site default might not be valid for user language
1341 global $wgDefaultUserOptions;
1342 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1343 $wgDefaultUserOptions['date'] = 'default';
1344 }
1345
1346 $epoch = wfTimestampNow();
1347 foreach ( $dateopts as $key ) {
1348 if ( $key == 'default' ) {
1349 $formatted = $context->msg( 'datedefault' )->escaped();
1350 } else {
1351 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1352 }
1353 $ret[$formatted] = $key;
1354 }
1355 }
1356 return $ret;
1357 }
1358
1359 /**
1360 * @param MessageLocalizer $l10n
1361 * @return array
1362 */
1363 protected function getImageSizes( MessageLocalizer $l10n ) {
1364 $ret = [];
1365 $pixels = $l10n->msg( 'unit-pixel' )->text();
1366
1367 foreach ( $this->config->get( 'ImageLimits' ) as $index => $limits ) {
1368 // Note: A left-to-right marker (U+200E) is inserted, see T144386
1369 $display = "{$limits[0]}\u{200E}×{$limits[1]}$pixels";
1370 $ret[$display] = $index;
1371 }
1372
1373 return $ret;
1374 }
1375
1376 /**
1377 * @param MessageLocalizer $l10n
1378 * @return array
1379 */
1380 protected function getThumbSizes( MessageLocalizer $l10n ) {
1381 $ret = [];
1382 $pixels = $l10n->msg( 'unit-pixel' )->text();
1383
1384 foreach ( $this->config->get( 'ThumbLimits' ) as $index => $size ) {
1385 $display = $size . $pixels;
1386 $ret[$display] = $index;
1387 }
1388
1389 return $ret;
1390 }
1391
1392 /**
1393 * @param string $signature
1394 * @param array $alldata
1395 * @param HTMLForm $form
1396 * @return bool|string
1397 */
1398 protected function validateSignature( $signature, $alldata, HTMLForm $form ) {
1399 $maxSigChars = $this->config->get( 'MaxSigChars' );
1400 if ( mb_strlen( $signature ) > $maxSigChars ) {
1401 return Xml::element( 'span', [ 'class' => 'error' ],
1402 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1403 } elseif ( isset( $alldata['fancysig'] ) &&
1404 $alldata['fancysig'] &&
1405 MediaWikiServices::getInstance()->getParser()->validateSig( $signature ) === false
1406 ) {
1407 return Xml::element(
1408 'span',
1409 [ 'class' => 'error' ],
1410 $form->msg( 'badsig' )->text()
1411 );
1412 } else {
1413 return true;
1414 }
1415 }
1416
1417 /**
1418 * @param string $signature
1419 * @param array $alldata
1420 * @param HTMLForm $form
1421 * @return string
1422 */
1423 protected function cleanSignature( $signature, $alldata, HTMLForm $form ) {
1424 $parser = MediaWikiServices::getInstance()->getParser();
1425 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1426 $signature = $parser->cleanSig( $signature );
1427 } else {
1428 // When no fancy sig used, make sure ~{3,5} get removed.
1429 $signature = Parser::cleanSigInSig( $signature );
1430 }
1431
1432 return $signature;
1433 }
1434
1435 /**
1436 * @param User $user
1437 * @param IContextSource $context
1438 * @param string $formClass
1439 * @param array $remove Array of items to remove
1440 * @return HTMLForm
1441 */
1442 public function getForm(
1443 User $user,
1444 IContextSource $context,
1445 $formClass = PreferencesFormLegacy::class,
1446 array $remove = []
1447 ) {
1448 // We use ButtonWidgets in some of the getPreferences() functions
1449 $context->getOutput()->enableOOUI();
1450
1451 $formDescriptor = $this->getFormDescriptor( $user, $context );
1452 if ( count( $remove ) ) {
1453 $removeKeys = array_flip( $remove );
1454 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1455 }
1456
1457 // Remove type=api preferences. They are not intended for rendering in the form.
1458 foreach ( $formDescriptor as $name => $info ) {
1459 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1460 unset( $formDescriptor[$name] );
1461 }
1462 }
1463
1464 /**
1465 * @var $htmlForm HTMLForm
1466 */
1467 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1468
1469 $htmlForm->setModifiedUser( $user );
1470 $htmlForm->setId( 'mw-prefs-form' );
1471 $htmlForm->setAutocomplete( 'off' );
1472 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1473 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1474 $htmlForm->setSubmitTooltip( 'preferences-save' );
1475 $htmlForm->setSubmitID( 'prefcontrol' );
1476 $htmlForm->setSubmitCallback(
1477 function ( array $formData, HTMLForm $form ) use ( $formDescriptor ) {
1478 return $this->submitForm( $formData, $form, $formDescriptor );
1479 }
1480 );
1481
1482 return $htmlForm;
1483 }
1484
1485 /**
1486 * @param IContextSource $context
1487 * @return array
1488 */
1489 protected function getTimezoneOptions( IContextSource $context ) {
1490 $opt = [];
1491
1492 $localTZoffset = $this->config->get( 'LocalTZoffset' );
1493 $timeZoneList = $this->getTimeZoneList( $context->getLanguage() );
1494
1495 $timestamp = MWTimestamp::getLocalInstance();
1496 // Check that the LocalTZoffset is the same as the local time zone offset
1497 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1498 $timezoneName = $timestamp->getTimezone()->getName();
1499 // Localize timezone
1500 if ( isset( $timeZoneList[$timezoneName] ) ) {
1501 $timezoneName = $timeZoneList[$timezoneName]['name'];
1502 }
1503 $server_tz_msg = $context->msg(
1504 'timezoneuseserverdefault',
1505 $timezoneName
1506 )->text();
1507 } else {
1508 $tzstring = sprintf(
1509 '%+03d:%02d',
1510 floor( $localTZoffset / 60 ),
1511 abs( $localTZoffset ) % 60
1512 );
1513 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1514 }
1515 $opt[$server_tz_msg] = "System|$localTZoffset";
1516 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1517 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1518
1519 foreach ( $timeZoneList as $timeZoneInfo ) {
1520 $region = $timeZoneInfo['region'];
1521 if ( !isset( $opt[$region] ) ) {
1522 $opt[$region] = [];
1523 }
1524 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1525 }
1526 return $opt;
1527 }
1528
1529 /**
1530 * Handle the form submission if everything validated properly
1531 *
1532 * @param array $formData
1533 * @param HTMLForm $form
1534 * @param array[] $formDescriptor
1535 * @return bool|Status|string
1536 */
1537 protected function saveFormData( $formData, HTMLForm $form, array $formDescriptor ) {
1538 /** @var \User $user */
1539 $user = $form->getModifiedUser();
1540 $hiddenPrefs = $this->config->get( 'HiddenPrefs' );
1541 $result = true;
1542
1543 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1544 return Status::newFatal( 'mypreferencesprotected' );
1545 }
1546
1547 // Filter input
1548 $this->applyFilters( $formData, $formDescriptor, 'filterFromForm' );
1549
1550 // Fortunately, the realname field is MUCH simpler
1551 // (not really "private", but still shouldn't be edited without permission)
1552
1553 if ( !in_array( 'realname', $hiddenPrefs )
1554 && $user->isAllowed( 'editmyprivateinfo' )
1555 && array_key_exists( 'realname', $formData )
1556 ) {
1557 $realName = $formData['realname'];
1558 $user->setRealName( $realName );
1559 }
1560
1561 if ( $user->isAllowed( 'editmyoptions' ) ) {
1562 $oldUserOptions = $user->getOptions();
1563
1564 foreach ( $this->getSaveBlacklist() as $b ) {
1565 unset( $formData[$b] );
1566 }
1567
1568 # If users have saved a value for a preference which has subsequently been disabled
1569 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1570 # is subsequently re-enabled
1571 foreach ( $hiddenPrefs as $pref ) {
1572 # If the user has not set a non-default value here, the default will be returned
1573 # and subsequently discarded
1574 $formData[$pref] = $user->getOption( $pref, null, true );
1575 }
1576
1577 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1578 if (
1579 isset( $formData['rclimit'] ) &&
1580 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1581 ) {
1582 $formData['rcfilters-limit'] = $formData['rclimit'];
1583 }
1584
1585 // Keep old preferences from interfering due to back-compat code, etc.
1586 $user->resetOptions( 'unused', $form->getContext() );
1587
1588 foreach ( $formData as $key => $value ) {
1589 $user->setOption( $key, $value );
1590 }
1591
1592 Hooks::run(
1593 'PreferencesFormPreSave',
1594 [ $formData, $form, $user, &$result, $oldUserOptions ]
1595 );
1596 }
1597
1598 $user->saveSettings();
1599
1600 return $result;
1601 }
1602
1603 /**
1604 * Applies filters to preferences either before or after form usage
1605 *
1606 * @param array &$preferences
1607 * @param array $formDescriptor
1608 * @param string $verb Name of the filter method to call, either 'filterFromForm' or
1609 * 'filterForForm'
1610 */
1611 protected function applyFilters( array &$preferences, array $formDescriptor, $verb ) {
1612 foreach ( $formDescriptor as $preference => $desc ) {
1613 if ( !isset( $desc['filter'] ) || !isset( $preferences[$preference] ) ) {
1614 continue;
1615 }
1616 $filterDesc = $desc['filter'];
1617 if ( $filterDesc instanceof Filter ) {
1618 $filter = $filterDesc;
1619 } elseif ( class_exists( $filterDesc ) ) {
1620 $filter = new $filterDesc();
1621 } elseif ( is_callable( $filterDesc ) ) {
1622 $filter = $filterDesc();
1623 } else {
1624 throw new UnexpectedValueException(
1625 "Unrecognized filter type for preference '$preference'"
1626 );
1627 }
1628 $preferences[$preference] = $filter->$verb( $preferences[$preference] );
1629 }
1630 }
1631
1632 /**
1633 * Save the form data and reload the page
1634 *
1635 * @param array $formData
1636 * @param HTMLForm $form
1637 * @param array $formDescriptor
1638 * @return Status
1639 */
1640 protected function submitForm( array $formData, HTMLForm $form, array $formDescriptor ) {
1641 $res = $this->saveFormData( $formData, $form, $formDescriptor );
1642
1643 if ( $res === true ) {
1644 $context = $form->getContext();
1645 $urlOptions = [];
1646
1647 if ( $res === 'eauth' ) {
1648 $urlOptions['eauth'] = 1;
1649 }
1650
1651 $urlOptions += $form->getExtraSuccessRedirectParameters();
1652
1653 $url = $form->getTitle()->getFullURL( $urlOptions );
1654
1655 // Set session data for the success message
1656 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1657
1658 $context->getOutput()->redirect( $url );
1659 }
1660
1661 return ( $res === true ? Status::newGood() : $res );
1662 }
1663
1664 /**
1665 * Get a list of all time zones
1666 * @param Language $language Language used for the localized names
1667 * @return array A list of all time zones. The system name of the time zone is used as key and
1668 * the value is an array which contains localized name, the timecorrection value used for
1669 * preferences and the region
1670 * @since 1.26
1671 */
1672 protected function getTimeZoneList( Language $language ) {
1673 $identifiers = DateTimeZone::listIdentifiers();
1674 if ( $identifiers === false ) {
1675 return [];
1676 }
1677 sort( $identifiers );
1678
1679 $tzRegions = [
1680 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1681 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1682 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1683 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1684 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1685 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1686 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1687 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1688 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1689 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1690 ];
1691 asort( $tzRegions );
1692
1693 $timeZoneList = [];
1694
1695 $now = new DateTime();
1696
1697 foreach ( $identifiers as $identifier ) {
1698 $parts = explode( '/', $identifier, 2 );
1699
1700 // DateTimeZone::listIdentifiers() returns a number of
1701 // backwards-compatibility entries. This filters them out of the
1702 // list presented to the user.
1703 if ( count( $parts ) !== 2 || !array_key_exists( $parts[0], $tzRegions ) ) {
1704 continue;
1705 }
1706
1707 // Localize region
1708 $parts[0] = $tzRegions[$parts[0]];
1709
1710 $dateTimeZone = new DateTimeZone( $identifier );
1711 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1712
1713 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1714 $value = "ZoneInfo|$minDiff|$identifier";
1715
1716 $timeZoneList[$identifier] = [
1717 'name' => $display,
1718 'timecorrection' => $value,
1719 'region' => $parts[0],
1720 ];
1721 }
1722
1723 return $timeZoneList;
1724 }
1725 }