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