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