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