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