Search in sources :

Example 1 with Preferences

use of org.olat.core.id.Preferences in project OpenOLAT by OpenOLAT.

the class MailHelper method getMailFooter.

public static String getMailFooter(Identity sender) {
    Preferences prefs = sender.getUser().getPreferences();
    Locale locale = I18nManager.getInstance().getLocaleOrDefault(prefs.getLanguage());
    return getMailFooter(locale, sender);
}
Also used : Locale(java.util.Locale) Preferences(org.olat.core.id.Preferences)

Example 2 with Preferences

use of org.olat.core.id.Preferences in project OpenOLAT by OpenOLAT.

the class UserBulkChangeManager method changeSelectedIdentities.

public void changeSelectedIdentities(List<Identity> selIdentities, Map<String, String> attributeChangeMap, Map<String, String> roleChangeMap, List<String> notUpdatedIdentities, boolean isAdministrativeUser, List<Long> ownGroups, List<Long> partGroups, Translator trans, Identity addingIdentity) {
    Translator transWithFallback = userManager.getPropertyHandlerTranslator(trans);
    String usageIdentifyer = UserBulkChangeStep00.class.getCanonicalName();
    notUpdatedIdentities.clear();
    List<Identity> changedIdentities = new ArrayList<>();
    List<UserPropertyHandler> userPropertyHandlers = userManager.getUserPropertyHandlersFor(usageIdentifyer, isAdministrativeUser);
    String[] securityGroups = { Constants.GROUP_USERMANAGERS, Constants.GROUP_GROUPMANAGERS, Constants.GROUP_AUTHORS, Constants.GROUP_ADMIN, Constants.GROUP_POOL_MANAGER, Constants.GROUP_INST_ORES_MANAGER };
    // loop over users to be edited:
    for (Identity identity : selIdentities) {
        // reload identity from cache, to prevent stale object
        identity = securityManager.loadIdentityByKey(identity.getKey());
        User user = identity.getUser();
        String oldEmail = user.getEmail();
        String errorDesc = "";
        boolean updateError = false;
        // change pwd
        if (attributeChangeMap.containsKey(PWD_IDENTIFYER)) {
            String newPwd = attributeChangeMap.get(PWD_IDENTIFYER);
            if (StringHelper.containsNonWhitespace(newPwd)) {
                if (!userManager.syntaxCheckOlatPassword(newPwd)) {
                    errorDesc = transWithFallback.translate("error.password");
                    updateError = true;
                }
            } else {
                newPwd = null;
            }
            olatAuthManager.changePasswordAsAdmin(identity, newPwd);
        }
        // set language
        String userLanguage = user.getPreferences().getLanguage();
        if (attributeChangeMap.containsKey(LANG_IDENTIFYER)) {
            String inputLanguage = attributeChangeMap.get(LANG_IDENTIFYER);
            if (!userLanguage.equals(inputLanguage)) {
                Preferences preferences = user.getPreferences();
                preferences.setLanguage(inputLanguage);
                user.setPreferences(preferences);
            }
        }
        Context vcContext = new VelocityContext();
        // set all properties as context
        setUserContext(identity, vcContext);
        // org.olat.admin.user.bulkChange.UserBulkChangeStep00
        for (int k = 0; k < userPropertyHandlers.size(); k++) {
            UserPropertyHandler propHandler = userPropertyHandlers.get(k);
            String propertyName = propHandler.getName();
            String userValue = identity.getUser().getProperty(propertyName, null);
            String inputFieldValue = "";
            if (attributeChangeMap.containsKey(propertyName)) {
                inputFieldValue = attributeChangeMap.get(propertyName);
                inputFieldValue = inputFieldValue.replace("$", "$!");
                String evaluatedInputFieldValue = evaluateValueWithUserContext(inputFieldValue, vcContext);
                // validate evaluated property-value
                ValidationError validationError = new ValidationError();
                // do validation checks with users current locale!
                Locale locale = transWithFallback.getLocale();
                if (!propHandler.isValidValue(identity.getUser(), evaluatedInputFieldValue, validationError, locale)) {
                    errorDesc = transWithFallback.translate(validationError.getErrorKey(), validationError.getArgs()) + " (" + evaluatedInputFieldValue + ")";
                    updateError = true;
                    break;
                }
                if (!evaluatedInputFieldValue.equals(userValue)) {
                    String stringValue = propHandler.getStringValue(evaluatedInputFieldValue, locale);
                    propHandler.setUserProperty(user, stringValue);
                }
            }
        }
        // loop over securityGroups defined above
        for (String securityGroup : securityGroups) {
            SecurityGroup secGroup = securityManager.findSecurityGroupByName(securityGroup);
            Boolean isInGroup = securityManager.isIdentityInSecurityGroup(identity, secGroup);
            String thisRoleAction = "";
            if (roleChangeMap.containsKey(securityGroup)) {
                thisRoleAction = roleChangeMap.get(securityGroup);
                // user not anymore in security group, remove him
                if (isInGroup && thisRoleAction.equals("remove")) {
                    securityManager.removeIdentityFromSecurityGroup(identity, secGroup);
                    log.audit("User::" + addingIdentity.getName() + " removed system role::" + securityGroup + " from user::" + identity.getName(), null);
                }
                // user not yet in security group, add him
                if (!isInGroup && thisRoleAction.equals("add")) {
                    securityManager.addIdentityToSecurityGroup(identity, secGroup);
                    log.audit("User::" + addingIdentity.getName() + " added system role::" + securityGroup + " to user::" + identity.getName(), null);
                }
            }
        }
        // set status
        if (roleChangeMap.containsKey("Status")) {
            Integer status = Integer.parseInt(roleChangeMap.get("Status"));
            int oldStatus = identity.getStatus();
            String oldStatusText = (oldStatus == Identity.STATUS_PERMANENT ? "permanent" : (oldStatus == Identity.STATUS_ACTIV ? "active" : (oldStatus == Identity.STATUS_LOGIN_DENIED ? "login_denied" : (oldStatus == Identity.STATUS_DELETED ? "deleted" : "unknown"))));
            String newStatusText = (status == Identity.STATUS_PERMANENT ? "permanent" : (status == Identity.STATUS_ACTIV ? "active" : (status == Identity.STATUS_LOGIN_DENIED ? "login_denied" : (status == Identity.STATUS_DELETED ? "deleted" : "unknown"))));
            if (oldStatus != status && status == Identity.STATUS_LOGIN_DENIED && Boolean.parseBoolean(roleChangeMap.get("sendLoginDeniedEmail"))) {
                sendLoginDeniedEmail(identity);
            }
            identity = securityManager.saveIdentityStatus(identity, status);
            log.audit("User::" + addingIdentity.getName() + " changed accout status for user::" + identity.getName() + " from::" + oldStatusText + " to::" + newStatusText, null);
        }
        // persist changes:
        if (updateError) {
            String errorOutput = identity.getName() + ": " + errorDesc;
            log.debug("error during bulkChange of users, following user could not be updated: " + errorOutput);
            notUpdatedIdentities.add(errorOutput);
        } else {
            userManager.updateUserFromIdentity(identity);
            securityManager.deleteInvalidAuthenticationsByEmail(oldEmail);
            changedIdentities.add(identity);
            log.audit("User::" + addingIdentity.getName() + " successfully changed account data for user::" + identity.getName() + " in bulk change", null);
        }
        // commit changes for this user
        dbInstance.commit();
    }
    // FXOLAT-101: add identity to new groups:
    if (ownGroups.size() != 0 || partGroups.size() != 0) {
        List<BusinessGroupMembershipChange> changes = new ArrayList<BusinessGroupMembershipChange>();
        for (Identity selIdentity : selIdentities) {
            if (ownGroups != null && !ownGroups.isEmpty()) {
                for (Long tutorGroupKey : ownGroups) {
                    BusinessGroupMembershipChange change = new BusinessGroupMembershipChange(selIdentity, tutorGroupKey);
                    change.setTutor(Boolean.TRUE);
                    changes.add(change);
                }
            }
            if (partGroups != null && !partGroups.isEmpty()) {
                for (Long partGroupKey : partGroups) {
                    BusinessGroupMembershipChange change = new BusinessGroupMembershipChange(selIdentity, partGroupKey);
                    change.setParticipant(Boolean.TRUE);
                    changes.add(change);
                }
            }
        }
        MailPackage mailing = new MailPackage();
        businessGroupService.updateMemberships(addingIdentity, changes, mailing);
        dbInstance.commit();
    }
}
Also used : Context(org.apache.velocity.context.Context) VelocityContext(org.apache.velocity.VelocityContext) Locale(java.util.Locale) User(org.olat.core.id.User) MailPackage(org.olat.core.util.mail.MailPackage) VelocityContext(org.apache.velocity.VelocityContext) ArrayList(java.util.ArrayList) SecurityGroup(org.olat.basesecurity.SecurityGroup) BusinessGroupMembershipChange(org.olat.group.model.BusinessGroupMembershipChange) Translator(org.olat.core.gui.translator.Translator) ValidationError(org.olat.core.gui.components.form.ValidationError) Identity(org.olat.core.id.Identity) Preferences(org.olat.core.id.Preferences) UserPropertyHandler(org.olat.user.propertyhandlers.UserPropertyHandler)

Example 3 with Preferences

use of org.olat.core.id.Preferences in project OpenOLAT by OpenOLAT.

the class UserManagerImpl method createUser.

@Override
public User createUser(String firstName, String lastName, String eMail) {
    UserImpl newUser = new UserImpl();
    newUser.setFirstName(firstName);
    newUser.setLastName(lastName);
    newUser.setEmail(eMail);
    newUser.setCreationDate(new Date());
    Preferences prefs = newUser.getPreferences();
    Locale loc;
    // for junit test case: use German Locale
    if (Settings.isJUnitTest()) {
        loc = Locale.GERMAN;
    } else {
        loc = I18nModule.getDefaultLocale();
    }
    // Locale loc
    prefs.setLanguage(loc.toString());
    prefs.setFontsize("normal");
    prefs.setPresenceMessagesPublic(false);
    prefs.setInformSessionTimeout(false);
    return newUser;
}
Also used : Locale(java.util.Locale) Preferences(org.olat.core.id.Preferences) Date(java.util.Date)

Example 4 with Preferences

use of org.olat.core.id.Preferences in project OpenOLAT by OpenOLAT.

the class PreferencesFormController method initForm.

/**
 * @see org.olat.core.gui.components.form.flexible.impl.FormBasicController#initForm(org.olat.core.gui.components.form.flexible.FormItemContainer,
 *      org.olat.core.gui.control.Controller, org.olat.core.gui.UserRequest)
 */
protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) {
    setFormTitle("title.prefs");
    setFormContextHelp("Configuration#_einstellungen");
    // load preferences
    Preferences prefs = tobeChangedIdentity.getUser().getPreferences();
    // Username
    StaticTextElement username = uifactory.addStaticTextElement("form.username", tobeChangedIdentity.getName(), formLayout);
    username.setElementCssClass("o_sel_home_settings_username");
    username.setEnabled(false);
    // Roles
    final String[] roleKeys = new String[] { Constants.GROUP_USERMANAGERS, Constants.GROUP_GROUPMANAGERS, Constants.GROUP_POOL_MANAGER, Constants.GROUP_AUTHORS, Constants.GROUP_INST_ORES_MANAGER, Constants.GROUP_ADMIN };
    String iname = getIdentity().getUser().getProperty("institutionalName", null);
    String ilabel = iname != null ? translate("rightsForm.isInstitutionalResourceManager.institution", iname) : translate("rightsForm.isInstitutionalResourceManager");
    final String[] roleValues = new String[] { translate("rightsForm.isUsermanager"), translate("rightsForm.isGroupmanager"), translate("rightsForm.isPoolmanager"), translate("rightsForm.isAuthor"), ilabel, translate("rightsForm.isAdmin") };
    final BaseSecurity securityManager = CoreSpringFactory.getImpl(BaseSecurity.class);
    String userRoles = "";
    List<String> roles = securityManager.getRolesAsString(tobeChangedIdentity);
    for (String role : roles) {
        for (int i = 0; i < roleKeys.length; i++) {
            if (roleKeys[i].equals(role)) {
                userRoles = userRoles + roleValues[i] + ", ";
            }
        }
    }
    if (userRoles.equals("")) {
        userRoles = translate("rightsForm.isAnonymous.false");
    } else {
        userRoles = userRoles.substring(0, userRoles.lastIndexOf(","));
    }
    uifactory.addStaticTextElement("rightsForm.roles", userRoles, formLayout);
    username.setElementCssClass("o_sel_home_settings_username");
    username.setEnabled(false);
    // Language
    Map<String, String> languages = I18nManager.getInstance().getEnabledLanguagesTranslated();
    String[] langKeys = StringHelper.getMapKeysAsStringArray(languages);
    String[] langValues = StringHelper.getMapValuesAsStringArray(languages);
    ArrayHelper.sort(langKeys, langValues, false, true, false);
    language = uifactory.addDropdownSingleselect("form.language", formLayout, langKeys, langValues, null);
    language.setElementCssClass("o_sel_home_settings_language");
    String langKey = prefs.getLanguage();
    // this server
    if (prefs.getLanguage() != null && i18nModule.getEnabledLanguageKeys().contains(langKey)) {
        language.select(prefs.getLanguage(), true);
    } else {
        language.select(I18nModule.getDefaultLocale().toString(), true);
    }
    // Font size
    String[] cssFontsizeValues = new String[] { translate("form.fontsize.xsmall"), translate("form.fontsize.small"), translate("form.fontsize.normal"), translate("form.fontsize.large"), translate("form.fontsize.xlarge"), translate("form.fontsize.presentation") };
    fontsize = uifactory.addDropdownSingleselect("form.fontsize", formLayout, cssFontsizeKeys, cssFontsizeValues, null);
    fontsize.setElementCssClass("o_sel_home_settings_fontsize");
    fontsize.select(prefs.getFontsize(), true);
    fontsize.addActionListener(FormEvent.ONCHANGE);
    // Email notification interval
    NotificationsManager nMgr = NotificationsManager.getInstance();
    List<String> intervals = nMgr.getEnabledNotificationIntervals();
    if (intervals.size() > 0) {
        String[] intervalKeys = new String[intervals.size()];
        intervals.toArray(intervalKeys);
        String[] intervalValues = new String[intervalKeys.length];
        String i18nPrefix = "interval.";
        for (int i = 0; i < intervalKeys.length; i++) {
            intervalValues[i] = translate(i18nPrefix + intervalKeys[i]);
        }
        notificationInterval = uifactory.addDropdownSingleselect("form.notification", formLayout, intervalKeys, intervalValues, null);
        notificationInterval.setElementCssClass("o_sel_home_settings_notification_interval");
        notificationInterval.select(prefs.getNotificationInterval(), true);
    }
    // fxdiff VCRP-16: intern mail system
    MailModule mailModule = (MailModule) CoreSpringFactory.getBean("mailModule");
    if (mailModule.isInternSystem()) {
        String userEmail = UserManager.getInstance().getUserDisplayEmail(tobeChangedIdentity, ureq.getLocale());
        String[] mailInternLabels = new String[] { translate("mail." + mailIntern[0], userEmail), translate("mail." + mailIntern[1], userEmail) };
        mailSystem = uifactory.addRadiosVertical("mail-system", "mail.system", formLayout, mailIntern, mailInternLabels);
        mailSystem.setElementCssClass("o_sel_home_settings_mail");
        String mailPrefs = prefs.getReceiveRealMail();
        if (StringHelper.containsNonWhitespace(mailPrefs)) {
            if ("true".equals(mailPrefs)) {
                mailSystem.select(mailIntern[1], true);
            } else {
                mailSystem.select(mailIntern[0], true);
            }
        } else if (mailModule.isReceiveRealMailUserDefaultSetting()) {
            mailSystem.select(mailIntern[1], true);
        } else {
            mailSystem.select(mailIntern[0], true);
        }
    }
    // Text encoding
    Map<String, Charset> charsets = Charset.availableCharsets();
    String currentCharset = UserManager.getInstance().getUserCharset(tobeChangedIdentity);
    String[] csKeys = StringHelper.getMapKeysAsStringArray(charsets);
    charset = uifactory.addDropdownSingleselect("form.charset", formLayout, csKeys, csKeys, null);
    charset.setElementCssClass("o_sel_home_settings_charset");
    if (currentCharset != null) {
        for (String csKey : csKeys) {
            if (csKey.equals(currentCharset)) {
                charset.select(currentCharset, true);
            }
        }
    }
    if (!charset.isOneSelected() && charsets.containsKey("UTF-8")) {
        charset.select("UTF-8", true);
    }
    // Submit and cancel buttons
    final FormLayoutContainer buttonLayout = FormLayoutContainer.createButtonLayout("button_layout", getTranslator());
    formLayout.add(buttonLayout);
    buttonLayout.setElementCssClass("o_sel_home_settings_prefs_buttons");
    uifactory.addFormSubmitButton("submit", buttonLayout);
    uifactory.addFormCancelButton("cancel", buttonLayout, ureq, getWindowControl());
}
Also used : Charset(java.nio.charset.Charset) FormLayoutContainer(org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer) BaseSecurity(org.olat.basesecurity.BaseSecurity) MailModule(org.olat.core.util.mail.MailModule) NotificationsManager(org.olat.core.commons.services.notifications.NotificationsManager) StaticTextElement(org.olat.core.gui.components.form.flexible.elements.StaticTextElement) Preferences(org.olat.core.id.Preferences)

Example 5 with Preferences

use of org.olat.core.id.Preferences in project OpenOLAT by OpenOLAT.

the class PwChangeController method sendEmail.

private TemporaryKey sendEmail(UserRequest ureq, Identity identity) {
    if (!userModule.isPwdChangeAllowed(identity)) {
        getWindowControl().setWarning(translate("password.cantchange"));
        return null;
    }
    Preferences prefs = identity.getUser().getPreferences();
    Locale locale = i18nManager.getLocaleOrDefault(prefs.getLanguage());
    ureq.getUserSession().setLocale(locale);
    myContent.contextPut("locale", locale);
    Translator userTrans = Util.createPackageTranslator(PwChangeController.class, locale);
    String emailAdress = identity.getUser().getProperty(UserConstants.EMAIL, locale);
    if (!StringHelper.containsNonWhitespace(emailAdress)) {
        // for security reason, don't show an error, go simply to the next step
        stepSendEmailConfiration();
        return null;
    }
    // get remote address
    String ip = ureq.getHttpReq().getRemoteAddr();
    String today = DateFormat.getDateInstance(DateFormat.LONG, ureq.getLocale()).format(new Date());
    // mailer configuration
    String serverpath = Settings.getServerContextPathURI();
    TemporaryKey tk = rm.createAndDeleteOldTemporaryKey(identity.getKey(), emailAdress, ip, RegistrationManager.PW_CHANGE);
    myContent.contextPut("pwKey", tk.getRegistrationKey());
    StringBuilder body = new StringBuilder();
    body.append("<style>").append(".o_footer {background: #FAFAFA; border: 1px solid #eee; border-radius: 5px; padding: 1em; margin: 1em;}").append(".o_body {background: #FAFAFA; padding: 1em; margin: 1em;}").append("</style>").append("<div class='o_body'>").append(userTrans.translate("pwchange.headline")).append(userTrans.translate("pwchange.intro", new String[] { identity.getName() })).append(userTrans.translate("pwchange.body", new String[] { serverpath, tk.getRegistrationKey(), i18nModule.getLocaleKey(ureq.getLocale()) })).append(userTrans.translate("pwchange.body.alt", new String[] { serverpath, tk.getRegistrationKey(), i18nModule.getLocaleKey(ureq.getLocale()) })).append("</div>").append("<div class='o_footer'>").append(userTrans.translate("reg.wherefrom", new String[] { serverpath, today, ip })).append("</div>");
    MailBundle bundle = new MailBundle();
    bundle.setToId(identity);
    bundle.setContent(userTrans.translate("pwchange.subject"), body.toString());
    MailerResult result = mailManager.sendExternMessage(bundle, null, false);
    if (result.getReturnCode() == MailerResult.OK) {
        getWindowControl().setInfo(translate("email.sent"));
    }
    stepSendEmailConfiration();
    return tk;
}
Also used : Locale(java.util.Locale) Translator(org.olat.core.gui.translator.Translator) MailerResult(org.olat.core.util.mail.MailerResult) Preferences(org.olat.core.id.Preferences) MailBundle(org.olat.core.util.mail.MailBundle) Date(java.util.Date)

Aggregations

Preferences (org.olat.core.id.Preferences)22 Locale (java.util.Locale)12 Translator (org.olat.core.gui.translator.Translator)8 Identity (org.olat.core.id.Identity)8 Date (java.util.Date)4 Path (javax.ws.rs.Path)4 Produces (javax.ws.rs.Produces)4 BaseSecurity (org.olat.basesecurity.BaseSecurity)4 User (org.olat.core.id.User)4 MailBundle (org.olat.core.util.mail.MailBundle)4 MailerResult (org.olat.core.util.mail.MailerResult)4 RestSecurityHelper.getIdentity (org.olat.restapi.security.RestSecurityHelper.getIdentity)4 UserPropertyHandler (org.olat.user.propertyhandlers.UserPropertyHandler)4 Charset (java.nio.charset.Charset)2 ArrayList (java.util.ArrayList)2 Consumes (javax.ws.rs.Consumes)2 GET (javax.ws.rs.GET)2 POST (javax.ws.rs.POST)2 WebApplicationException (javax.ws.rs.WebApplicationException)2 VelocityContext (org.apache.velocity.VelocityContext)2