ApiQueryBase: Fix addWhereFld for PHP 7.2
[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 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1175 $msg = $context->msg( "skinname-{$skinkey}" );
1176 if ( $msg->exists() ) {
1177 $skinname = htmlspecialchars( $msg->text() );
1178 }
1179 }
1180
1181 $config = $context->getConfig();
1182 $defaultSkin = $config->get( 'DefaultSkin' );
1183 $allowUserCss = $config->get( 'AllowUserCss' );
1184 $allowUserJs = $config->get( 'AllowUserJs' );
1185
1186 # Sort by the internal name, so that the ordering is the same for each display language,
1187 # especially if some skin names are translated to use a different alphabet and some are not.
1188 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1189 # Display the default first in the list by comparing it as lesser than any other.
1190 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1191 return -1;
1192 }
1193 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1194 return 1;
1195 }
1196 return strcasecmp( $a, $b );
1197 } );
1198
1199 $foundDefault = false;
1200 foreach ( $validSkinNames as $skinkey => $sn ) {
1201 $linkTools = [];
1202
1203 # Mark the default skin
1204 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1205 $linkTools[] = $context->msg( 'default' )->escaped();
1206 $foundDefault = true;
1207 }
1208
1209 # Create preview link
1210 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1211 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1212
1213 # Create links to user CSS/JS pages
1214 if ( $allowUserCss ) {
1215 $cssPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.css' );
1216 $linkTools[] = $linkRenderer->makeLink( $cssPage, $context->msg( 'prefs-custom-css' )->text() );
1217 }
1218
1219 if ( $allowUserJs ) {
1220 $jsPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.js' );
1221 $linkTools[] = $linkRenderer->makeLink( $jsPage, $context->msg( 'prefs-custom-js' )->text() );
1222 }
1223
1224 $display = $sn . ' ' . $context->msg( 'parentheses' )
1225 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1226 ->escaped();
1227 $ret[$display] = $skinkey;
1228 }
1229
1230 if ( !$foundDefault ) {
1231 // If the default skin is not available, things are going to break horribly because the
1232 // default value for skin selector will not be a valid value. Let's just not show it then.
1233 return [];
1234 }
1235
1236 return $ret;
1237 }
1238
1239 /**
1240 * @param IContextSource $context
1241 * @return array
1242 */
1243 static function getDateOptions( IContextSource $context ) {
1244 $lang = $context->getLanguage();
1245 $dateopts = $lang->getDatePreferences();
1246
1247 $ret = [];
1248
1249 if ( $dateopts ) {
1250 if ( !in_array( 'default', $dateopts ) ) {
1251 $dateopts[] = 'default'; // Make sure default is always valid T21237
1252 }
1253
1254 // FIXME KLUGE: site default might not be valid for user language
1255 global $wgDefaultUserOptions;
1256 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1257 $wgDefaultUserOptions['date'] = 'default';
1258 }
1259
1260 $epoch = wfTimestampNow();
1261 foreach ( $dateopts as $key ) {
1262 if ( $key == 'default' ) {
1263 $formatted = $context->msg( 'datedefault' )->escaped();
1264 } else {
1265 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1266 }
1267 $ret[$formatted] = $key;
1268 }
1269 }
1270 return $ret;
1271 }
1272
1273 /**
1274 * @param IContextSource $context
1275 * @return array
1276 */
1277 static function getImageSizes( IContextSource $context ) {
1278 $ret = [];
1279 $pixels = $context->msg( 'unit-pixel' )->text();
1280
1281 foreach ( $context->getConfig()->get( 'ImageLimits' ) as $index => $limits ) {
1282 // Note: A left-to-right marker (\u200e) is inserted, see T144386
1283 $display = "{$limits[0]}" . json_decode( '"\u200e"' ) . "×{$limits[1]}" . $pixels;
1284 $ret[$display] = $index;
1285 }
1286
1287 return $ret;
1288 }
1289
1290 /**
1291 * @param IContextSource $context
1292 * @return array
1293 */
1294 static function getThumbSizes( IContextSource $context ) {
1295 $ret = [];
1296 $pixels = $context->msg( 'unit-pixel' )->text();
1297
1298 foreach ( $context->getConfig()->get( 'ThumbLimits' ) as $index => $size ) {
1299 $display = $size . $pixels;
1300 $ret[$display] = $index;
1301 }
1302
1303 return $ret;
1304 }
1305
1306 /**
1307 * @param string $signature
1308 * @param array $alldata
1309 * @param HTMLForm $form
1310 * @return bool|string
1311 */
1312 static function validateSignature( $signature, $alldata, $form ) {
1313 global $wgParser;
1314 $maxSigChars = $form->getConfig()->get( 'MaxSigChars' );
1315 if ( mb_strlen( $signature ) > $maxSigChars ) {
1316 return Xml::element( 'span', [ 'class' => 'error' ],
1317 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1318 } elseif ( isset( $alldata['fancysig'] ) &&
1319 $alldata['fancysig'] &&
1320 $wgParser->validateSig( $signature ) === false
1321 ) {
1322 return Xml::element(
1323 'span',
1324 [ 'class' => 'error' ],
1325 $form->msg( 'badsig' )->text()
1326 );
1327 } else {
1328 return true;
1329 }
1330 }
1331
1332 /**
1333 * @param string $signature
1334 * @param array $alldata
1335 * @param HTMLForm $form
1336 * @return string
1337 */
1338 static function cleanSignature( $signature, $alldata, $form ) {
1339 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1340 global $wgParser;
1341 $signature = $wgParser->cleanSig( $signature );
1342 } else {
1343 // When no fancy sig used, make sure ~{3,5} get removed.
1344 $signature = Parser::cleanSigInSig( $signature );
1345 }
1346
1347 return $signature;
1348 }
1349
1350 /**
1351 * @param User $user
1352 * @param IContextSource $context
1353 * @param string $formClass
1354 * @param array $remove Array of items to remove
1355 * @return PreferencesForm|HTMLForm
1356 */
1357 static function getFormObject(
1358 $user,
1359 IContextSource $context,
1360 $formClass = 'PreferencesForm',
1361 array $remove = []
1362 ) {
1363 $formDescriptor = self::getPreferences( $user, $context );
1364 if ( count( $remove ) ) {
1365 $removeKeys = array_flip( $remove );
1366 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1367 }
1368
1369 // Remove type=api preferences. They are not intended for rendering in the form.
1370 foreach ( $formDescriptor as $name => $info ) {
1371 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1372 unset( $formDescriptor[$name] );
1373 }
1374 }
1375
1376 /**
1377 * @var $htmlForm PreferencesForm
1378 */
1379 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1380
1381 $htmlForm->setModifiedUser( $user );
1382 $htmlForm->setId( 'mw-prefs-form' );
1383 $htmlForm->setAutocomplete( 'off' );
1384 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1385 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1386 $htmlForm->setSubmitTooltip( 'preferences-save' );
1387 $htmlForm->setSubmitID( 'prefcontrol' );
1388 $htmlForm->setSubmitCallback( [ 'Preferences', 'tryFormSubmit' ] );
1389
1390 return $htmlForm;
1391 }
1392
1393 /**
1394 * @param IContextSource $context
1395 * @return array
1396 */
1397 static function getTimezoneOptions( IContextSource $context ) {
1398 $opt = [];
1399
1400 $localTZoffset = $context->getConfig()->get( 'LocalTZoffset' );
1401 $timeZoneList = self::getTimeZoneList( $context->getLanguage() );
1402
1403 $timestamp = MWTimestamp::getLocalInstance();
1404 // Check that the LocalTZoffset is the same as the local time zone offset
1405 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1406 $timezoneName = $timestamp->getTimezone()->getName();
1407 // Localize timezone
1408 if ( isset( $timeZoneList[$timezoneName] ) ) {
1409 $timezoneName = $timeZoneList[$timezoneName]['name'];
1410 }
1411 $server_tz_msg = $context->msg(
1412 'timezoneuseserverdefault',
1413 $timezoneName
1414 )->text();
1415 } else {
1416 $tzstring = sprintf(
1417 '%+03d:%02d',
1418 floor( $localTZoffset / 60 ),
1419 abs( $localTZoffset ) % 60
1420 );
1421 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1422 }
1423 $opt[$server_tz_msg] = "System|$localTZoffset";
1424 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1425 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1426
1427 foreach ( $timeZoneList as $timeZoneInfo ) {
1428 $region = $timeZoneInfo['region'];
1429 if ( !isset( $opt[$region] ) ) {
1430 $opt[$region] = [];
1431 }
1432 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1433 }
1434 return $opt;
1435 }
1436
1437 /**
1438 * @param string $value
1439 * @param array $alldata
1440 * @return int
1441 */
1442 static function filterIntval( $value, $alldata ) {
1443 return intval( $value );
1444 }
1445
1446 /**
1447 * @param string $tz
1448 * @param array $alldata
1449 * @return string
1450 */
1451 static function filterTimezoneInput( $tz, $alldata ) {
1452 $data = explode( '|', $tz, 3 );
1453 switch ( $data[0] ) {
1454 case 'ZoneInfo':
1455 $valid = false;
1456
1457 if ( count( $data ) === 3 ) {
1458 // Make sure this timezone exists
1459 try {
1460 new DateTimeZone( $data[2] );
1461 // If the constructor didn't throw, we know it's valid
1462 $valid = true;
1463 } catch ( Exception $e ) {
1464 // Not a valid timezone
1465 }
1466 }
1467
1468 if ( !$valid ) {
1469 // If the supplied timezone doesn't exist, fall back to the encoded offset
1470 return 'Offset|' . intval( $tz[1] );
1471 }
1472 return $tz;
1473 case 'System':
1474 return $tz;
1475 default:
1476 $data = explode( ':', $tz, 2 );
1477 if ( count( $data ) == 2 ) {
1478 $data[0] = intval( $data[0] );
1479 $data[1] = intval( $data[1] );
1480 $minDiff = abs( $data[0] ) * 60 + $data[1];
1481 if ( $data[0] < 0 ) {
1482 $minDiff = - $minDiff;
1483 }
1484 } else {
1485 $minDiff = intval( $data[0] ) * 60;
1486 }
1487
1488 # Max is +14:00 and min is -12:00, see:
1489 # https://en.wikipedia.org/wiki/Timezone
1490 $minDiff = min( $minDiff, 840 ); # 14:00
1491 $minDiff = max( $minDiff, -720 ); # -12:00
1492 return 'Offset|' . $minDiff;
1493 }
1494 }
1495
1496 /**
1497 * Handle the form submission if everything validated properly
1498 *
1499 * @param array $formData
1500 * @param PreferencesForm $form
1501 * @return bool|Status|string
1502 */
1503 static function tryFormSubmit( $formData, $form ) {
1504 $user = $form->getModifiedUser();
1505 $hiddenPrefs = $form->getConfig()->get( 'HiddenPrefs' );
1506 $result = true;
1507
1508 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1509 return Status::newFatal( 'mypreferencesprotected' );
1510 }
1511
1512 // Filter input
1513 foreach ( array_keys( $formData ) as $name ) {
1514 if ( isset( self::$saveFilters[$name] ) ) {
1515 $formData[$name] =
1516 call_user_func( self::$saveFilters[$name], $formData[$name], $formData );
1517 }
1518 }
1519
1520 // Fortunately, the realname field is MUCH simpler
1521 // (not really "private", but still shouldn't be edited without permission)
1522
1523 if ( !in_array( 'realname', $hiddenPrefs )
1524 && $user->isAllowed( 'editmyprivateinfo' )
1525 && array_key_exists( 'realname', $formData )
1526 ) {
1527 $realName = $formData['realname'];
1528 $user->setRealName( $realName );
1529 }
1530
1531 if ( $user->isAllowed( 'editmyoptions' ) ) {
1532 $oldUserOptions = $user->getOptions();
1533
1534 foreach ( self::$saveBlacklist as $b ) {
1535 unset( $formData[$b] );
1536 }
1537
1538 # If users have saved a value for a preference which has subsequently been disabled
1539 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1540 # is subsequently re-enabled
1541 foreach ( $hiddenPrefs as $pref ) {
1542 # If the user has not set a non-default value here, the default will be returned
1543 # and subsequently discarded
1544 $formData[$pref] = $user->getOption( $pref, null, true );
1545 }
1546
1547 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1548 if (
1549 isset( $formData['rclimit'] ) &&
1550 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1551 ) {
1552 $formData['rcfilters-limit'] = $formData['rclimit'];
1553 }
1554
1555 // Keep old preferences from interfering due to back-compat code, etc.
1556 $user->resetOptions( 'unused', $form->getContext() );
1557
1558 foreach ( $formData as $key => $value ) {
1559 $user->setOption( $key, $value );
1560 }
1561
1562 Hooks::run(
1563 'PreferencesFormPreSave',
1564 [ $formData, $form, $user, &$result, $oldUserOptions ]
1565 );
1566 }
1567
1568 MediaWiki\Auth\AuthManager::callLegacyAuthPlugin( 'updateExternalDB', [ $user ] );
1569 $user->saveSettings();
1570
1571 return $result;
1572 }
1573
1574 /**
1575 * @param array $formData
1576 * @param PreferencesForm $form
1577 * @return Status
1578 */
1579 public static function tryUISubmit( $formData, $form ) {
1580 $res = self::tryFormSubmit( $formData, $form );
1581
1582 if ( $res ) {
1583 $urlOptions = [];
1584
1585 if ( $res === 'eauth' ) {
1586 $urlOptions['eauth'] = 1;
1587 }
1588
1589 $urlOptions += $form->getExtraSuccessRedirectParameters();
1590
1591 $url = $form->getTitle()->getFullURL( $urlOptions );
1592
1593 $context = $form->getContext();
1594 // Set session data for the success message
1595 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1596
1597 $context->getOutput()->redirect( $url );
1598 }
1599
1600 return Status::newGood();
1601 }
1602
1603 /**
1604 * Get a list of all time zones
1605 * @param Language $language Language used for the localized names
1606 * @return array A list of all time zones. The system name of the time zone is used as key and
1607 * the value is an array which contains localized name, the timecorrection value used for
1608 * preferences and the region
1609 * @since 1.26
1610 */
1611 public static function getTimeZoneList( Language $language ) {
1612 $identifiers = DateTimeZone::listIdentifiers();
1613 if ( $identifiers === false ) {
1614 return [];
1615 }
1616 sort( $identifiers );
1617
1618 $tzRegions = [
1619 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1620 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1621 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1622 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1623 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1624 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1625 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1626 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1627 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1628 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1629 ];
1630 asort( $tzRegions );
1631
1632 $timeZoneList = [];
1633
1634 $now = new DateTime();
1635
1636 foreach ( $identifiers as $identifier ) {
1637 $parts = explode( '/', $identifier, 2 );
1638
1639 // DateTimeZone::listIdentifiers() returns a number of
1640 // backwards-compatibility entries. This filters them out of the
1641 // list presented to the user.
1642 if ( count( $parts ) !== 2 || !array_key_exists( $parts[0], $tzRegions ) ) {
1643 continue;
1644 }
1645
1646 // Localize region
1647 $parts[0] = $tzRegions[$parts[0]];
1648
1649 $dateTimeZone = new DateTimeZone( $identifier );
1650 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1651
1652 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1653 $value = "ZoneInfo|$minDiff|$identifier";
1654
1655 $timeZoneList[$identifier] = [
1656 'name' => $display,
1657 'timecorrection' => $value,
1658 'region' => $parts[0],
1659 ];
1660 }
1661
1662 return $timeZoneList;
1663 }
1664 }