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