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