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