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