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