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