Merge "Fix submit button id on Special:Preferences"
[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
559 if ( $config->get( 'EnotifWatchlist' ) ) {
560 $defaultPreferences['enotifwatchlistpages'] = [
561 'type' => 'toggle',
562 'section' => 'personal/email',
563 'label-message' => 'tog-enotifwatchlistpages',
564 'disabled' => $disableEmailPrefs,
565 ];
566 }
567 if ( $config->get( 'EnotifUserTalk' ) ) {
568 $defaultPreferences['enotifusertalkpages'] = [
569 'type' => 'toggle',
570 'section' => 'personal/email',
571 'label-message' => 'tog-enotifusertalkpages',
572 'disabled' => $disableEmailPrefs,
573 ];
574 }
575 if ( $config->get( 'EnotifUserTalk' ) || $config->get( 'EnotifWatchlist' ) ) {
576 if ( $config->get( 'EnotifMinorEdits' ) ) {
577 $defaultPreferences['enotifminoredits'] = [
578 'type' => 'toggle',
579 'section' => 'personal/email',
580 'label-message' => 'tog-enotifminoredits',
581 'disabled' => $disableEmailPrefs,
582 ];
583 }
584
585 if ( $config->get( 'EnotifRevealEditorAddress' ) ) {
586 $defaultPreferences['enotifrevealaddr'] = [
587 'type' => 'toggle',
588 'section' => 'personal/email',
589 'label-message' => 'tog-enotifrevealaddr',
590 'disabled' => $disableEmailPrefs,
591 ];
592 }
593 }
594 }
595 }
596
597 /**
598 * @param User $user
599 * @param IContextSource $context
600 * @param array &$defaultPreferences
601 * @return void
602 */
603 static function skinPreferences( $user, IContextSource $context, &$defaultPreferences ) {
604 # # Skin #####################################
605
606 // Skin selector, if there is at least one valid skin
607 $skinOptions = self::generateSkinOptions( $user, $context );
608 if ( $skinOptions ) {
609 $defaultPreferences['skin'] = [
610 'type' => 'radio',
611 'options' => $skinOptions,
612 'label' => '&#160;',
613 'section' => 'rendering/skin',
614 ];
615 }
616
617 $config = $context->getConfig();
618 $allowUserCss = $config->get( 'AllowUserCss' );
619 $allowUserJs = $config->get( 'AllowUserJs' );
620 # Create links to user CSS/JS pages for all skins
621 # This code is basically copied from generateSkinOptions(). It'd
622 # be nice to somehow merge this back in there to avoid redundancy.
623 if ( $allowUserCss || $allowUserJs ) {
624 $linkTools = [];
625 $userName = $user->getName();
626
627 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
628 if ( $allowUserCss ) {
629 $cssPage = Title::makeTitleSafe( NS_USER, $userName . '/common.css' );
630 $linkTools[] = $linkRenderer->makeLink( $cssPage, $context->msg( 'prefs-custom-css' )->text() );
631 }
632
633 if ( $allowUserJs ) {
634 $jsPage = Title::makeTitleSafe( NS_USER, $userName . '/common.js' );
635 $linkTools[] = $linkRenderer->makeLink( $jsPage, $context->msg( 'prefs-custom-js' )->text() );
636 }
637
638 $defaultPreferences['commoncssjs'] = [
639 'type' => 'info',
640 'raw' => true,
641 'default' => $context->getLanguage()->pipeList( $linkTools ),
642 'label-message' => 'prefs-common-css-js',
643 'section' => 'rendering/skin',
644 ];
645 }
646 }
647
648 /**
649 * @param User $user
650 * @param IContextSource $context
651 * @param array &$defaultPreferences
652 */
653 static function filesPreferences( $user, IContextSource $context, &$defaultPreferences ) {
654 # # Files #####################################
655 $defaultPreferences['imagesize'] = [
656 'type' => 'select',
657 'options' => self::getImageSizes( $context ),
658 'label-message' => 'imagemaxsize',
659 'section' => 'rendering/files',
660 ];
661 $defaultPreferences['thumbsize'] = [
662 'type' => 'select',
663 'options' => self::getThumbSizes( $context ),
664 'label-message' => 'thumbsize',
665 'section' => 'rendering/files',
666 ];
667 }
668
669 /**
670 * @param User $user
671 * @param IContextSource $context
672 * @param array &$defaultPreferences
673 * @return void
674 */
675 static function datetimePreferences( $user, IContextSource $context, &$defaultPreferences ) {
676 # # Date and time #####################################
677 $dateOptions = self::getDateOptions( $context );
678 if ( $dateOptions ) {
679 $defaultPreferences['date'] = [
680 'type' => 'radio',
681 'options' => $dateOptions,
682 'label' => '&#160;',
683 'section' => 'rendering/dateformat',
684 ];
685 }
686
687 // Info
688 $now = wfTimestampNow();
689 $lang = $context->getLanguage();
690 $nowlocal = Xml::element( 'span', [ 'id' => 'wpLocalTime' ],
691 $lang->userTime( $now, $user ) );
692 $nowserver = $lang->userTime( $now, $user,
693 [ 'format' => false, 'timecorrection' => false ] ) .
694 Html::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 + (int)substr( $now, 10, 2 ) );
695
696 $defaultPreferences['nowserver'] = [
697 'type' => 'info',
698 'raw' => 1,
699 'label-message' => 'servertime',
700 'default' => $nowserver,
701 'section' => 'rendering/timeoffset',
702 ];
703
704 $defaultPreferences['nowlocal'] = [
705 'type' => 'info',
706 'raw' => 1,
707 'label-message' => 'localtime',
708 'default' => $nowlocal,
709 'section' => 'rendering/timeoffset',
710 ];
711
712 // Grab existing pref.
713 $tzOffset = $user->getOption( 'timecorrection' );
714 $tz = explode( '|', $tzOffset, 3 );
715
716 $tzOptions = self::getTimezoneOptions( $context );
717
718 $tzSetting = $tzOffset;
719 if ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
720 !in_array( $tzOffset, HTMLFormField::flattenOptions( $tzOptions ) )
721 ) {
722 // Timezone offset can vary with DST
723 try {
724 $userTZ = new DateTimeZone( $tz[2] );
725 $minDiff = floor( $userTZ->getOffset( new DateTime( 'now' ) ) / 60 );
726 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
727 } catch ( Exception $e ) {
728 // User has an invalid time zone set. Fall back to just using the offset
729 $tz[0] = 'Offset';
730 }
731 }
732 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
733 $minDiff = $tz[1];
734 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) % 60 );
735 }
736
737 $defaultPreferences['timecorrection'] = [
738 'class' => 'HTMLSelectOrOtherField',
739 'label-message' => 'timezonelegend',
740 'options' => $tzOptions,
741 'default' => $tzSetting,
742 'size' => 20,
743 'section' => 'rendering/timeoffset',
744 ];
745 }
746
747 /**
748 * @param User $user
749 * @param IContextSource $context
750 * @param array &$defaultPreferences
751 */
752 static function renderingPreferences( $user, IContextSource $context, &$defaultPreferences ) {
753 # # Diffs ####################################
754 $defaultPreferences['diffonly'] = [
755 'type' => 'toggle',
756 'section' => 'rendering/diffs',
757 'label-message' => 'tog-diffonly',
758 ];
759 $defaultPreferences['norollbackdiff'] = [
760 'type' => 'toggle',
761 'section' => 'rendering/diffs',
762 'label-message' => 'tog-norollbackdiff',
763 ];
764
765 # # Page Rendering ##############################
766 if ( $context->getConfig()->get( 'AllowUserCssPrefs' ) ) {
767 $defaultPreferences['underline'] = [
768 'type' => 'select',
769 'options' => [
770 $context->msg( 'underline-never' )->text() => 0,
771 $context->msg( 'underline-always' )->text() => 1,
772 $context->msg( 'underline-default' )->text() => 2,
773 ],
774 'label-message' => 'tog-underline',
775 'section' => 'rendering/advancedrendering',
776 ];
777 }
778
779 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
780 $stubThresholdOptions = [ $context->msg( 'stub-threshold-disabled' )->text() => 0 ];
781 foreach ( $stubThresholdValues as $value ) {
782 $stubThresholdOptions[$context->msg( 'size-bytes', $value )->text()] = $value;
783 }
784
785 $defaultPreferences['stubthreshold'] = [
786 'type' => 'select',
787 'section' => 'rendering/advancedrendering',
788 'options' => $stubThresholdOptions,
789 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
790 'label-raw' => $context->msg( 'stub-threshold' )->rawParams(
791 '<a href="#" class="stub">' .
792 $context->msg( 'stub-threshold-sample-link' )->parse() .
793 '</a>' )->parse(),
794 ];
795
796 $defaultPreferences['showhiddencats'] = [
797 'type' => 'toggle',
798 'section' => 'rendering/advancedrendering',
799 'label-message' => 'tog-showhiddencats'
800 ];
801
802 $defaultPreferences['numberheadings'] = [
803 'type' => 'toggle',
804 'section' => 'rendering/advancedrendering',
805 'label-message' => 'tog-numberheadings',
806 ];
807 }
808
809 /**
810 * @param User $user
811 * @param IContextSource $context
812 * @param array &$defaultPreferences
813 */
814 static function editingPreferences( $user, IContextSource $context, &$defaultPreferences ) {
815 # # Editing #####################################
816 $defaultPreferences['editsectiononrightclick'] = [
817 'type' => 'toggle',
818 'section' => 'editing/advancedediting',
819 'label-message' => 'tog-editsectiononrightclick',
820 ];
821 $defaultPreferences['editondblclick'] = [
822 'type' => 'toggle',
823 'section' => 'editing/advancedediting',
824 'label-message' => 'tog-editondblclick',
825 ];
826
827 if ( $context->getConfig()->get( 'AllowUserCssPrefs' ) ) {
828 $defaultPreferences['editfont'] = [
829 'type' => 'select',
830 'section' => 'editing/editor',
831 'label-message' => 'editfont-style',
832 'options' => [
833 $context->msg( 'editfont-monospace' )->text() => 'monospace',
834 $context->msg( 'editfont-sansserif' )->text() => 'sans-serif',
835 $context->msg( 'editfont-serif' )->text() => 'serif',
836 $context->msg( 'editfont-default' )->text() => 'default',
837 ]
838 ];
839 }
840
841 if ( $user->isAllowed( 'minoredit' ) ) {
842 $defaultPreferences['minordefault'] = [
843 'type' => 'toggle',
844 'section' => 'editing/editor',
845 'label-message' => 'tog-minordefault',
846 ];
847 }
848
849 $defaultPreferences['forceeditsummary'] = [
850 'type' => 'toggle',
851 'section' => 'editing/editor',
852 'label-message' => 'tog-forceeditsummary',
853 ];
854 $defaultPreferences['useeditwarning'] = [
855 'type' => 'toggle',
856 'section' => 'editing/editor',
857 'label-message' => 'tog-useeditwarning',
858 ];
859 $defaultPreferences['showtoolbar'] = [
860 'type' => 'toggle',
861 'section' => 'editing/editor',
862 'label-message' => 'tog-showtoolbar',
863 ];
864
865 $defaultPreferences['previewonfirst'] = [
866 'type' => 'toggle',
867 'section' => 'editing/preview',
868 'label-message' => 'tog-previewonfirst',
869 ];
870 $defaultPreferences['previewontop'] = [
871 'type' => 'toggle',
872 'section' => 'editing/preview',
873 'label-message' => 'tog-previewontop',
874 ];
875 $defaultPreferences['uselivepreview'] = [
876 'type' => 'toggle',
877 'section' => 'editing/preview',
878 'label-message' => 'tog-uselivepreview',
879 ];
880 }
881
882 /**
883 * @param User $user
884 * @param IContextSource $context
885 * @param array &$defaultPreferences
886 */
887 static function rcPreferences( $user, IContextSource $context, &$defaultPreferences ) {
888 $config = $context->getConfig();
889 $rcMaxAge = $config->get( 'RCMaxAge' );
890 # # RecentChanges #####################################
891 $defaultPreferences['rcdays'] = [
892 'type' => 'float',
893 'label-message' => 'recentchangesdays',
894 'section' => 'rc/displayrc',
895 'min' => 1,
896 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
897 'help' => $context->msg( 'recentchangesdays-max' )->numParams(
898 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
899 ];
900 $defaultPreferences['rclimit'] = [
901 'type' => 'int',
902 'min' => 0,
903 'max' => 1000,
904 'label-message' => 'recentchangescount',
905 'help-message' => 'prefs-help-recentchangescount',
906 'section' => 'rc/displayrc',
907 ];
908 $defaultPreferences['usenewrc'] = [
909 'type' => 'toggle',
910 'label-message' => 'tog-usenewrc',
911 'section' => 'rc/advancedrc',
912 ];
913 $defaultPreferences['hideminor'] = [
914 'type' => 'toggle',
915 'label-message' => 'tog-hideminor',
916 'section' => 'rc/advancedrc',
917 ];
918 $defaultPreferences['rcfilters-saved-queries'] = [
919 'type' => 'api',
920 ];
921 $defaultPreferences['rcfilters-wl-saved-queries'] = [
922 'type' => 'api',
923 ];
924 $defaultPreferences['rcfilters-rclimit'] = [
925 'type' => 'api',
926 ];
927
928 if ( $config->get( 'RCWatchCategoryMembership' ) ) {
929 $defaultPreferences['hidecategorization'] = [
930 'type' => 'toggle',
931 'label-message' => 'tog-hidecategorization',
932 'section' => 'rc/advancedrc',
933 ];
934 }
935
936 if ( $user->useRCPatrol() ) {
937 $defaultPreferences['hidepatrolled'] = [
938 'type' => 'toggle',
939 'section' => 'rc/advancedrc',
940 'label-message' => 'tog-hidepatrolled',
941 ];
942 }
943
944 if ( $user->useNPPatrol() ) {
945 $defaultPreferences['newpageshidepatrolled'] = [
946 'type' => 'toggle',
947 'section' => 'rc/advancedrc',
948 'label-message' => 'tog-newpageshidepatrolled',
949 ];
950 }
951
952 if ( $config->get( 'RCShowWatchingUsers' ) ) {
953 $defaultPreferences['shownumberswatching'] = [
954 'type' => 'toggle',
955 'section' => 'rc/advancedrc',
956 'label-message' => 'tog-shownumberswatching',
957 ];
958 }
959
960 if ( $config->get( 'StructuredChangeFiltersShowPreference' ) ) {
961 $defaultPreferences['rcenhancedfilters-disable'] = [
962 'type' => 'toggle',
963 'section' => 'rc/advancedrc',
964 'label-message' => 'rcfilters-preference-label',
965 'help-message' => 'rcfilters-preference-help',
966 ];
967 }
968 }
969
970 /**
971 * @param User $user
972 * @param IContextSource $context
973 * @param array &$defaultPreferences
974 */
975 static function watchlistPreferences( $user, IContextSource $context, &$defaultPreferences ) {
976 $config = $context->getConfig();
977 $watchlistdaysMax = ceil( $config->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
978
979 # # Watchlist #####################################
980 if ( $user->isAllowed( 'editmywatchlist' ) ) {
981 $editWatchlistLinks = [];
982 $editWatchlistModes = [
983 'edit' => [ 'EditWatchlist', false ],
984 'raw' => [ 'EditWatchlist', 'raw' ],
985 'clear' => [ 'EditWatchlist', 'clear' ],
986 ];
987 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
988 foreach ( $editWatchlistModes as $editWatchlistMode => $mode ) {
989 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
990 $editWatchlistLinks[] = $linkRenderer->makeKnownLink(
991 SpecialPage::getTitleFor( $mode[0], $mode[1] ),
992 new HtmlArmor( $context->msg( "prefs-editwatchlist-{$editWatchlistMode}" )->parse() )
993 );
994 }
995
996 $defaultPreferences['editwatchlist'] = [
997 'type' => 'info',
998 'raw' => true,
999 'default' => $context->getLanguage()->pipeList( $editWatchlistLinks ),
1000 'label-message' => 'prefs-editwatchlist-label',
1001 'section' => 'watchlist/editwatchlist',
1002 ];
1003 }
1004
1005 $defaultPreferences['watchlistdays'] = [
1006 'type' => 'float',
1007 'min' => 0,
1008 'max' => $watchlistdaysMax,
1009 'section' => 'watchlist/displaywatchlist',
1010 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1011 $watchlistdaysMax )->escaped(),
1012 'label-message' => 'prefs-watchlist-days',
1013 ];
1014 $defaultPreferences['wllimit'] = [
1015 'type' => 'int',
1016 'min' => 0,
1017 'max' => 1000,
1018 'label-message' => 'prefs-watchlist-edits',
1019 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1020 'section' => 'watchlist/displaywatchlist',
1021 ];
1022 $defaultPreferences['extendwatchlist'] = [
1023 'type' => 'toggle',
1024 'section' => 'watchlist/advancedwatchlist',
1025 'label-message' => 'tog-extendwatchlist',
1026 ];
1027 $defaultPreferences['watchlisthideminor'] = [
1028 'type' => 'toggle',
1029 'section' => 'watchlist/advancedwatchlist',
1030 'label-message' => 'tog-watchlisthideminor',
1031 ];
1032 $defaultPreferences['watchlisthidebots'] = [
1033 'type' => 'toggle',
1034 'section' => 'watchlist/advancedwatchlist',
1035 'label-message' => 'tog-watchlisthidebots',
1036 ];
1037 $defaultPreferences['watchlisthideown'] = [
1038 'type' => 'toggle',
1039 'section' => 'watchlist/advancedwatchlist',
1040 'label-message' => 'tog-watchlisthideown',
1041 ];
1042 $defaultPreferences['watchlisthideanons'] = [
1043 'type' => 'toggle',
1044 'section' => 'watchlist/advancedwatchlist',
1045 'label-message' => 'tog-watchlisthideanons',
1046 ];
1047 $defaultPreferences['watchlisthideliu'] = [
1048 'type' => 'toggle',
1049 'section' => 'watchlist/advancedwatchlist',
1050 'label-message' => 'tog-watchlisthideliu',
1051 ];
1052 $defaultPreferences['watchlistreloadautomatically'] = [
1053 'type' => 'toggle',
1054 'section' => 'watchlist/advancedwatchlist',
1055 'label-message' => 'tog-watchlistreloadautomatically',
1056 ];
1057 $defaultPreferences['watchlistunwatchlinks'] = [
1058 'type' => 'toggle',
1059 'section' => 'watchlist/advancedwatchlist',
1060 'label-message' => 'tog-watchlistunwatchlinks',
1061 ];
1062
1063 if ( $config->get( 'RCWatchCategoryMembership' ) ) {
1064 $defaultPreferences['watchlisthidecategorization'] = [
1065 'type' => 'toggle',
1066 'section' => 'watchlist/advancedwatchlist',
1067 'label-message' => 'tog-watchlisthidecategorization',
1068 ];
1069 }
1070
1071 if ( $user->useRCPatrol() ) {
1072 $defaultPreferences['watchlisthidepatrolled'] = [
1073 'type' => 'toggle',
1074 'section' => 'watchlist/advancedwatchlist',
1075 'label-message' => 'tog-watchlisthidepatrolled',
1076 ];
1077 }
1078
1079 $watchTypes = [
1080 'edit' => 'watchdefault',
1081 'move' => 'watchmoves',
1082 'delete' => 'watchdeletion'
1083 ];
1084
1085 // Kinda hacky
1086 if ( $user->isAllowed( 'createpage' ) || $user->isAllowed( 'createtalk' ) ) {
1087 $watchTypes['read'] = 'watchcreations';
1088 }
1089
1090 if ( $user->isAllowed( 'rollback' ) ) {
1091 $watchTypes['rollback'] = 'watchrollback';
1092 }
1093
1094 if ( $user->isAllowed( 'upload' ) ) {
1095 $watchTypes['upload'] = 'watchuploads';
1096 }
1097
1098 foreach ( $watchTypes as $action => $pref ) {
1099 if ( $user->isAllowed( $action ) ) {
1100 // Messages:
1101 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1102 // tog-watchrollback
1103 $defaultPreferences[$pref] = [
1104 'type' => 'toggle',
1105 'section' => 'watchlist/advancedwatchlist',
1106 'label-message' => "tog-$pref",
1107 ];
1108 }
1109 }
1110
1111 if ( $config->get( 'EnableAPI' ) ) {
1112 $defaultPreferences['watchlisttoken'] = [
1113 'type' => 'api',
1114 ];
1115 $defaultPreferences['watchlisttoken-info'] = [
1116 'type' => 'info',
1117 'section' => 'watchlist/tokenwatchlist',
1118 'label-message' => 'prefs-watchlist-token',
1119 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1120 'help-message' => 'prefs-help-watchlist-token2',
1121 ];
1122 }
1123 }
1124
1125 /**
1126 * @param User $user
1127 * @param IContextSource $context
1128 * @param array &$defaultPreferences
1129 */
1130 static function searchPreferences( $user, IContextSource $context, &$defaultPreferences ) {
1131 foreach ( MWNamespace::getValidNamespaces() as $n ) {
1132 $defaultPreferences['searchNs' . $n] = [
1133 'type' => 'api',
1134 ];
1135 }
1136 }
1137
1138 /**
1139 * Dummy, kept for backwards-compatibility.
1140 * @param User $user
1141 * @param IContextSource $context
1142 * @param array &$defaultPreferences
1143 */
1144 static function miscPreferences( $user, IContextSource $context, &$defaultPreferences ) {
1145 }
1146
1147 /**
1148 * @param User $user The User object
1149 * @param IContextSource $context
1150 * @return array Text/links to display as key; $skinkey as value
1151 */
1152 static function generateSkinOptions( $user, IContextSource $context ) {
1153 $ret = [];
1154
1155 $mptitle = Title::newMainPage();
1156 $previewtext = $context->msg( 'skin-preview' )->escaped();
1157
1158 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1159
1160 # Only show skins that aren't disabled in $wgSkipSkins
1161 $validSkinNames = Skin::getAllowedSkins();
1162
1163 # Sort by UI skin name. First though need to update validSkinNames as sometimes
1164 # the skinkey & UI skinname differ (e.g. "standard" skinkey is "Classic" in the UI).
1165 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1166 $msg = $context->msg( "skinname-{$skinkey}" );
1167 if ( $msg->exists() ) {
1168 $skinname = htmlspecialchars( $msg->text() );
1169 }
1170 }
1171 asort( $validSkinNames );
1172
1173 $config = $context->getConfig();
1174 $defaultSkin = $config->get( 'DefaultSkin' );
1175 $allowUserCss = $config->get( 'AllowUserCss' );
1176 $allowUserJs = $config->get( 'AllowUserJs' );
1177
1178 $foundDefault = false;
1179 foreach ( $validSkinNames as $skinkey => $sn ) {
1180 $linkTools = [];
1181
1182 # Mark the default skin
1183 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1184 $linkTools[] = $context->msg( 'default' )->escaped();
1185 $foundDefault = true;
1186 }
1187
1188 # Create preview link
1189 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1190 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1191
1192 # Create links to user CSS/JS pages
1193 if ( $allowUserCss ) {
1194 $cssPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.css' );
1195 $linkTools[] = $linkRenderer->makeLink( $cssPage, $context->msg( 'prefs-custom-css' )->text() );
1196 }
1197
1198 if ( $allowUserJs ) {
1199 $jsPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.js' );
1200 $linkTools[] = $linkRenderer->makeLink( $jsPage, $context->msg( 'prefs-custom-js' )->text() );
1201 }
1202
1203 $display = $sn . ' ' . $context->msg( 'parentheses' )
1204 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1205 ->escaped();
1206 $ret[$display] = $skinkey;
1207 }
1208
1209 if ( !$foundDefault ) {
1210 // If the default skin is not available, things are going to break horribly because the
1211 // default value for skin selector will not be a valid value. Let's just not show it then.
1212 return [];
1213 }
1214
1215 return $ret;
1216 }
1217
1218 /**
1219 * @param IContextSource $context
1220 * @return array
1221 */
1222 static function getDateOptions( IContextSource $context ) {
1223 $lang = $context->getLanguage();
1224 $dateopts = $lang->getDatePreferences();
1225
1226 $ret = [];
1227
1228 if ( $dateopts ) {
1229 if ( !in_array( 'default', $dateopts ) ) {
1230 $dateopts[] = 'default'; // Make sure default is always valid T21237
1231 }
1232
1233 // FIXME KLUGE: site default might not be valid for user language
1234 global $wgDefaultUserOptions;
1235 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1236 $wgDefaultUserOptions['date'] = 'default';
1237 }
1238
1239 $epoch = wfTimestampNow();
1240 foreach ( $dateopts as $key ) {
1241 if ( $key == 'default' ) {
1242 $formatted = $context->msg( 'datedefault' )->escaped();
1243 } else {
1244 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1245 }
1246 $ret[$formatted] = $key;
1247 }
1248 }
1249 return $ret;
1250 }
1251
1252 /**
1253 * @param IContextSource $context
1254 * @return array
1255 */
1256 static function getImageSizes( IContextSource $context ) {
1257 $ret = [];
1258 $pixels = $context->msg( 'unit-pixel' )->text();
1259
1260 foreach ( $context->getConfig()->get( 'ImageLimits' ) as $index => $limits ) {
1261 // Note: A left-to-right marker (\u200e) is inserted, see T144386
1262 $display = "{$limits[0]}" . json_decode( '"\u200e"' ) . "×{$limits[1]}" . $pixels;
1263 $ret[$display] = $index;
1264 }
1265
1266 return $ret;
1267 }
1268
1269 /**
1270 * @param IContextSource $context
1271 * @return array
1272 */
1273 static function getThumbSizes( IContextSource $context ) {
1274 $ret = [];
1275 $pixels = $context->msg( 'unit-pixel' )->text();
1276
1277 foreach ( $context->getConfig()->get( 'ThumbLimits' ) as $index => $size ) {
1278 $display = $size . $pixels;
1279 $ret[$display] = $index;
1280 }
1281
1282 return $ret;
1283 }
1284
1285 /**
1286 * @param string $signature
1287 * @param array $alldata
1288 * @param HTMLForm $form
1289 * @return bool|string
1290 */
1291 static function validateSignature( $signature, $alldata, $form ) {
1292 global $wgParser;
1293 $maxSigChars = $form->getConfig()->get( 'MaxSigChars' );
1294 if ( mb_strlen( $signature ) > $maxSigChars ) {
1295 return Xml::element( 'span', [ 'class' => 'error' ],
1296 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1297 } elseif ( isset( $alldata['fancysig'] ) &&
1298 $alldata['fancysig'] &&
1299 $wgParser->validateSig( $signature ) === false
1300 ) {
1301 return Xml::element(
1302 'span',
1303 [ 'class' => 'error' ],
1304 $form->msg( 'badsig' )->text()
1305 );
1306 } else {
1307 return true;
1308 }
1309 }
1310
1311 /**
1312 * @param string $signature
1313 * @param array $alldata
1314 * @param HTMLForm $form
1315 * @return string
1316 */
1317 static function cleanSignature( $signature, $alldata, $form ) {
1318 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1319 global $wgParser;
1320 $signature = $wgParser->cleanSig( $signature );
1321 } else {
1322 // When no fancy sig used, make sure ~{3,5} get removed.
1323 $signature = Parser::cleanSigInSig( $signature );
1324 }
1325
1326 return $signature;
1327 }
1328
1329 /**
1330 * @param User $user
1331 * @param IContextSource $context
1332 * @param string $formClass
1333 * @param array $remove Array of items to remove
1334 * @return PreferencesForm|HtmlForm
1335 */
1336 static function getFormObject(
1337 $user,
1338 IContextSource $context,
1339 $formClass = 'PreferencesForm',
1340 array $remove = []
1341 ) {
1342 $formDescriptor = self::getPreferences( $user, $context );
1343 if ( count( $remove ) ) {
1344 $removeKeys = array_flip( $remove );
1345 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1346 }
1347
1348 // Remove type=api preferences. They are not intended for rendering in the form.
1349 foreach ( $formDescriptor as $name => $info ) {
1350 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1351 unset( $formDescriptor[$name] );
1352 }
1353 }
1354
1355 /**
1356 * @var $htmlForm PreferencesForm
1357 */
1358 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1359
1360 $htmlForm->setModifiedUser( $user );
1361 $htmlForm->setId( 'mw-prefs-form' );
1362 $htmlForm->setAutocomplete( 'off' );
1363 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1364 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1365 $htmlForm->setSubmitTooltip( 'preferences-save' );
1366 $htmlForm->setSubmitID( 'prefcontrol' );
1367 $htmlForm->setSubmitCallback( [ 'Preferences', 'tryFormSubmit' ] );
1368
1369 return $htmlForm;
1370 }
1371
1372 /**
1373 * @param IContextSource $context
1374 * @return array
1375 */
1376 static function getTimezoneOptions( IContextSource $context ) {
1377 $opt = [];
1378
1379 $localTZoffset = $context->getConfig()->get( 'LocalTZoffset' );
1380 $timeZoneList = self::getTimeZoneList( $context->getLanguage() );
1381
1382 $timestamp = MWTimestamp::getLocalInstance();
1383 // Check that the LocalTZoffset is the same as the local time zone offset
1384 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1385 $timezoneName = $timestamp->getTimezone()->getName();
1386 // Localize timezone
1387 if ( isset( $timeZoneList[$timezoneName] ) ) {
1388 $timezoneName = $timeZoneList[$timezoneName]['name'];
1389 }
1390 $server_tz_msg = $context->msg(
1391 'timezoneuseserverdefault',
1392 $timezoneName
1393 )->text();
1394 } else {
1395 $tzstring = sprintf(
1396 '%+03d:%02d',
1397 floor( $localTZoffset / 60 ),
1398 abs( $localTZoffset ) % 60
1399 );
1400 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1401 }
1402 $opt[$server_tz_msg] = "System|$localTZoffset";
1403 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1404 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1405
1406 foreach ( $timeZoneList as $timeZoneInfo ) {
1407 $region = $timeZoneInfo['region'];
1408 if ( !isset( $opt[$region] ) ) {
1409 $opt[$region] = [];
1410 }
1411 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1412 }
1413 return $opt;
1414 }
1415
1416 /**
1417 * @param string $value
1418 * @param array $alldata
1419 * @return int
1420 */
1421 static function filterIntval( $value, $alldata ) {
1422 return intval( $value );
1423 }
1424
1425 /**
1426 * @param string $tz
1427 * @param array $alldata
1428 * @return string
1429 */
1430 static function filterTimezoneInput( $tz, $alldata ) {
1431 $data = explode( '|', $tz, 3 );
1432 switch ( $data[0] ) {
1433 case 'ZoneInfo':
1434 $valid = false;
1435
1436 if ( count( $data ) === 3 ) {
1437 // Make sure this timezone exists
1438 try {
1439 new DateTimeZone( $data[2] );
1440 // If the constructor didn't throw, we know it's valid
1441 $valid = true;
1442 } catch ( Exception $e ) {
1443 // Not a valid timezone
1444 }
1445 }
1446
1447 if ( !$valid ) {
1448 // If the supplied timezone doesn't exist, fall back to the encoded offset
1449 return 'Offset|' . intval( $tz[1] );
1450 }
1451 return $tz;
1452 case 'System':
1453 return $tz;
1454 default:
1455 $data = explode( ':', $tz, 2 );
1456 if ( count( $data ) == 2 ) {
1457 $data[0] = intval( $data[0] );
1458 $data[1] = intval( $data[1] );
1459 $minDiff = abs( $data[0] ) * 60 + $data[1];
1460 if ( $data[0] < 0 ) {
1461 $minDiff = - $minDiff;
1462 }
1463 } else {
1464 $minDiff = intval( $data[0] ) * 60;
1465 }
1466
1467 # Max is +14:00 and min is -12:00, see:
1468 # https://en.wikipedia.org/wiki/Timezone
1469 $minDiff = min( $minDiff, 840 ); # 14:00
1470 $minDiff = max( $minDiff, -720 ); # -12:00
1471 return 'Offset|' . $minDiff;
1472 }
1473 }
1474
1475 /**
1476 * Handle the form submission if everything validated properly
1477 *
1478 * @param array $formData
1479 * @param PreferencesForm $form
1480 * @return bool|Status|string
1481 */
1482 static function tryFormSubmit( $formData, $form ) {
1483 $user = $form->getModifiedUser();
1484 $hiddenPrefs = $form->getConfig()->get( 'HiddenPrefs' );
1485 $result = true;
1486
1487 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1488 return Status::newFatal( 'mypreferencesprotected' );
1489 }
1490
1491 // Filter input
1492 foreach ( array_keys( $formData ) as $name ) {
1493 if ( isset( self::$saveFilters[$name] ) ) {
1494 $formData[$name] =
1495 call_user_func( self::$saveFilters[$name], $formData[$name], $formData );
1496 }
1497 }
1498
1499 // Fortunately, the realname field is MUCH simpler
1500 // (not really "private", but still shouldn't be edited without permission)
1501
1502 if ( !in_array( 'realname', $hiddenPrefs )
1503 && $user->isAllowed( 'editmyprivateinfo' )
1504 && array_key_exists( 'realname', $formData )
1505 ) {
1506 $realName = $formData['realname'];
1507 $user->setRealName( $realName );
1508 }
1509
1510 if ( $user->isAllowed( 'editmyoptions' ) ) {
1511 $oldUserOptions = $user->getOptions();
1512
1513 foreach ( self::$saveBlacklist as $b ) {
1514 unset( $formData[$b] );
1515 }
1516
1517 # If users have saved a value for a preference which has subsequently been disabled
1518 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1519 # is subsequently re-enabled
1520 foreach ( $hiddenPrefs as $pref ) {
1521 # If the user has not set a non-default value here, the default will be returned
1522 # and subsequently discarded
1523 $formData[$pref] = $user->getOption( $pref, null, true );
1524 }
1525
1526 // Keep old preferences from interfering due to back-compat code, etc.
1527 $user->resetOptions( 'unused', $form->getContext() );
1528
1529 foreach ( $formData as $key => $value ) {
1530 $user->setOption( $key, $value );
1531 }
1532
1533 Hooks::run(
1534 'PreferencesFormPreSave',
1535 [ $formData, $form, $user, &$result, $oldUserOptions ]
1536 );
1537 }
1538
1539 MediaWiki\Auth\AuthManager::callLegacyAuthPlugin( 'updateExternalDB', [ $user ] );
1540 $user->saveSettings();
1541
1542 return $result;
1543 }
1544
1545 /**
1546 * @param array $formData
1547 * @param PreferencesForm $form
1548 * @return Status
1549 */
1550 public static function tryUISubmit( $formData, $form ) {
1551 $res = self::tryFormSubmit( $formData, $form );
1552
1553 if ( $res ) {
1554 $urlOptions = [];
1555
1556 if ( $res === 'eauth' ) {
1557 $urlOptions['eauth'] = 1;
1558 }
1559
1560 $urlOptions += $form->getExtraSuccessRedirectParameters();
1561
1562 $url = $form->getTitle()->getFullURL( $urlOptions );
1563
1564 $context = $form->getContext();
1565 // Set session data for the success message
1566 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1567
1568 $context->getOutput()->redirect( $url );
1569 }
1570
1571 return Status::newGood();
1572 }
1573
1574 /**
1575 * Get a list of all time zones
1576 * @param Language $language Language used for the localized names
1577 * @return array A list of all time zones. The system name of the time zone is used as key and
1578 * the value is an array which contains localized name, the timecorrection value used for
1579 * preferences and the region
1580 * @since 1.26
1581 */
1582 public static function getTimeZoneList( Language $language ) {
1583 $identifiers = DateTimeZone::listIdentifiers();
1584 if ( $identifiers === false ) {
1585 return [];
1586 }
1587 sort( $identifiers );
1588
1589 $tzRegions = [
1590 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1591 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1592 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1593 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1594 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1595 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1596 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1597 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1598 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1599 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1600 ];
1601 asort( $tzRegions );
1602
1603 $timeZoneList = [];
1604
1605 $now = new DateTime();
1606
1607 foreach ( $identifiers as $identifier ) {
1608 $parts = explode( '/', $identifier, 2 );
1609
1610 // DateTimeZone::listIdentifiers() returns a number of
1611 // backwards-compatibility entries. This filters them out of the
1612 // list presented to the user.
1613 if ( count( $parts ) !== 2 || !array_key_exists( $parts[0], $tzRegions ) ) {
1614 continue;
1615 }
1616
1617 // Localize region
1618 $parts[0] = $tzRegions[$parts[0]];
1619
1620 $dateTimeZone = new DateTimeZone( $identifier );
1621 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1622
1623 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1624 $value = "ZoneInfo|$minDiff|$identifier";
1625
1626 $timeZoneList[$identifier] = [
1627 'name' => $display,
1628 'timecorrection' => $value,
1629 'region' => $parts[0],
1630 ];
1631 }
1632
1633 return $timeZoneList;
1634 }
1635 }