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