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