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