001
014
015 package com.liferay.portal.service.impl;
016
017 import com.liferay.mail.service.MailService;
018 import com.liferay.portal.CompanyMaxUsersException;
019 import com.liferay.portal.ContactBirthdayException;
020 import com.liferay.portal.ContactNameException;
021 import com.liferay.portal.DuplicateOpenIdException;
022 import com.liferay.portal.GroupFriendlyURLException;
023 import com.liferay.portal.ModelListenerException;
024 import com.liferay.portal.NoSuchImageException;
025 import com.liferay.portal.NoSuchOrganizationException;
026 import com.liferay.portal.NoSuchTicketException;
027 import com.liferay.portal.NoSuchUserException;
028 import com.liferay.portal.PasswordExpiredException;
029 import com.liferay.portal.RequiredUserException;
030 import com.liferay.portal.SendPasswordException;
031 import com.liferay.portal.UserEmailAddressException;
032 import com.liferay.portal.UserIdException;
033 import com.liferay.portal.UserLockoutException;
034 import com.liferay.portal.UserPasswordException;
035 import com.liferay.portal.UserReminderQueryException;
036 import com.liferay.portal.UserScreenNameException;
037 import com.liferay.portal.UserSmsException;
038 import com.liferay.portal.kernel.bean.BeanReference;
039 import com.liferay.portal.kernel.cache.PortalCache;
040 import com.liferay.portal.kernel.cache.PortalCacheMapSynchronizeUtil;
041 import com.liferay.portal.kernel.cache.PortalCacheMapSynchronizeUtil.Synchronizer;
042 import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
043 import com.liferay.portal.kernel.dao.orm.QueryUtil;
044 import com.liferay.portal.kernel.dao.orm.WildcardMode;
045 import com.liferay.portal.kernel.exception.PortalException;
046 import com.liferay.portal.kernel.exception.SystemException;
047 import com.liferay.portal.kernel.language.LanguageUtil;
048 import com.liferay.portal.kernel.log.Log;
049 import com.liferay.portal.kernel.log.LogFactoryUtil;
050 import com.liferay.portal.kernel.messaging.DestinationNames;
051 import com.liferay.portal.kernel.messaging.Message;
052 import com.liferay.portal.kernel.messaging.MessageBusUtil;
053 import com.liferay.portal.kernel.search.BaseModelSearchResult;
054 import com.liferay.portal.kernel.search.Hits;
055 import com.liferay.portal.kernel.search.Indexer;
056 import com.liferay.portal.kernel.search.IndexerRegistryUtil;
057 import com.liferay.portal.kernel.search.QueryConfig;
058 import com.liferay.portal.kernel.search.SearchContext;
059 import com.liferay.portal.kernel.search.SearchException;
060 import com.liferay.portal.kernel.search.Sort;
061 import com.liferay.portal.kernel.spring.aop.Skip;
062 import com.liferay.portal.kernel.transaction.Propagation;
063 import com.liferay.portal.kernel.transaction.TransactionCommitCallbackUtil;
064 import com.liferay.portal.kernel.transaction.Transactional;
065 import com.liferay.portal.kernel.util.ArrayUtil;
066 import com.liferay.portal.kernel.util.Digester;
067 import com.liferay.portal.kernel.util.DigesterUtil;
068 import com.liferay.portal.kernel.util.GetterUtil;
069 import com.liferay.portal.kernel.util.KeyValuePair;
070 import com.liferay.portal.kernel.util.ListUtil;
071 import com.liferay.portal.kernel.util.LocaleUtil;
072 import com.liferay.portal.kernel.util.LocalizationUtil;
073 import com.liferay.portal.kernel.util.MapUtil;
074 import com.liferay.portal.kernel.util.OrderByComparator;
075 import com.liferay.portal.kernel.util.ParamUtil;
076 import com.liferay.portal.kernel.util.PropsKeys;
077 import com.liferay.portal.kernel.util.PwdGenerator;
078 import com.liferay.portal.kernel.util.SetUtil;
079 import com.liferay.portal.kernel.util.StringBundler;
080 import com.liferay.portal.kernel.util.StringPool;
081 import com.liferay.portal.kernel.util.StringUtil;
082 import com.liferay.portal.kernel.util.UnicodeProperties;
083 import com.liferay.portal.kernel.util.Validator;
084 import com.liferay.portal.kernel.workflow.WorkflowConstants;
085 import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil;
086 import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
087 import com.liferay.portal.model.Account;
088 import com.liferay.portal.model.Company;
089 import com.liferay.portal.model.CompanyConstants;
090 import com.liferay.portal.model.Contact;
091 import com.liferay.portal.model.ContactConstants;
092 import com.liferay.portal.model.Group;
093 import com.liferay.portal.model.GroupConstants;
094 import com.liferay.portal.model.Layout;
095 import com.liferay.portal.model.Organization;
096 import com.liferay.portal.model.PasswordPolicy;
097 import com.liferay.portal.model.ResourceConstants;
098 import com.liferay.portal.model.Role;
099 import com.liferay.portal.model.RoleConstants;
100 import com.liferay.portal.model.Team;
101 import com.liferay.portal.model.Ticket;
102 import com.liferay.portal.model.TicketConstants;
103 import com.liferay.portal.model.User;
104 import com.liferay.portal.model.UserGroup;
105 import com.liferay.portal.model.UserGroupRole;
106 import com.liferay.portal.model.impl.LayoutImpl;
107 import com.liferay.portal.model.impl.UserCacheModel;
108 import com.liferay.portal.model.impl.UserImpl;
109 import com.liferay.portal.security.auth.AuthPipeline;
110 import com.liferay.portal.security.auth.Authenticator;
111 import com.liferay.portal.security.auth.EmailAddressGenerator;
112 import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
113 import com.liferay.portal.security.auth.EmailAddressValidator;
114 import com.liferay.portal.security.auth.EmailAddressValidatorFactory;
115 import com.liferay.portal.security.auth.FullNameDefinition;
116 import com.liferay.portal.security.auth.FullNameDefinitionFactory;
117 import com.liferay.portal.security.auth.FullNameGenerator;
118 import com.liferay.portal.security.auth.FullNameGeneratorFactory;
119 import com.liferay.portal.security.auth.FullNameValidator;
120 import com.liferay.portal.security.auth.FullNameValidatorFactory;
121 import com.liferay.portal.security.auth.PrincipalException;
122 import com.liferay.portal.security.auth.PrincipalThreadLocal;
123 import com.liferay.portal.security.auth.ScreenNameGenerator;
124 import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
125 import com.liferay.portal.security.auth.ScreenNameValidator;
126 import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
127 import com.liferay.portal.security.ldap.LDAPSettingsUtil;
128 import com.liferay.portal.security.permission.PermissionCacheUtil;
129 import com.liferay.portal.security.pwd.PasswordEncryptorUtil;
130 import com.liferay.portal.security.pwd.PwdAuthenticator;
131 import com.liferay.portal.security.pwd.PwdToolkitUtil;
132 import com.liferay.portal.security.pwd.RegExpToolkit;
133 import com.liferay.portal.service.BaseServiceImpl;
134 import com.liferay.portal.service.ServiceContext;
135 import com.liferay.portal.service.ServiceContextThreadLocal;
136 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
137 import com.liferay.portal.service.persistence.UserGroupRolePK;
138 import com.liferay.portal.util.PortalUtil;
139 import com.liferay.portal.util.PrefsPropsUtil;
140 import com.liferay.portal.util.PropsValues;
141 import com.liferay.portal.util.SubscriptionSender;
142 import com.liferay.portlet.messageboards.model.MBMessage;
143 import com.liferay.portlet.social.model.SocialRelation;
144 import com.liferay.portlet.social.model.SocialRelationConstants;
145 import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
146 import com.liferay.util.Encryptor;
147 import com.liferay.util.EncryptorException;
148
149 import java.io.Serializable;
150
151 import java.util.ArrayList;
152 import java.util.Arrays;
153 import java.util.Calendar;
154 import java.util.Collections;
155 import java.util.Date;
156 import java.util.HashMap;
157 import java.util.HashSet;
158 import java.util.LinkedHashMap;
159 import java.util.LinkedHashSet;
160 import java.util.List;
161 import java.util.Locale;
162 import java.util.Map;
163 import java.util.Set;
164 import java.util.concurrent.Callable;
165 import java.util.concurrent.ConcurrentHashMap;
166
167 import javax.portlet.PortletPreferences;
168
169
181 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
182
183
195 @Override
196 public User addDefaultAdminUser(
197 long companyId, String screenName, String emailAddress,
198 Locale locale, String firstName, String middleName, String lastName)
199 throws PortalException {
200
201 long creatorUserId = 0;
202 boolean autoPassword = false;
203 String password1 = PropsValues.DEFAULT_ADMIN_PASSWORD;
204 String password2 = password1;
205 boolean autoScreenName = false;
206
207 screenName = getLogin(screenName);
208
209 for (int i = 1;; i++) {
210 User screenNameUser = userPersistence.fetchByC_SN(
211 companyId, screenName);
212
213 if (screenNameUser == null) {
214 break;
215 }
216
217 screenName = screenName + i;
218 }
219
220 long facebookId = 0;
221 String openId = StringPool.BLANK;
222 long prefixId = 0;
223 long suffixId = 0;
224 boolean male = true;
225 int birthdayMonth = Calendar.JANUARY;
226 int birthdayDay = 1;
227 int birthdayYear = 1970;
228 String jobTitle = StringPool.BLANK;
229
230 Group guestGroup = groupLocalService.getGroup(
231 companyId, GroupConstants.GUEST);
232
233 long[] groupIds = {guestGroup.getGroupId()};
234
235 long[] organizationIds = null;
236
237 Role adminRole = roleLocalService.getRole(
238 companyId, RoleConstants.ADMINISTRATOR);
239
240 Role powerUserRole = roleLocalService.getRole(
241 companyId, RoleConstants.POWER_USER);
242
243 long[] roleIds = {adminRole.getRoleId(), powerUserRole.getRoleId()};
244
245 long[] userGroupIds = null;
246 boolean sendEmail = false;
247 ServiceContext serviceContext = new ServiceContext();
248
249 User defaultAdminUser = addUser(
250 creatorUserId, companyId, autoPassword, password1, password2,
251 autoScreenName, screenName, emailAddress, facebookId, openId,
252 locale, firstName, middleName, lastName, prefixId, suffixId, male,
253 birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
254 organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
255
256 updateEmailAddressVerified(defaultAdminUser.getUserId(), true);
257
258 updateLastLogin(
259 defaultAdminUser.getUserId(), defaultAdminUser.getLoginIP());
260
261 updatePasswordReset(defaultAdminUser.getUserId(), false);
262
263 return defaultAdminUser;
264 }
265
266
274 @Override
275 public void addDefaultGroups(long userId) throws PortalException {
276 User user = userPersistence.findByPrimaryKey(userId);
277
278 Set<Long> groupIdsSet = new HashSet<>();
279
280 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
281 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
282 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
283
284 for (String defaultGroupName : defaultGroupNames) {
285 Company company = companyPersistence.findByPrimaryKey(
286 user.getCompanyId());
287
288 Account account = company.getAccount();
289
290 if (StringUtil.equalsIgnoreCase(
291 defaultGroupName, account.getName())) {
292
293 defaultGroupName = GroupConstants.GUEST;
294 }
295
296 Group group = groupPersistence.fetchByC_GK(
297 user.getCompanyId(), defaultGroupName);
298
299 if ((group != null) &&
300 !userPersistence.containsGroup(
301 userId, group.getGroupId())) {
302
303 groupIdsSet.add(group.getGroupId());
304 }
305 }
306
307 String[] defaultOrganizationGroupNames = PrefsPropsUtil.getStringArray(
308 user.getCompanyId(),
309 PropsKeys.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES,
310 StringPool.NEW_LINE,
311 PropsValues.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES);
312
313 for (String defaultOrganizationGroupName :
314 defaultOrganizationGroupNames) {
315
316 defaultOrganizationGroupName +=
317 GroupLocalServiceImpl.ORGANIZATION_NAME_SUFFIX;
318
319 Group group = groupPersistence.fetchByC_GK(
320 user.getCompanyId(), defaultOrganizationGroupName);
321
322 if ((group != null) &&
323 !userPersistence.containsGroup(
324 userId, group.getGroupId())) {
325
326 groupIdsSet.add(group.getGroupId());
327 }
328 }
329
330 long[] groupIds = ArrayUtil.toArray(
331 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
332
333 groupLocalService.addUserGroups(userId, groupIds);
334 }
335
336
344 @Override
345 public void addDefaultRoles(long userId) throws PortalException {
346 User user = userPersistence.findByPrimaryKey(userId);
347
348 Set<Long> roleIdSet = new HashSet<>();
349
350 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
351 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
352 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
353
354 for (String defaultRoleName : defaultRoleNames) {
355 Role role = rolePersistence.fetchByC_N(
356 user.getCompanyId(), defaultRoleName);
357
358 if ((role != null) &&
359 !userPersistence.containsRole(userId, role.getRoleId())) {
360
361 roleIdSet.add(role.getRoleId());
362 }
363 }
364
365 Set<Long> groupRoleIdsSet = new HashSet<>();
366 Set<Long> regularRoleIdsSet = new HashSet<>();
367
368 long[] roleIds = ArrayUtil.toLongArray(roleIdSet);
369
370 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
371
372 for (long roleId : roleIds) {
373 Role role = roleLocalService.getRole(roleId);
374
375 if (role.getType() == RoleConstants.TYPE_REGULAR) {
376 regularRoleIdsSet.add(roleId);
377 }
378 else {
379 groupRoleIdsSet.add(roleId);
380 }
381 }
382
383 long[] regularRoleIds = ArrayUtil.toLongArray(regularRoleIdsSet);
384
385 userPersistence.addRoles(userId, regularRoleIds);
386
387 Set<UserGroupRole> userGroupRolesSet = new LinkedHashSet<>();
388
389 long[] groupIds = user.getGroupIds();
390
391 for (long groupRoleId : groupRoleIdsSet) {
392 for (long groupId : groupIds) {
393 UserGroupRolePK userGroupRolePK = new UserGroupRolePK(
394 userId, groupId, groupRoleId);
395
396 UserGroupRole userGroupRole = userGroupRolePersistence.create(
397 userGroupRolePK);
398
399 userGroupRolesSet.add(userGroupRole);
400 }
401 }
402
403 List<UserGroupRole> previousUserGroupRoles =
404 userGroupRolePersistence.findByUserId(userId);
405
406 updateUserGroupRoles(
407 user, groupIds, null, new ArrayList<>(userGroupRolesSet),
408 previousUserGroupRoles);
409 }
410
411
419 @Override
420 @SuppressWarnings("deprecation")
421 public void addDefaultUserGroups(long userId) throws PortalException {
422 User user = userPersistence.findByPrimaryKey(userId);
423
424 Set<Long> userGroupIdSet = new HashSet<>();
425
426 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
427 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
428 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
429
430 for (String defaultUserGroupName : defaultUserGroupNames) {
431 UserGroup userGroup = userGroupPersistence.fetchByC_N(
432 user.getCompanyId(), defaultUserGroupName);
433
434 if ((userGroup != null) &&
435 !userPersistence.containsUserGroup(
436 userId, userGroup.getUserGroupId())) {
437
438 userGroupIdSet.add(userGroup.getUserGroupId());
439 }
440 }
441
442 long[] userGroupIds = ArrayUtil.toArray(
443 userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
444
445 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
446 for (long userGroupId : userGroupIds) {
447 userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
448 }
449 }
450
451 userPersistence.addUserGroups(userId, userGroupIds);
452 }
453
454
460 @Override
461 public void addGroupUsers(long groupId, long[] userIds)
462 throws PortalException {
463
464 groupPersistence.addUsers(groupId, userIds);
465
466 reindex(userIds);
467
468 PermissionCacheUtil.clearCache(userIds);
469
470 addDefaultRolesAndTeams(groupId, userIds);
471 }
472
473
479 @Override
480 public void addOrganizationUsers(long organizationId, long[] userIds)
481 throws PortalException {
482
483 organizationPersistence.addUsers(organizationId, userIds);
484
485 reindex(userIds);
486
487 PermissionCacheUtil.clearCache(userIds);
488 }
489
490
497 @Override
498 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds) {
499 passwordPolicyRelLocalService.addPasswordPolicyRels(
500 passwordPolicyId, User.class.getName(), userIds);
501 }
502
503
509 @Override
510 public void addRoleUsers(long roleId, long[] userIds)
511 throws PortalException {
512
513 rolePersistence.addUsers(roleId, userIds);
514
515 reindex(userIds);
516
517 PermissionCacheUtil.clearCache(userIds);
518 }
519
520
526 @Override
527 public void addTeamUsers(long teamId, long[] userIds)
528 throws PortalException {
529
530 teamPersistence.addUsers(teamId, userIds);
531
532 reindex(userIds);
533
534 PermissionCacheUtil.clearCache(userIds);
535 }
536
537
583 @Override
584 public User addUser(
585 long creatorUserId, long companyId, boolean autoPassword,
586 String password1, String password2, boolean autoScreenName,
587 String screenName, String emailAddress, long facebookId,
588 String openId, Locale locale, String firstName, String middleName,
589 String lastName, long prefixId, long suffixId, boolean male,
590 int birthdayMonth, int birthdayDay, int birthdayYear,
591 String jobTitle, long[] groupIds, long[] organizationIds,
592 long[] roleIds, long[] userGroupIds, boolean sendEmail,
593 ServiceContext serviceContext)
594 throws PortalException {
595
596 boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
597
598 try {
599 WorkflowThreadLocal.setEnabled(false);
600
601 if (serviceContext == null) {
602 serviceContext = new ServiceContext();
603 }
604
605 if (serviceContext.getWorkflowAction() !=
606 WorkflowConstants.ACTION_PUBLISH) {
607
608 serviceContext.setWorkflowAction(
609 WorkflowConstants.ACTION_PUBLISH);
610 }
611
612 return addUserWithWorkflow(
613 creatorUserId, companyId, autoPassword, password1, password2,
614 autoScreenName, screenName, emailAddress, facebookId, openId,
615 locale, firstName, middleName, lastName, prefixId, suffixId,
616 male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
617 groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
618 serviceContext);
619 }
620 finally {
621 WorkflowThreadLocal.setEnabled(workflowEnabled);
622 }
623 }
624
625
631 @Override
632 @SuppressWarnings("deprecation")
633 public void addUserGroupUsers(long userGroupId, long[] userIds)
634 throws PortalException {
635
636 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
637 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
638 }
639
640 userGroupPersistence.addUsers(userGroupId, userIds);
641
642 reindex(userIds);
643
644 PermissionCacheUtil.clearCache(userIds);
645 }
646
647
693 @Override
694 @SuppressWarnings("deprecation")
695 public User addUserWithWorkflow(
696 long creatorUserId, long companyId, boolean autoPassword,
697 String password1, String password2, boolean autoScreenName,
698 String screenName, String emailAddress, long facebookId,
699 String openId, Locale locale, String firstName, String middleName,
700 String lastName, long prefixId, long suffixId, boolean male,
701 int birthdayMonth, int birthdayDay, int birthdayYear,
702 String jobTitle, long[] groupIds, long[] organizationIds,
703 long[] roleIds, long[] userGroupIds, boolean sendEmail,
704 ServiceContext serviceContext)
705 throws PortalException {
706
707
708
709 Company company = companyPersistence.findByPrimaryKey(companyId);
710 screenName = getLogin(screenName);
711 openId = StringUtil.trim(openId);
712
713 if (PrefsPropsUtil.getBoolean(
714 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
715
716 autoScreenName = true;
717 }
718
719
720
721 long userId = counterLocalService.increment();
722
723 EmailAddressGenerator emailAddressGenerator =
724 EmailAddressGeneratorFactory.getInstance();
725
726 if ((emailAddress == null) ||
727 emailAddressGenerator.isGenerated(emailAddress)) {
728
729 emailAddress = StringPool.BLANK;
730 }
731 else {
732 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
733 }
734
735 if (!PrefsPropsUtil.getBoolean(
736 companyId, PropsKeys.USERS_EMAIL_ADDRESS_REQUIRED) &&
737 Validator.isNull(emailAddress)) {
738
739 emailAddress = emailAddressGenerator.generate(companyId, userId);
740 }
741
742 validate(
743 companyId, userId, autoPassword, password1, password2,
744 autoScreenName, screenName, emailAddress, openId, firstName,
745 middleName, lastName, organizationIds, locale);
746
747 if (!autoPassword) {
748 if (Validator.isNull(password1) || Validator.isNull(password2)) {
749 throw new UserPasswordException.MustNotBeNull(userId);
750 }
751 }
752
753 if (autoScreenName) {
754 ScreenNameGenerator screenNameGenerator =
755 ScreenNameGeneratorFactory.getInstance();
756
757 try {
758 screenName = screenNameGenerator.generate(
759 companyId, userId, emailAddress);
760 }
761 catch (Exception e) {
762 throw new SystemException(e);
763 }
764 }
765
766 User defaultUser = getDefaultUser(companyId);
767
768 FullNameGenerator fullNameGenerator =
769 FullNameGeneratorFactory.getInstance();
770
771 String fullName = fullNameGenerator.getFullName(
772 firstName, middleName, lastName);
773
774 String greeting = LanguageUtil.format(
775 locale, "welcome-x", fullName, false);
776
777 User user = userPersistence.create(userId);
778
779 if (serviceContext != null) {
780 String uuid = serviceContext.getUuid();
781
782 if (Validator.isNotNull(uuid)) {
783 user.setUuid(uuid);
784 }
785 }
786
787 user.setCompanyId(companyId);
788 user.setDefaultUser(false);
789 user.setContactId(counterLocalService.increment());
790
791 if (Validator.isNotNull(password1)) {
792 user.setPassword(PasswordEncryptorUtil.encrypt(password1));
793 user.setPasswordUnencrypted(password1);
794 }
795
796 user.setPasswordEncrypted(true);
797
798 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
799
800 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
801 passwordPolicy.isChangeRequired()) {
802
803 user.setPasswordReset(true);
804 }
805 else {
806 user.setPasswordReset(false);
807 }
808
809 user.setDigest(StringPool.BLANK);
810 user.setScreenName(screenName);
811 user.setEmailAddress(emailAddress);
812 user.setFacebookId(facebookId);
813
814 Long ldapServerId = null;
815
816 if (serviceContext != null) {
817 ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
818 }
819
820 if (ldapServerId != null) {
821 user.setLdapServerId(ldapServerId);
822 }
823 else {
824 user.setLdapServerId(-1);
825 }
826
827 user.setOpenId(openId);
828 user.setLanguageId(LocaleUtil.toLanguageId(locale));
829 user.setTimeZoneId(defaultUser.getTimeZoneId());
830 user.setGreeting(greeting);
831 user.setFirstName(firstName);
832 user.setMiddleName(middleName);
833 user.setLastName(lastName);
834 user.setJobTitle(jobTitle);
835 user.setStatus(WorkflowConstants.STATUS_DRAFT);
836 user.setExpandoBridgeAttributes(serviceContext);
837
838 userPersistence.update(user, serviceContext);
839
840
841
842 String creatorUserName = StringPool.BLANK;
843
844 if (creatorUserId <= 0) {
845 creatorUserId = user.getUserId();
846
847
848
849
850
851 }
852 else {
853 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
854
855 creatorUserName = creatorUser.getFullName();
856 }
857
858 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
859
860 Contact contact = contactPersistence.create(user.getContactId());
861
862 contact.setCompanyId(user.getCompanyId());
863 contact.setUserId(creatorUserId);
864 contact.setUserName(creatorUserName);
865 contact.setClassName(User.class.getName());
866 contact.setClassPK(user.getUserId());
867 contact.setAccountId(company.getAccountId());
868 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
869 contact.setEmailAddress(user.getEmailAddress());
870 contact.setFirstName(firstName);
871 contact.setMiddleName(middleName);
872 contact.setLastName(lastName);
873 contact.setPrefixId(prefixId);
874 contact.setSuffixId(suffixId);
875 contact.setMale(male);
876 contact.setBirthday(birthday);
877 contact.setJobTitle(jobTitle);
878
879 contactPersistence.update(contact, serviceContext);
880
881
882
883 groupLocalService.addGroup(
884 user.getUserId(), GroupConstants.DEFAULT_PARENT_GROUP_ID,
885 User.class.getName(), user.getUserId(),
886 GroupConstants.DEFAULT_LIVE_GROUP_ID, (Map<Locale, String>)null,
887 null, 0, true, GroupConstants.DEFAULT_MEMBERSHIP_RESTRICTION,
888 StringPool.SLASH + screenName, false, true, null);
889
890
891
892 if (!ArrayUtil.isEmpty(groupIds)) {
893 List<Group> groups = new ArrayList<>();
894
895 for (long groupId : groupIds) {
896 Group group = groupLocalService.fetchGroup(groupId);
897
898 if (group != null) {
899 groups.add(group);
900 }
901 else {
902 if (_log.isWarnEnabled()) {
903 _log.warn("Group " + groupId + " does not exist");
904 }
905 }
906 }
907
908 groupLocalService.addUserGroups(userId, groups);
909 }
910
911 addDefaultGroups(userId);
912
913
914
915 updateOrganizations(userId, organizationIds, false);
916
917
918
919 if (roleIds != null) {
920 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
921
922 userPersistence.setRoles(userId, roleIds);
923 }
924
925 addDefaultRoles(userId);
926
927
928
929 if (userGroupIds != null) {
930 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
931 for (long userGroupId : userGroupIds) {
932 userGroupLocalService.copyUserGroupLayouts(
933 userGroupId, new long[] {userId});
934 }
935 }
936
937 userPersistence.setUserGroups(userId, userGroupIds);
938 }
939
940 addDefaultUserGroups(userId);
941
942
943
944 resourceLocalService.addResources(
945 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
946 false, false, false);
947
948
949
950 if (serviceContext != null) {
951 updateAsset(
952 creatorUserId, user, serviceContext.getAssetCategoryIds(),
953 serviceContext.getAssetTagNames());
954 }
955
956
957
958 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
959 reindex(user);
960 }
961
962
963
964 long workflowUserId = creatorUserId;
965
966 if (workflowUserId == userId) {
967 workflowUserId = defaultUser.getUserId();
968 }
969
970 ServiceContext workflowServiceContext = serviceContext;
971
972 if (workflowServiceContext == null) {
973 workflowServiceContext = new ServiceContext();
974 }
975
976 workflowServiceContext.setAttribute("autoPassword", autoPassword);
977 workflowServiceContext.setAttribute("passwordUnencrypted", password1);
978 workflowServiceContext.setAttribute("sendEmail", sendEmail);
979
980 WorkflowHandlerRegistryUtil.startWorkflowInstance(
981 companyId, workflowUserId, User.class.getName(), userId, user,
982 workflowServiceContext);
983
984 if (serviceContext != null) {
985 String passwordUnencrypted = (String)serviceContext.getAttribute(
986 "passwordUnencrypted");
987
988 if (Validator.isNotNull(passwordUnencrypted)) {
989 user.setPasswordUnencrypted(passwordUnencrypted);
990 }
991 }
992
993 return user;
994 }
995
996 @Override
997 public void afterPropertiesSet() {
998 super.afterPropertiesSet();
999
1000 PortalCache<Serializable, Serializable> portalCache =
1001 EntityCacheUtil.getPortalCache(UserImpl.class);
1002
1003 PortalCacheMapSynchronizeUtil.synchronize(
1004 portalCache, _defaultUsers,
1005 new Synchronizer<Serializable, Serializable>() {
1006
1007 @Override
1008 public void onSynchronize(
1009 Map<? extends Serializable, ? extends Serializable> map,
1010 Serializable key, Serializable value, int timeToLive) {
1011
1012 if (!(value instanceof UserCacheModel)) {
1013 return;
1014 }
1015
1016 UserCacheModel userCacheModel = (UserCacheModel)value;
1017
1018 if (userCacheModel.defaultUser) {
1019 _defaultUsers.remove(userCacheModel.companyId);
1020 }
1021 }
1022
1023 });
1024 }
1025
1026
1045 @Override
1046 public int authenticateByEmailAddress(
1047 long companyId, String emailAddress, String password,
1048 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1049 Map<String, Object> resultsMap)
1050 throws PortalException {
1051
1052 return authenticate(
1053 companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
1054 headerMap, parameterMap, resultsMap);
1055 }
1056
1057
1076 @Override
1077 public int authenticateByScreenName(
1078 long companyId, String screenName, String password,
1079 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1080 Map<String, Object> resultsMap)
1081 throws PortalException {
1082
1083 return authenticate(
1084 companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
1085 headerMap, parameterMap, resultsMap);
1086 }
1087
1088
1107 @Override
1108 public int authenticateByUserId(
1109 long companyId, long userId, String password,
1110 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1111 Map<String, Object> resultsMap)
1112 throws PortalException {
1113
1114 return authenticate(
1115 companyId, String.valueOf(userId), password,
1116 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap, resultsMap);
1117 }
1118
1119
1152 @Override
1153 @Transactional(propagation = Propagation.SUPPORTS)
1154 public long authenticateForBasic(
1155 long companyId, String authType, String login, String password)
1156 throws PortalException {
1157
1158 if (PropsValues.AUTH_LOGIN_DISABLED) {
1159 return 0;
1160 }
1161
1162 User user = null;
1163
1164 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1165 user = fetchUserByEmailAddress(companyId, login);
1166 }
1167 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1168 user = fetchUserByScreenName(companyId, login);
1169 }
1170 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1171 user = userPersistence.fetchByPrimaryKey(GetterUtil.getLong(login));
1172 }
1173
1174 if (user == null) {
1175 return 0;
1176 }
1177
1178 if (!isUserAllowedToAuthenticate(user)) {
1179 return 0;
1180 }
1181
1182 if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
1183 return user.getUserId();
1184 }
1185
1186 String userPassword = user.getPassword();
1187
1188 if (!user.isPasswordEncrypted()) {
1189 userPassword = PasswordEncryptorUtil.encrypt(userPassword);
1190 }
1191
1192 String encPassword = PasswordEncryptorUtil.encrypt(
1193 password, userPassword);
1194
1195 if (userPassword.equals(password) || userPassword.equals(encPassword)) {
1196 resetFailedLoginAttempts(user);
1197
1198 return user.getUserId();
1199 }
1200
1201 handleAuthenticationFailure(
1202 login, authType, user, Collections.<String, String[]>emptyMap(),
1203 Collections.<String, String[]>emptyMap());
1204
1205 return 0;
1206 }
1207
1208
1224 @Override
1225 @Transactional(propagation = Propagation.SUPPORTS)
1226 public long authenticateForDigest(
1227 long companyId, String username, String realm, String nonce,
1228 String method, String uri, String response)
1229 throws PortalException {
1230
1231 if (PropsValues.AUTH_LOGIN_DISABLED) {
1232 return 0;
1233 }
1234
1235
1236
1237 User user = fetchUserByEmailAddress(companyId, username);
1238
1239 if (user == null) {
1240 user = fetchUserByScreenName(companyId, username);
1241 }
1242
1243 if (user == null) {
1244 user = userPersistence.fetchByPrimaryKey(
1245 GetterUtil.getLong(username));
1246 }
1247
1248 if (user == null) {
1249 return 0;
1250 }
1251
1252 if (!isUserAllowedToAuthenticate(user)) {
1253 return 0;
1254 }
1255
1256
1257
1258 String digest = user.getDigest();
1259
1260 if (Validator.isNull(digest)) {
1261 _log.error(
1262 "User must first login through the portal " + user.getUserId());
1263
1264 return 0;
1265 }
1266
1267 String[] digestArray = StringUtil.split(user.getDigest());
1268
1269 for (String ha1 : digestArray) {
1270 String ha2 = DigesterUtil.digestHex(Digester.MD5, method, uri);
1271
1272 String curResponse = DigesterUtil.digestHex(
1273 Digester.MD5, ha1, nonce, ha2);
1274
1275 if (response.equals(curResponse)) {
1276 resetFailedLoginAttempts(user);
1277
1278 return user.getUserId();
1279 }
1280 }
1281
1282 Company company = companyPersistence.findByPrimaryKey(companyId);
1283
1284 handleAuthenticationFailure(
1285 username, company.getAuthType(), user,
1286 new HashMap<String, String[]>(), new HashMap<String, String[]>());
1287
1288 return 0;
1289 }
1290
1291
1300 @Override
1301 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1302 public boolean authenticateForJAAS(long userId, String encPassword) {
1303 if (PropsValues.AUTH_LOGIN_DISABLED) {
1304 return false;
1305 }
1306
1307 try {
1308 User user = userPersistence.findByPrimaryKey(userId);
1309
1310 if (user.isDefaultUser()) {
1311 if (_log.isInfoEnabled()) {
1312 _log.info(
1313 "JAAS authentication is disabled for the default user");
1314 }
1315
1316 return false;
1317 }
1318 else if (!user.isActive()) {
1319 if (_log.isInfoEnabled()) {
1320 _log.info(
1321 "JAAS authentication is disabled for inactive user " +
1322 userId);
1323 }
1324
1325 return false;
1326 }
1327
1328 String userPassword = user.getPassword();
1329
1330 if (user.isPasswordEncrypted()) {
1331 if (userPassword.equals(encPassword)) {
1332 return true;
1333 }
1334
1335 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1336 encPassword = PasswordEncryptorUtil.encrypt(
1337 encPassword, userPassword);
1338
1339 if (userPassword.equals(encPassword)) {
1340 return true;
1341 }
1342 }
1343 }
1344 else {
1345 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1346 if (userPassword.equals(encPassword)) {
1347 return true;
1348 }
1349 }
1350
1351 userPassword = PasswordEncryptorUtil.encrypt(
1352 userPassword, encPassword);
1353
1354 if (userPassword.equals(encPassword)) {
1355 return true;
1356 }
1357 }
1358 }
1359 catch (Exception e) {
1360 _log.error(e);
1361 }
1362
1363 return false;
1364 }
1365
1366
1372 @Override
1373 public void checkLockout(User user) throws PortalException {
1374 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1375 return;
1376 }
1377
1378 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1379
1380 if (!passwordPolicy.isLockout()) {
1381 return;
1382 }
1383
1384
1385
1386 Date now = new Date();
1387 int failedLoginAttempts = user.getFailedLoginAttempts();
1388
1389 if (failedLoginAttempts > 0) {
1390 long failedLoginTime = user.getLastFailedLoginDate().getTime();
1391 long elapsedTime = now.getTime() - failedLoginTime;
1392 long requiredElapsedTime =
1393 passwordPolicy.getResetFailureCount() * 1000;
1394
1395 if ((requiredElapsedTime != 0) &&
1396 (elapsedTime > requiredElapsedTime)) {
1397
1398 user.setFailedLoginAttempts(0);
1399
1400 userPersistence.update(user);
1401 }
1402 }
1403
1404
1405
1406 if (user.isLockout()) {
1407 long lockoutTime = user.getLockoutDate().getTime();
1408 long elapsedTime = now.getTime() - lockoutTime;
1409 long requiredElapsedTime =
1410 passwordPolicy.getLockoutDuration() * 1000;
1411
1412 if ((requiredElapsedTime != 0) &&
1413 (elapsedTime > requiredElapsedTime)) {
1414
1415 user.setLockout(false);
1416 user.setLockoutDate(null);
1417
1418 userPersistence.update(user);
1419 }
1420 }
1421
1422 if (user.isLockout()) {
1423 throw new UserLockoutException.PasswordPolicyLockout(
1424 user, passwordPolicy);
1425 }
1426 }
1427
1428
1434 @Override
1435 public void checkLoginFailure(User user) {
1436 int failedLoginAttempts = user.getFailedLoginAttempts();
1437
1438 user.setLastFailedLoginDate(new Date());
1439 user.setFailedLoginAttempts(++failedLoginAttempts);
1440
1441 userPersistence.update(user);
1442 }
1443
1444
1451 @Override
1452 public void checkLoginFailureByEmailAddress(
1453 long companyId, String emailAddress)
1454 throws PortalException {
1455
1456 User user = getUserByEmailAddress(companyId, emailAddress);
1457
1458 checkLoginFailure(user);
1459 }
1460
1461
1467 @Override
1468 public void checkLoginFailureById(long userId) throws PortalException {
1469 User user = userPersistence.findByPrimaryKey(userId);
1470
1471 checkLoginFailure(user);
1472 }
1473
1474
1481 @Override
1482 public void checkLoginFailureByScreenName(long companyId, String screenName)
1483 throws PortalException {
1484
1485 User user = getUserByScreenName(companyId, screenName);
1486
1487 checkLoginFailure(user);
1488 }
1489
1490
1497 @Override
1498 public void checkPasswordExpired(User user) throws PortalException {
1499 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1500 return;
1501 }
1502
1503 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1504
1505
1506
1507 if (isPasswordExpired(user)) {
1508 int graceLoginCount = user.getGraceLoginCount();
1509
1510 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
1511 user.setGraceLoginCount(++graceLoginCount);
1512
1513 userPersistence.update(user);
1514 }
1515 else {
1516 user.setDigest(StringPool.BLANK);
1517
1518 userPersistence.update(user);
1519
1520 throw new PasswordExpiredException();
1521 }
1522 }
1523
1524
1525
1526 if (passwordPolicy.isChangeable() &&
1527 passwordPolicy.isChangeRequired()) {
1528
1529 if (user.getLastLoginDate() == null) {
1530 user.setPasswordReset(true);
1531
1532 userPersistence.update(user);
1533 }
1534 }
1535 }
1536
1537
1542 @Override
1543 public void clearOrganizationUsers(long organizationId) {
1544 organizationPersistence.clearUsers(organizationId);
1545
1546 PermissionCacheUtil.clearCache();
1547 }
1548
1549
1554 @Override
1555 public void clearUserGroupUsers(long userGroupId) {
1556 userGroupPersistence.clearUsers(userGroupId);
1557
1558 PermissionCacheUtil.clearCache();
1559 }
1560
1561
1574 @Override
1575 public void completeUserRegistration(
1576 User user, ServiceContext serviceContext)
1577 throws PortalException {
1578
1579 boolean autoPassword = ParamUtil.getBoolean(
1580 serviceContext, "autoPassword");
1581
1582 String password = (String)serviceContext.getAttribute(
1583 "passwordUnencrypted");
1584
1585 if (autoPassword) {
1586 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1587 if (_log.isWarnEnabled()) {
1588 StringBundler sb = new StringBundler(4);
1589
1590 sb.append("When LDAP password policy is enabled, it is ");
1591 sb.append("possible that portal generated passwords will ");
1592 sb.append("not match the LDAP policy. Using ");
1593 sb.append("RegExpToolkit to generate new password.");
1594
1595 _log.warn(sb.toString());
1596 }
1597
1598 RegExpToolkit regExpToolkit = new RegExpToolkit();
1599
1600 password = regExpToolkit.generate(null);
1601 }
1602 else {
1603 PasswordPolicy passwordPolicy =
1604 passwordPolicyLocalService.getPasswordPolicy(
1605 user.getCompanyId(), user.getOrganizationIds());
1606
1607 password = PwdToolkitUtil.generate(passwordPolicy);
1608 }
1609
1610 serviceContext.setAttribute("passwordUnencrypted", password);
1611
1612 user.setPassword(PasswordEncryptorUtil.encrypt(password));
1613 user.setPasswordUnencrypted(password);
1614 user.setPasswordEncrypted(true);
1615 user.setPasswordModified(true);
1616 user.setPasswordModifiedDate(new Date());
1617
1618 userPersistence.update(user);
1619
1620 user.setPasswordModified(false);
1621 }
1622
1623 if (user.hasCompanyMx()) {
1624 mailService.addUser(
1625 user.getCompanyId(), user.getUserId(), password,
1626 user.getFirstName(), user.getMiddleName(), user.getLastName(),
1627 user.getEmailAddress());
1628 }
1629
1630 boolean sendEmail = ParamUtil.getBoolean(serviceContext, "sendEmail");
1631
1632 if (sendEmail) {
1633 notifyUser(user, password, serviceContext);
1634 }
1635
1636 Company company = companyPersistence.findByPrimaryKey(
1637 user.getCompanyId());
1638
1639 if (company.isStrangersVerify()) {
1640 sendEmailAddressVerification(
1641 user, user.getEmailAddress(), serviceContext);
1642 }
1643 }
1644
1645
1655 @Override
1656 public KeyValuePair decryptUserId(
1657 long companyId, String name, String password)
1658 throws PortalException {
1659
1660 Company company = companyPersistence.findByPrimaryKey(companyId);
1661
1662 try {
1663 name = Encryptor.decrypt(company.getKeyObj(), name);
1664 }
1665 catch (EncryptorException ee) {
1666 throw new SystemException(ee);
1667 }
1668
1669 long userId = GetterUtil.getLong(name);
1670
1671 User user = userPersistence.findByPrimaryKey(userId);
1672
1673 try {
1674 password = Encryptor.decrypt(company.getKeyObj(), password);
1675 }
1676 catch (EncryptorException ee) {
1677 throw new SystemException(ee);
1678 }
1679
1680 String userPassword = user.getPassword();
1681 String encPassword = PasswordEncryptorUtil.encrypt(
1682 password, userPassword);
1683
1684 if (userPassword.equals(encPassword)) {
1685 if (isPasswordExpired(user)) {
1686 user.setPasswordReset(true);
1687
1688 userPersistence.update(user);
1689 }
1690
1691 return new KeyValuePair(name, password);
1692 }
1693 else {
1694 throw new PrincipalException.MustBeAuthenticated(userId);
1695 }
1696 }
1697
1698
1703 @Override
1704 public void deletePortrait(long userId) throws PortalException {
1705 User user = userPersistence.findByPrimaryKey(userId);
1706
1707 PortalUtil.updateImageId(user, false, null, "portraitId", 0, 0, 0);
1708 }
1709
1710
1716 @Override
1717 public void deleteRoleUser(long roleId, long userId)
1718 throws PortalException {
1719
1720 rolePersistence.removeUser(roleId, userId);
1721
1722 reindex(userId);
1723
1724 PermissionCacheUtil.clearCache(userId);
1725 }
1726
1727
1733 @Override
1734 public User deleteUser(long userId) throws PortalException {
1735 User user = userPersistence.findByPrimaryKey(userId);
1736
1737 return deleteUser(user);
1738 }
1739
1740
1746 @Override
1747 public User deleteUser(User user) throws PortalException {
1748 if (!PropsValues.USERS_DELETE) {
1749 throw new RequiredUserException();
1750 }
1751
1752
1753
1754 browserTrackerLocalService.deleteUserBrowserTracker(user.getUserId());
1755
1756
1757
1758 Group group = null;
1759
1760 if (!user.isDefaultUser()) {
1761 group = user.getGroup();
1762 }
1763
1764 if (group != null) {
1765 groupLocalService.deleteGroup(group);
1766 }
1767
1768
1769
1770 try {
1771 imageLocalService.deleteImage(user.getPortraitId());
1772 }
1773 catch (NoSuchImageException nsie) {
1774 if (_log.isWarnEnabled()) {
1775 _log.warn(
1776 "Unable to delete image " + user.getPortraitId(), nsie);
1777 }
1778 }
1779
1780
1781
1782 passwordPolicyRelLocalService.deletePasswordPolicyRel(
1783 User.class.getName(), user.getUserId());
1784
1785
1786
1787 passwordTrackerLocalService.deletePasswordTrackers(user.getUserId());
1788
1789
1790
1791 subscriptionLocalService.deleteSubscriptions(user.getUserId());
1792
1793
1794
1795 userIdMapperLocalService.deleteUserIdMappers(user.getUserId());
1796
1797
1798
1799 announcementsDeliveryLocalService.deleteDeliveries(user.getUserId());
1800
1801
1802
1803 assetEntryLocalService.deleteEntry(
1804 User.class.getName(), user.getUserId());
1805
1806
1807
1808 blogsStatsUserLocalService.deleteStatsUserByUserId(user.getUserId());
1809
1810
1811
1812 dlFileRankLocalService.deleteFileRanksByUserId(user.getUserId());
1813
1814
1815
1816 expandoRowLocalService.deleteRows(user.getUserId());
1817
1818
1819
1820 mbBanLocalService.deleteBansByBanUserId(user.getUserId());
1821 mbStatsUserLocalService.deleteStatsUsersByUserId(user.getUserId());
1822 mbThreadFlagLocalService.deleteThreadFlagsByUserId(user.getUserId());
1823
1824
1825
1826 membershipRequestLocalService.deleteMembershipRequestsByUserId(
1827 user.getUserId());
1828
1829
1830
1831 ratingsStatsLocalService.deleteStats(
1832 User.class.getName(), user.getUserId());
1833
1834
1835
1836 socialActivityLocalService.deleteUserActivities(user.getUserId());
1837 socialRequestLocalService.deleteReceiverUserRequests(user.getUserId());
1838 socialRequestLocalService.deleteUserRequests(user.getUserId());
1839
1840
1841
1842 mailService.deleteUser(user.getCompanyId(), user.getUserId());
1843
1844
1845
1846 Contact contact = contactLocalService.fetchContact(user.getContactId());
1847
1848 if (contact != null) {
1849 contactLocalService.deleteContact(contact);
1850 }
1851
1852
1853
1854 userGroupRoleLocalService.deleteUserGroupRolesByUserId(
1855 user.getUserId());
1856
1857
1858
1859 recentLayoutBranchLocalService.deleteUserRecentLayoutBranches(
1860 user.getUserId());
1861 recentLayoutRevisionLocalService.deleteUserRecentLayoutRevisions(
1862 user.getUserId());
1863 recentLayoutSetBranchLocalService.deleteUserRecentLayoutSetBranches(
1864 user.getUserId());
1865
1866
1867
1868 resourceLocalService.deleteResource(
1869 user.getCompanyId(), User.class.getName(),
1870 ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
1871
1872
1873
1874 userPersistence.remove(user);
1875
1876
1877
1878 PermissionCacheUtil.clearCache(user.getUserId());
1879
1880
1881
1882 workflowInstanceLinkLocalService.deleteWorkflowInstanceLinks(
1883 user.getCompanyId(), 0, User.class.getName(), user.getUserId());
1884
1885 return user;
1886 }
1887
1888
1894 @Override
1895 public void deleteUserGroupUser(long userGroupId, long userId)
1896 throws PortalException {
1897
1898 userGroupPersistence.removeUser(userGroupId, userId);
1899
1900 reindex(userId);
1901
1902 PermissionCacheUtil.clearCache(userId);
1903 }
1904
1905
1912 @Override
1913 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1914 public String encryptUserId(String name) throws PortalException {
1915 long userId = GetterUtil.getLong(name);
1916
1917 User user = userPersistence.findByPrimaryKey(userId);
1918
1919 Company company = companyPersistence.findByPrimaryKey(
1920 user.getCompanyId());
1921
1922 try {
1923 return Encryptor.encrypt(company.getKeyObj(), name);
1924 }
1925 catch (EncryptorException ee) {
1926 throw new SystemException(ee);
1927 }
1928 }
1929
1930
1937 @Override
1938 public User fetchUserByContactId(long contactId) {
1939 return userPersistence.fetchByContactId(contactId);
1940 }
1941
1942
1950 @Override
1951 public User fetchUserByEmailAddress(long companyId, String emailAddress) {
1952 emailAddress = getLogin(emailAddress);
1953
1954 return userPersistence.fetchByC_EA(companyId, emailAddress);
1955 }
1956
1957
1965 @Override
1966 public User fetchUserByFacebookId(long companyId, long facebookId) {
1967 return userPersistence.fetchByC_FID(companyId, facebookId);
1968 }
1969
1970
1977 @Override
1978 public User fetchUserById(long userId) {
1979 return userPersistence.fetchByPrimaryKey(userId);
1980 }
1981
1982
1990 @Override
1991 public User fetchUserByOpenId(long companyId, String openId) {
1992 return userPersistence.fetchByC_O(companyId, openId);
1993 }
1994
1995
2002 @Override
2003 public User fetchUserByPortraitId(long portraitId) {
2004 return userPersistence.fetchByPortraitId(portraitId);
2005 }
2006
2007
2015 @Override
2016 public User fetchUserByScreenName(long companyId, String screenName) {
2017 screenName = getLogin(screenName);
2018
2019 return userPersistence.fetchByC_SN(companyId, screenName);
2020 }
2021
2022
2039 @Override
2040 public List<User> getCompanyUsers(long companyId, int start, int end) {
2041 return userPersistence.findByCompanyId(companyId, start, end);
2042 }
2043
2044
2050 @Override
2051 public int getCompanyUsersCount(long companyId) {
2052 return userPersistence.countByCompanyId(companyId);
2053 }
2054
2055
2061 @Override
2062 @Skip
2063 public User getDefaultUser(long companyId) throws PortalException {
2064 User userModel = _defaultUsers.get(companyId);
2065
2066 if (userModel == null) {
2067 userModel = userLocalService.loadGetDefaultUser(companyId);
2068
2069 _defaultUsers.put(companyId, userModel);
2070 }
2071
2072 return userModel;
2073 }
2074
2075
2081 @Override
2082 @Skip
2083 public long getDefaultUserId(long companyId) throws PortalException {
2084 User user = getDefaultUser(companyId);
2085
2086 return user.getUserId();
2087 }
2088
2089
2095 @Override
2096 public long[] getGroupUserIds(long groupId) {
2097 return groupPersistence.getUserPrimaryKeys(groupId);
2098 }
2099
2100
2107 @Override
2108 public int getGroupUsersCount(long groupId, int status)
2109 throws PortalException {
2110
2111 Group group = groupPersistence.findByPrimaryKey(groupId);
2112
2113 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2114
2115 params.put("usersGroups", Long.valueOf(groupId));
2116
2117 return searchCount(group.getCompanyId(), null, status, params);
2118 }
2119
2120 @Override
2121 public List<User> getInheritedRoleUsers(
2122 long roleId, int start, int end, OrderByComparator<User> obc)
2123 throws PortalException {
2124
2125 Role role = rolePersistence.findByPrimaryKey(roleId);
2126
2127 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2128
2129 params.put("inherit", Boolean.TRUE);
2130 params.put("usersRoles", roleId);
2131
2132 return search(
2133 role.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2134 params, start, end, obc);
2135 }
2136
2137
2144 @Override
2145 public List<User> getNoAnnouncementsDeliveries(String type) {
2146 return userFinder.findByNoAnnouncementsDeliveries(type);
2147 }
2148
2149
2154 @Override
2155 public List<User> getNoContacts() {
2156 return userFinder.findByNoContacts();
2157 }
2158
2159
2165 @Override
2166 public List<User> getNoGroups() {
2167 return userFinder.findByNoGroups();
2168 }
2169
2170
2176 @Override
2177 public long[] getOrganizationUserIds(long organizationId) {
2178 return organizationPersistence.getUserPrimaryKeys(organizationId);
2179 }
2180
2181
2189 @Override
2190 public int getOrganizationUsersCount(long organizationId, int status)
2191 throws PortalException {
2192
2193 Organization organization = organizationPersistence.findByPrimaryKey(
2194 organizationId);
2195
2196 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2197
2198 params.put("usersOrgs", Long.valueOf(organizationId));
2199
2200 return searchCount(organization.getCompanyId(), null, status, params);
2201 }
2202
2203
2209 @Override
2210 public long[] getRoleUserIds(long roleId) {
2211 return rolePersistence.getUserPrimaryKeys(roleId);
2212 }
2213
2214
2221 @Override
2222 public int getRoleUsersCount(long roleId, int status)
2223 throws PortalException {
2224
2225 Role role = rolePersistence.findByPrimaryKey(roleId);
2226
2227 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2228
2229 params.put("usersRoles", Long.valueOf(roleId));
2230
2231 return searchCount(role.getCompanyId(), null, status, params);
2232 }
2233
2234
2259 @Deprecated
2260 @Override
2261 public List<User> getSocialUsers(
2262 long userId, int socialRelationType, int start, int end,
2263 OrderByComparator<User> obc)
2264 throws PortalException {
2265
2266 return getSocialUsers(
2267 userId, socialRelationType, StringPool.EQUAL, start, end, obc);
2268 }
2269
2270
2293 @Deprecated
2294 @Override
2295 public List<User> getSocialUsers(
2296 long userId, int start, int end, OrderByComparator<User> obc)
2297 throws PortalException {
2298
2299 return getSocialUsers(
2300 userId, SocialRelationConstants.TYPE_UNI_ENEMY,
2301 StringPool.NOT_EQUAL, start, end, obc);
2302 }
2303
2304 @Override
2305 public List<User> getSocialUsers(
2306 long userId, int socialRelationType,
2307 String socialRelationTypeComparator, int start, int end,
2308 OrderByComparator<User> obc)
2309 throws PortalException {
2310
2311 if (!socialRelationTypeComparator.equals(StringPool.EQUAL) &&
2312 !socialRelationTypeComparator.equals(StringPool.NOT_EQUAL)) {
2313
2314 throw new IllegalArgumentException(
2315 "Invalid social relation type comparator " +
2316 socialRelationTypeComparator);
2317 }
2318
2319 if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS)) {
2320 List<SocialRelation> socialRelations =
2321 socialRelationPersistence.findByU1_T(
2322 userId, socialRelationType);
2323
2324 if (socialRelationTypeComparator.equals(StringPool.NOT_EQUAL)) {
2325 socialRelations = ListUtil.remove(
2326 socialRelationPersistence.findByUserId1(userId),
2327 socialRelations);
2328 }
2329
2330 List<User> users = new ArrayList<>();
2331
2332 for (SocialRelation socialRelation : socialRelations) {
2333 User user = userPersistence.findByPrimaryKey(
2334 socialRelation.getUserId2());
2335
2336 if (user.isDefaultUser() ||
2337 (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {
2338
2339 continue;
2340 }
2341
2342 if (!users.contains(user)) {
2343 users.add(user);
2344 }
2345 }
2346
2347 if (obc != null) {
2348 users = ListUtil.sort(users, obc);
2349 }
2350
2351 return users;
2352 }
2353
2354 User user = userPersistence.findByPrimaryKey(userId);
2355
2356 return userFinder.findBySocialUsers(
2357 user.getCompanyId(), userId, socialRelationType,
2358 socialRelationTypeComparator, WorkflowConstants.STATUS_APPROVED,
2359 start, end, obc);
2360 }
2361
2362
2386 @Override
2387 public List<User> getSocialUsers(
2388 long userId1, long userId2, int socialRelationType, int start,
2389 int end, OrderByComparator<User> obc)
2390 throws PortalException {
2391
2392 User user1 = userPersistence.findByPrimaryKey(userId1);
2393
2394 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2395
2396 params.put(
2397 "socialMutualRelationType",
2398 new Long[] {
2399 userId1, Long.valueOf(socialRelationType), userId2,
2400 Long.valueOf(socialRelationType)
2401 });
2402
2403 return search(
2404 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2405 params, start, end, obc);
2406 }
2407
2408
2430 @Override
2431 public List<User> getSocialUsers(
2432 long userId1, long userId2, int start, int end,
2433 OrderByComparator<User> obc)
2434 throws PortalException {
2435
2436 User user1 = userPersistence.findByPrimaryKey(userId1);
2437
2438 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2439
2440 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2441
2442 return search(
2443 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2444 params, start, end, obc);
2445 }
2446
2447
2455 @Deprecated
2456 @Override
2457 public int getSocialUsersCount(long userId) throws PortalException {
2458 return getSocialUsersCount(
2459 userId, SocialRelationConstants.TYPE_UNI_ENEMY,
2460 StringPool.NOT_EQUAL);
2461 }
2462
2463
2475 @Deprecated
2476 @Override
2477 public int getSocialUsersCount(long userId, int socialRelationType)
2478 throws PortalException {
2479
2480 return getSocialUsersCount(
2481 userId, socialRelationType, StringPool.EQUAL);
2482 }
2483
2484
2492 @Override
2493 public int getSocialUsersCount(
2494 long userId, int socialRelationType,
2495 String socialRelationTypeComparator)
2496 throws PortalException {
2497
2498 User user = userPersistence.findByPrimaryKey(userId);
2499
2500 if (!socialRelationTypeComparator.equals(StringPool.EQUAL) &&
2501 !socialRelationTypeComparator.equals(StringPool.NOT_EQUAL)) {
2502
2503 throw new IllegalArgumentException(
2504 "Invalid social relation type comparator " +
2505 socialRelationTypeComparator);
2506 }
2507
2508 return userFinder.countBySocialUsers(
2509 user.getCompanyId(), user.getUserId(), socialRelationType,
2510 socialRelationTypeComparator, WorkflowConstants.STATUS_APPROVED);
2511 }
2512
2513
2521 @Override
2522 public int getSocialUsersCount(long userId1, long userId2)
2523 throws PortalException {
2524
2525 User user1 = userPersistence.findByPrimaryKey(userId1);
2526
2527 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2528
2529 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2530
2531 return searchCount(
2532 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2533 params);
2534 }
2535
2536
2547 @Override
2548 public int getSocialUsersCount(
2549 long userId1, long userId2, int socialRelationType)
2550 throws PortalException {
2551
2552 User user1 = userPersistence.findByPrimaryKey(userId1);
2553
2554 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2555
2556 params.put(
2557 "socialMutualRelationType",
2558 new Long[] {
2559 userId1, Long.valueOf(socialRelationType), userId2,
2560 Long.valueOf(socialRelationType)
2561 });
2562
2563 return searchCount(
2564 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2565 params);
2566 }
2567
2568
2574 @Override
2575 public User getUserByContactId(long contactId) throws PortalException {
2576 return userPersistence.findByContactId(contactId);
2577 }
2578
2579
2586 @Override
2587 public User getUserByEmailAddress(long companyId, String emailAddress)
2588 throws PortalException {
2589
2590 emailAddress = getLogin(emailAddress);
2591
2592 return userPersistence.findByC_EA(companyId, emailAddress);
2593 }
2594
2595
2602 @Override
2603 public User getUserByFacebookId(long companyId, long facebookId)
2604 throws PortalException {
2605
2606 return userPersistence.findByC_FID(companyId, facebookId);
2607 }
2608
2609
2615 @Override
2616 public User getUserById(long userId) throws PortalException {
2617 return userPersistence.findByPrimaryKey(userId);
2618 }
2619
2620
2627 @Override
2628 public User getUserById(long companyId, long userId)
2629 throws PortalException {
2630
2631 return userPersistence.findByC_U(companyId, userId);
2632 }
2633
2634
2641 @Override
2642 public User getUserByOpenId(long companyId, String openId)
2643 throws PortalException {
2644
2645 return userPersistence.findByC_O(companyId, openId);
2646 }
2647
2648
2654 @Override
2655 public User getUserByPortraitId(long portraitId) throws PortalException {
2656 return userPersistence.findByPortraitId(portraitId);
2657 }
2658
2659
2666 @Override
2667 public User getUserByScreenName(long companyId, String screenName)
2668 throws PortalException {
2669
2670 screenName = getLogin(screenName);
2671
2672 return userPersistence.findByC_SN(companyId, screenName);
2673 }
2674
2675
2683 @Deprecated
2684 @Override
2685 public User getUserByUuid(String uuid) throws PortalException {
2686 List<User> users = userPersistence.findByUuid(uuid);
2687
2688 if (users.isEmpty()) {
2689 throw new NoSuchUserException("{uuid=" + uuid + "}");
2690 }
2691 else {
2692 return users.get(0);
2693 }
2694 }
2695
2696
2703 @Override
2704 public User getUserByUuidAndCompanyId(String uuid, long companyId)
2705 throws PortalException {
2706
2707 List<User> users = userPersistence.findByUuid_C(uuid, companyId);
2708
2709 if (users.isEmpty()) {
2710 StringBundler sb = new StringBundler(5);
2711
2712 sb.append("{uuid=");
2713 sb.append(uuid);
2714 sb.append(", companyId=");
2715 sb.append(companyId);
2716 sb.append("}");
2717
2718 throw new NoSuchUserException(sb.toString());
2719 }
2720 else {
2721 return users.get(0);
2722 }
2723 }
2724
2725
2732 @Override
2733 public int getUserGroupUsersCount(long userGroupId, int status)
2734 throws PortalException {
2735
2736 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
2737 userGroupId);
2738
2739 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2740
2741 params.put("usersUserGroups", Long.valueOf(userGroupId));
2742
2743 return searchCount(userGroup.getCompanyId(), null, status, params);
2744 }
2745
2746
2753 @Override
2754 public long getUserIdByEmailAddress(long companyId, String emailAddress)
2755 throws PortalException {
2756
2757 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
2758
2759 User user = userPersistence.findByC_EA(companyId, emailAddress);
2760
2761 return user.getUserId();
2762 }
2763
2764
2771 @Override
2772 public long getUserIdByScreenName(long companyId, String screenName)
2773 throws PortalException {
2774
2775 screenName = getLogin(screenName);
2776
2777 User user = userPersistence.findByC_SN(companyId, screenName);
2778
2779 return user.getUserId();
2780 }
2781
2782
2791 @Override
2792 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId) {
2793 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
2794 passwordPolicyId, User.class.getName(), userId);
2795 }
2796
2797
2810 @Override
2811 public boolean hasRoleUser(
2812 long companyId, String name, long userId, boolean inherited)
2813 throws PortalException {
2814
2815 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
2816 }
2817
2818
2825 @Override
2826 public boolean isPasswordExpired(User user) throws PortalException {
2827 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2828
2829 if ((passwordPolicy != null) && passwordPolicy.getExpireable()) {
2830 Date now = new Date();
2831
2832 if (user.getPasswordModifiedDate() == null) {
2833 user.setPasswordModifiedDate(now);
2834
2835 userLocalService.updateUser(user);
2836 }
2837
2838 long passwordStartTime = user.getPasswordModifiedDate().getTime();
2839 long elapsedTime = now.getTime() - passwordStartTime;
2840
2841 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
2842 return true;
2843 }
2844 else {
2845 return false;
2846 }
2847 }
2848
2849 return false;
2850 }
2851
2852
2861 @Override
2862 public boolean isPasswordExpiringSoon(User user) throws PortalException {
2863 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2864
2865 if ((passwordPolicy != null) && passwordPolicy.isExpireable() &&
2866 (passwordPolicy.getWarningTime() > 0)) {
2867
2868 Date now = new Date();
2869
2870 if (user.getPasswordModifiedDate() == null) {
2871 user.setPasswordModifiedDate(now);
2872
2873 userLocalService.updateUser(user);
2874 }
2875
2876 long timeModified = user.getPasswordModifiedDate().getTime();
2877 long passwordExpiresOn =
2878 (passwordPolicy.getMaxAge() * 1000) + timeModified;
2879
2880 long timeStartWarning =
2881 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
2882
2883 if (now.getTime() > timeStartWarning) {
2884 return true;
2885 }
2886 else {
2887 return false;
2888 }
2889 }
2890
2891 return false;
2892 }
2893
2894
2900 @Override
2901 public User loadGetDefaultUser(long companyId) throws PortalException {
2902 return userPersistence.findByC_DU(companyId, true);
2903 }
2904
2905
2935 @Override
2936 public List<User> search(
2937 long companyId, String keywords, int status,
2938 LinkedHashMap<String, Object> params, int start, int end,
2939 OrderByComparator<User> obc) {
2940
2941 Indexer<?> indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
2942
2943 if (!indexer.isIndexerEnabled() ||
2944 !PropsValues.USERS_SEARCH_WITH_INDEX || isUseCustomSQL(params)) {
2945
2946 return userFinder.findByKeywords(
2947 companyId, keywords, status, params, start, end, obc);
2948 }
2949
2950 try {
2951 return UsersAdminUtil.getUsers(
2952 search(
2953 companyId, keywords, status, params, start, end,
2954 getSorts(obc)));
2955 }
2956 catch (Exception e) {
2957 throw new SystemException(e);
2958 }
2959 }
2960
2961
2990 @Override
2991 public Hits search(
2992 long companyId, String keywords, int status,
2993 LinkedHashMap<String, Object> params, int start, int end, Sort sort) {
2994
2995 return search(
2996 companyId, keywords, status, params, start, end, new Sort[] {sort});
2997 }
2998
2999 @Override
3000 public Hits search(
3001 long companyId, String keywords, int status,
3002 LinkedHashMap<String, Object> params, int start, int end,
3003 Sort[] sorts) {
3004
3005 String firstName = null;
3006 String middleName = null;
3007 String lastName = null;
3008 String fullName = null;
3009 String screenName = null;
3010 String emailAddress = null;
3011 String street = null;
3012 String city = null;
3013 String zip = null;
3014 String region = null;
3015 String country = null;
3016 boolean andOperator = false;
3017
3018 if (Validator.isNotNull(keywords)) {
3019 firstName = keywords;
3020 middleName = keywords;
3021 lastName = keywords;
3022 fullName = keywords;
3023 screenName = keywords;
3024 emailAddress = keywords;
3025 street = keywords;
3026 city = keywords;
3027 zip = keywords;
3028 region = keywords;
3029 country = keywords;
3030 }
3031 else {
3032 andOperator = true;
3033 }
3034
3035 if (params != null) {
3036 params.put("keywords", keywords);
3037 }
3038
3039 try {
3040 Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3041 User.class);
3042
3043 SearchContext searchContext = buildSearchContext(
3044 companyId, firstName, middleName, lastName, fullName,
3045 screenName, emailAddress, street, city, zip, region, country,
3046 status, params, andOperator, start, end, sorts);
3047
3048 return indexer.search(searchContext);
3049 }
3050 catch (Exception e) {
3051 throw new SystemException(e);
3052 }
3053 }
3054
3055
3093 @Override
3094 public List<User> search(
3095 long companyId, String firstName, String middleName, String lastName,
3096 String screenName, String emailAddress, int status,
3097 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3098 int end, OrderByComparator<User> obc) {
3099
3100 Indexer<?> indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3101
3102 if (!indexer.isIndexerEnabled() ||
3103 !PropsValues.USERS_SEARCH_WITH_INDEX || isUseCustomSQL(params)) {
3104
3105 return userFinder.findByC_FN_MN_LN_SN_EA_S(
3106 companyId, firstName, middleName, lastName, screenName,
3107 emailAddress, status, params, andSearch, start, end, obc);
3108 }
3109
3110 try {
3111 return UsersAdminUtil.getUsers(
3112 search(
3113 companyId, firstName, middleName, lastName, screenName,
3114 emailAddress, status, params, andSearch, start, end,
3115 getSorts(obc)));
3116 }
3117 catch (Exception e) {
3118 throw new SystemException(e);
3119 }
3120 }
3121
3122
3159 @Override
3160 public Hits search(
3161 long companyId, String firstName, String middleName, String lastName,
3162 String screenName, String emailAddress, int status,
3163 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3164 int end, Sort sort) {
3165
3166 return search(
3167 companyId, firstName, middleName, lastName, screenName,
3168 emailAddress, status, params, andSearch, start, end,
3169 new Sort[] {sort});
3170 }
3171
3172 @Override
3173 public Hits search(
3174 long companyId, String firstName, String middleName, String lastName,
3175 String screenName, String emailAddress, int status,
3176 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3177 int end, Sort[] sorts) {
3178
3179 try {
3180 Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3181 User.class);
3182
3183 SearchContext searchContext = buildSearchContext(
3184 companyId, firstName, middleName, lastName, null, screenName,
3185 emailAddress, null, null, null, null, null, status, params,
3186 andSearch, start, end, sorts);
3187
3188 return indexer.search(searchContext);
3189 }
3190 catch (Exception e) {
3191 throw new SystemException(e);
3192 }
3193 }
3194
3195
3208 @Override
3209 public int searchCount(
3210 long companyId, String keywords, int status,
3211 LinkedHashMap<String, Object> params) {
3212
3213 Indexer<?> indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3214
3215 if (!indexer.isIndexerEnabled() ||
3216 !PropsValues.USERS_SEARCH_WITH_INDEX || isUseCustomSQL(params)) {
3217
3218 return userFinder.countByKeywords(
3219 companyId, keywords, status, params);
3220 }
3221
3222 try {
3223 String firstName = null;
3224 String middleName = null;
3225 String lastName = null;
3226 String fullName = null;
3227 String screenName = null;
3228 String emailAddress = null;
3229 String street = null;
3230 String city = null;
3231 String zip = null;
3232 String region = null;
3233 String country = null;
3234 boolean andOperator = false;
3235
3236 if (Validator.isNotNull(keywords)) {
3237 firstName = keywords;
3238 middleName = keywords;
3239 lastName = keywords;
3240 fullName = keywords;
3241 screenName = keywords;
3242 emailAddress = keywords;
3243 street = keywords;
3244 city = keywords;
3245 zip = keywords;
3246 region = keywords;
3247 country = keywords;
3248 }
3249 else {
3250 andOperator = true;
3251 }
3252
3253 if (params != null) {
3254 params.put("keywords", keywords);
3255 }
3256
3257 SearchContext searchContext = buildSearchContext(
3258 companyId, firstName, middleName, lastName, fullName,
3259 screenName, emailAddress, street, city, zip, region, country,
3260 status, params, andOperator, QueryUtil.ALL_POS,
3261 QueryUtil.ALL_POS, null);
3262
3263 return (int)indexer.searchCount(searchContext);
3264 }
3265 catch (Exception e) {
3266 throw new SystemException(e);
3267 }
3268 }
3269
3270
3291 @Override
3292 public int searchCount(
3293 long companyId, String firstName, String middleName, String lastName,
3294 String screenName, String emailAddress, int status,
3295 LinkedHashMap<String, Object> params, boolean andSearch) {
3296
3297 Indexer<?> indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3298
3299 if (!indexer.isIndexerEnabled() ||
3300 !PropsValues.USERS_SEARCH_WITH_INDEX || isUseCustomSQL(params)) {
3301
3302 return userFinder.countByC_FN_MN_LN_SN_EA_S(
3303 companyId, firstName, middleName, lastName, screenName,
3304 emailAddress, status, params, andSearch);
3305 }
3306
3307 try {
3308 FullNameGenerator fullNameGenerator =
3309 FullNameGeneratorFactory.getInstance();
3310
3311 String fullName = fullNameGenerator.getFullName(
3312 firstName, middleName, lastName);
3313
3314 SearchContext searchContext = buildSearchContext(
3315 companyId, firstName, middleName, lastName, fullName,
3316 screenName, emailAddress, null, null, null, null, null, status,
3317 params, true, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
3318
3319 return (int)indexer.searchCount(searchContext);
3320 }
3321 catch (Exception e) {
3322 throw new SystemException(e);
3323 }
3324 }
3325
3326 @Override
3327 public Map<Long, Integer> searchCounts(
3328 long companyId, int status, long[] groupIds) {
3329
3330 return userFinder.countByGroups(companyId, status, groupIds);
3331 }
3332
3333 @Override
3334 public List<User> searchSocial(
3335 long userId, int[] socialRelationTypes, String keywords, int start,
3336 int end)
3337 throws PortalException {
3338
3339 User user = userPersistence.findByPrimaryKey(userId);
3340
3341 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
3342
3343 params.put(
3344 "socialRelationType",
3345 new Long[][] {
3346 new Long[] {userId}, ArrayUtil.toLongArray(socialRelationTypes)
3347 });
3348 params.put("wildcardMode", WildcardMode.TRAILING);
3349
3350 return userFinder.findByKeywords(
3351 user.getCompanyId(), keywords, WorkflowConstants.STATUS_APPROVED,
3352 params, start, end, null);
3353 }
3354
3355 @Override
3356 public List<User> searchSocial(
3357 long companyId, long[] groupIds, String keywords, int start, int end) {
3358
3359 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
3360
3361 params.put("usersGroups", ArrayUtil.toLongArray(groupIds));
3362 params.put("wildcardMode", WildcardMode.TRAILING);
3363
3364 return userFinder.findByKeywords(
3365 companyId, keywords, WorkflowConstants.STATUS_APPROVED, params,
3366 start, end, null);
3367 }
3368
3369 @Override
3370 public List<User> searchSocial(
3371 long[] groupIds, long userId, int[] socialRelationTypes,
3372 String keywords, int start, int end)
3373 throws PortalException {
3374
3375 User user = userPersistence.findByPrimaryKey(userId);
3376
3377 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
3378
3379 params.put(
3380 "socialRelationType",
3381 new Long[][] {
3382 new Long[] {userId}, ArrayUtil.toLongArray(socialRelationTypes)
3383 });
3384 params.put("socialRelationTypeUnionUserGroups", true);
3385 params.put("usersGroups", ArrayUtil.toLongArray(groupIds));
3386 params.put("wildcardMode", WildcardMode.TRAILING);
3387
3388 return userFinder.findByKeywords(
3389 user.getCompanyId(), keywords, WorkflowConstants.STATUS_APPROVED,
3390 params, start, end, null);
3391 }
3392
3393 @Override
3394 public BaseModelSearchResult<User> searchUsers(
3395 long companyId, String keywords, int status,
3396 LinkedHashMap<String, Object> params, int start, int end, Sort sort)
3397 throws PortalException {
3398
3399 return searchUsers(
3400 companyId, keywords, status, params, start, end, new Sort[] {sort});
3401 }
3402
3403 @Override
3404 public BaseModelSearchResult<User> searchUsers(
3405 long companyId, String keywords, int status,
3406 LinkedHashMap<String, Object> params, int start, int end,
3407 Sort[] sorts)
3408 throws PortalException {
3409
3410 String firstName = null;
3411 String middleName = null;
3412 String lastName = null;
3413 String fullName = null;
3414 String screenName = null;
3415 String emailAddress = null;
3416 String street = null;
3417 String city = null;
3418 String zip = null;
3419 String region = null;
3420 String country = null;
3421 boolean andOperator = false;
3422
3423 if (Validator.isNotNull(keywords)) {
3424 firstName = keywords;
3425 middleName = keywords;
3426 lastName = keywords;
3427 fullName = keywords;
3428 screenName = keywords;
3429 emailAddress = keywords;
3430 street = keywords;
3431 city = keywords;
3432 zip = keywords;
3433 region = keywords;
3434 country = keywords;
3435 }
3436 else {
3437 andOperator = true;
3438 }
3439
3440 if (params != null) {
3441 params.put("keywords", keywords);
3442 }
3443
3444 SearchContext searchContext = buildSearchContext(
3445 companyId, firstName, middleName, lastName, fullName, screenName,
3446 emailAddress, street, city, zip, region, country, status, params,
3447 andOperator, start, end, sorts);
3448
3449 return searchUsers(searchContext);
3450 }
3451
3452 @Override
3453 public BaseModelSearchResult<User> searchUsers(
3454 long companyId, String firstName, String middleName,
3455 String lastName, String screenName, String emailAddress, int status,
3456 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3457 int end, Sort sort)
3458 throws PortalException {
3459
3460 return searchUsers(
3461 companyId, firstName, middleName, lastName, screenName,
3462 emailAddress, status, params, andSearch, start, end,
3463 new Sort[] {sort});
3464 }
3465
3466 @Override
3467 public BaseModelSearchResult<User> searchUsers(
3468 long companyId, String firstName, String middleName,
3469 String lastName, String screenName, String emailAddress, int status,
3470 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3471 int end, Sort[] sorts)
3472 throws PortalException {
3473
3474 SearchContext searchContext = buildSearchContext(
3475 companyId, firstName, middleName, lastName, null, screenName,
3476 emailAddress, null, null, null, null, null, status, params,
3477 andSearch, start, end, sorts);
3478
3479 return searchUsers(searchContext);
3480 }
3481
3482
3491 @Override
3492 public void sendEmailAddressVerification(
3493 User user, String emailAddress, ServiceContext serviceContext)
3494 throws PortalException {
3495
3496 if (user.isEmailAddressVerified() &&
3497 StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
3498
3499 return;
3500 }
3501
3502 Ticket ticket = ticketLocalService.addDistinctTicket(
3503 user.getCompanyId(), User.class.getName(), user.getUserId(),
3504 TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3505 serviceContext);
3506
3507 String verifyEmailAddressURL =
3508 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3509 "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3510
3511 long plid = serviceContext.getPlid();
3512
3513 if (plid > 0) {
3514 Layout layout = layoutLocalService.fetchLayout(plid);
3515
3516 if (layout != null) {
3517 Group group = layout.getGroup();
3518
3519 if (!layout.isPrivateLayout() && !group.isUser()) {
3520 verifyEmailAddressURL +=
3521 "&p_l_id=" + serviceContext.getPlid();
3522 }
3523 }
3524 }
3525
3526 String fromName = PrefsPropsUtil.getString(
3527 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3528 String fromAddress = PrefsPropsUtil.getString(
3529 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3530
3531 String toName = user.getFullName();
3532 String toAddress = emailAddress;
3533
3534 PortletPreferences companyPortletPreferences =
3535 PrefsPropsUtil.getPreferences(user.getCompanyId(), true);
3536
3537 Map<Locale, String> localizedSubjectMap =
3538 LocalizationUtil.getLocalizationMap(
3539 companyPortletPreferences, "adminEmailVerificationSubject",
3540 PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3541 Map<Locale, String> localizedBodyMap =
3542 LocalizationUtil.getLocalizationMap(
3543 companyPortletPreferences, "adminEmailVerificationBody",
3544 PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3545
3546 SubscriptionSender subscriptionSender = new SubscriptionSender();
3547
3548 subscriptionSender.setCompanyId(user.getCompanyId());
3549 subscriptionSender.setContextAttributes(
3550 "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3551 "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3552 "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3553 "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_ID$]",
3554 user.getUserId(), "[$USER_SCREENNAME$]", user.getScreenName());
3555 subscriptionSender.setFrom(fromAddress, fromName);
3556 subscriptionSender.setHtmlFormat(true);
3557 subscriptionSender.setLocalizedBodyMap(localizedBodyMap);
3558 subscriptionSender.setLocalizedSubjectMap(localizedSubjectMap);
3559 subscriptionSender.setMailId("user", user.getUserId());
3560 subscriptionSender.setServiceContext(serviceContext);
3561
3562 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3563
3564 subscriptionSender.flushNotificationsAsync();
3565 }
3566
3567
3583 @Override
3584 public boolean sendPassword(
3585 long companyId, String emailAddress, String fromName,
3586 String fromAddress, String subject, String body,
3587 ServiceContext serviceContext)
3588 throws PortalException {
3589
3590 Company company = companyPersistence.findByPrimaryKey(companyId);
3591
3592 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3593 throw new SendPasswordException.MustBeEnabled(company);
3594 }
3595
3596 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
3597
3598 if (Validator.isNull(emailAddress)) {
3599 throw new UserEmailAddressException.MustNotBeNull();
3600 }
3601
3602 User user = userPersistence.findByC_EA(companyId, emailAddress);
3603
3604 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3605
3606 String newPassword = StringPool.BLANK;
3607 String passwordResetURL = StringPool.BLANK;
3608
3609 if (company.isSendPasswordResetLink()) {
3610 Date expirationDate = null;
3611
3612 if ((passwordPolicy != null) &&
3613 (passwordPolicy.getResetTicketMaxAge() > 0)) {
3614
3615 expirationDate = new Date(
3616 System.currentTimeMillis() +
3617 (passwordPolicy.getResetTicketMaxAge() * 1000));
3618 }
3619
3620 Ticket ticket = ticketLocalService.addDistinctTicket(
3621 companyId, User.class.getName(), user.getUserId(),
3622 TicketConstants.TYPE_PASSWORD, null, expirationDate,
3623 serviceContext);
3624
3625 passwordResetURL =
3626 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3627 "/portal/update_password?p_l_id="+
3628 serviceContext.getPlid() +
3629 "&ticketKey=" + ticket.getKey();
3630 }
3631 else {
3632 if (!Validator.equals(
3633 PasswordEncryptorUtil.getDefaultPasswordAlgorithmType(),
3634 PasswordEncryptorUtil.TYPE_NONE)) {
3635
3636 if (LDAPSettingsUtil.isPasswordPolicyEnabled(
3637 user.getCompanyId())) {
3638
3639 if (_log.isWarnEnabled()) {
3640 StringBundler sb = new StringBundler(5);
3641
3642 sb.append("When LDAP password policy is enabled, ");
3643 sb.append("it is possible that portal generated ");
3644 sb.append("passwords will not match the LDAP policy.");
3645 sb.append("Using RegExpToolkit to generate new ");
3646 sb.append("password.");
3647
3648 _log.warn(sb.toString());
3649 }
3650
3651 RegExpToolkit regExpToolkit = new RegExpToolkit();
3652
3653 newPassword = regExpToolkit.generate(null);
3654 }
3655 else {
3656 newPassword = PwdToolkitUtil.generate(passwordPolicy);
3657 }
3658
3659 boolean passwordReset = false;
3660
3661 if (passwordPolicy.getChangeable() &&
3662 passwordPolicy.getChangeRequired()) {
3663
3664 passwordReset = true;
3665 }
3666
3667 user.setPassword(PasswordEncryptorUtil.encrypt(newPassword));
3668 user.setPasswordUnencrypted(newPassword);
3669 user.setPasswordEncrypted(true);
3670 user.setPasswordReset(passwordReset);
3671 user.setPasswordModified(true);
3672 user.setPasswordModifiedDate(new Date());
3673
3674 userPersistence.update(user);
3675
3676 user.setPasswordModified(false);
3677 }
3678 else {
3679 newPassword = user.getPassword();
3680 }
3681 }
3682
3683 sendPasswordNotification(
3684 user, companyId, newPassword, passwordResetURL, fromName,
3685 fromAddress, subject, body, serviceContext);
3686
3687 return company.isSendPassword();
3688 }
3689
3690
3710 @Override
3711 public boolean sendPasswordByEmailAddress(
3712 long companyId, String emailAddress)
3713 throws PortalException {
3714
3715 User user = userPersistence.findByC_EA(companyId, emailAddress);
3716
3717 return sendPassword(
3718 user.getCompanyId(), user.getEmailAddress(), null, null, null, null,
3719 ServiceContextThreadLocal.getServiceContext());
3720 }
3721
3722
3741 @Override
3742 public boolean sendPasswordByScreenName(long companyId, String screenName)
3743 throws PortalException {
3744
3745 User user = userPersistence.findByC_SN(companyId, screenName);
3746
3747 return sendPassword(
3748 user.getCompanyId(), user.getEmailAddress(), null, null, null, null,
3749 ServiceContextThreadLocal.getServiceContext());
3750 }
3751
3752
3770 @Override
3771 public boolean sendPasswordByUserId(long userId) throws PortalException {
3772 User user = userPersistence.findByPrimaryKey(userId);
3773
3774 return sendPassword(
3775 user.getCompanyId(), user.getEmailAddress(), null, null, null, null,
3776 ServiceContextThreadLocal.getServiceContext());
3777 }
3778
3779
3786 @Override
3787 public void setRoleUsers(long roleId, long[] userIds)
3788 throws PortalException {
3789
3790 long[] oldUserIds = rolePersistence.getUserPrimaryKeys(roleId);
3791
3792 Set<Long> updatedUserIdsSet = SetUtil.symmetricDifference(
3793 userIds, oldUserIds);
3794
3795 long[] updateUserIds = ArrayUtil.toLongArray(updatedUserIdsSet);
3796
3797 rolePersistence.setUsers(roleId, userIds);
3798
3799 reindex(updateUserIds);
3800
3801 PermissionCacheUtil.clearCache(updateUserIds);
3802 }
3803
3804
3811 @Override
3812 @SuppressWarnings("deprecation")
3813 public void setUserGroupUsers(long userGroupId, long[] userIds)
3814 throws PortalException {
3815
3816 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3817 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3818 }
3819
3820 long[] oldUserIds = userGroupPersistence.getUserPrimaryKeys(
3821 userGroupId);
3822
3823 Set<Long> updatedUserIdsSet = SetUtil.symmetricDifference(
3824 userIds, oldUserIds);
3825
3826 long[] updateUserIds = ArrayUtil.toLongArray(updatedUserIdsSet);
3827
3828 userGroupPersistence.setUsers(userGroupId, userIds);
3829
3830 reindex(updateUserIds);
3831
3832 PermissionCacheUtil.clearCache(updateUserIds);
3833 }
3834
3835
3841 @Override
3842 public void unsetGroupTeamsUsers(long groupId, long[] userIds)
3843 throws PortalException {
3844
3845 List<Team> teams = teamPersistence.findByGroupId(groupId);
3846
3847 for (Team team : teams) {
3848 unsetTeamUsers(team.getTeamId(), userIds);
3849 }
3850
3851 PermissionCacheUtil.clearCache(userIds);
3852 }
3853
3854
3862 @Override
3863 public void unsetGroupUsers(
3864 final long groupId, final long[] userIds,
3865 ServiceContext serviceContext)
3866 throws PortalException {
3867
3868 userGroupRoleLocalService.deleteUserGroupRoles(
3869 userIds, groupId, RoleConstants.TYPE_SITE);
3870
3871 unsetGroupTeamsUsers(groupId, userIds);
3872
3873 groupPersistence.removeUsers(groupId, userIds);
3874
3875 reindex(userIds);
3876
3877 PermissionCacheUtil.clearCache(userIds);
3878
3879 Callable<Void> callable = new Callable<Void>() {
3880
3881 @Override
3882 public Void call() throws Exception {
3883 Message message = new Message();
3884
3885 message.put("groupId", groupId);
3886 message.put("userIds", userIds);
3887
3888 MessageBusUtil.sendMessage(
3889 DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
3890
3891 return null;
3892 }
3893
3894 };
3895
3896 TransactionCommitCallbackUtil.registerCallback(callable);
3897 }
3898
3899
3905 @Override
3906 public void unsetOrganizationUsers(
3907 long organizationId, final long[] userIds)
3908 throws PortalException {
3909
3910 Organization organization = organizationPersistence.findByPrimaryKey(
3911 organizationId);
3912
3913 final Group group = organization.getGroup();
3914
3915 userGroupRoleLocalService.deleteUserGroupRoles(
3916 userIds, group.getGroupId());
3917
3918 organizationPersistence.removeUsers(organizationId, userIds);
3919
3920 reindex(userIds);
3921
3922 PermissionCacheUtil.clearCache(userIds);
3923
3924 Callable<Void> callable = new Callable<Void>() {
3925
3926 @Override
3927 public Void call() throws Exception {
3928 Message message = new Message();
3929
3930 message.put("groupId", group.getGroupId());
3931 message.put("userIds", userIds);
3932
3933 MessageBusUtil.sendMessage(
3934 DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
3935
3936 return null;
3937 }
3938
3939 };
3940
3941 TransactionCommitCallbackUtil.registerCallback(callable);
3942 }
3943
3944
3950 @Override
3951 public void unsetPasswordPolicyUsers(
3952 long passwordPolicyId, long[] userIds) {
3953
3954 passwordPolicyRelLocalService.deletePasswordPolicyRels(
3955 passwordPolicyId, User.class.getName(), userIds);
3956 }
3957
3958
3964 @Override
3965 public void unsetRoleUsers(long roleId, List<User> users)
3966 throws PortalException {
3967
3968 Role role = rolePersistence.findByPrimaryKey(roleId);
3969
3970 String roleName = role.getName();
3971
3972 if ((roleName.equals(RoleConstants.ADMINISTRATOR) &&
3973 (getRoleUsersCount(role.getRoleId()) <= 1)) ||
3974 roleName.equals(RoleConstants.USER)) {
3975
3976 return;
3977 }
3978
3979 rolePersistence.removeUsers(roleId, users);
3980
3981 Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3982 User.class);
3983
3984 indexer.reindex(users);
3985
3986 long[] userIds = new long[users.size()];
3987
3988 for (int i = 0; i < users.size(); i++) {
3989 User user = users.get(i);
3990
3991 userIds[i] = user.getUserId();
3992 }
3993
3994 PermissionCacheUtil.clearCache(userIds);
3995 }
3996
3997
4003 @Override
4004 public void unsetRoleUsers(long roleId, long[] userIds)
4005 throws PortalException {
4006
4007 Role role = rolePersistence.findByPrimaryKey(roleId);
4008
4009 String roleName = role.getName();
4010
4011 if (roleName.equals(RoleConstants.USER) ||
4012 (roleName.equals(RoleConstants.ADMINISTRATOR) &&
4013 getRoleUsersCount(role.getRoleId()) <= 1)) {
4014
4015 return;
4016 }
4017
4018 rolePersistence.removeUsers(roleId, userIds);
4019
4020 reindex(userIds);
4021
4022 PermissionCacheUtil.clearCache(userIds);
4023 }
4024
4025
4031 @Override
4032 public void unsetTeamUsers(long teamId, long[] userIds)
4033 throws PortalException {
4034
4035 teamPersistence.removeUsers(teamId, userIds);
4036
4037 reindex(userIds);
4038
4039 PermissionCacheUtil.clearCache(userIds);
4040 }
4041
4042
4048 @Override
4049 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
4050 throws PortalException {
4051
4052 userGroupPersistence.removeUsers(userGroupId, userIds);
4053
4054 reindex(userIds);
4055
4056 PermissionCacheUtil.clearCache(userIds);
4057 }
4058
4059
4067 @Override
4068 public User updateAgreedToTermsOfUse(
4069 long userId, boolean agreedToTermsOfUse)
4070 throws PortalException {
4071
4072 User user = userPersistence.findByPrimaryKey(userId);
4073
4074 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
4075
4076 userPersistence.update(user);
4077
4078 return user;
4079 }
4080
4081
4090 @Override
4091 public void updateAsset(
4092 long userId, User user, long[] assetCategoryIds,
4093 String[] assetTagNames)
4094 throws PortalException {
4095
4096 User owner = userPersistence.findByPrimaryKey(userId);
4097
4098 Company company = companyPersistence.findByPrimaryKey(
4099 owner.getCompanyId());
4100
4101 Group companyGroup = company.getGroup();
4102
4103 assetEntryLocalService.updateEntry(
4104 userId, companyGroup.getGroupId(), user.getCreateDate(),
4105 user.getModifiedDate(), User.class.getName(), user.getUserId(),
4106 user.getUuid(), 0, assetCategoryIds, assetTagNames, false, null,
4107 null, null, null, user.getFullName(), null, null, null, null, 0, 0,
4108 null);
4109 }
4110
4111
4118 @Override
4119 public User updateCreateDate(long userId, Date createDate)
4120 throws PortalException {
4121
4122 User user = userPersistence.findByPrimaryKey(userId);
4123
4124 user.setCreateDate(createDate);
4125
4126 userPersistence.update(user);
4127
4128 return user;
4129 }
4130
4131
4140 @Override
4141 public User updateEmailAddress(
4142 long userId, String password, String emailAddress1,
4143 String emailAddress2)
4144 throws PortalException {
4145
4146 emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
4147 emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
4148
4149 User user = userPersistence.findByPrimaryKey(userId);
4150
4151 validateEmailAddress(user, emailAddress1, emailAddress2);
4152
4153 setEmailAddress(
4154 user, password, user.getFirstName(), user.getMiddleName(),
4155 user.getLastName(), emailAddress1);
4156
4157 userPersistence.update(user);
4158
4159 Contact contact = user.getContact();
4160
4161 contact.setEmailAddress(user.getEmailAddress());
4162
4163 contactPersistence.update(contact);
4164
4165 return user;
4166 }
4167
4168
4180 @Override
4181 public User updateEmailAddress(
4182 long userId, String password, String emailAddress1,
4183 String emailAddress2, ServiceContext serviceContext)
4184 throws PortalException {
4185
4186 emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
4187 emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
4188
4189 User user = userPersistence.findByPrimaryKey(userId);
4190
4191 validateEmailAddress(user, emailAddress1, emailAddress2);
4192
4193 Company company = companyPersistence.findByPrimaryKey(
4194 user.getCompanyId());
4195
4196 if (company.isStrangersVerify() &&
4197 !StringUtil.equalsIgnoreCase(
4198 emailAddress1, user.getEmailAddress())) {
4199
4200 sendEmailAddressVerification(user, emailAddress1, serviceContext);
4201 }
4202 else {
4203 setEmailAddress(
4204 user, password, user.getFirstName(), user.getMiddleName(),
4205 user.getLastName(), emailAddress1);
4206
4207 userPersistence.update(user);
4208
4209 Contact contact = user.getContact();
4210
4211 contact.setEmailAddress(user.getEmailAddress());
4212
4213 contactPersistence.update(contact);
4214 }
4215
4216 return user;
4217 }
4218
4219
4226 @Override
4227 public User updateEmailAddressVerified(
4228 long userId, boolean emailAddressVerified)
4229 throws PortalException {
4230
4231 User user = userPersistence.findByPrimaryKey(userId);
4232
4233 user.setEmailAddressVerified(emailAddressVerified);
4234
4235 userPersistence.update(user);
4236
4237 return user;
4238 }
4239
4240
4247 @Override
4248 public User updateFacebookId(long userId, long facebookId)
4249 throws PortalException {
4250
4251 User user = userPersistence.findByPrimaryKey(userId);
4252
4253 user.setFacebookId(facebookId);
4254
4255 userPersistence.update(user);
4256
4257 return user;
4258 }
4259
4260
4268 @Override
4269 public void updateGroups(
4270 long userId, long[] newGroupIds, ServiceContext serviceContext)
4271 throws PortalException {
4272
4273 boolean indexingEnabled = true;
4274
4275 if (serviceContext != null) {
4276 indexingEnabled = serviceContext.isIndexingEnabled();
4277 }
4278
4279 updateGroups(userId, newGroupIds, serviceContext, indexingEnabled);
4280 }
4281
4282
4319 @Override
4320 public User updateIncompleteUser(
4321 long creatorUserId, long companyId, boolean autoPassword,
4322 String password1, String password2, boolean autoScreenName,
4323 String screenName, String emailAddress, long facebookId,
4324 String openId, Locale locale, String firstName, String middleName,
4325 String lastName, long prefixId, long suffixId, boolean male,
4326 int birthdayMonth, int birthdayDay, int birthdayYear,
4327 String jobTitle, boolean updateUserInformation, boolean sendEmail,
4328 ServiceContext serviceContext)
4329 throws PortalException {
4330
4331 User user = getUserByEmailAddress(companyId, emailAddress);
4332
4333 if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
4334 throw new PortalException("Invalid user status");
4335 }
4336
4337 User defaultUser = getDefaultUser(companyId);
4338
4339 if (facebookId > 0) {
4340 autoPassword = false;
4341
4342 if ((password1 == null) || (password2 == null)) {
4343 password1 = PwdGenerator.getPassword();
4344 password2 = password1;
4345 }
4346
4347 sendEmail = false;
4348 }
4349
4350 if (updateUserInformation) {
4351 autoScreenName = false;
4352
4353 if (PrefsPropsUtil.getBoolean(
4354 companyId,
4355 PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
4356
4357 autoScreenName = true;
4358 }
4359
4360 validate(
4361 companyId, user.getUserId(), autoPassword, password1, password2,
4362 autoScreenName, screenName, emailAddress, openId, firstName,
4363 middleName, lastName, null, locale);
4364
4365 if (!autoPassword) {
4366 if (Validator.isNull(password1) ||
4367 Validator.isNull(password2)) {
4368
4369 throw new UserPasswordException.MustNotBeNull(
4370 user.getUserId());
4371 }
4372 }
4373
4374 if (autoScreenName) {
4375 ScreenNameGenerator screenNameGenerator =
4376 ScreenNameGeneratorFactory.getInstance();
4377
4378 try {
4379 screenName = screenNameGenerator.generate(
4380 companyId, user.getUserId(), emailAddress);
4381 }
4382 catch (Exception e) {
4383 throw new SystemException(e);
4384 }
4385 }
4386
4387 FullNameGenerator fullNameGenerator =
4388 FullNameGeneratorFactory.getInstance();
4389
4390 String fullName = fullNameGenerator.getFullName(
4391 firstName, middleName, lastName);
4392
4393 String greeting = LanguageUtil.format(
4394 locale, "welcome-x", fullName, false);
4395
4396 if (Validator.isNotNull(password1)) {
4397 user.setPassword(PasswordEncryptorUtil.encrypt(password1));
4398 user.setPasswordUnencrypted(password1);
4399 }
4400
4401 user.setPasswordEncrypted(true);
4402
4403 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
4404
4405 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
4406 passwordPolicy.isChangeRequired()) {
4407
4408 user.setPasswordReset(true);
4409 }
4410 else {
4411 user.setPasswordReset(false);
4412 }
4413
4414 user.setScreenName(screenName);
4415 user.setFacebookId(facebookId);
4416 user.setOpenId(openId);
4417 user.setLanguageId(locale.toString());
4418 user.setTimeZoneId(defaultUser.getTimeZoneId());
4419 user.setGreeting(greeting);
4420 user.setFirstName(firstName);
4421 user.setMiddleName(middleName);
4422 user.setLastName(lastName);
4423 user.setJobTitle(jobTitle);
4424 user.setExpandoBridgeAttributes(serviceContext);
4425
4426 Date birthday = getBirthday(
4427 birthdayMonth, birthdayDay, birthdayYear);
4428
4429 Contact contact = user.getContact();
4430
4431 contact.setFirstName(firstName);
4432 contact.setMiddleName(middleName);
4433 contact.setLastName(lastName);
4434 contact.setPrefixId(prefixId);
4435 contact.setSuffixId(suffixId);
4436 contact.setMale(male);
4437 contact.setBirthday(birthday);
4438 contact.setJobTitle(jobTitle);
4439
4440 contactPersistence.update(contact, serviceContext);
4441
4442
4443
4444 Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4445 User.class);
4446
4447 indexer.reindex(user);
4448 }
4449
4450 user.setStatus(WorkflowConstants.STATUS_DRAFT);
4451
4452 userPersistence.update(user, serviceContext);
4453
4454
4455
4456 long workflowUserId = creatorUserId;
4457
4458 if (workflowUserId == user.getUserId()) {
4459 workflowUserId = defaultUser.getUserId();
4460 }
4461
4462 ServiceContext workflowServiceContext = serviceContext;
4463
4464 if (workflowServiceContext == null) {
4465 workflowServiceContext = new ServiceContext();
4466 }
4467
4468 workflowServiceContext.setAttribute("autoPassword", autoPassword);
4469 workflowServiceContext.setAttribute("passwordUnencrypted", password1);
4470 workflowServiceContext.setAttribute("sendEmail", sendEmail);
4471
4472 WorkflowHandlerRegistryUtil.startWorkflowInstance(
4473 companyId, workflowUserId, User.class.getName(), user.getUserId(),
4474 user, workflowServiceContext);
4475
4476 return getUserByEmailAddress(companyId, emailAddress);
4477 }
4478
4479
4486 @Override
4487 public User updateJobTitle(long userId, String jobTitle)
4488 throws PortalException {
4489
4490 User user = userPersistence.findByPrimaryKey(userId);
4491
4492 user.setJobTitle(jobTitle);
4493
4494 userPersistence.update(user);
4495
4496 Contact contact = contactPersistence.findByPrimaryKey(
4497 user.getContactId());
4498
4499 contact.setJobTitle(jobTitle);
4500
4501 contactPersistence.update(contact);
4502
4503 return user;
4504 }
4505
4506
4513 @Override
4514 public User updateLastLogin(long userId, String loginIP)
4515 throws PortalException {
4516
4517 User user = userPersistence.findByPrimaryKey(userId);
4518
4519 Date lastLoginDate = user.getLoginDate();
4520
4521 if (lastLoginDate == null) {
4522 lastLoginDate = new Date();
4523 }
4524
4525 String lastLoginIP = user.getLoginIP();
4526
4527 if (lastLoginIP == null) {
4528 lastLoginIP = loginIP;
4529 }
4530
4531 user.setLoginDate(new Date());
4532 user.setLoginIP(loginIP);
4533 user.setLastLoginDate(lastLoginDate);
4534 user.setLastLoginIP(lastLoginIP);
4535
4536 resetFailedLoginAttempts(user, true);
4537
4538 return user;
4539 }
4540
4541
4548 @Override
4549 public User updateLockout(User user, boolean lockout)
4550 throws PortalException {
4551
4552 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
4553
4554 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
4555 return user;
4556 }
4557
4558 Date lockoutDate = null;
4559
4560 if (lockout) {
4561 lockoutDate = new Date();
4562 }
4563
4564 user.setLockout(lockout);
4565 user.setLockoutDate(lockoutDate);
4566
4567 if (!lockout) {
4568 user.setFailedLoginAttempts(0);
4569 }
4570
4571 userPersistence.update(user);
4572
4573 return user;
4574 }
4575
4576
4584 @Override
4585 public User updateLockoutByEmailAddress(
4586 long companyId, String emailAddress, boolean lockout)
4587 throws PortalException {
4588
4589 User user = getUserByEmailAddress(companyId, emailAddress);
4590
4591 return updateLockout(user, lockout);
4592 }
4593
4594
4601 @Override
4602 public User updateLockoutById(long userId, boolean lockout)
4603 throws PortalException {
4604
4605 User user = userPersistence.findByPrimaryKey(userId);
4606
4607 return updateLockout(user, lockout);
4608 }
4609
4610
4618 @Override
4619 public User updateLockoutByScreenName(
4620 long companyId, String screenName, boolean lockout)
4621 throws PortalException {
4622
4623 User user = getUserByScreenName(companyId, screenName);
4624
4625 return updateLockout(user, lockout);
4626 }
4627
4628
4635 @Override
4636 public User updateModifiedDate(long userId, Date modifiedDate)
4637 throws PortalException {
4638
4639 User user = userPersistence.findByPrimaryKey(userId);
4640
4641 userPersistence.update(user);
4642
4643 return user;
4644 }
4645
4646
4653 @Override
4654 public User updateOpenId(long userId, String openId)
4655 throws PortalException {
4656
4657 openId = openId.trim();
4658
4659 User user = userPersistence.findByPrimaryKey(userId);
4660
4661 user.setOpenId(openId);
4662
4663 userPersistence.update(user);
4664
4665 return user;
4666 }
4667
4668
4677 @Override
4678 public void updateOrganizations(
4679 long userId, long[] newOrganizationIds,
4680 ServiceContext serviceContext)
4681 throws PortalException {
4682
4683 updateOrganizations(
4684 userId, newOrganizationIds, serviceContext.isIndexingEnabled());
4685 }
4686
4687
4697 @Override
4698 public User updatePassword(
4699 long userId, String password1, String password2,
4700 boolean passwordReset)
4701 throws PortalException {
4702
4703 return updatePassword(
4704 userId, password1, password2, passwordReset, false);
4705 }
4706
4707
4720 @Override
4721 public User updatePassword(
4722 long userId, String password1, String password2,
4723 boolean passwordReset, boolean silentUpdate)
4724 throws PortalException {
4725
4726 User user = userPersistence.findByPrimaryKey(userId);
4727
4728 if (!silentUpdate) {
4729 validatePassword(user.getCompanyId(), userId, password1, password2);
4730 }
4731
4732 String oldEncPwd = user.getPassword();
4733
4734 if (!user.isPasswordEncrypted()) {
4735 oldEncPwd = PasswordEncryptorUtil.encrypt(user.getPassword());
4736 }
4737
4738 String newEncPwd = PasswordEncryptorUtil.encrypt(password1);
4739
4740 if (user.hasCompanyMx()) {
4741 mailService.updatePassword(user.getCompanyId(), userId, password1);
4742 }
4743
4744 user.setPassword(newEncPwd);
4745 user.setPasswordUnencrypted(password1);
4746 user.setPasswordEncrypted(true);
4747 user.setPasswordReset(passwordReset);
4748
4749 if (!silentUpdate || (user.getPasswordModifiedDate() == null)) {
4750 user.setPasswordModifiedDate(new Date());
4751 }
4752
4753 user.setDigest(StringPool.BLANK);
4754 user.setGraceLoginCount(0);
4755
4756 if (!silentUpdate) {
4757 user.setPasswordModified(true);
4758 }
4759
4760 try {
4761 userPersistence.update(user);
4762 }
4763 catch (ModelListenerException mle) {
4764 String msg = GetterUtil.getString(mle.getCause().getMessage());
4765
4766 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
4767 String errorPasswordHistory =
4768 LDAPSettingsUtil.getErrorPasswordHistory(
4769 user.getCompanyId());
4770
4771 if (msg.contains(errorPasswordHistory)) {
4772 throw new UserPasswordException.MustNotBeRecentlyUsed(
4773 userId);
4774 }
4775 }
4776
4777 throw new UserPasswordException.MustComplyWithModelListeners(
4778 userId, mle);
4779 }
4780
4781 if (!silentUpdate) {
4782 user.setPasswordModified(false);
4783
4784 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
4785 }
4786
4787 if (!silentUpdate && (PrincipalThreadLocal.getUserId() != userId)) {
4788 sendPasswordNotification(
4789 user, user.getCompanyId(), password1, null, null, null, null,
4790 null, ServiceContextThreadLocal.getServiceContext());
4791 }
4792
4793 return user;
4794 }
4795
4796
4808 @Override
4809 public User updatePasswordManually(
4810 long userId, String password, boolean passwordEncrypted,
4811 boolean passwordReset, Date passwordModifiedDate)
4812 throws PortalException {
4813
4814
4815
4816 User user = userPersistence.findByPrimaryKey(userId);
4817
4818 user.setPassword(password);
4819 user.setPasswordEncrypted(passwordEncrypted);
4820 user.setPasswordReset(passwordReset);
4821 user.setPasswordModifiedDate(passwordModifiedDate);
4822 user.setDigest(StringPool.BLANK);
4823
4824 userPersistence.update(user);
4825
4826 return user;
4827 }
4828
4829
4838 @Override
4839 public User updatePasswordReset(long userId, boolean passwordReset)
4840 throws PortalException {
4841
4842 User user = userPersistence.findByPrimaryKey(userId);
4843
4844 user.setPasswordReset(passwordReset);
4845
4846 userPersistence.update(user);
4847
4848 return user;
4849 }
4850
4851
4858 @Override
4859 public User updatePortrait(long userId, byte[] bytes)
4860 throws PortalException {
4861
4862 User user = userPersistence.findByPrimaryKey(userId);
4863
4864 PortalUtil.updateImageId(
4865 user, true, bytes, "portraitId",
4866 PrefsPropsUtil.getLong(PropsKeys.USERS_IMAGE_MAX_SIZE),
4867 PropsValues.USERS_IMAGE_MAX_HEIGHT,
4868 PropsValues.USERS_IMAGE_MAX_WIDTH);
4869
4870 return userPersistence.update(user);
4871 }
4872
4873
4881 @Override
4882 public User updateReminderQuery(long userId, String question, String answer)
4883 throws PortalException {
4884
4885 validateReminderQuery(question, answer);
4886
4887 User user = userPersistence.findByPrimaryKey(userId);
4888
4889 user.setReminderQueryQuestion(question);
4890 user.setReminderQueryAnswer(answer);
4891
4892 userPersistence.update(user);
4893
4894 return user;
4895 }
4896
4897
4904 @Override
4905 public User updateScreenName(long userId, String screenName)
4906 throws PortalException {
4907
4908
4909
4910 User user = userPersistence.findByPrimaryKey(userId);
4911
4912 screenName = getLogin(screenName);
4913
4914 validateScreenName(user.getCompanyId(), userId, screenName);
4915
4916 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
4917 user.setDigest(StringPool.BLANK);
4918 }
4919
4920 user.setScreenName(screenName);
4921
4922 userPersistence.update(user);
4923
4924
4925
4926 Group group = groupLocalService.getUserGroup(
4927 user.getCompanyId(), userId);
4928
4929 group.setFriendlyURL(StringPool.SLASH + screenName);
4930
4931 groupPersistence.update(group);
4932
4933 return user;
4934 }
4935
4936
4945 @Deprecated
4946 @Override
4947 public User updateStatus(long userId, int status) throws PortalException {
4948 return updateStatus(userId, status, new ServiceContext());
4949 }
4950
4951
4961 @Override
4962 public User updateStatus(
4963 long userId, int status, ServiceContext serviceContext)
4964 throws PortalException {
4965
4966 User user = userPersistence.findByPrimaryKey(userId);
4967
4968 if ((status == WorkflowConstants.STATUS_APPROVED) &&
4969 (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {
4970
4971 validateCompanyMaxUsers(user.getCompanyId());
4972 }
4973
4974 String passwordUnencrypted = (String)serviceContext.getAttribute(
4975 "passwordUnencrypted");
4976
4977 if (Validator.isNotNull(passwordUnencrypted)) {
4978 user.setPasswordUnencrypted(passwordUnencrypted);
4979 }
4980
4981 user.setStatus(status);
4982
4983 userPersistence.update(user);
4984
4985 reindex(user);
4986
4987 Group group = user.getGroup();
4988
4989 if (status == WorkflowConstants.STATUS_INACTIVE) {
4990 group.setActive(false);
4991 }
4992 else {
4993 group.setActive(true);
4994 }
4995
4996 groupLocalService.updateGroup(group);
4997
4998 return user;
4999 }
5000
5001
5051 @Override
5052 @SuppressWarnings("deprecation")
5053 public User updateUser(
5054 long userId, String oldPassword, String newPassword1,
5055 String newPassword2, boolean passwordReset,
5056 String reminderQueryQuestion, String reminderQueryAnswer,
5057 String screenName, String emailAddress, long facebookId,
5058 String openId, boolean portrait, byte[] portraitBytes,
5059 String languageId, String timeZoneId, String greeting,
5060 String comments, String firstName, String middleName,
5061 String lastName, long prefixId, long suffixId, boolean male,
5062 int birthdayMonth, int birthdayDay, int birthdayYear, String smsSn,
5063 String facebookSn, String jabberSn, String skypeSn,
5064 String twitterSn, String jobTitle, long[] groupIds,
5065 long[] organizationIds, long[] roleIds,
5066 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
5067 ServiceContext serviceContext)
5068 throws PortalException {
5069
5070
5071
5072 User user = userPersistence.findByPrimaryKey(userId);
5073 Company company = companyPersistence.findByPrimaryKey(
5074 user.getCompanyId());
5075 String password = oldPassword;
5076 screenName = getLogin(screenName);
5077 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
5078 openId = openId.trim();
5079 String oldFullName = user.getFullName();
5080 facebookSn = StringUtil.toLowerCase(facebookSn.trim());
5081 jabberSn = StringUtil.toLowerCase(jabberSn.trim());
5082 skypeSn = StringUtil.toLowerCase(skypeSn.trim());
5083 twitterSn = StringUtil.toLowerCase(twitterSn.trim());
5084
5085 EmailAddressGenerator emailAddressGenerator =
5086 EmailAddressGeneratorFactory.getInstance();
5087
5088 if (emailAddressGenerator.isGenerated(emailAddress)) {
5089 emailAddress = StringPool.BLANK;
5090 }
5091
5092 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
5093 Validator.isNull(emailAddress)) {
5094
5095 emailAddress = emailAddressGenerator.generate(
5096 user.getCompanyId(), userId);
5097 }
5098
5099 Locale locale = LocaleUtil.fromLanguageId(languageId);
5100
5101 validate(
5102 userId, screenName, emailAddress, openId, firstName, middleName,
5103 lastName, smsSn, locale);
5104
5105 if (Validator.isNotNull(newPassword1) ||
5106 Validator.isNotNull(newPassword2)) {
5107
5108 user = updatePassword(
5109 userId, newPassword1, newPassword2, passwordReset);
5110
5111 password = newPassword1;
5112
5113 user.setDigest(StringPool.BLANK);
5114 }
5115
5116 if (user.getContactId() <= 0) {
5117 user.setContactId(counterLocalService.increment());
5118 }
5119
5120 user.setPasswordReset(passwordReset);
5121
5122 if (Validator.isNotNull(reminderQueryQuestion) &&
5123 Validator.isNotNull(reminderQueryAnswer)) {
5124
5125 user.setReminderQueryQuestion(reminderQueryQuestion);
5126 user.setReminderQueryAnswer(reminderQueryAnswer);
5127 }
5128
5129 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
5130 user.setScreenName(screenName);
5131
5132 user.setDigest(StringPool.BLANK);
5133 }
5134
5135 boolean sendEmailAddressVerification = false;
5136
5137 if (company.isStrangersVerify() &&
5138 !StringUtil.equalsIgnoreCase(
5139 emailAddress, user.getEmailAddress())) {
5140
5141 sendEmailAddressVerification = true;
5142 }
5143 else {
5144 setEmailAddress(
5145 user, password, firstName, middleName, lastName, emailAddress);
5146 }
5147
5148 if (serviceContext != null) {
5149 String uuid = serviceContext.getUuid();
5150
5151 if (Validator.isNotNull(uuid)) {
5152 user.setUuid(uuid);
5153 }
5154 }
5155
5156 user.setFacebookId(facebookId);
5157
5158 Long ldapServerId = null;
5159
5160 if (serviceContext != null) {
5161 ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
5162 }
5163
5164 if (ldapServerId != null) {
5165 user.setLdapServerId(ldapServerId);
5166 }
5167
5168 user.setOpenId(openId);
5169
5170 PortalUtil.updateImageId(
5171 user, portrait, portraitBytes, "portraitId",
5172 PrefsPropsUtil.getLong(PropsKeys.USERS_IMAGE_MAX_SIZE),
5173 PropsValues.USERS_IMAGE_MAX_HEIGHT,
5174 PropsValues.USERS_IMAGE_MAX_WIDTH);
5175
5176 user.setLanguageId(languageId);
5177 user.setTimeZoneId(timeZoneId);
5178 user.setGreeting(greeting);
5179 user.setComments(comments);
5180 user.setFirstName(firstName);
5181 user.setMiddleName(middleName);
5182 user.setLastName(lastName);
5183 user.setJobTitle(jobTitle);
5184 user.setExpandoBridgeAttributes(serviceContext);
5185
5186 userPersistence.update(user, serviceContext);
5187
5188
5189
5190 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
5191
5192 long contactId = user.getContactId();
5193
5194 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
5195
5196 if (contact == null) {
5197 contact = contactPersistence.create(contactId);
5198
5199 contact.setCompanyId(user.getCompanyId());
5200 contact.setUserName(StringPool.BLANK);
5201 contact.setClassName(User.class.getName());
5202 contact.setClassPK(user.getUserId());
5203 contact.setAccountId(company.getAccountId());
5204 contact.setParentContactId(
5205 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
5206 }
5207
5208 contact.setEmailAddress(user.getEmailAddress());
5209 contact.setFirstName(firstName);
5210 contact.setMiddleName(middleName);
5211 contact.setLastName(lastName);
5212 contact.setPrefixId(prefixId);
5213 contact.setSuffixId(suffixId);
5214 contact.setMale(male);
5215 contact.setBirthday(birthday);
5216 contact.setSmsSn(smsSn);
5217 contact.setFacebookSn(facebookSn);
5218 contact.setJabberSn(jabberSn);
5219 contact.setSkypeSn(skypeSn);
5220 contact.setTwitterSn(twitterSn);
5221 contact.setJobTitle(jobTitle);
5222
5223 contactPersistence.update(contact, serviceContext);
5224
5225
5226
5227 Group group = groupLocalService.getUserGroup(
5228 user.getCompanyId(), userId);
5229
5230 group.setFriendlyURL(StringPool.SLASH + screenName);
5231
5232 groupPersistence.update(group);
5233
5234
5235
5236
5237
5238
5239
5240 List<UserGroupRole> previousUserGroupRoles =
5241 userGroupRolePersistence.findByUserId(userId);
5242
5243 updateGroups(userId, groupIds, serviceContext, false);
5244 updateOrganizations(userId, organizationIds, false);
5245
5246
5247
5248 if (roleIds != null) {
5249 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
5250
5251 userPersistence.setRoles(userId, roleIds);
5252 }
5253
5254
5255
5256 updateUserGroupRoles(
5257 user, groupIds, organizationIds, userGroupRoles,
5258 previousUserGroupRoles);
5259
5260
5261
5262 if (userGroupIds != null) {
5263 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
5264 userGroupLocalService.copyUserGroupLayouts(
5265 userGroupIds, userId);
5266 }
5267
5268 userPersistence.setUserGroups(userId, userGroupIds);
5269 }
5270
5271
5272
5273 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
5274
5275
5276
5277 if (serviceContext != null) {
5278 updateAsset(
5279 userId, user, serviceContext.getAssetCategoryIds(),
5280 serviceContext.getAssetTagNames());
5281 }
5282
5283
5284
5285 if (GetterUtil.getBoolean(
5286 PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
5287 !oldFullName.equals(user.getFullName())) {
5288
5289 mbMessageLocalService.updateUserName(userId, user.getFullName());
5290 }
5291
5292
5293
5294 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
5295 Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5296 User.class);
5297
5298 indexer.reindex(user);
5299 }
5300
5301
5302
5303 if ((serviceContext != null) && sendEmailAddressVerification) {
5304 sendEmailAddressVerification(user, emailAddress, serviceContext);
5305 }
5306
5307
5308
5309 PermissionCacheUtil.clearCache(userId);
5310
5311 return user;
5312 }
5313
5314
5369 @Deprecated
5370 @Override
5371 public User updateUser(
5372 long userId, String oldPassword, String newPassword1,
5373 String newPassword2, boolean passwordReset,
5374 String reminderQueryQuestion, String reminderQueryAnswer,
5375 String screenName, String emailAddress, long facebookId,
5376 String openId, String languageId, String timeZoneId,
5377 String greeting, String comments, String firstName,
5378 String middleName, String lastName, long prefixId, long suffixId,
5379 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
5380 String smsSn, String facebookSn, String jabberSn, String skypeSn,
5381 String twitterSn, String jobTitle, long[] groupIds,
5382 long[] organizationIds, long[] roleIds,
5383 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
5384 ServiceContext serviceContext)
5385 throws PortalException {
5386
5387 return updateUser(
5388 userId, oldPassword, newPassword1, newPassword2, passwordReset,
5389 reminderQueryQuestion, reminderQueryAnswer, screenName,
5390 emailAddress, facebookId, openId, true, null, languageId,
5391 timeZoneId, greeting, comments, firstName, middleName, lastName,
5392 prefixId, suffixId, male, birthdayMonth, birthdayDay, birthdayYear,
5393 smsSn, facebookSn, jabberSn, skypeSn, twitterSn, jobTitle, groupIds,
5394 organizationIds, roleIds, userGroupRoles, userGroupIds,
5395 serviceContext);
5396 }
5397
5398
5403 @Override
5404 public void verifyEmailAddress(String ticketKey) throws PortalException {
5405 Ticket ticket = ticketLocalService.getTicket(ticketKey);
5406
5407 if (ticket.isExpired() ||
5408 (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
5409
5410 throw new NoSuchTicketException("{ticketKey=" + ticketKey + "}");
5411 }
5412
5413 User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
5414
5415 String emailAddress = ticket.getExtraInfo();
5416
5417 emailAddress = StringUtil.toLowerCase(emailAddress).trim();
5418
5419 if (!emailAddress.equals(user.getEmailAddress())) {
5420 if (userPersistence.fetchByC_EA(
5421 user.getCompanyId(), emailAddress) != null) {
5422
5423 throw new UserEmailAddressException.MustNotBeDuplicate(
5424 user.getUserId(), emailAddress);
5425 }
5426
5427 setEmailAddress(
5428 user, StringPool.BLANK, user.getFirstName(),
5429 user.getMiddleName(), user.getLastName(), emailAddress);
5430
5431 Contact contact = user.getContact();
5432
5433 contact.setEmailAddress(user.getEmailAddress());
5434
5435 contactPersistence.update(contact);
5436 }
5437
5438 user.setEmailAddressVerified(true);
5439
5440 userPersistence.update(user);
5441
5442 ticketLocalService.deleteTicket(ticket);
5443 }
5444
5445 protected void addDefaultRolesAndTeams(long groupId, long[] userIds)
5446 throws PortalException {
5447
5448 List<Role> defaultSiteRoles = new ArrayList<>();
5449
5450 Group group = groupLocalService.getGroup(groupId);
5451
5452 UnicodeProperties typeSettingsProperties =
5453 group.getTypeSettingsProperties();
5454
5455 long[] defaultSiteRoleIds = StringUtil.split(
5456 typeSettingsProperties.getProperty("defaultSiteRoleIds"), 0L);
5457
5458 for (long defaultSiteRoleId : defaultSiteRoleIds) {
5459 Role defaultSiteRole = rolePersistence.fetchByPrimaryKey(
5460 defaultSiteRoleId);
5461
5462 if (defaultSiteRole == null) {
5463 if (_log.isWarnEnabled()) {
5464 _log.warn("Unable to find role " + defaultSiteRoleId);
5465 }
5466
5467 continue;
5468 }
5469
5470 defaultSiteRoles.add(defaultSiteRole);
5471 }
5472
5473 List<Team> defaultTeams = new ArrayList<>();
5474
5475 long[] defaultTeamIds = StringUtil.split(
5476 typeSettingsProperties.getProperty("defaultTeamIds"), 0L);
5477
5478 for (long defaultTeamId : defaultTeamIds) {
5479 Team defaultTeam = teamPersistence.findByPrimaryKey(defaultTeamId);
5480
5481 if (defaultTeam == null) {
5482 if (_log.isWarnEnabled()) {
5483 _log.warn("Unable to find team " + defaultTeamId);
5484 }
5485
5486 continue;
5487 }
5488
5489 defaultTeams.add(defaultTeam);
5490 }
5491
5492 for (long userId : userIds) {
5493 Set<Long> userRoleIdsSet = new HashSet<>();
5494
5495 for (Role role : defaultSiteRoles) {
5496 if (!userPersistence.containsRole(userId, role.getRoleId())) {
5497 userRoleIdsSet.add(role.getRoleId());
5498 }
5499 }
5500
5501 long[] userRoleIds = ArrayUtil.toArray(
5502 userRoleIdsSet.toArray(new Long[userRoleIdsSet.size()]));
5503
5504 userGroupRoleLocalService.addUserGroupRoles(
5505 userId, groupId, userRoleIds);
5506
5507 Set<Long> userTeamIdsSet = new HashSet<>();
5508
5509 for (Team team : defaultTeams) {
5510 if (!userPersistence.containsTeam(userId, team.getTeamId())) {
5511 userTeamIdsSet.add(team.getTeamId());
5512 }
5513 }
5514
5515 long[] userTeamIds = ArrayUtil.toArray(
5516 userTeamIdsSet.toArray(new Long[userTeamIdsSet.size()]));
5517
5518 userPersistence.addTeams(userId, userTeamIds);
5519 }
5520 }
5521
5522
5563 protected int authenticate(
5564 long companyId, String login, String password, String authType,
5565 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
5566 Map<String, Object> resultsMap)
5567 throws PortalException {
5568
5569 if (PropsValues.AUTH_LOGIN_DISABLED) {
5570 return Authenticator.FAILURE;
5571 }
5572
5573 login = StringUtil.toLowerCase(login.trim());
5574
5575 long userId = GetterUtil.getLong(login);
5576
5577
5578
5579 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5580 if (Validator.isNull(login)) {
5581 throw new UserEmailAddressException.MustNotBeNull();
5582 }
5583 }
5584 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5585 if (Validator.isNull(login)) {
5586 throw new UserScreenNameException.MustNotBeNull();
5587 }
5588 }
5589 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5590 if (Validator.isNull(login)) {
5591 throw new UserIdException.MustNotBeNull();
5592 }
5593 }
5594
5595 if (Validator.isNull(password)) {
5596 throw new UserPasswordException.MustNotBeNull(userId);
5597 }
5598
5599 int authResult = Authenticator.FAILURE;
5600
5601
5602
5603 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5604 authResult = AuthPipeline.authenticateByEmailAddress(
5605 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5606 headerMap, parameterMap);
5607 }
5608 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5609 authResult = AuthPipeline.authenticateByScreenName(
5610 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5611 headerMap, parameterMap);
5612 }
5613 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5614 authResult = AuthPipeline.authenticateByUserId(
5615 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
5616 headerMap, parameterMap);
5617 }
5618
5619
5620
5621 User user = null;
5622
5623 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5624 user = fetchUserByEmailAddress(companyId, login);
5625 }
5626 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5627 user = fetchUserByScreenName(companyId, login);
5628 }
5629 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5630 user = userPersistence.fetchByPrimaryKey(GetterUtil.getLong(login));
5631 }
5632
5633 if (user == null) {
5634 return Authenticator.DNE;
5635 }
5636
5637 if (!isUserAllowedToAuthenticate(user)) {
5638 return Authenticator.FAILURE;
5639 }
5640
5641 if (!user.isPasswordEncrypted()) {
5642 user.setPassword(PasswordEncryptorUtil.encrypt(user.getPassword()));
5643 user.setPasswordEncrypted(true);
5644
5645 userPersistence.update(user);
5646 }
5647
5648
5649
5650 boolean skipLiferayCheck = false;
5651
5652 if (authResult == Authenticator.SKIP_LIFERAY_CHECK) {
5653 authResult = Authenticator.SUCCESS;
5654
5655 skipLiferayCheck = true;
5656 }
5657 else if ((authResult == Authenticator.SUCCESS) &&
5658 PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5659
5660 boolean authenticated = PwdAuthenticator.authenticate(
5661 login, password, user.getPassword());
5662
5663 if (authenticated) {
5664 authResult = Authenticator.SUCCESS;
5665 }
5666 else {
5667 authResult = Authenticator.FAILURE;
5668 }
5669 }
5670
5671
5672
5673 if (authResult == Authenticator.SUCCESS) {
5674 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5675 authResult = AuthPipeline.authenticateByEmailAddress(
5676 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5677 headerMap, parameterMap);
5678 }
5679 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5680 authResult = AuthPipeline.authenticateByScreenName(
5681 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5682 headerMap, parameterMap);
5683 }
5684 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5685 authResult = AuthPipeline.authenticateByUserId(
5686 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5687 headerMap, parameterMap);
5688 }
5689 }
5690
5691 if (resultsMap != null) {
5692 resultsMap.put("userId", user.getUserId());
5693 }
5694
5695 if (authResult == Authenticator.SUCCESS) {
5696
5697
5698
5699 if (skipLiferayCheck ||
5700 !PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK ||
5701 Validator.isNull(user.getDigest())) {
5702
5703 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5704
5705 String digest = user.getDigest(password);
5706
5707 user.setDigest(digest);
5708
5709 userPersistence.update(user);
5710 }
5711 }
5712
5713
5714
5715 if (authResult == Authenticator.FAILURE) {
5716 authResult = handleAuthenticationFailure(
5717 login, authType, user, headerMap, parameterMap);
5718 }
5719 else {
5720 resetFailedLoginAttempts(user);
5721 }
5722
5723
5724
5725 return authResult;
5726 }
5727
5728 protected SearchContext buildSearchContext(
5729 long companyId, String firstName, String middleName, String lastName,
5730 String fullName, String screenName, String emailAddress, String street,
5731 String city, String zip, String region, String country, int status,
5732 LinkedHashMap<String, Object> params, boolean andSearch, int start,
5733 int end, Sort[] sorts) {
5734
5735 SearchContext searchContext = new SearchContext();
5736
5737 searchContext.setAndSearch(andSearch);
5738
5739 Map<String, Serializable> attributes = new HashMap<>();
5740
5741 attributes.put("city", city);
5742 attributes.put("country", country);
5743 attributes.put("emailAddress", emailAddress);
5744 attributes.put("firstName", firstName);
5745 attributes.put("fullName", fullName);
5746 attributes.put("lastName", lastName);
5747 attributes.put("middleName", middleName);
5748 attributes.put("params", params);
5749 attributes.put("region", region);
5750 attributes.put("screenName", screenName);
5751 attributes.put("street", street);
5752 attributes.put("status", status);
5753 attributes.put("zip", zip);
5754
5755 searchContext.setAttributes(attributes);
5756
5757 searchContext.setCompanyId(companyId);
5758 searchContext.setEnd(end);
5759
5760 if (params != null) {
5761 String keywords = (String)params.remove("keywords");
5762
5763 if (Validator.isNotNull(keywords)) {
5764 searchContext.setKeywords(keywords);
5765 }
5766 }
5767
5768 if (sorts != null) {
5769 searchContext.setSorts(sorts);
5770 }
5771
5772 searchContext.setStart(start);
5773
5774 QueryConfig queryConfig = searchContext.getQueryConfig();
5775
5776 queryConfig.setHighlightEnabled(false);
5777 queryConfig.setScoreEnabled(false);
5778
5779 return searchContext;
5780 }
5781
5782 protected Date getBirthday(
5783 int birthdayMonth, int birthdayDay, int birthdayYear)
5784 throws PortalException {
5785
5786 Date birthday = PortalUtil.getDate(
5787 birthdayMonth, birthdayDay, birthdayYear,
5788 ContactBirthdayException.class);
5789
5790 if (birthday.after(new Date())) {
5791 throw new ContactBirthdayException();
5792 }
5793
5794 return birthday;
5795 }
5796
5797 protected String getLogin(String login) {
5798 return StringUtil.lowerCase(StringUtil.trim(login));
5799 }
5800
5801 protected Sort[] getSorts(OrderByComparator<User> obc) {
5802 if (obc == null) {
5803 return new Sort[0];
5804 }
5805
5806 String[] orderByClauses = StringUtil.split(obc.getOrderBy());
5807 String[] orderByFields = obc.getOrderByFields();
5808
5809 Sort[] sorts = new Sort[orderByFields.length];
5810
5811 for (int i = 0; i < orderByFields.length; i++) {
5812 boolean reverse = orderByClauses[i].contains("DESC");
5813
5814 sorts[i] = new Sort(orderByFields[i], reverse);
5815 }
5816
5817 return sorts;
5818 }
5819
5820 protected int handleAuthenticationFailure(
5821 String login, String authType, User user,
5822 Map<String, String[]> headerMap, Map<String, String[]> parameterMap) {
5823
5824 if (user == null) {
5825 return Authenticator.DNE;
5826 }
5827
5828 try {
5829 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5830 AuthPipeline.onFailureByEmailAddress(
5831 PropsKeys.AUTH_FAILURE, user.getCompanyId(), login,
5832 headerMap, parameterMap);
5833 }
5834 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5835 AuthPipeline.onFailureByScreenName(
5836 PropsKeys.AUTH_FAILURE, user.getCompanyId(), login,
5837 headerMap, parameterMap);
5838 }
5839 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5840 AuthPipeline.onFailureByUserId(
5841 PropsKeys.AUTH_FAILURE, user.getCompanyId(),
5842 user.getUserId(), headerMap, parameterMap);
5843 }
5844
5845 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5846
5847 if (user == null) {
5848 return Authenticator.DNE;
5849 }
5850
5851
5852
5853 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5854 user.getCompanyId())) {
5855
5856 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5857
5858 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5859
5860 int failedLoginAttempts = user.getFailedLoginAttempts();
5861 int maxFailures = passwordPolicy.getMaxFailure();
5862
5863 if ((failedLoginAttempts >= maxFailures) &&
5864 (maxFailures != 0)) {
5865
5866 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5867 AuthPipeline.onMaxFailuresByEmailAddress(
5868 PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
5869 login, headerMap, parameterMap);
5870 }
5871 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5872 AuthPipeline.onMaxFailuresByScreenName(
5873 PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
5874 login, headerMap, parameterMap);
5875 }
5876 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5877 AuthPipeline.onMaxFailuresByUserId(
5878 PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
5879 user.getUserId(), headerMap, parameterMap);
5880 }
5881 }
5882 }
5883 }
5884 catch (Exception e) {
5885 _log.error(e, e);
5886 }
5887
5888 return Authenticator.FAILURE;
5889 }
5890
5891 protected boolean isUseCustomSQL(LinkedHashMap<String, Object> params) {
5892 if (MapUtil.isEmpty(params)) {
5893 return false;
5894 }
5895
5896 for (String key : params.keySet()) {
5897 if (!key.equals("inherit") && !key.equals("usersGroups") &&
5898 !key.equals("usersOrgs") && !key.equals("usersOrgsCount") &&
5899 !key.equals("usersRoles") && !key.equals("usersTeams") &&
5900 !key.equals("usersUserGroups")) {
5901
5902 return true;
5903 }
5904 }
5905
5906 Boolean inherit = (Boolean)params.get("inherit");
5907
5908 if ((inherit != null) && inherit) {
5909 return true;
5910 }
5911
5912 return false;
5913 }
5914
5915 protected boolean isUserAllowedToAuthenticate(User user)
5916 throws PortalException {
5917
5918 if (user.isDefaultUser()) {
5919 if (_log.isInfoEnabled()) {
5920 _log.info("Authentication is disabled for the default user");
5921 }
5922
5923 return false;
5924 }
5925 else if (!user.isActive()) {
5926 if (_log.isInfoEnabled()) {
5927 _log.info(
5928 "Authentication is disabled for inactive user " +
5929 user.getUserId());
5930 }
5931
5932 return false;
5933 }
5934
5935
5936
5937
5938 checkLockout(user);
5939
5940 checkPasswordExpired(user);
5941
5942 return true;
5943 }
5944
5945 protected void notifyUser(
5946 User user, String password, ServiceContext serviceContext) {
5947
5948 if (!PrefsPropsUtil.getBoolean(
5949 user.getCompanyId(),
5950 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
5951
5952 return;
5953 }
5954
5955 String fromName = PrefsPropsUtil.getString(
5956 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
5957 String fromAddress = PrefsPropsUtil.getString(
5958 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
5959
5960 String toName = user.getFullName();
5961 String toAddress = user.getEmailAddress();
5962
5963 PortletPreferences companyPortletPreferences =
5964 PrefsPropsUtil.getPreferences(user.getCompanyId(), true);
5965
5966 Map<Locale, String> localizedSubjectMap =
5967 LocalizationUtil.getLocalizationMap(
5968 companyPortletPreferences, "adminEmailUserAddedSubject",
5969 PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
5970
5971 Map<Locale, String> localizedBodyMap = null;
5972
5973 if (Validator.isNotNull(password)) {
5974 localizedBodyMap = LocalizationUtil.getLocalizationMap(
5975 companyPortletPreferences, "adminEmailUserAddedBody",
5976 PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
5977 }
5978 else {
5979 localizedBodyMap = LocalizationUtil.getLocalizationMap(
5980 companyPortletPreferences, "adminEmailUserAddedNoPasswordBody",
5981 PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
5982 }
5983
5984 SubscriptionSender subscriptionSender = new SubscriptionSender();
5985
5986 subscriptionSender.setCompanyId(user.getCompanyId());
5987 subscriptionSender.setContextAttributes(
5988 "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
5989 "[$USER_SCREENNAME$]", user.getScreenName());
5990 subscriptionSender.setFrom(fromAddress, fromName);
5991 subscriptionSender.setHtmlFormat(true);
5992 subscriptionSender.setLocalizedBodyMap(localizedBodyMap);
5993 subscriptionSender.setLocalizedSubjectMap(localizedSubjectMap);
5994 subscriptionSender.setMailId("user", user.getUserId());
5995 subscriptionSender.setServiceContext(serviceContext);
5996
5997 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
5998
5999 subscriptionSender.flushNotificationsAsync();
6000 }
6001
6002 protected void reindex(long userId) throws SearchException {
6003 Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6004 User.class);
6005
6006 User user = userLocalService.fetchUser(userId);
6007
6008 indexer.reindex(user);
6009 }
6010
6011 protected void reindex(long[] userIds) throws SearchException {
6012 Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6013 User.class);
6014
6015 List<User> users = new ArrayList<>(userIds.length);
6016
6017 for (Long userId : userIds) {
6018 User user = userLocalService.fetchUser(userId);
6019
6020 users.add(user);
6021 }
6022
6023 indexer.reindex(users);
6024 }
6025
6026 protected void reindex(final User user) throws SearchException {
6027 Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6028 User.class);
6029
6030 indexer.reindex(user);
6031 }
6032
6033 protected void resetFailedLoginAttempts(User user) {
6034 resetFailedLoginAttempts(user, false);
6035 }
6036
6037 protected void resetFailedLoginAttempts(User user, boolean forceUpdate) {
6038 if (forceUpdate || (user.getFailedLoginAttempts() > 0)) {
6039 user.setFailedLoginAttempts(0);
6040
6041 userPersistence.update(user);
6042 }
6043 }
6044
6045 protected BaseModelSearchResult<User> searchUsers(
6046 SearchContext searchContext)
6047 throws PortalException {
6048
6049 Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6050 User.class);
6051
6052 for (int i = 0; i < 10; i++) {
6053 Hits hits = indexer.search(searchContext);
6054
6055 List<User> users = UsersAdminUtil.getUsers(hits);
6056
6057 if (users != null) {
6058 return new BaseModelSearchResult<>(users, hits.getLength());
6059 }
6060 }
6061
6062 throw new SearchException(
6063 "Unable to fix the search index after 10 attempts");
6064 }
6065
6066 protected void sendPasswordNotification(
6067 User user, long companyId, String newPassword, String passwordResetURL,
6068 String fromName, String fromAddress, String subject, String body,
6069 ServiceContext serviceContext) {
6070
6071 if (Validator.isNull(fromName)) {
6072 fromName = PrefsPropsUtil.getString(
6073 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
6074 }
6075
6076 if (Validator.isNull(fromAddress)) {
6077 fromAddress = PrefsPropsUtil.getString(
6078 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
6079 }
6080
6081 String toName = user.getFullName();
6082 String toAddress = user.getEmailAddress();
6083
6084 PortletPreferences companyPortletPreferences =
6085 PrefsPropsUtil.getPreferences(companyId, true);
6086
6087 Map<Locale, String> localizedSubjectMap = null;
6088 Map<Locale, String> localizedBodyMap = null;
6089
6090 String bodyProperty = null;
6091 String prefix = null;
6092 String subjectProperty = null;
6093
6094 if (Validator.isNotNull(passwordResetURL)) {
6095 bodyProperty = PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY;
6096 prefix = "adminEmailPasswordReset";
6097 subjectProperty = PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT;
6098 }
6099 else {
6100 bodyProperty = PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY;
6101 prefix = "adminEmailPasswordSent";
6102 subjectProperty = PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT;
6103 }
6104
6105 if (Validator.isNull(body)) {
6106 localizedBodyMap = LocalizationUtil.getLocalizationMap(
6107 companyPortletPreferences, prefix + "Body", bodyProperty);
6108 }
6109
6110 if (Validator.isNull(subject)) {
6111 localizedSubjectMap = LocalizationUtil.getLocalizationMap(
6112 companyPortletPreferences, prefix + "Subject", subjectProperty);
6113 }
6114
6115 SubscriptionSender subscriptionSender = new SubscriptionSender();
6116
6117 subscriptionSender.setCompanyId(companyId);
6118 subscriptionSender.setContextAttributes(
6119 "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
6120 serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
6121 serviceContext.getRemoteHost(), "[$USER_ID$]", user.getUserId(),
6122 "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
6123 user.getScreenName());
6124 subscriptionSender.setFrom(fromAddress, fromName);
6125 subscriptionSender.setHtmlFormat(true);
6126 subscriptionSender.setLocalizedBodyMap(localizedBodyMap);
6127 subscriptionSender.setLocalizedSubjectMap(localizedSubjectMap);
6128 subscriptionSender.setMailId("user", user.getUserId());
6129 subscriptionSender.setServiceContext(serviceContext);
6130
6131 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
6132
6133 subscriptionSender.flushNotificationsAsync();
6134 }
6135
6136 protected void setEmailAddress(
6137 User user, String password, String firstName, String middleName,
6138 String lastName, String emailAddress)
6139 throws PortalException {
6140
6141 if (StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
6142 return;
6143 }
6144
6145 long userId = user.getUserId();
6146
6147
6148
6149 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
6150 Validator.isNotNull(password)) {
6151
6152 mailService.addUser(
6153 user.getCompanyId(), userId, password, firstName, middleName,
6154 lastName, emailAddress);
6155 }
6156
6157
6158
6159 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
6160 mailService.updateEmailAddress(
6161 user.getCompanyId(), userId, emailAddress);
6162 }
6163
6164
6165
6166 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
6167 mailService.deleteEmailAddress(user.getCompanyId(), userId);
6168 }
6169
6170 user.setEmailAddress(emailAddress);
6171 user.setDigest(StringPool.BLANK);
6172 }
6173
6174 protected void updateGroups(
6175 long userId, long[] newGroupIds, ServiceContext serviceContext,
6176 boolean indexingEnabled)
6177 throws PortalException {
6178
6179 if (newGroupIds == null) {
6180 return;
6181 }
6182
6183 long[] oldGroupIds = getGroupPrimaryKeys(userId);
6184
6185 for (long oldGroupId : oldGroupIds) {
6186 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
6187 unsetGroupUsers(
6188 oldGroupId, new long[] {userId}, serviceContext);
6189 }
6190 }
6191
6192 for (long newGroupId : newGroupIds) {
6193 if (!ArrayUtil.contains(oldGroupIds, newGroupId)) {
6194 addGroupUsers(newGroupId, new long[] {userId});
6195 }
6196 }
6197
6198 if (indexingEnabled) {
6199 reindex(userId);
6200 }
6201
6202 PermissionCacheUtil.clearCache(userId);
6203 }
6204
6205 protected void updateOrganizations(
6206 long userId, long[] newOrganizationIds, boolean indexingEnabled)
6207 throws PortalException {
6208
6209 if (newOrganizationIds == null) {
6210 return;
6211 }
6212
6213 long[] oldOrganizationIds = getOrganizationPrimaryKeys(userId);
6214
6215 for (long oldOrganizationId : oldOrganizationIds) {
6216 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
6217 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
6218 }
6219 }
6220
6221 for (long newOrganizationId : newOrganizationIds) {
6222 if (!ArrayUtil.contains(oldOrganizationIds, newOrganizationId)) {
6223 addOrganizationUsers(newOrganizationId, new long[] {userId});
6224 }
6225 }
6226
6227 if (indexingEnabled) {
6228 reindex(userId);
6229 }
6230
6231 PermissionCacheUtil.clearCache(userId);
6232 }
6233
6234 protected void updateUserGroupRoles(
6235 User user, long[] groupIds, long[] organizationIds,
6236 List<UserGroupRole> userGroupRoles,
6237 List<UserGroupRole> previousUserGroupRoles)
6238 throws PortalException {
6239
6240 if (userGroupRoles == null) {
6241 return;
6242 }
6243
6244 userGroupRoles = new ArrayList<>(userGroupRoles);
6245
6246 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
6247 if (userGroupRoles.contains(userGroupRole)) {
6248 userGroupRoles.remove(userGroupRole);
6249 }
6250 else {
6251 userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
6252 }
6253 }
6254
6255 if (ListUtil.isEmpty(userGroupRoles)) {
6256 return;
6257 }
6258
6259 long[] validGroupIds = null;
6260
6261 if (groupIds != null) {
6262 validGroupIds = ArrayUtil.clone(groupIds);
6263 }
6264 else {
6265 validGroupIds = user.getGroupIds();
6266 }
6267
6268 if (organizationIds == null) {
6269 organizationIds = user.getOrganizationIds();
6270 }
6271
6272 for (long organizationId : organizationIds) {
6273 Organization organization =
6274 organizationPersistence.findByPrimaryKey(organizationId);
6275
6276 validGroupIds = ArrayUtil.append(
6277 validGroupIds, organization.getGroupId());
6278 }
6279
6280 Arrays.sort(validGroupIds);
6281
6282 for (UserGroupRole userGroupRole : userGroupRoles) {
6283 if (Arrays.binarySearch(
6284 validGroupIds, userGroupRole.getGroupId()) >= 0) {
6285
6286 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
6287 }
6288 }
6289 }
6290
6291 protected void validate(
6292 long companyId, long userId, boolean autoPassword, String password1,
6293 String password2, boolean autoScreenName, String screenName,
6294 String emailAddress, String openId, String firstName,
6295 String middleName, String lastName, long[] organizationIds,
6296 Locale locale)
6297 throws PortalException {
6298
6299 validateCompanyMaxUsers(companyId);
6300
6301 if (!autoScreenName) {
6302 validateScreenName(companyId, userId, screenName);
6303 }
6304
6305 if (!autoPassword) {
6306 PasswordPolicy passwordPolicy =
6307 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
6308
6309 PwdToolkitUtil.validate(
6310 companyId, 0, password1, password2, passwordPolicy);
6311 }
6312
6313 validateEmailAddress(companyId, emailAddress);
6314
6315 if (Validator.isNotNull(emailAddress)) {
6316 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
6317
6318 if ((user != null) && (user.getUserId() != userId)) {
6319 throw new UserEmailAddressException.MustNotBeDuplicate(
6320 userId, emailAddress);
6321 }
6322 }
6323
6324 validateOpenId(companyId, userId, openId);
6325
6326 validateFullName(companyId, firstName, middleName, lastName, locale);
6327
6328 if (organizationIds != null) {
6329 for (long organizationId : organizationIds) {
6330 Organization organization =
6331 organizationPersistence.fetchByPrimaryKey(organizationId);
6332
6333 if (organization == null) {
6334 throw new NoSuchOrganizationException(
6335 "{organizationId=" + organizationId + "}");
6336 }
6337 }
6338 }
6339 }
6340
6341 protected void validate(
6342 long userId, String screenName, String emailAddress, String openId,
6343 String firstName, String middleName, String lastName, String smsSn,
6344 Locale locale)
6345 throws PortalException {
6346
6347 User user = userPersistence.findByPrimaryKey(userId);
6348
6349 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
6350 validateScreenName(user.getCompanyId(), userId, screenName);
6351 }
6352
6353 validateEmailAddress(user.getCompanyId(), emailAddress);
6354
6355 validateOpenId(user.getCompanyId(), userId, openId);
6356
6357 if (!user.isDefaultUser()) {
6358 if (Validator.isNotNull(emailAddress) &&
6359 !StringUtil.equalsIgnoreCase(
6360 user.getEmailAddress(), emailAddress)) {
6361
6362 if (userPersistence.fetchByC_EA(
6363 user.getCompanyId(), emailAddress) != null) {
6364
6365 throw new UserEmailAddressException.MustNotBeDuplicate(
6366 userId, emailAddress);
6367 }
6368 }
6369
6370 validateFullName(
6371 user.getCompanyId(), firstName, middleName, lastName, locale);
6372 }
6373
6374 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
6375 throw new UserSmsException.MustBeEmailAddress(smsSn);
6376 }
6377 }
6378
6379 protected void validateCompanyMaxUsers(long companyId)
6380 throws PortalException {
6381
6382 Company company = companyPersistence.findByPrimaryKey(companyId);
6383
6384 if (company.isSystem() || (company.getMaxUsers() == 0)) {
6385 return;
6386 }
6387
6388 int userCount = searchCount(
6389 companyId, null, WorkflowConstants.STATUS_APPROVED, null);
6390
6391 if (userCount >= company.getMaxUsers()) {
6392 throw new CompanyMaxUsersException();
6393 }
6394 }
6395
6396 protected void validateEmailAddress(long companyId, String emailAddress)
6397 throws PortalException {
6398
6399 if (Validator.isNull(emailAddress) &&
6400 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
6401
6402 return;
6403 }
6404
6405 EmailAddressValidator emailAddressValidator =
6406 EmailAddressValidatorFactory.getInstance();
6407
6408 if (!emailAddressValidator.validate(companyId, emailAddress)) {
6409 throw new UserEmailAddressException.MustValidate(
6410 emailAddress, emailAddressValidator);
6411 }
6412
6413 String pop3User = PrefsPropsUtil.getString(
6414 PropsKeys.MAIL_SESSION_MAIL_POP3_USER,
6415 PropsValues.MAIL_SESSION_MAIL_POP3_USER);
6416
6417 if (StringUtil.equalsIgnoreCase(emailAddress, pop3User)) {
6418 throw new UserEmailAddressException.MustNotBePOP3User(emailAddress);
6419 }
6420
6421 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
6422 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
6423 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
6424
6425 for (String reservedEmailAddress : reservedEmailAddresses) {
6426 if (StringUtil.equalsIgnoreCase(
6427 emailAddress, reservedEmailAddress)) {
6428
6429 throw new UserEmailAddressException.MustNotBeReserved(
6430 emailAddress, reservedEmailAddresses);
6431 }
6432 }
6433 }
6434
6435 protected void validateEmailAddress(
6436 User user, String emailAddress1, String emailAddress2)
6437 throws PortalException {
6438
6439 if (!emailAddress1.equals(emailAddress2)) {
6440 throw new UserEmailAddressException.MustBeEqual(
6441 user, emailAddress1, emailAddress2);
6442 }
6443
6444 validateEmailAddress(user.getCompanyId(), emailAddress1);
6445 validateEmailAddress(user.getCompanyId(), emailAddress2);
6446
6447 if (!StringUtil.equalsIgnoreCase(
6448 emailAddress1, user.getEmailAddress())) {
6449
6450 if (userPersistence.fetchByC_EA(
6451 user.getCompanyId(), emailAddress1) != null) {
6452
6453 throw new UserEmailAddressException.MustNotBeDuplicate(
6454 user.getUserId(), emailAddress1);
6455 }
6456 }
6457 }
6458
6459 protected void validateFullName(
6460 long companyId, String firstName, String middleName,
6461 String lastName, Locale locale)
6462 throws PortalException {
6463
6464 FullNameDefinition fullNameDefinition =
6465 FullNameDefinitionFactory.getInstance(locale);
6466
6467 if (Validator.isNull(firstName)) {
6468 throw new ContactNameException.MustHaveFirstName();
6469 }
6470 else if (Validator.isNull(middleName) &&
6471 fullNameDefinition.isFieldRequired("middle-name")) {
6472
6473 throw new ContactNameException.MustHaveMiddleName();
6474 }
6475 else if (Validator.isNull(lastName) &&
6476 fullNameDefinition.isFieldRequired("last-name")) {
6477
6478 throw new ContactNameException.MustHaveLastName();
6479 }
6480
6481 FullNameValidator fullNameValidator =
6482 FullNameValidatorFactory.getInstance();
6483
6484 if (!fullNameValidator.validate(
6485 companyId, firstName, middleName, lastName)) {
6486
6487 throw new ContactNameException.MustHaveValidFullName(
6488 fullNameValidator);
6489 }
6490 }
6491
6492 protected void validateOpenId(long companyId, long userId, String openId)
6493 throws PortalException {
6494
6495 if (Validator.isNull(openId)) {
6496 return;
6497 }
6498
6499 User user = userPersistence.fetchByC_O(companyId, openId);
6500
6501 if ((user != null) && (user.getUserId() != userId)) {
6502 throw new DuplicateOpenIdException("{userId=" + userId + "}");
6503 }
6504 }
6505
6506 protected void validatePassword(
6507 long companyId, long userId, String password1, String password2)
6508 throws PortalException {
6509
6510 if (Validator.isNull(password1) || Validator.isNull(password2)) {
6511 throw new UserPasswordException.MustNotBeNull(userId);
6512 }
6513
6514 if (!password1.equals(password2)) {
6515 throw new UserPasswordException.MustMatch(userId);
6516 }
6517
6518 PasswordPolicy passwordPolicy =
6519 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
6520
6521 PwdToolkitUtil.validate(
6522 companyId, userId, password1, password2, passwordPolicy);
6523 }
6524
6525 protected void validateReminderQuery(String question, String answer)
6526 throws PortalException {
6527
6528 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
6529 return;
6530 }
6531
6532 if (Validator.isNull(question)) {
6533 throw new UserReminderQueryException("Question is null");
6534 }
6535
6536 if (Validator.isNull(answer)) {
6537 throw new UserReminderQueryException("Answer is null");
6538 }
6539 }
6540
6541 protected void validateScreenName(
6542 long companyId, long userId, String screenName)
6543 throws PortalException {
6544
6545 if (Validator.isNull(screenName)) {
6546 throw new UserScreenNameException.MustNotBeNull(userId);
6547 }
6548
6549 ScreenNameValidator screenNameValidator =
6550 ScreenNameValidatorFactory.getInstance();
6551
6552 if (!screenNameValidator.validate(companyId, screenName)) {
6553 throw new UserScreenNameException.MustValidate(
6554 userId, screenName, screenNameValidator);
6555 }
6556
6557 if (Validator.isNumber(screenName)) {
6558 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
6559 throw new UserScreenNameException.MustNotBeNumeric(
6560 userId, screenName);
6561 }
6562
6563 if (!screenName.equals(String.valueOf(userId))) {
6564 Group group = groupPersistence.fetchByPrimaryKey(
6565 GetterUtil.getLong(screenName));
6566
6567 if (group != null) {
6568 throw new UserScreenNameException.MustNotBeUsedByGroup(
6569 userId, screenName, group);
6570 }
6571 }
6572 }
6573
6574 String[] anonymousNames = BaseServiceImpl.ANONYMOUS_NAMES;
6575
6576 for (String anonymousName : anonymousNames) {
6577 if (StringUtil.equalsIgnoreCase(screenName, anonymousName)) {
6578 throw new UserScreenNameException.MustNotBeReservedForAnonymous(
6579 userId, screenName, anonymousNames);
6580 }
6581 }
6582
6583 User user = userPersistence.fetchByC_SN(companyId, screenName);
6584
6585 if ((user != null) && (user.getUserId() != userId)) {
6586 throw new UserScreenNameException.MustNotBeDuplicate(
6587 user.getUserId(), screenName);
6588 }
6589
6590 String friendlyURL = StringPool.SLASH + screenName;
6591
6592 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
6593
6594 if ((group != null) && (group.getClassPK() != userId)) {
6595 GroupFriendlyURLException gfurle = new GroupFriendlyURLException(
6596 GroupFriendlyURLException.DUPLICATE);
6597
6598 gfurle.setDuplicateClassPK(group.getGroupId());
6599 gfurle.setDuplicateClassName(Group.class.getName());
6600
6601 throw gfurle;
6602 }
6603
6604 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
6605
6606 if (exceptionType != -1) {
6607 throw new UserScreenNameException.MustProduceValidFriendlyURL(
6608 userId, screenName, exceptionType);
6609 }
6610
6611 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
6612 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
6613 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
6614
6615 for (String reservedScreenName : reservedScreenNames) {
6616 if (StringUtil.equalsIgnoreCase(screenName, reservedScreenName)) {
6617 throw new UserScreenNameException.MustNotBeReserved(
6618 userId, screenName, reservedScreenNames);
6619 }
6620 }
6621 }
6622
6623 @BeanReference(type = MailService.class)
6624 protected MailService mailService;
6625
6626 private static final Log _log = LogFactoryUtil.getLog(
6627 UserLocalServiceImpl.class);
6628
6629 private final Map<Long, User> _defaultUsers = new ConcurrentHashMap<>();
6630
6631 }