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