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