MediaWiki REL1_28
Preferences.php
Go to the documentation of this file.
1<?php
24
52 protected static $defaultPreferences = null;
53
55 protected static $saveFilters = [
56 'timecorrection' => [ 'Preferences', 'filterTimezoneInput' ],
57 'cols' => [ 'Preferences', 'filterIntval' ],
58 'rows' => [ 'Preferences', 'filterIntval' ],
59 'rclimit' => [ 'Preferences', 'filterIntval' ],
60 'wllimit' => [ 'Preferences', 'filterIntval' ],
61 'searchlimit' => [ 'Preferences', 'filterIntval' ],
62 ];
63
64 // Stuff that shouldn't be saved as a preference.
65 private static $saveBlacklist = [
66 'realname',
67 'emailaddress',
68 ];
69
73 static function getSaveBlacklist() {
75 }
76
107
117 # # Remove preferences that wikis don't want to use
118 foreach ( $context->getConfig()->get( 'HiddenPrefs' ) as $pref ) {
119 if ( isset( $defaultPreferences[$pref] ) ) {
120 unset( $defaultPreferences[$pref] );
121 }
122 }
123
124 # # Make sure that form fields have their parent set. See bug 41337.
125 $dummyForm = new HTMLForm( [], $context );
126
127 $disable = !$user->isAllowed( 'editmyoptions' );
128
129 $defaultOptions = User::getDefaultOptions();
130 # # Prod in defaults from the user
131 foreach ( $defaultPreferences as $name => &$info ) {
132 $prefFromUser = self::getOptionFromUser( $name, $info, $user );
133 if ( $disable && !in_array( $name, self::$saveBlacklist ) ) {
134 $info['disabled'] = 'disabled';
135 }
136 $field = HTMLForm::loadInputFromParameters( $name, $info, $dummyForm ); // For validation
137 $globalDefault = isset( $defaultOptions[$name] )
138 ? $defaultOptions[$name]
139 : null;
140
141 // If it validates, set it as the default
142 if ( isset( $info['default'] ) ) {
143 // Already set, no problem
144 continue;
145 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
146 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
147 $info['default'] = $prefFromUser;
148 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
149 $info['default'] = $globalDefault;
150 } else {
151 throw new MWException( "Global default '$globalDefault' is invalid for field $name" );
152 }
153 }
154
155 return $defaultPreferences;
156 }
157
166 static function getOptionFromUser( $name, $info, $user ) {
167 $val = $user->getOption( $name );
168
169 // Handling for multiselect preferences
170 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
171 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
172 $options = HTMLFormField::flattenOptions( $info['options'] );
173 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
174 $val = [];
175
176 foreach ( $options as $value ) {
177 if ( $user->getOption( "$prefix$value" ) ) {
178 $val[] = $value;
179 }
180 }
181 }
182
183 // Handling for checkmatrix preferences
184 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
185 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
186 $columns = HTMLFormField::flattenOptions( $info['columns'] );
187 $rows = HTMLFormField::flattenOptions( $info['rows'] );
188 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
189 $val = [];
190
191 foreach ( $columns as $column ) {
192 foreach ( $rows as $row ) {
193 if ( $user->getOption( "$prefix$column-$row" ) ) {
194 $val[] = "$column-$row";
195 }
196 }
197 }
198 }
199
200 return $val;
201 }
202
211
212 $authManager = AuthManager::singleton();
213 $config = $context->getConfig();
214 // retrieving user name for GENDER and misc.
215 $userName = $user->getName();
216
217 # # User info #####################################
218 // Information panel
219 $defaultPreferences['username'] = [
220 'type' => 'info',
221 'label-message' => [ 'username', $userName ],
222 'default' => $userName,
223 'section' => 'personal/info',
224 ];
225
226 # Get groups to which the user belongs
227 $userEffectiveGroups = $user->getEffectiveGroups();
228 $userGroups = $userMembers = [];
229 foreach ( $userEffectiveGroups as $ueg ) {
230 if ( $ueg == '*' ) {
231 // Skip the default * group, seems useless here
232 continue;
233 }
234 $groupName = User::getGroupName( $ueg );
235 $userGroups[] = User::makeGroupLinkHTML( $ueg, $groupName );
236
237 $memberName = User::getGroupMember( $ueg, $userName );
238 $userMembers[] = User::makeGroupLinkHTML( $ueg, $memberName );
239 }
240 asort( $userGroups );
241 asort( $userMembers );
242
243 $lang = $context->getLanguage();
244
245 $defaultPreferences['usergroups'] = [
246 'type' => 'info',
247 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
248 count( $userGroups ) )->params( $userName )->parse(),
249 'default' => $context->msg( 'prefs-memberingroups-type' )
250 ->rawParams( $lang->commaList( $userGroups ), $lang->commaList( $userMembers ) )
251 ->escaped(),
252 'raw' => true,
253 'section' => 'personal/info',
254 ];
255
256 $editCount = Linker::link( SpecialPage::getTitleFor( "Contributions", $userName ),
257 $lang->formatNum( $user->getEditCount() ) );
258
259 $defaultPreferences['editcount'] = [
260 'type' => 'info',
261 'raw' => true,
262 'label-message' => 'prefs-edits',
263 'default' => $editCount,
264 'section' => 'personal/info',
265 ];
266
267 if ( $user->getRegistration() ) {
268 $displayUser = $context->getUser();
269 $userRegistration = $user->getRegistration();
270 $defaultPreferences['registrationdate'] = [
271 'type' => 'info',
272 'label-message' => 'prefs-registration',
273 'default' => $context->msg(
274 'prefs-registration-date-time',
275 $lang->userTimeAndDate( $userRegistration, $displayUser ),
276 $lang->userDate( $userRegistration, $displayUser ),
277 $lang->userTime( $userRegistration, $displayUser )
278 )->parse(),
279 'section' => 'personal/info',
280 ];
281 }
282
283 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
284 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
285
286 // Actually changeable stuff
287 $defaultPreferences['realname'] = [
288 // (not really "private", but still shouldn't be edited without permission)
289 'type' => $canEditPrivateInfo && $authManager->allowsPropertyChange( 'realname' )
290 ? 'text' : 'info',
291 'default' => $user->getRealName(),
292 'section' => 'personal/info',
293 'label-message' => 'yourrealname',
294 'help-message' => 'prefs-help-realname',
295 ];
296
297 if ( $canEditPrivateInfo && $authManager->allowsAuthenticationDataChange(
298 new PasswordAuthenticationRequest(), false )->isGood()
299 ) {
300 $link = Linker::link( SpecialPage::getTitleFor( 'ChangePassword' ),
301 $context->msg( 'prefs-resetpass' )->escaped(), [],
302 [ 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText() ] );
303
304 $defaultPreferences['password'] = [
305 'type' => 'info',
306 'raw' => true,
307 'default' => $link,
308 'label-message' => 'yourpassword',
309 'section' => 'personal/info',
310 ];
311 }
312 // Only show prefershttps if secure login is turned on
313 if ( $config->get( 'SecureLogin' ) && wfCanIPUseHTTPS( $context->getRequest()->getIP() ) ) {
314 $defaultPreferences['prefershttps'] = [
315 'type' => 'toggle',
316 'label-message' => 'tog-prefershttps',
317 'help-message' => 'prefs-help-prefershttps',
318 'section' => 'personal/info'
319 ];
320 }
321
322 // Language
323 $languages = Language::fetchLanguageNames( null, 'mw' );
324 $languageCode = $config->get( 'LanguageCode' );
325 if ( !array_key_exists( $languageCode, $languages ) ) {
326 $languages[$languageCode] = $languageCode;
327 }
328 ksort( $languages );
329
330 $options = [];
331 foreach ( $languages as $code => $name ) {
332 $display = wfBCP47( $code ) . ' - ' . $name;
333 $options[$display] = $code;
334 }
335 $defaultPreferences['language'] = [
336 'type' => 'select',
337 'section' => 'personal/i18n',
338 'options' => $options,
339 'label-message' => 'yourlanguage',
340 ];
341
342 $defaultPreferences['gender'] = [
343 'type' => 'radio',
344 'section' => 'personal/i18n',
345 'options' => [
346 $context->msg( 'parentheses' )
347 ->params( $context->msg( 'gender-unknown' )->plain() )
348 ->escaped() => 'unknown',
349 $context->msg( 'gender-female' )->escaped() => 'female',
350 $context->msg( 'gender-male' )->escaped() => 'male',
351 ],
352 'label-message' => 'yourgender',
353 'help-message' => 'prefs-help-gender',
354 ];
355
356 // see if there are multiple language variants to choose from
357 if ( !$config->get( 'DisableLangConversion' ) ) {
358 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
359 if ( $langCode == $wgContLang->getCode() ) {
360 $variants = $wgContLang->getVariants();
361
362 if ( count( $variants ) <= 1 ) {
363 continue;
364 }
365
366 $variantArray = [];
367 foreach ( $variants as $v ) {
368 $v = str_replace( '_', '-', strtolower( $v ) );
369 $variantArray[$v] = $lang->getVariantname( $v, false );
370 }
371
372 $options = [];
373 foreach ( $variantArray as $code => $name ) {
374 $display = wfBCP47( $code ) . ' - ' . $name;
375 $options[$display] = $code;
376 }
377
378 $defaultPreferences['variant'] = [
379 'label-message' => 'yourvariant',
380 'type' => 'select',
381 'options' => $options,
382 'section' => 'personal/i18n',
383 'help-message' => 'prefs-help-variant',
384 ];
385 } else {
386 $defaultPreferences["variant-$langCode"] = [
387 'type' => 'api',
388 ];
389 }
390 }
391 }
392
393 // Stuff from Language::getExtraUserToggles()
394 // FIXME is this dead code? $extraUserToggles doesn't seem to be defined for any language
395 $toggles = $wgContLang->getExtraUserToggles();
396
397 foreach ( $toggles as $toggle ) {
398 $defaultPreferences[$toggle] = [
399 'type' => 'toggle',
400 'section' => 'personal/i18n',
401 'label-message' => "tog-$toggle",
402 ];
403 }
404
405 // show a preview of the old signature first
406 $oldsigWikiText = $wgParser->preSaveTransform(
407 '~~~',
408 $context->getTitle(),
409 $user,
411 );
412 $oldsigHTML = $context->getOutput()->parseInline( $oldsigWikiText, true, true );
413 $defaultPreferences['oldsig'] = [
414 'type' => 'info',
415 'raw' => true,
416 'label-message' => 'tog-oldsig',
417 'default' => $oldsigHTML,
418 'section' => 'personal/signature',
419 ];
420 $defaultPreferences['nickname'] = [
421 'type' => $authManager->allowsPropertyChange( 'nickname' ) ? 'text' : 'info',
422 'maxlength' => $config->get( 'MaxSigChars' ),
423 'label-message' => 'yournick',
424 'validation-callback' => [ 'Preferences', 'validateSignature' ],
425 'section' => 'personal/signature',
426 'filter-callback' => [ 'Preferences', 'cleanSignature' ],
427 ];
428 $defaultPreferences['fancysig'] = [
429 'type' => 'toggle',
430 'label-message' => 'tog-fancysig',
431 // show general help about signature at the bottom of the section
432 'help-message' => 'prefs-help-signature',
433 'section' => 'personal/signature'
434 ];
435
436 # # Email stuff
437
438 if ( $config->get( 'EnableEmail' ) ) {
439 if ( $canViewPrivateInfo ) {
440 $helpMessages[] = $config->get( 'EmailConfirmToEdit' )
441 ? 'prefs-help-email-required'
442 : 'prefs-help-email';
443
444 if ( $config->get( 'EnableUserEmail' ) ) {
445 // additional messages when users can send email to each other
446 $helpMessages[] = 'prefs-help-email-others';
447 }
448
449 $emailAddress = $user->getEmail() ? htmlspecialchars( $user->getEmail() ) : '';
450 if ( $canEditPrivateInfo && $authManager->allowsPropertyChange( 'emailaddress' ) ) {
452 SpecialPage::getTitleFor( 'ChangeEmail' ),
453 $context->msg( $user->getEmail() ? 'prefs-changeemail' : 'prefs-setemail' )->escaped(),
454 [],
455 [ 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText() ] );
456
457 $emailAddress .= $emailAddress == '' ? $link : (
458 $context->msg( 'word-separator' )->escaped()
459 . $context->msg( 'parentheses' )->rawParams( $link )->escaped()
460 );
461 }
462
463 $defaultPreferences['emailaddress'] = [
464 'type' => 'info',
465 'raw' => true,
466 'default' => $emailAddress,
467 'label-message' => 'youremail',
468 'section' => 'personal/email',
469 'help-messages' => $helpMessages,
470 # 'cssclass' chosen below
471 ];
472 }
473
474 $disableEmailPrefs = false;
475
476 if ( $config->get( 'EmailAuthentication' ) ) {
477 $emailauthenticationclass = 'mw-email-not-authenticated';
478 if ( $user->getEmail() ) {
479 if ( $user->getEmailAuthenticationTimestamp() ) {
480 // date and time are separate parameters to facilitate localisation.
481 // $time is kept for backward compat reasons.
482 // 'emailauthenticated' is also used in SpecialConfirmemail.php
483 $displayUser = $context->getUser();
484 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
485 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
486 $d = $lang->userDate( $emailTimestamp, $displayUser );
487 $t = $lang->userTime( $emailTimestamp, $displayUser );
488 $emailauthenticated = $context->msg( 'emailauthenticated',
489 $time, $d, $t )->parse() . '<br />';
490 $disableEmailPrefs = false;
491 $emailauthenticationclass = 'mw-email-authenticated';
492 } else {
493 $disableEmailPrefs = true;
494 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
496 SpecialPage::getTitleFor( 'Confirmemail' ),
497 $context->msg( 'emailconfirmlink' )->escaped()
498 ) . '<br />';
499 $emailauthenticationclass = "mw-email-not-authenticated";
500 }
501 } else {
502 $disableEmailPrefs = true;
503 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
504 $emailauthenticationclass = 'mw-email-none';
505 }
506
507 if ( $canViewPrivateInfo ) {
508 $defaultPreferences['emailauthentication'] = [
509 'type' => 'info',
510 'raw' => true,
511 'section' => 'personal/email',
512 'label-message' => 'prefs-emailconfirm-label',
513 'default' => $emailauthenticated,
514 # Apply the same CSS class used on the input to the message:
515 'cssclass' => $emailauthenticationclass,
516 ];
517 }
518 }
519
520 if ( $config->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
521 $defaultPreferences['disablemail'] = [
522 'type' => 'toggle',
523 'invert' => true,
524 'section' => 'personal/email',
525 'label-message' => 'allowemail',
526 'disabled' => $disableEmailPrefs,
527 ];
528 $defaultPreferences['ccmeonemails'] = [
529 'type' => 'toggle',
530 'section' => 'personal/email',
531 'label-message' => 'tog-ccmeonemails',
532 'disabled' => $disableEmailPrefs,
533 ];
534 }
535
536 if ( $config->get( 'EnotifWatchlist' ) ) {
537 $defaultPreferences['enotifwatchlistpages'] = [
538 'type' => 'toggle',
539 'section' => 'personal/email',
540 'label-message' => 'tog-enotifwatchlistpages',
541 'disabled' => $disableEmailPrefs,
542 ];
543 }
544 if ( $config->get( 'EnotifUserTalk' ) ) {
545 $defaultPreferences['enotifusertalkpages'] = [
546 'type' => 'toggle',
547 'section' => 'personal/email',
548 'label-message' => 'tog-enotifusertalkpages',
549 'disabled' => $disableEmailPrefs,
550 ];
551 }
552 if ( $config->get( 'EnotifUserTalk' ) || $config->get( 'EnotifWatchlist' ) ) {
553 if ( $config->get( 'EnotifMinorEdits' ) ) {
554 $defaultPreferences['enotifminoredits'] = [
555 'type' => 'toggle',
556 'section' => 'personal/email',
557 'label-message' => 'tog-enotifminoredits',
558 'disabled' => $disableEmailPrefs,
559 ];
560 }
561
562 if ( $config->get( 'EnotifRevealEditorAddress' ) ) {
563 $defaultPreferences['enotifrevealaddr'] = [
564 'type' => 'toggle',
565 'section' => 'personal/email',
566 'label-message' => 'tog-enotifrevealaddr',
567 'disabled' => $disableEmailPrefs,
568 ];
569 }
570 }
571 }
572 }
573
581 # # Skin #####################################
582
583 // Skin selector, if there is at least one valid skin
584 $skinOptions = self::generateSkinOptions( $user, $context );
585 if ( $skinOptions ) {
586 $defaultPreferences['skin'] = [
587 'type' => 'radio',
588 'options' => $skinOptions,
589 'label' => '&#160;',
590 'section' => 'rendering/skin',
591 ];
592 }
593
594 $config = $context->getConfig();
595 $allowUserCss = $config->get( 'AllowUserCss' );
596 $allowUserJs = $config->get( 'AllowUserJs' );
597 # Create links to user CSS/JS pages for all skins
598 # This code is basically copied from generateSkinOptions(). It'd
599 # be nice to somehow merge this back in there to avoid redundancy.
600 if ( $allowUserCss || $allowUserJs ) {
601 $linkTools = [];
602 $userName = $user->getName();
603
604 if ( $allowUserCss ) {
605 $cssPage = Title::makeTitleSafe( NS_USER, $userName . '/common.css' );
606 $linkTools[] = Linker::link( $cssPage, $context->msg( 'prefs-custom-css' )->escaped() );
607 }
608
609 if ( $allowUserJs ) {
610 $jsPage = Title::makeTitleSafe( NS_USER, $userName . '/common.js' );
611 $linkTools[] = Linker::link( $jsPage, $context->msg( 'prefs-custom-js' )->escaped() );
612 }
613
614 $defaultPreferences['commoncssjs'] = [
615 'type' => 'info',
616 'raw' => true,
617 'default' => $context->getLanguage()->pipeList( $linkTools ),
618 'label-message' => 'prefs-common-css-js',
619 'section' => 'rendering/skin',
620 ];
621 }
622 }
623
630 # # Files #####################################
631 $defaultPreferences['imagesize'] = [
632 'type' => 'select',
633 'options' => self::getImageSizes( $context ),
634 'label-message' => 'imagemaxsize',
635 'section' => 'rendering/files',
636 ];
637 $defaultPreferences['thumbsize'] = [
638 'type' => 'select',
639 'options' => self::getThumbSizes( $context ),
640 'label-message' => 'thumbsize',
641 'section' => 'rendering/files',
642 ];
643 }
644
652 # # Date and time #####################################
653 $dateOptions = self::getDateOptions( $context );
654 if ( $dateOptions ) {
655 $defaultPreferences['date'] = [
656 'type' => 'radio',
657 'options' => $dateOptions,
658 'label' => '&#160;',
659 'section' => 'rendering/dateformat',
660 ];
661 }
662
663 // Info
664 $now = wfTimestampNow();
665 $lang = $context->getLanguage();
666 $nowlocal = Xml::element( 'span', [ 'id' => 'wpLocalTime' ],
667 $lang->userTime( $now, $user ) );
668 $nowserver = $lang->userTime( $now, $user,
669 [ 'format' => false, 'timecorrection' => false ] ) .
670 Html::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 + (int)substr( $now, 10, 2 ) );
671
672 $defaultPreferences['nowserver'] = [
673 'type' => 'info',
674 'raw' => 1,
675 'label-message' => 'servertime',
676 'default' => $nowserver,
677 'section' => 'rendering/timeoffset',
678 ];
679
680 $defaultPreferences['nowlocal'] = [
681 'type' => 'info',
682 'raw' => 1,
683 'label-message' => 'localtime',
684 'default' => $nowlocal,
685 'section' => 'rendering/timeoffset',
686 ];
687
688 // Grab existing pref.
689 $tzOffset = $user->getOption( 'timecorrection' );
690 $tz = explode( '|', $tzOffset, 3 );
691
692 $tzOptions = self::getTimezoneOptions( $context );
693
694 $tzSetting = $tzOffset;
695 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
696 $minDiff = $tz[1];
697 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) % 60 );
698 } elseif ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
699 !in_array( $tzOffset, HTMLFormField::flattenOptions( $tzOptions ) )
700 ) {
701 # Timezone offset can vary with DST
702 $userTZ = timezone_open( $tz[2] );
703 if ( $userTZ !== false ) {
704 $minDiff = floor( timezone_offset_get( $userTZ, date_create( 'now' ) ) / 60 );
705 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
706 }
707 }
708
709 $defaultPreferences['timecorrection'] = [
710 'class' => 'HTMLSelectOrOtherField',
711 'label-message' => 'timezonelegend',
712 'options' => $tzOptions,
713 'default' => $tzSetting,
714 'size' => 20,
715 'section' => 'rendering/timeoffset',
716 ];
717 }
718
725 # # Diffs ####################################
726 $defaultPreferences['diffonly'] = [
727 'type' => 'toggle',
728 'section' => 'rendering/diffs',
729 'label-message' => 'tog-diffonly',
730 ];
731 $defaultPreferences['norollbackdiff'] = [
732 'type' => 'toggle',
733 'section' => 'rendering/diffs',
734 'label-message' => 'tog-norollbackdiff',
735 ];
736
737 # # Page Rendering ##############################
738 if ( $context->getConfig()->get( 'AllowUserCssPrefs' ) ) {
739 $defaultPreferences['underline'] = [
740 'type' => 'select',
741 'options' => [
742 $context->msg( 'underline-never' )->text() => 0,
743 $context->msg( 'underline-always' )->text() => 1,
744 $context->msg( 'underline-default' )->text() => 2,
745 ],
746 'label-message' => 'tog-underline',
747 'section' => 'rendering/advancedrendering',
748 ];
749 }
750
751 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
752 $stubThresholdOptions = [ $context->msg( 'stub-threshold-disabled' )->text() => 0 ];
753 foreach ( $stubThresholdValues as $value ) {
754 $stubThresholdOptions[$context->msg( 'size-bytes', $value )->text()] = $value;
755 }
756
757 $defaultPreferences['stubthreshold'] = [
758 'type' => 'select',
759 'section' => 'rendering/advancedrendering',
760 'options' => $stubThresholdOptions,
761 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
762 'label-raw' => $context->msg( 'stub-threshold' )->rawParams(
763 '<a href="#" class="stub">' .
764 $context->msg( 'stub-threshold-sample-link' )->parse() .
765 '</a>' )->parse(),
766 ];
767
768 $defaultPreferences['showhiddencats'] = [
769 'type' => 'toggle',
770 'section' => 'rendering/advancedrendering',
771 'label-message' => 'tog-showhiddencats'
772 ];
773
774 $defaultPreferences['numberheadings'] = [
775 'type' => 'toggle',
776 'section' => 'rendering/advancedrendering',
777 'label-message' => 'tog-numberheadings',
778 ];
779 }
780
787 # # Editing #####################################
788 $defaultPreferences['editsectiononrightclick'] = [
789 'type' => 'toggle',
790 'section' => 'editing/advancedediting',
791 'label-message' => 'tog-editsectiononrightclick',
792 ];
793 $defaultPreferences['editondblclick'] = [
794 'type' => 'toggle',
795 'section' => 'editing/advancedediting',
796 'label-message' => 'tog-editondblclick',
797 ];
798
799 if ( $context->getConfig()->get( 'AllowUserCssPrefs' ) ) {
800 $defaultPreferences['editfont'] = [
801 'type' => 'select',
802 'section' => 'editing/editor',
803 'label-message' => 'editfont-style',
804 'options' => [
805 $context->msg( 'editfont-default' )->text() => 'default',
806 $context->msg( 'editfont-monospace' )->text() => 'monospace',
807 $context->msg( 'editfont-sansserif' )->text() => 'sans-serif',
808 $context->msg( 'editfont-serif' )->text() => 'serif',
809 ]
810 ];
811 }
812 $defaultPreferences['cols'] = [
813 'type' => 'int',
814 'label-message' => 'columns',
815 'section' => 'editing/editor',
816 'min' => 4,
817 'max' => 1000,
818 ];
819 $defaultPreferences['rows'] = [
820 'type' => 'int',
821 'label-message' => 'rows',
822 'section' => 'editing/editor',
823 'min' => 4,
824 'max' => 1000,
825 ];
826 if ( $user->isAllowed( 'minoredit' ) ) {
827 $defaultPreferences['minordefault'] = [
828 'type' => 'toggle',
829 'section' => 'editing/editor',
830 'label-message' => 'tog-minordefault',
831 ];
832 }
833 $defaultPreferences['forceeditsummary'] = [
834 'type' => 'toggle',
835 'section' => 'editing/editor',
836 'label-message' => 'tog-forceeditsummary',
837 ];
838 $defaultPreferences['useeditwarning'] = [
839 'type' => 'toggle',
840 'section' => 'editing/editor',
841 'label-message' => 'tog-useeditwarning',
842 ];
843 $defaultPreferences['showtoolbar'] = [
844 'type' => 'toggle',
845 'section' => 'editing/editor',
846 'label-message' => 'tog-showtoolbar',
847 ];
848
849 $defaultPreferences['previewonfirst'] = [
850 'type' => 'toggle',
851 'section' => 'editing/preview',
852 'label-message' => 'tog-previewonfirst',
853 ];
854 $defaultPreferences['previewontop'] = [
855 'type' => 'toggle',
856 'section' => 'editing/preview',
857 'label-message' => 'tog-previewontop',
858 ];
859 $defaultPreferences['uselivepreview'] = [
860 'type' => 'toggle',
861 'section' => 'editing/preview',
862 'label-message' => 'tog-uselivepreview',
863 ];
864
865 }
866
873 $config = $context->getConfig();
874 $rcMaxAge = $config->get( 'RCMaxAge' );
875 # # RecentChanges #####################################
876 $defaultPreferences['rcdays'] = [
877 'type' => 'float',
878 'label-message' => 'recentchangesdays',
879 'section' => 'rc/displayrc',
880 'min' => 1,
881 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
882 'help' => $context->msg( 'recentchangesdays-max' )->numParams(
883 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
884 ];
885 $defaultPreferences['rclimit'] = [
886 'type' => 'int',
887 'label-message' => 'recentchangescount',
888 'help-message' => 'prefs-help-recentchangescount',
889 'section' => 'rc/displayrc',
890 ];
891 $defaultPreferences['usenewrc'] = [
892 'type' => 'toggle',
893 'label-message' => 'tog-usenewrc',
894 'section' => 'rc/advancedrc',
895 ];
896 $defaultPreferences['hideminor'] = [
897 'type' => 'toggle',
898 'label-message' => 'tog-hideminor',
899 'section' => 'rc/advancedrc',
900 ];
901
902 if ( $config->get( 'RCWatchCategoryMembership' ) ) {
903 $defaultPreferences['hidecategorization'] = [
904 'type' => 'toggle',
905 'label-message' => 'tog-hidecategorization',
906 'section' => 'rc/advancedrc',
907 ];
908 }
909
910 if ( $user->useRCPatrol() ) {
911 $defaultPreferences['hidepatrolled'] = [
912 'type' => 'toggle',
913 'section' => 'rc/advancedrc',
914 'label-message' => 'tog-hidepatrolled',
915 ];
916 }
917
918 if ( $user->useNPPatrol() ) {
919 $defaultPreferences['newpageshidepatrolled'] = [
920 'type' => 'toggle',
921 'section' => 'rc/advancedrc',
922 'label-message' => 'tog-newpageshidepatrolled',
923 ];
924 }
925
926 if ( $config->get( 'RCShowWatchingUsers' ) ) {
927 $defaultPreferences['shownumberswatching'] = [
928 'type' => 'toggle',
929 'section' => 'rc/advancedrc',
930 'label-message' => 'tog-shownumberswatching',
931 ];
932 }
933 }
934
941 $config = $context->getConfig();
942 $watchlistdaysMax = ceil( $config->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
943
944 # # Watchlist #####################################
945 if ( $user->isAllowed( 'editmywatchlist' ) ) {
946 $editWatchlistLinks = [];
947 $editWatchlistModes = [
948 'edit' => [ 'EditWatchlist', false ],
949 'raw' => [ 'EditWatchlist', 'raw' ],
950 'clear' => [ 'EditWatchlist', 'clear' ],
951 ];
952 foreach ( $editWatchlistModes as $editWatchlistMode => $mode ) {
953 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
954 $editWatchlistLinks[] = Linker::linkKnown(
955 SpecialPage::getTitleFor( $mode[0], $mode[1] ),
956 $context->msg( "prefs-editwatchlist-{$editWatchlistMode}" )->parse()
957 );
958 }
959
960 $defaultPreferences['editwatchlist'] = [
961 'type' => 'info',
962 'raw' => true,
963 'default' => $context->getLanguage()->pipeList( $editWatchlistLinks ),
964 'label-message' => 'prefs-editwatchlist-label',
965 'section' => 'watchlist/editwatchlist',
966 ];
967 }
968
969 $defaultPreferences['watchlistdays'] = [
970 'type' => 'float',
971 'min' => 0,
972 'max' => $watchlistdaysMax,
973 'section' => 'watchlist/displaywatchlist',
974 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
975 $watchlistdaysMax )->escaped(),
976 'label-message' => 'prefs-watchlist-days',
977 ];
978 $defaultPreferences['wllimit'] = [
979 'type' => 'int',
980 'min' => 0,
981 'max' => 1000,
982 'label-message' => 'prefs-watchlist-edits',
983 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
984 'section' => 'watchlist/displaywatchlist',
985 ];
986 $defaultPreferences['extendwatchlist'] = [
987 'type' => 'toggle',
988 'section' => 'watchlist/advancedwatchlist',
989 'label-message' => 'tog-extendwatchlist',
990 ];
991 $defaultPreferences['watchlisthideminor'] = [
992 'type' => 'toggle',
993 'section' => 'watchlist/advancedwatchlist',
994 'label-message' => 'tog-watchlisthideminor',
995 ];
996 $defaultPreferences['watchlisthidebots'] = [
997 'type' => 'toggle',
998 'section' => 'watchlist/advancedwatchlist',
999 'label-message' => 'tog-watchlisthidebots',
1000 ];
1001 $defaultPreferences['watchlisthideown'] = [
1002 'type' => 'toggle',
1003 'section' => 'watchlist/advancedwatchlist',
1004 'label-message' => 'tog-watchlisthideown',
1005 ];
1006 $defaultPreferences['watchlisthideanons'] = [
1007 'type' => 'toggle',
1008 'section' => 'watchlist/advancedwatchlist',
1009 'label-message' => 'tog-watchlisthideanons',
1010 ];
1011 $defaultPreferences['watchlisthideliu'] = [
1012 'type' => 'toggle',
1013 'section' => 'watchlist/advancedwatchlist',
1014 'label-message' => 'tog-watchlisthideliu',
1015 ];
1016 $defaultPreferences['watchlistreloadautomatically'] = [
1017 'type' => 'toggle',
1018 'section' => 'watchlist/advancedwatchlist',
1019 'label-message' => 'tog-watchlistreloadautomatically',
1020 ];
1021
1022 if ( $config->get( 'RCWatchCategoryMembership' ) ) {
1023 $defaultPreferences['watchlisthidecategorization'] = [
1024 'type' => 'toggle',
1025 'section' => 'watchlist/advancedwatchlist',
1026 'label-message' => 'tog-watchlisthidecategorization',
1027 ];
1028 }
1029
1030 if ( $user->useRCPatrol() ) {
1031 $defaultPreferences['watchlisthidepatrolled'] = [
1032 'type' => 'toggle',
1033 'section' => 'watchlist/advancedwatchlist',
1034 'label-message' => 'tog-watchlisthidepatrolled',
1035 ];
1036 }
1037
1038 $watchTypes = [
1039 'edit' => 'watchdefault',
1040 'move' => 'watchmoves',
1041 'delete' => 'watchdeletion'
1042 ];
1043
1044 // Kinda hacky
1045 if ( $user->isAllowed( 'createpage' ) || $user->isAllowed( 'createtalk' ) ) {
1046 $watchTypes['read'] = 'watchcreations';
1047 }
1048
1049 if ( $user->isAllowed( 'rollback' ) ) {
1050 $watchTypes['rollback'] = 'watchrollback';
1051 }
1052
1053 if ( $user->isAllowed( 'upload' ) ) {
1054 $watchTypes['upload'] = 'watchuploads';
1055 }
1056
1057 foreach ( $watchTypes as $action => $pref ) {
1058 if ( $user->isAllowed( $action ) ) {
1059 // Messages:
1060 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1061 // tog-watchrollback
1062 $defaultPreferences[$pref] = [
1063 'type' => 'toggle',
1064 'section' => 'watchlist/advancedwatchlist',
1065 'label-message' => "tog-$pref",
1066 ];
1067 }
1068 }
1069
1070 if ( $config->get( 'EnableAPI' ) ) {
1071 $defaultPreferences['watchlisttoken'] = [
1072 'type' => 'api',
1073 ];
1074 $defaultPreferences['watchlisttoken-info'] = [
1075 'type' => 'info',
1076 'section' => 'watchlist/tokenwatchlist',
1077 'label-message' => 'prefs-watchlist-token',
1078 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1079 'help-message' => 'prefs-help-watchlist-token2',
1080 ];
1081 }
1082 }
1083
1090 foreach ( MWNamespace::getValidNamespaces() as $n ) {
1091 $defaultPreferences['searchNs' . $n] = [
1092 'type' => 'api',
1093 ];
1094 }
1095 }
1096
1101 }
1102
1108 static function generateSkinOptions( $user, IContextSource $context ) {
1109 $ret = [];
1110
1111 $mptitle = Title::newMainPage();
1112 $previewtext = $context->msg( 'skin-preview' )->escaped();
1113
1114 # Only show skins that aren't disabled in $wgSkipSkins
1115 $validSkinNames = Skin::getAllowedSkins();
1116
1117 # Sort by UI skin name. First though need to update validSkinNames as sometimes
1118 # the skinkey & UI skinname differ (e.g. "standard" skinkey is "Classic" in the UI).
1119 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1120 $msg = $context->msg( "skinname-{$skinkey}" );
1121 if ( $msg->exists() ) {
1122 $skinname = htmlspecialchars( $msg->text() );
1123 }
1124 }
1125 asort( $validSkinNames );
1126
1127 $config = $context->getConfig();
1128 $defaultSkin = $config->get( 'DefaultSkin' );
1129 $allowUserCss = $config->get( 'AllowUserCss' );
1130 $allowUserJs = $config->get( 'AllowUserJs' );
1131
1132 $foundDefault = false;
1133 foreach ( $validSkinNames as $skinkey => $sn ) {
1134 $linkTools = [];
1135
1136 # Mark the default skin
1137 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1138 $linkTools[] = $context->msg( 'default' )->escaped();
1139 $foundDefault = true;
1140 }
1141
1142 # Create preview link
1143 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1144 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1145
1146 # Create links to user CSS/JS pages
1147 if ( $allowUserCss ) {
1148 $cssPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.css' );
1149 $linkTools[] = Linker::link( $cssPage, $context->msg( 'prefs-custom-css' )->escaped() );
1150 }
1151
1152 if ( $allowUserJs ) {
1153 $jsPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.js' );
1154 $linkTools[] = Linker::link( $jsPage, $context->msg( 'prefs-custom-js' )->escaped() );
1155 }
1156
1157 $display = $sn . ' ' . $context->msg( 'parentheses' )
1158 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1159 ->escaped();
1160 $ret[$display] = $skinkey;
1161 }
1162
1163 if ( !$foundDefault ) {
1164 // If the default skin is not available, things are going to break horribly because the
1165 // default value for skin selector will not be a valid value. Let's just not show it then.
1166 return [];
1167 }
1168
1169 return $ret;
1170 }
1171
1177 $lang = $context->getLanguage();
1178 $dateopts = $lang->getDatePreferences();
1179
1180 $ret = [];
1181
1182 if ( $dateopts ) {
1183 if ( !in_array( 'default', $dateopts ) ) {
1184 $dateopts[] = 'default'; // Make sure default is always valid
1185 // Bug 19237
1186 }
1187
1188 // FIXME KLUGE: site default might not be valid for user language
1190 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1191 $wgDefaultUserOptions['date'] = 'default';
1192 }
1193
1194 $epoch = wfTimestampNow();
1195 foreach ( $dateopts as $key ) {
1196 if ( $key == 'default' ) {
1197 $formatted = $context->msg( 'datedefault' )->escaped();
1198 } else {
1199 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1200 }
1201 $ret[$formatted] = $key;
1202 }
1203 }
1204 return $ret;
1205 }
1206
1212 $ret = [];
1213 $pixels = $context->msg( 'unit-pixel' )->text();
1214
1215 foreach ( $context->getConfig()->get( 'ImageLimits' ) as $index => $limits ) {
1216 $display = "{$limits[0]}×{$limits[1]}" . $pixels;
1217 $ret[$display] = $index;
1218 }
1219
1220 return $ret;
1221 }
1222
1228 $ret = [];
1229 $pixels = $context->msg( 'unit-pixel' )->text();
1230
1231 foreach ( $context->getConfig()->get( 'ThumbLimits' ) as $index => $size ) {
1232 $display = $size . $pixels;
1233 $ret[$display] = $index;
1234 }
1235
1236 return $ret;
1237 }
1238
1245 static function validateSignature( $signature, $alldata, $form ) {
1247 $maxSigChars = $form->getConfig()->get( 'MaxSigChars' );
1248 if ( mb_strlen( $signature ) > $maxSigChars ) {
1249 return Xml::element( 'span', [ 'class' => 'error' ],
1250 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1251 } elseif ( isset( $alldata['fancysig'] ) &&
1252 $alldata['fancysig'] &&
1253 $wgParser->validateSig( $signature ) === false
1254 ) {
1255 return Xml::element(
1256 'span',
1257 [ 'class' => 'error' ],
1258 $form->msg( 'badsig' )->text()
1259 );
1260 } else {
1261 return true;
1262 }
1263 }
1264
1271 static function cleanSignature( $signature, $alldata, $form ) {
1272 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1274 $signature = $wgParser->cleanSig( $signature );
1275 } else {
1276 // When no fancy sig used, make sure ~{3,5} get removed.
1277 $signature = Parser::cleanSigInSig( $signature );
1278 }
1279
1280 return $signature;
1281 }
1282
1290 static function getFormObject(
1291 $user,
1293 $formClass = 'PreferencesForm',
1294 array $remove = []
1295 ) {
1296 $formDescriptor = Preferences::getPreferences( $user, $context );
1297 if ( count( $remove ) ) {
1298 $removeKeys = array_flip( $remove );
1299 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1300 }
1301
1302 // Remove type=api preferences. They are not intended for rendering in the form.
1303 foreach ( $formDescriptor as $name => $info ) {
1304 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1305 unset( $formDescriptor[$name] );
1306 }
1307 }
1308
1312 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1313
1314 $htmlForm->setModifiedUser( $user );
1315 $htmlForm->setId( 'mw-prefs-form' );
1316 $htmlForm->setAutocomplete( 'off' );
1317 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1318 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1319 $htmlForm->setSubmitTooltip( 'preferences-save' );
1320 $htmlForm->setSubmitID( 'prefsubmit' );
1321 $htmlForm->setSubmitCallback( [ 'Preferences', 'tryFormSubmit' ] );
1322
1323 return $htmlForm;
1324 }
1325
1331 $opt = [];
1332
1333 $localTZoffset = $context->getConfig()->get( 'LocalTZoffset' );
1334 $timeZoneList = self::getTimeZoneList( $context->getLanguage() );
1335
1337 // Check that the LocalTZoffset is the same as the local time zone offset
1338 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1339 $timezoneName = $timestamp->getTimezone()->getName();
1340 // Localize timezone
1341 if ( isset( $timeZoneList[$timezoneName] ) ) {
1342 $timezoneName = $timeZoneList[$timezoneName]['name'];
1343 }
1344 $server_tz_msg = $context->msg(
1345 'timezoneuseserverdefault',
1346 $timezoneName
1347 )->text();
1348 } else {
1349 $tzstring = sprintf(
1350 '%+03d:%02d',
1351 floor( $localTZoffset / 60 ),
1352 abs( $localTZoffset ) % 60
1353 );
1354 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1355 }
1356 $opt[$server_tz_msg] = "System|$localTZoffset";
1357 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1358 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1359
1360 foreach ( $timeZoneList as $timeZoneInfo ) {
1361 $region = $timeZoneInfo['region'];
1362 if ( !isset( $opt[$region] ) ) {
1363 $opt[$region] = [];
1364 }
1365 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1366 }
1367 return $opt;
1368 }
1369
1375 static function filterIntval( $value, $alldata ) {
1376 return intval( $value );
1377 }
1378
1384 static function filterTimezoneInput( $tz, $alldata ) {
1385 $data = explode( '|', $tz, 3 );
1386 switch ( $data[0] ) {
1387 case 'ZoneInfo':
1388 case 'System':
1389 return $tz;
1390 default:
1391 $data = explode( ':', $tz, 2 );
1392 if ( count( $data ) == 2 ) {
1393 $data[0] = intval( $data[0] );
1394 $data[1] = intval( $data[1] );
1395 $minDiff = abs( $data[0] ) * 60 + $data[1];
1396 if ( $data[0] < 0 ) {
1397 $minDiff = - $minDiff;
1398 }
1399 } else {
1400 $minDiff = intval( $data[0] ) * 60;
1401 }
1402
1403 # Max is +14:00 and min is -12:00, see:
1404 # https://en.wikipedia.org/wiki/Timezone
1405 $minDiff = min( $minDiff, 840 ); # 14:00
1406 $minDiff = max( $minDiff, - 720 ); # -12:00
1407 return 'Offset|' . $minDiff;
1408 }
1409 }
1410
1418 static function tryFormSubmit( $formData, $form ) {
1419 $user = $form->getModifiedUser();
1420 $hiddenPrefs = $form->getConfig()->get( 'HiddenPrefs' );
1421 $result = true;
1422
1423 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1424 return Status::newFatal( 'mypreferencesprotected' );
1425 }
1426
1427 // Filter input
1428 foreach ( array_keys( $formData ) as $name ) {
1429 if ( isset( self::$saveFilters[$name] ) ) {
1430 $formData[$name] =
1431 call_user_func( self::$saveFilters[$name], $formData[$name], $formData );
1432 }
1433 }
1434
1435 // Fortunately, the realname field is MUCH simpler
1436 // (not really "private", but still shouldn't be edited without permission)
1437
1438 if ( !in_array( 'realname', $hiddenPrefs )
1439 && $user->isAllowed( 'editmyprivateinfo' )
1440 && array_key_exists( 'realname', $formData )
1441 ) {
1442 $realName = $formData['realname'];
1443 $user->setRealName( $realName );
1444 }
1445
1446 if ( $user->isAllowed( 'editmyoptions' ) ) {
1447 foreach ( self::$saveBlacklist as $b ) {
1448 unset( $formData[$b] );
1449 }
1450
1451 # If users have saved a value for a preference which has subsequently been disabled
1452 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1453 # is subsequently re-enabled
1454 foreach ( $hiddenPrefs as $pref ) {
1455 # If the user has not set a non-default value here, the default will be returned
1456 # and subsequently discarded
1457 $formData[$pref] = $user->getOption( $pref, null, true );
1458 }
1459
1460 // Keep old preferences from interfering due to back-compat code, etc.
1461 $user->resetOptions( 'unused', $form->getContext() );
1462
1463 foreach ( $formData as $key => $value ) {
1464 $user->setOption( $key, $value );
1465 }
1466
1467 Hooks::run( 'PreferencesFormPreSave', [ $formData, $form, $user, &$result ] );
1468 }
1469
1470 MediaWiki\Auth\AuthManager::callLegacyAuthPlugin( 'updateExternalDB', [ $user ] );
1471 $user->saveSettings();
1472
1473 return $result;
1474 }
1475
1481 public static function tryUISubmit( $formData, $form ) {
1482 $res = self::tryFormSubmit( $formData, $form );
1483
1484 if ( $res ) {
1485 $urlOptions = [];
1486
1487 if ( $res === 'eauth' ) {
1488 $urlOptions['eauth'] = 1;
1489 }
1490
1491 $urlOptions += $form->getExtraSuccessRedirectParameters();
1492
1493 $url = $form->getTitle()->getFullURL( $urlOptions );
1494
1495 $context = $form->getContext();
1496 // Set session data for the success message
1497 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1498
1499 $context->getOutput()->redirect( $url );
1500 }
1501
1502 return Status::newGood();
1503 }
1504
1513 public static function getTimeZoneList( Language $language ) {
1514 $identifiers = DateTimeZone::listIdentifiers();
1515 if ( $identifiers === false ) {
1516 return [];
1517 }
1518 sort( $identifiers );
1519
1520 $tzRegions = [
1521 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1522 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1523 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1524 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1525 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1526 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1527 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1528 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1529 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1530 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1531 ];
1532 asort( $tzRegions );
1533
1534 $timeZoneList = [];
1535
1536 $now = new DateTime();
1537
1538 foreach ( $identifiers as $identifier ) {
1539 $parts = explode( '/', $identifier, 2 );
1540
1541 // DateTimeZone::listIdentifiers() returns a number of
1542 // backwards-compatibility entries. This filters them out of the
1543 // list presented to the user.
1544 if ( count( $parts ) !== 2 || !array_key_exists( $parts[0], $tzRegions ) ) {
1545 continue;
1546 }
1547
1548 // Localize region
1549 $parts[0] = $tzRegions[$parts[0]];
1550
1551 $dateTimeZone = new DateTimeZone( $identifier );
1552 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1553
1554 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1555 $value = "ZoneInfo|$minDiff|$identifier";
1556
1557 $timeZoneList[$identifier] = [
1558 'name' => $display,
1559 'timecorrection' => $value,
1560 'region' => $parts[0],
1561 ];
1562 }
1563
1564 return $timeZoneList;
1565 }
1566}
1567
1570 // Override default value from HTMLForm
1571 protected $mSubSectionBeforeFields = false;
1572
1574
1578 public function setModifiedUser( $user ) {
1579 $this->modifiedUser = $user;
1580 }
1581
1585 public function getModifiedUser() {
1586 if ( $this->modifiedUser === null ) {
1587 return $this->getUser();
1588 } else {
1589 return $this->modifiedUser;
1590 }
1591 }
1592
1600 return [];
1601 }
1602
1607 function wrapForm( $html ) {
1608 $html = Xml::tags( 'div', [ 'id' => 'preferences' ], $html );
1609
1610 return parent::wrapForm( $html );
1611 }
1612
1616 function getButtons() {
1617
1618 $attrs = [ 'id' => 'mw-prefs-restoreprefs' ];
1619
1620 if ( !$this->getModifiedUser()->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1621 return '';
1622 }
1623
1624 $html = parent::getButtons();
1625
1626 if ( $this->getModifiedUser()->isAllowed( 'editmyoptions' ) ) {
1627 $t = SpecialPage::getTitleFor( 'Preferences', 'reset' );
1628
1629 $html .= "\n" . Linker::link( $t, $this->msg( 'restoreprefs' )->escaped(),
1630 Html::buttonAttributes( $attrs, [ 'mw-ui-quiet' ] ) );
1631
1632 $html = Xml::tags( 'div', [ 'class' => 'mw-prefs-buttons' ], $html );
1633 }
1634
1635 return $html;
1636 }
1637
1644 function filterDataForSubmit( $data ) {
1645 foreach ( $this->mFlatFields as $fieldname => $field ) {
1646 if ( $field instanceof HTMLNestedFilterable ) {
1647 $info = $field->mParams;
1648 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $fieldname;
1649 foreach ( $field->filterDataForSubmit( $data[$fieldname] ) as $key => $value ) {
1650 $data["$prefix$key"] = $value;
1651 }
1652 unset( $data[$fieldname] );
1653 }
1654 }
1655
1656 return $data;
1657 }
1658
1663 function getBody() {
1664 return $this->displaySection( $this->mFieldTree, '', 'mw-prefsection-' );
1665 }
1666
1673 function getLegend( $key ) {
1674 $legend = parent::getLegend( $key );
1675 Hooks::run( 'PreferencesGetLegend', [ $this, $key, &$legend ] );
1676 return $legend;
1677 }
1678
1684 return array_keys( array_filter( $this->mFieldTree, 'is_array' ) );
1685 }
1686}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
$wgDefaultUserOptions
Settings added to this array will override the default globals for the user preferences used by anony...
wfBCP47( $code)
Get the normalised IETF language tag See unit test for examples.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfCanIPUseHTTPS( $ip)
Determine whether the client at a given source IP is likely to be able to access the wiki via HTTPS.
$wgParser
Definition Setup.php:821
getUser()
Get the User object.
msg()
Get a Message object with context set Parameters are the same as wfMessage()
getOutput()
Get the OutputPage object.
static flattenOptions( $options)
flatten an array of options to a single array, for instance, a set of "<options>" inside "<optgroups>...
Object handling generic submission, CSRF protection, layout and other logic for UI forms.
Definition HTMLForm.php:128
static loadInputFromParameters( $fieldname, $descriptor, HTMLForm $parent=null)
Initialise a new Object for the field.
Definition HTMLForm.php:478
displaySection( $fields, $sectionName='', $fieldsetIDPrefix='', &$hasUserVisibleFields=false)
static array $languagesWithVariants
languages supporting variants
Internationalisation code.
Definition Language.php:35
static link( $target, $html=null, $customAttribs=[], $query=[], $options=[])
This function returns an HTML link to the given target.
Definition Linker.php:203
static linkKnown( $target, $html=null, $customAttribs=[], $query=[], $options=[ 'known'])
Identical to link(), except $options defaults to 'known'.
Definition Linker.php:255
MediaWiki exception.
static getLocalInstance( $ts=false)
Get a timestamp instance in the server local timezone ($wgLocaltimezone)
This serves as the entry point to the authentication system.
This is a value object for authentication requests with a username and password.
static newFromContext(IContextSource $context)
Get a ParserOptions object from a IContextSource object.
Some tweaks to allow js prefs to work.
getBody()
Get the whole body of the form.
setModifiedUser( $user)
filterDataForSubmit( $data)
Separate multi-option preferences into multiple preferences, since we have to store them separately.
getExtraSuccessRedirectParameters()
Get extra parameters for the query string when redirecting after successful save.
getPreferenceSections()
Get the keys of each top level preference section.
getLegend( $key)
Get the "<legend>" for a given section key.
We're now using the HTMLForm object with some customisation to generate the Preferences form.
static getOptionFromUser( $name, $info, $user)
Pull option from a user account.
static searchPreferences( $user, IContextSource $context, &$defaultPreferences)
static array $saveFilters
static rcPreferences( $user, IContextSource $context, &$defaultPreferences)
static filterIntval( $value, $alldata)
static generateSkinOptions( $user, IContextSource $context)
static loadPreferenceValues( $user, $context, &$defaultPreferences)
Loads existing values for a given array of preferences.
static getSaveBlacklist()
static tryUISubmit( $formData, $form)
static filesPreferences( $user, IContextSource $context, &$defaultPreferences)
static getImageSizes(IContextSource $context)
static getPreferences( $user, IContextSource $context)
static getTimeZoneList(Language $language)
Get a list of all time zones.
static watchlistPreferences( $user, IContextSource $context, &$defaultPreferences)
static datetimePreferences( $user, IContextSource $context, &$defaultPreferences)
static tryFormSubmit( $formData, $form)
Handle the form submission if everything validated properly.
static $saveBlacklist
static getDateOptions(IContextSource $context)
static miscPreferences( $user, IContextSource $context, &$defaultPreferences)
Dummy, kept for backwards-compatibility.
static profilePreferences( $user, IContextSource $context, &$defaultPreferences)
static getFormObject( $user, IContextSource $context, $formClass='PreferencesForm', array $remove=[])
static cleanSignature( $signature, $alldata, $form)
static array $defaultPreferences
static renderingPreferences( $user, IContextSource $context, &$defaultPreferences)
static getTimezoneOptions(IContextSource $context)
static skinPreferences( $user, IContextSource $context, &$defaultPreferences)
static getThumbSizes(IContextSource $context)
static filterTimezoneInput( $tz, $alldata)
static validateSignature( $signature, $alldata, $form)
static editingPreferences( $user, IContextSource $context, &$defaultPreferences)
static getAllowedSkins()
Fetch the list of user-selectable skins in regards to $wgSkipSkins.
Definition Skin.php:72
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don't need a full Title object,...
static tags( $element, $attribs=null, $contents)
Same as Xml::element(), but does not escape contents.
Definition Xml.php:131
static element( $element, $attribs=null, $contents='', $allowShortTag=true)
Format an XML element with given attributes and, optionally, text content.
Definition Xml.php:39
$res
Definition database.txt:21
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the local content language as $wgContLang
Definition design.txt:57
when a variable name is used in a it is silently declared as a new local masking the global
Definition design.txt:95
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
const NS_USER
Definition Defines.php:58
the array() calling protocol came about after MediaWiki 1.4rc1.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition hooks.txt:249
see documentation in includes Linker php for Linker::makeImageLink & $time
Definition hooks.txt:1752
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Associative array mapping language codes to prefixed links of the form "language:title". & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition hooks.txt:1937
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition hooks.txt:1096
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition hooks.txt:1949
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses & $html
Definition hooks.txt:1957
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition hooks.txt:2900
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:304
processing should stop and the error should be shown to the user * false
Definition hooks.txt:189
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition hooks.txt:887
if( $limit) $timestamp
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
Interface for objects which can provide a MediaWiki context on request.
$context
Definition load.php:50
if(!isset( $args[0])) $lang
switch( $options['output']) $languages
Definition transstat.php:76