001
014
015 package com.liferay.portal.service.impl;
016
017 import com.liferay.portal.CompanyMaxUsersException;
018 import com.liferay.portal.ContactBirthdayException;
019 import com.liferay.portal.ContactNameException;
020 import com.liferay.portal.DuplicateOpenIdException;
021 import com.liferay.portal.GroupFriendlyURLException;
022 import com.liferay.portal.ModelListenerException;
023 import com.liferay.portal.NoSuchImageException;
024 import com.liferay.portal.NoSuchOrganizationException;
025 import com.liferay.portal.NoSuchTicketException;
026 import com.liferay.portal.NoSuchUserException;
027 import com.liferay.portal.PasswordExpiredException;
028 import com.liferay.portal.RequiredUserException;
029 import com.liferay.portal.SendPasswordException;
030 import com.liferay.portal.UserEmailAddressException;
031 import com.liferay.portal.UserIdException;
032 import com.liferay.portal.UserLockoutException;
033 import com.liferay.portal.UserPasswordException;
034 import com.liferay.portal.UserReminderQueryException;
035 import com.liferay.portal.UserScreenNameException;
036 import com.liferay.portal.UserSmsException;
037 import com.liferay.portal.kernel.cache.PortalCache;
038 import com.liferay.portal.kernel.cache.PortalCacheMapSynchronizeUtil;
039 import com.liferay.portal.kernel.cache.PortalCacheMapSynchronizeUtil.Synchronizer;
040 import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
041 import com.liferay.portal.kernel.dao.orm.QueryUtil;
042 import com.liferay.portal.kernel.dao.orm.WildcardMode;
043 import com.liferay.portal.kernel.exception.PortalException;
044 import com.liferay.portal.kernel.exception.SystemException;
045 import com.liferay.portal.kernel.language.LanguageUtil;
046 import com.liferay.portal.kernel.log.Log;
047 import com.liferay.portal.kernel.log.LogFactoryUtil;
048 import com.liferay.portal.kernel.messaging.DestinationNames;
049 import com.liferay.portal.kernel.messaging.Message;
050 import com.liferay.portal.kernel.messaging.MessageBusUtil;
051 import com.liferay.portal.kernel.search.BaseModelSearchResult;
052 import com.liferay.portal.kernel.search.Hits;
053 import com.liferay.portal.kernel.search.Indexer;
054 import com.liferay.portal.kernel.search.IndexerRegistryUtil;
055 import com.liferay.portal.kernel.search.QueryConfig;
056 import com.liferay.portal.kernel.search.SearchContext;
057 import com.liferay.portal.kernel.search.SearchException;
058 import com.liferay.portal.kernel.search.Sort;
059 import com.liferay.portal.kernel.spring.aop.Skip;
060 import com.liferay.portal.kernel.transaction.Propagation;
061 import com.liferay.portal.kernel.transaction.TransactionCommitCallbackUtil;
062 import com.liferay.portal.kernel.transaction.Transactional;
063 import com.liferay.portal.kernel.util.ArrayUtil;
064 import com.liferay.portal.kernel.util.Digester;
065 import com.liferay.portal.kernel.util.DigesterUtil;
066 import com.liferay.portal.kernel.util.GetterUtil;
067 import com.liferay.portal.kernel.util.KeyValuePair;
068 import com.liferay.portal.kernel.util.ListUtil;
069 import com.liferay.portal.kernel.util.LocaleUtil;
070 import com.liferay.portal.kernel.util.LocalizationUtil;
071 import com.liferay.portal.kernel.util.MapUtil;
072 import com.liferay.portal.kernel.util.OrderByComparator;
073 import com.liferay.portal.kernel.util.ParamUtil;
074 import com.liferay.portal.kernel.util.PropsKeys;
075 import com.liferay.portal.kernel.util.PwdGenerator;
076 import com.liferay.portal.kernel.util.SetUtil;
077 import com.liferay.portal.kernel.util.StringBundler;
078 import com.liferay.portal.kernel.util.StringPool;
079 import com.liferay.portal.kernel.util.StringUtil;
080 import com.liferay.portal.kernel.util.UnicodeProperties;
081 import com.liferay.portal.kernel.util.Validator;
082 import com.liferay.portal.kernel.workflow.WorkflowConstants;
083 import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil;
084 import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
085 import com.liferay.portal.model.Account;
086 import com.liferay.portal.model.Company;
087 import com.liferay.portal.model.CompanyConstants;
088 import com.liferay.portal.model.Contact;
089 import com.liferay.portal.model.ContactConstants;
090 import com.liferay.portal.model.Group;
091 import com.liferay.portal.model.GroupConstants;
092 import com.liferay.portal.model.Layout;
093 import com.liferay.portal.model.Organization;
094 import com.liferay.portal.model.PasswordPolicy;
095 import com.liferay.portal.model.ResourceConstants;
096 import com.liferay.portal.model.Role;
097 import com.liferay.portal.model.RoleConstants;
098 import com.liferay.portal.model.Team;
099 import com.liferay.portal.model.Ticket;
100 import com.liferay.portal.model.TicketConstants;
101 import com.liferay.portal.model.User;
102 import com.liferay.portal.model.UserGroup;
103 import com.liferay.portal.model.UserGroupRole;
104 import com.liferay.portal.model.impl.LayoutImpl;
105 import com.liferay.portal.model.impl.UserCacheModel;
106 import com.liferay.portal.model.impl.UserImpl;
107 import com.liferay.portal.security.auth.AuthPipeline;
108 import com.liferay.portal.security.auth.Authenticator;
109 import com.liferay.portal.security.auth.EmailAddressGenerator;
110 import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
111 import com.liferay.portal.security.auth.EmailAddressValidator;
112 import com.liferay.portal.security.auth.EmailAddressValidatorFactory;
113 import com.liferay.portal.security.auth.FullNameDefinition;
114 import com.liferay.portal.security.auth.FullNameDefinitionFactory;
115 import com.liferay.portal.security.auth.FullNameGenerator;
116 import com.liferay.portal.security.auth.FullNameGeneratorFactory;
117 import com.liferay.portal.security.auth.FullNameValidator;
118 import com.liferay.portal.security.auth.FullNameValidatorFactory;
119 import com.liferay.portal.security.auth.PrincipalException;
120 import com.liferay.portal.security.auth.PrincipalThreadLocal;
121 import com.liferay.portal.security.auth.ScreenNameGenerator;
122 import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
123 import com.liferay.portal.security.auth.ScreenNameValidator;
124 import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
125 import com.liferay.portal.security.ldap.LDAPSettingsUtil;
126 import com.liferay.portal.security.permission.PermissionCacheUtil;
127 import com.liferay.portal.security.pwd.PasswordEncryptorUtil;
128 import com.liferay.portal.security.pwd.PwdAuthenticator;
129 import com.liferay.portal.security.pwd.PwdToolkitUtil;
130 import com.liferay.portal.security.pwd.RegExpToolkit;
131 import com.liferay.portal.service.BaseServiceImpl;
132 import com.liferay.portal.service.ServiceContext;
133 import com.liferay.portal.service.ServiceContextThreadLocal;
134 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
135 import com.liferay.portal.service.persistence.UserGroupRolePK;
136 import com.liferay.portal.util.PortalUtil;
137 import com.liferay.portal.util.PrefsPropsUtil;
138 import com.liferay.portal.util.PropsValues;
139 import com.liferay.portal.util.SubscriptionSender;
140 import com.liferay.portlet.messageboards.model.MBMessage;
141 import com.liferay.portlet.social.model.SocialRelation;
142 import com.liferay.portlet.social.model.SocialRelationConstants;
143 import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
144 import com.liferay.util.Encryptor;
145 import com.liferay.util.EncryptorException;
146
147 import java.io.Serializable;
148
149 import java.util.ArrayList;
150 import java.util.Arrays;
151 import java.util.Calendar;
152 import java.util.Collections;
153 import java.util.Date;
154 import java.util.HashMap;
155 import java.util.HashSet;
156 import java.util.LinkedHashMap;
157 import java.util.LinkedHashSet;
158 import java.util.List;
159 import java.util.Locale;
160 import java.util.Map;
161 import java.util.Set;
162 import java.util.concurrent.Callable;
163 import java.util.concurrent.ConcurrentHashMap;
164
165 import javax.portlet.PortletPreferences;
166
167
179 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
180
181
194 @Override
195 public User addDefaultAdminUser(
196 long companyId, String screenName, String emailAddress,
197 Locale locale, String firstName, String middleName, String lastName)
198 throws PortalException {
199
200 long creatorUserId = 0;
201 boolean autoPassword = false;
202 String password1 = PropsValues.DEFAULT_ADMIN_PASSWORD;
203 String password2 = password1;
204 boolean autoScreenName = false;
205
206 screenName = getLogin(screenName);
207
208 for (int i = 1;; i++) {
209 User screenNameUser = userPersistence.fetchByC_SN(
210 companyId, screenName);
211
212 if (screenNameUser == null) {
213 break;
214 }
215
216 screenName = screenName + i;
217 }
218
219 long facebookId = 0;
220 String openId = StringPool.BLANK;
221 long prefixId = 0;
222 long suffixId = 0;
223 boolean male = true;
224 int birthdayMonth = Calendar.JANUARY;
225 int birthdayDay = 1;
226 int birthdayYear = 1970;
227 String jobTitle = StringPool.BLANK;
228
229 Group guestGroup = groupLocalService.getGroup(
230 companyId, GroupConstants.GUEST);
231
232 long[] groupIds = {guestGroup.getGroupId()};
233
234 long[] organizationIds = null;
235
236 Role adminRole = roleLocalService.getRole(
237 companyId, RoleConstants.ADMINISTRATOR);
238
239 Role powerUserRole = roleLocalService.getRole(
240 companyId, RoleConstants.POWER_USER);
241
242 long[] roleIds = {adminRole.getRoleId(), powerUserRole.getRoleId()};
243
244 long[] userGroupIds = null;
245 boolean sendEmail = false;
246 ServiceContext serviceContext = new ServiceContext();
247
248 User defaultAdminUser = addUser(
249 creatorUserId, companyId, autoPassword, password1, password2,
250 autoScreenName, screenName, emailAddress, facebookId, openId,
251 locale, firstName, middleName, lastName, prefixId, suffixId, male,
252 birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
253 organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
254
255 updateEmailAddressVerified(defaultAdminUser.getUserId(), true);
256
257 updateLastLogin(
258 defaultAdminUser.getUserId(), defaultAdminUser.getLoginIP());
259
260 updatePasswordReset(defaultAdminUser.getUserId(), false);
261
262 return defaultAdminUser;
263 }
264
265
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
345 @Override
346 public void addDefaultRoles(long userId) throws PortalException {
347 User user = userPersistence.findByPrimaryKey(userId);
348
349 Set<Long> roleIdSet = new HashSet<>();
350
351 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
352 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
353 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
354
355 for (String defaultRoleName : defaultRoleNames) {
356 Role role = rolePersistence.fetchByC_N(
357 user.getCompanyId(), defaultRoleName);
358
359 if ((role != null) &&
360 !userPersistence.containsRole(userId, role.getRoleId())) {
361
362 roleIdSet.add(role.getRoleId());
363 }
364 }
365
366 Set<Long> groupRoleIdsSet = new HashSet<>();
367 Set<Long> regularRoleIdsSet = new HashSet<>();
368
369 long[] roleIds = ArrayUtil.toLongArray(roleIdSet);
370
371 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
372
373 for (long roleId : roleIds) {
374 Role role = roleLocalService.getRole(roleId);
375
376 if (role.getType() == RoleConstants.TYPE_REGULAR) {
377 regularRoleIdsSet.add(roleId);
378 }
379 else {
380 groupRoleIdsSet.add(roleId);
381 }
382 }
383
384 long[] regularRoleIds = ArrayUtil.toLongArray(regularRoleIdsSet);
385
386 userPersistence.addRoles(userId, regularRoleIds);
387
388 Set<UserGroupRole> userGroupRolesSet = new LinkedHashSet<>();
389
390 long[] groupIds = user.getGroupIds();
391
392 for (long groupRoleId : groupRoleIdsSet) {
393 for (long groupId : groupIds) {
394 UserGroupRolePK userGroupRolePK = new UserGroupRolePK(
395 userId, groupId, groupRoleId);
396
397 UserGroupRole userGroupRole = userGroupRolePersistence.create(
398 userGroupRolePK);
399
400 userGroupRolesSet.add(userGroupRole);
401 }
402 }
403
404 List<UserGroupRole> previousUserGroupRoles =
405 userGroupRolePersistence.findByUserId(userId);
406
407 updateUserGroupRoles(
408 user, groupIds, null, new ArrayList<>(userGroupRolesSet),
409 previousUserGroupRoles);
410 }
411
412
421 @Override
422 @SuppressWarnings("deprecation")
423 public void addDefaultUserGroups(long userId) throws PortalException {
424 User user = userPersistence.findByPrimaryKey(userId);
425
426 Set<Long> userGroupIdSet = new HashSet<>();
427
428 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
429 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
430 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
431
432 for (String defaultUserGroupName : defaultUserGroupNames) {
433 UserGroup userGroup = userGroupPersistence.fetchByC_N(
434 user.getCompanyId(), defaultUserGroupName);
435
436 if ((userGroup != null) &&
437 !userPersistence.containsUserGroup(
438 userId, userGroup.getUserGroupId())) {
439
440 userGroupIdSet.add(userGroup.getUserGroupId());
441 }
442 }
443
444 long[] userGroupIds = ArrayUtil.toArray(
445 userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
446
447 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
448 for (long userGroupId : userGroupIds) {
449 userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
450 }
451 }
452
453 userPersistence.addUserGroups(userId, userGroupIds);
454 }
455
456
464 @Override
465 public void addGroupUsers(long groupId, long[] userIds)
466 throws PortalException {
467
468 groupPersistence.addUsers(groupId, userIds);
469
470 reindex(userIds);
471
472 PermissionCacheUtil.clearCache(userIds);
473
474 addDefaultRolesAndTeams(groupId, userIds);
475 }
476
477
485 @Override
486 public void addOrganizationUsers(long organizationId, long[] userIds)
487 throws PortalException {
488
489 organizationPersistence.addUsers(organizationId, userIds);
490
491 reindex(userIds);
492
493 PermissionCacheUtil.clearCache(userIds);
494 }
495
496
503 @Override
504 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds) {
505 passwordPolicyRelLocalService.addPasswordPolicyRels(
506 passwordPolicyId, User.class.getName(), userIds);
507 }
508
509
517 @Override
518 public void addRoleUsers(long roleId, long[] userIds)
519 throws PortalException {
520
521 rolePersistence.addUsers(roleId, userIds);
522
523 reindex(userIds);
524
525 PermissionCacheUtil.clearCache(userIds);
526 }
527
528
536 @Override
537 public void addTeamUsers(long teamId, long[] userIds)
538 throws PortalException {
539
540 teamPersistence.addUsers(teamId, userIds);
541
542 reindex(userIds);
543
544 PermissionCacheUtil.clearCache(userIds);
545 }
546
547
594 @Override
595 public User addUser(
596 long creatorUserId, long companyId, boolean autoPassword,
597 String password1, String password2, boolean autoScreenName,
598 String screenName, String emailAddress, long facebookId,
599 String openId, Locale locale, String firstName, String middleName,
600 String lastName, long prefixId, long suffixId, boolean male,
601 int birthdayMonth, int birthdayDay, int birthdayYear,
602 String jobTitle, long[] groupIds, long[] organizationIds,
603 long[] roleIds, long[] userGroupIds, boolean sendEmail,
604 ServiceContext serviceContext)
605 throws PortalException {
606
607 boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
608
609 try {
610 WorkflowThreadLocal.setEnabled(false);
611
612 if (serviceContext == null) {
613 serviceContext = new ServiceContext();
614 }
615
616 if (serviceContext.getWorkflowAction() !=
617 WorkflowConstants.ACTION_PUBLISH) {
618
619 serviceContext.setWorkflowAction(
620 WorkflowConstants.ACTION_PUBLISH);
621 }
622
623 return addUserWithWorkflow(
624 creatorUserId, companyId, autoPassword, password1, password2,
625 autoScreenName, screenName, emailAddress, facebookId, openId,
626 locale, firstName, middleName, lastName, prefixId, suffixId,
627 male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
628 groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
629 serviceContext);
630 }
631 finally {
632 WorkflowThreadLocal.setEnabled(workflowEnabled);
633 }
634 }
635
636
644 @Override
645 @SuppressWarnings("deprecation")
646 public void addUserGroupUsers(long userGroupId, long[] userIds)
647 throws PortalException {
648
649 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
650 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
651 }
652
653 userGroupPersistence.addUsers(userGroupId, userIds);
654
655 reindex(userIds);
656
657 PermissionCacheUtil.clearCache(userIds);
658 }
659
660
707 @Override
708 @SuppressWarnings("deprecation")
709 public User addUserWithWorkflow(
710 long creatorUserId, long companyId, boolean autoPassword,
711 String password1, String password2, boolean autoScreenName,
712 String screenName, String emailAddress, long facebookId,
713 String openId, Locale locale, String firstName, String middleName,
714 String lastName, long prefixId, long suffixId, boolean male,
715 int birthdayMonth, int birthdayDay, int birthdayYear,
716 String jobTitle, long[] groupIds, long[] organizationIds,
717 long[] roleIds, long[] userGroupIds, boolean sendEmail,
718 ServiceContext serviceContext)
719 throws PortalException {
720
721
722
723 Company company = companyPersistence.findByPrimaryKey(companyId);
724 screenName = getLogin(screenName);
725 openId = StringUtil.trim(openId);
726
727 if (PrefsPropsUtil.getBoolean(
728 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
729
730 autoScreenName = true;
731 }
732
733
734
735 long userId = counterLocalService.increment();
736
737 EmailAddressGenerator emailAddressGenerator =
738 EmailAddressGeneratorFactory.getInstance();
739
740 if ((emailAddress == null) ||
741 emailAddressGenerator.isGenerated(emailAddress)) {
742
743 emailAddress = StringPool.BLANK;
744 }
745 else {
746 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
747 }
748
749 if (!PrefsPropsUtil.getBoolean(
750 companyId, PropsKeys.USERS_EMAIL_ADDRESS_REQUIRED) &&
751 Validator.isNull(emailAddress)) {
752
753 emailAddress = emailAddressGenerator.generate(companyId, userId);
754 }
755
756 validate(
757 companyId, userId, autoPassword, password1, password2,
758 autoScreenName, screenName, emailAddress, openId, firstName,
759 middleName, lastName, organizationIds, locale);
760
761 if (!autoPassword) {
762 if (Validator.isNull(password1) || Validator.isNull(password2)) {
763 throw new UserPasswordException.MustNotBeNull(userId);
764 }
765 }
766
767 if (autoScreenName) {
768 ScreenNameGenerator screenNameGenerator =
769 ScreenNameGeneratorFactory.getInstance();
770
771 try {
772 screenName = screenNameGenerator.generate(
773 companyId, userId, emailAddress);
774 }
775 catch (Exception e) {
776 throw new SystemException(e);
777 }
778 }
779
780 User defaultUser = getDefaultUser(companyId);
781
782 FullNameGenerator fullNameGenerator =
783 FullNameGeneratorFactory.getInstance();
784
785 String fullName = fullNameGenerator.getFullName(
786 firstName, middleName, lastName);
787
788 String greeting = LanguageUtil.format(
789 locale, "welcome-x", fullName, false);
790
791 User user = userPersistence.create(userId);
792
793 if (serviceContext != null) {
794 String uuid = serviceContext.getUuid();
795
796 if (Validator.isNotNull(uuid)) {
797 user.setUuid(uuid);
798 }
799 }
800
801 user.setCompanyId(companyId);
802 user.setDefaultUser(false);
803 user.setContactId(counterLocalService.increment());
804
805 if (Validator.isNotNull(password1)) {
806 user.setPassword(PasswordEncryptorUtil.encrypt(password1));
807 user.setPasswordUnencrypted(password1);
808 }
809
810 user.setPasswordEncrypted(true);
811
812 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
813
814 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
815 passwordPolicy.isChangeRequired()) {
816
817 user.setPasswordReset(true);
818 }
819 else {
820 user.setPasswordReset(false);
821 }
822
823 user.setDigest(StringPool.BLANK);
824 user.setScreenName(screenName);
825 user.setEmailAddress(emailAddress);
826 user.setFacebookId(facebookId);
827
828 Long ldapServerId = null;
829
830 if (serviceContext != null) {
831 ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
832 }
833
834 if (ldapServerId != null) {
835 user.setLdapServerId(ldapServerId);
836 }
837 else {
838 user.setLdapServerId(-1);
839 }
840
841 user.setOpenId(openId);
842 user.setLanguageId(LocaleUtil.toLanguageId(locale));
843 user.setTimeZoneId(defaultUser.getTimeZoneId());
844 user.setGreeting(greeting);
845 user.setFirstName(firstName);
846 user.setMiddleName(middleName);
847 user.setLastName(lastName);
848 user.setJobTitle(jobTitle);
849 user.setStatus(WorkflowConstants.STATUS_DRAFT);
850 user.setExpandoBridgeAttributes(serviceContext);
851
852 userPersistence.update(user, serviceContext);
853
854
855
856 String creatorUserName = StringPool.BLANK;
857
858 if (creatorUserId <= 0) {
859 creatorUserId = user.getUserId();
860
861
862
863
864
865 }
866 else {
867 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
868
869 creatorUserName = creatorUser.getFullName();
870 }
871
872 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
873
874 Contact contact = contactPersistence.create(user.getContactId());
875
876 contact.setCompanyId(user.getCompanyId());
877 contact.setUserId(creatorUserId);
878 contact.setUserName(creatorUserName);
879 contact.setClassName(User.class.getName());
880 contact.setClassPK(user.getUserId());
881 contact.setAccountId(company.getAccountId());
882 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
883 contact.setEmailAddress(user.getEmailAddress());
884 contact.setFirstName(firstName);
885 contact.setMiddleName(middleName);
886 contact.setLastName(lastName);
887 contact.setPrefixId(prefixId);
888 contact.setSuffixId(suffixId);
889 contact.setMale(male);
890 contact.setBirthday(birthday);
891 contact.setJobTitle(jobTitle);
892
893 contactPersistence.update(contact, serviceContext);
894
895
896
897 groupLocalService.addGroup(
898 user.getUserId(), GroupConstants.DEFAULT_PARENT_GROUP_ID,
899 User.class.getName(), user.getUserId(),
900 GroupConstants.DEFAULT_LIVE_GROUP_ID, (Map<Locale, String>)null,
901 null, 0, true, GroupConstants.DEFAULT_MEMBERSHIP_RESTRICTION,
902 StringPool.SLASH + screenName, false, true, null);
903
904
905
906 if (groupIds != null) {
907 List<Group> groups = new ArrayList<>();
908
909 for (long groupId : groupIds) {
910 Group group = groupLocalService.fetchGroup(groupId);
911
912 if (group != null) {
913 groups.add(group);
914 }
915 else {
916 if (_log.isWarnEnabled()) {
917 _log.warn("Group " + groupId + " does not exist");
918 }
919 }
920 }
921
922 groupLocalService.addUserGroups(userId, groups);
923 }
924
925 addDefaultGroups(userId);
926
927
928
929 updateOrganizations(userId, organizationIds, false);
930
931
932
933 if (roleIds != null) {
934 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
935
936 userPersistence.setRoles(userId, roleIds);
937 }
938
939 addDefaultRoles(userId);
940
941
942
943 if (userGroupIds != null) {
944 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
945 for (long userGroupId : userGroupIds) {
946 userGroupLocalService.copyUserGroupLayouts(
947 userGroupId, new long[] {userId});
948 }
949 }
950
951 userPersistence.setUserGroups(userId, userGroupIds);
952 }
953
954 addDefaultUserGroups(userId);
955
956
957
958 resourceLocalService.addResources(
959 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
960 false, false, false);
961
962
963
964 if (serviceContext != null) {
965 updateAsset(
966 creatorUserId, user, serviceContext.getAssetCategoryIds(),
967 serviceContext.getAssetTagNames());
968 }
969
970
971
972 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
973 reindex(user);
974 }
975
976
977
978 long workflowUserId = creatorUserId;
979
980 if (workflowUserId == userId) {
981 workflowUserId = defaultUser.getUserId();
982 }
983
984 ServiceContext workflowServiceContext = serviceContext;
985
986 if (workflowServiceContext == null) {
987 workflowServiceContext = new ServiceContext();
988 }
989
990 workflowServiceContext.setAttribute("autoPassword", autoPassword);
991 workflowServiceContext.setAttribute("passwordUnencrypted", password1);
992 workflowServiceContext.setAttribute("sendEmail", sendEmail);
993
994 WorkflowHandlerRegistryUtil.startWorkflowInstance(
995 companyId, workflowUserId, User.class.getName(), userId, user,
996 workflowServiceContext);
997
998 if (serviceContext != null) {
999 String passwordUnencrypted = (String)serviceContext.getAttribute(
1000 "passwordUnencrypted");
1001
1002 if (Validator.isNotNull(passwordUnencrypted)) {
1003 user.setPasswordUnencrypted(passwordUnencrypted);
1004 }
1005 }
1006
1007 return user;
1008 }
1009
1010 @Override
1011 public void afterPropertiesSet() {
1012 super.afterPropertiesSet();
1013
1014 PortalCache<Serializable, Serializable> portalCache =
1015 EntityCacheUtil.getPortalCache(UserImpl.class);
1016
1017 PortalCacheMapSynchronizeUtil.synchronize(
1018 portalCache, _defaultUsers,
1019 new Synchronizer<Serializable, Serializable>() {
1020
1021 @Override
1022 public void onSynchronize(
1023 Map<? extends Serializable, ? extends Serializable> map,
1024 Serializable key, Serializable value, int timeToLive) {
1025
1026 if (!(value instanceof UserCacheModel)) {
1027 return;
1028 }
1029
1030 UserCacheModel userCacheModel = (UserCacheModel)value;
1031
1032 if (userCacheModel.defaultUser) {
1033 _defaultUsers.remove(userCacheModel.companyId);
1034 }
1035 }
1036
1037 });
1038 }
1039
1040
1061 @Override
1062 public int authenticateByEmailAddress(
1063 long companyId, String emailAddress, String password,
1064 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1065 Map<String, Object> resultsMap)
1066 throws PortalException {
1067
1068 return authenticate(
1069 companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
1070 headerMap, parameterMap, resultsMap);
1071 }
1072
1073
1094 @Override
1095 public int authenticateByScreenName(
1096 long companyId, String screenName, String password,
1097 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1098 Map<String, Object> resultsMap)
1099 throws PortalException {
1100
1101 return authenticate(
1102 companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
1103 headerMap, parameterMap, resultsMap);
1104 }
1105
1106
1127 @Override
1128 public int authenticateByUserId(
1129 long companyId, long userId, String password,
1130 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1131 Map<String, Object> resultsMap)
1132 throws PortalException {
1133
1134 return authenticate(
1135 companyId, String.valueOf(userId), password,
1136 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap, resultsMap);
1137 }
1138
1139
1173 @Override
1174 @Transactional(propagation = Propagation.SUPPORTS)
1175 public long authenticateForBasic(
1176 long companyId, String authType, String login, String password)
1177 throws PortalException {
1178
1179 if (PropsValues.AUTH_LOGIN_DISABLED) {
1180 return 0;
1181 }
1182
1183 User user = null;
1184
1185 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1186 user = fetchUserByEmailAddress(companyId, login);
1187 }
1188 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1189 user = fetchUserByScreenName(companyId, login);
1190 }
1191 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1192 user = userPersistence.fetchByPrimaryKey(GetterUtil.getLong(login));
1193 }
1194
1195 if (user == null) {
1196 return 0;
1197 }
1198
1199 if (!isUserAllowedToAuthenticate(user)) {
1200 return 0;
1201 }
1202
1203 if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
1204 return user.getUserId();
1205 }
1206
1207 String userPassword = user.getPassword();
1208
1209 if (!user.isPasswordEncrypted()) {
1210 userPassword = PasswordEncryptorUtil.encrypt(userPassword);
1211 }
1212
1213 String encPassword = PasswordEncryptorUtil.encrypt(
1214 password, userPassword);
1215
1216 if (userPassword.equals(password) || userPassword.equals(encPassword)) {
1217 resetFailedLoginAttempts(user);
1218
1219 return user.getUserId();
1220 }
1221
1222 handleAuthenticationFailure(
1223 login, authType, user, Collections.<String, String[]>emptyMap(),
1224 Collections.<String, String[]>emptyMap());
1225
1226 return 0;
1227 }
1228
1229
1246 @Override
1247 @Transactional(propagation = Propagation.SUPPORTS)
1248 public long authenticateForDigest(
1249 long companyId, String username, String realm, String nonce,
1250 String method, String uri, String response)
1251 throws PortalException {
1252
1253 if (PropsValues.AUTH_LOGIN_DISABLED) {
1254 return 0;
1255 }
1256
1257
1258
1259 User user = fetchUserByEmailAddress(companyId, username);
1260
1261 if (user == null) {
1262 user = fetchUserByScreenName(companyId, username);
1263 }
1264
1265 if (user == null) {
1266 user = userPersistence.fetchByPrimaryKey(
1267 GetterUtil.getLong(username));
1268 }
1269
1270 if (user == null) {
1271 return 0;
1272 }
1273
1274 if (!isUserAllowedToAuthenticate(user)) {
1275 return 0;
1276 }
1277
1278
1279
1280 String digest = user.getDigest();
1281
1282 if (Validator.isNull(digest)) {
1283 _log.error(
1284 "User must first login through the portal " + user.getUserId());
1285
1286 return 0;
1287 }
1288
1289 String[] digestArray = StringUtil.split(user.getDigest());
1290
1291 for (String ha1 : digestArray) {
1292 String ha2 = DigesterUtil.digestHex(Digester.MD5, method, uri);
1293
1294 String curResponse = DigesterUtil.digestHex(
1295 Digester.MD5, ha1, nonce, ha2);
1296
1297 if (response.equals(curResponse)) {
1298 resetFailedLoginAttempts(user);
1299
1300 return user.getUserId();
1301 }
1302 }
1303
1304 Company company = companyPersistence.findByPrimaryKey(companyId);
1305
1306 handleAuthenticationFailure(
1307 username, company.getAuthType(), user,
1308 new HashMap<String, String[]>(), new HashMap<String, String[]>());
1309
1310 return 0;
1311 }
1312
1313
1322 @Override
1323 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1324 public boolean authenticateForJAAS(long userId, String encPassword) {
1325 if (PropsValues.AUTH_LOGIN_DISABLED) {
1326 return false;
1327 }
1328
1329 try {
1330 User user = userPersistence.findByPrimaryKey(userId);
1331
1332 if (user.isDefaultUser()) {
1333 if (_log.isInfoEnabled()) {
1334 _log.info(
1335 "JAAS authentication is disabled for the default user");
1336 }
1337
1338 return false;
1339 }
1340 else if (!user.isActive()) {
1341 if (_log.isInfoEnabled()) {
1342 _log.info(
1343 "JAAS authentication is disabled for inactive user " +
1344 userId);
1345 }
1346
1347 return false;
1348 }
1349
1350 String userPassword = user.getPassword();
1351
1352 if (user.isPasswordEncrypted()) {
1353 if (userPassword.equals(encPassword)) {
1354 return true;
1355 }
1356
1357 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1358 encPassword = PasswordEncryptorUtil.encrypt(
1359 encPassword, userPassword);
1360
1361 if (userPassword.equals(encPassword)) {
1362 return true;
1363 }
1364 }
1365 }
1366 else {
1367 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1368 if (userPassword.equals(encPassword)) {
1369 return true;
1370 }
1371 }
1372
1373 userPassword = PasswordEncryptorUtil.encrypt(
1374 userPassword, encPassword);
1375
1376 if (userPassword.equals(encPassword)) {
1377 return true;
1378 }
1379 }
1380 }
1381 catch (Exception e) {
1382 _log.error(e);
1383 }
1384
1385 return false;
1386 }
1387
1388
1395 @Override
1396 public void checkLockout(User user) throws PortalException {
1397 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1398 return;
1399 }
1400
1401 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1402
1403 if (!passwordPolicy.isLockout()) {
1404 return;
1405 }
1406
1407
1408
1409 Date now = new Date();
1410 int failedLoginAttempts = user.getFailedLoginAttempts();
1411
1412 if (failedLoginAttempts > 0) {
1413 long failedLoginTime = user.getLastFailedLoginDate().getTime();
1414 long elapsedTime = now.getTime() - failedLoginTime;
1415 long requiredElapsedTime =
1416 passwordPolicy.getResetFailureCount() * 1000;
1417
1418 if ((requiredElapsedTime != 0) &&
1419 (elapsedTime > requiredElapsedTime)) {
1420
1421 user.setFailedLoginAttempts(0);
1422
1423 userPersistence.update(user);
1424 }
1425 }
1426
1427
1428
1429 if (user.isLockout()) {
1430 long lockoutTime = user.getLockoutDate().getTime();
1431 long elapsedTime = now.getTime() - lockoutTime;
1432 long requiredElapsedTime =
1433 passwordPolicy.getLockoutDuration() * 1000;
1434
1435 if ((requiredElapsedTime != 0) &&
1436 (elapsedTime > requiredElapsedTime)) {
1437
1438 user.setLockout(false);
1439 user.setLockoutDate(null);
1440
1441 userPersistence.update(user);
1442 }
1443 }
1444
1445 if (user.isLockout()) {
1446 throw new UserLockoutException.PasswordPolicyLockout(
1447 user, passwordPolicy);
1448 }
1449 }
1450
1451
1457 @Override
1458 public void checkLoginFailure(User user) {
1459 int failedLoginAttempts = user.getFailedLoginAttempts();
1460
1461 user.setLastFailedLoginDate(new Date());
1462 user.setFailedLoginAttempts(++failedLoginAttempts);
1463
1464 userPersistence.update(user);
1465 }
1466
1467
1476 @Override
1477 public void checkLoginFailureByEmailAddress(
1478 long companyId, String emailAddress)
1479 throws PortalException {
1480
1481 User user = getUserByEmailAddress(companyId, emailAddress);
1482
1483 checkLoginFailure(user);
1484 }
1485
1486
1493 @Override
1494 public void checkLoginFailureById(long userId) throws PortalException {
1495 User user = userPersistence.findByPrimaryKey(userId);
1496
1497 checkLoginFailure(user);
1498 }
1499
1500
1508 @Override
1509 public void checkLoginFailureByScreenName(long companyId, String screenName)
1510 throws PortalException {
1511
1512 User user = getUserByScreenName(companyId, screenName);
1513
1514 checkLoginFailure(user);
1515 }
1516
1517
1526 @Override
1527 public void checkPasswordExpired(User user) throws PortalException {
1528 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1529 return;
1530 }
1531
1532 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1533
1534
1535
1536 if (isPasswordExpired(user)) {
1537 int graceLoginCount = user.getGraceLoginCount();
1538
1539 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
1540 user.setGraceLoginCount(++graceLoginCount);
1541
1542 userPersistence.update(user);
1543 }
1544 else {
1545 user.setDigest(StringPool.BLANK);
1546
1547 userPersistence.update(user);
1548
1549 throw new PasswordExpiredException();
1550 }
1551 }
1552
1553
1554
1555 if (passwordPolicy.isChangeable() &&
1556 passwordPolicy.isChangeRequired()) {
1557
1558 if (user.getLastLoginDate() == null) {
1559 user.setPasswordReset(true);
1560
1561 userPersistence.update(user);
1562 }
1563 }
1564 }
1565
1566
1571 @Override
1572 public void clearOrganizationUsers(long organizationId) {
1573 organizationPersistence.clearUsers(organizationId);
1574
1575 PermissionCacheUtil.clearCache();
1576 }
1577
1578
1583 @Override
1584 public void clearUserGroupUsers(long userGroupId) {
1585 userGroupPersistence.clearUsers(userGroupId);
1586
1587 PermissionCacheUtil.clearCache();
1588 }
1589
1590
1604 @Override
1605 public void completeUserRegistration(
1606 User user, ServiceContext serviceContext)
1607 throws PortalException {
1608
1609 boolean autoPassword = ParamUtil.getBoolean(
1610 serviceContext, "autoPassword");
1611
1612 String password = (String)serviceContext.getAttribute(
1613 "passwordUnencrypted");
1614
1615 if (autoPassword) {
1616 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1617 if (_log.isWarnEnabled()) {
1618 StringBundler sb = new StringBundler(4);
1619
1620 sb.append("When LDAP password policy is enabled, it is ");
1621 sb.append("possible that portal generated passwords will ");
1622 sb.append("not match the LDAP policy. Using ");
1623 sb.append("RegExpToolkit to generate new password.");
1624
1625 _log.warn(sb.toString());
1626 }
1627
1628 RegExpToolkit regExpToolkit = new RegExpToolkit();
1629
1630 password = regExpToolkit.generate(null);
1631 }
1632 else {
1633 PasswordPolicy passwordPolicy =
1634 passwordPolicyLocalService.getPasswordPolicy(
1635 user.getCompanyId(), user.getOrganizationIds());
1636
1637 password = PwdToolkitUtil.generate(passwordPolicy);
1638 }
1639
1640 serviceContext.setAttribute("passwordUnencrypted", password);
1641
1642 user.setPassword(PasswordEncryptorUtil.encrypt(password));
1643 user.setPasswordUnencrypted(password);
1644 user.setPasswordEncrypted(true);
1645 user.setPasswordModified(true);
1646 user.setPasswordModifiedDate(new Date());
1647
1648 userPersistence.update(user);
1649
1650 user.setPasswordModified(false);
1651 }
1652
1653 if (user.hasCompanyMx()) {
1654 mailService.addUser(
1655 user.getCompanyId(), user.getUserId(), password,
1656 user.getFirstName(), user.getMiddleName(), user.getLastName(),
1657 user.getEmailAddress());
1658 }
1659
1660 boolean sendEmail = ParamUtil.getBoolean(serviceContext, "sendEmail");
1661
1662 if (sendEmail) {
1663 notifyUser(user, password, serviceContext);
1664 }
1665
1666 Company company = companyPersistence.findByPrimaryKey(
1667 user.getCompanyId());
1668
1669 if (company.isStrangersVerify()) {
1670 sendEmailAddressVerification(
1671 user, user.getEmailAddress(), serviceContext);
1672 }
1673 }
1674
1675
1687 @Override
1688 public KeyValuePair decryptUserId(
1689 long companyId, String name, String password)
1690 throws PortalException {
1691
1692 Company company = companyPersistence.findByPrimaryKey(companyId);
1693
1694 try {
1695 name = Encryptor.decrypt(company.getKeyObj(), name);
1696 }
1697 catch (EncryptorException ee) {
1698 throw new SystemException(ee);
1699 }
1700
1701 long userId = GetterUtil.getLong(name);
1702
1703 User user = userPersistence.findByPrimaryKey(userId);
1704
1705 try {
1706 password = Encryptor.decrypt(company.getKeyObj(), password);
1707 }
1708 catch (EncryptorException ee) {
1709 throw new SystemException(ee);
1710 }
1711
1712 String userPassword = user.getPassword();
1713 String encPassword = PasswordEncryptorUtil.encrypt(
1714 password, userPassword);
1715
1716 if (userPassword.equals(encPassword)) {
1717 if (isPasswordExpired(user)) {
1718 user.setPasswordReset(true);
1719
1720 userPersistence.update(user);
1721 }
1722
1723 return new KeyValuePair(name, password);
1724 }
1725 else {
1726 throw new PrincipalException.MustBeAuthenticated(userId);
1727 }
1728 }
1729
1730
1737 @Override
1738 public void deletePortrait(long userId) throws PortalException {
1739 User user = userPersistence.findByPrimaryKey(userId);
1740
1741 PortalUtil.updateImageId(user, false, null, "portraitId", 0, 0, 0);
1742 }
1743
1744
1752 @Override
1753 public void deleteRoleUser(long roleId, long userId)
1754 throws PortalException {
1755
1756 rolePersistence.removeUser(roleId, userId);
1757
1758 reindex(userId);
1759
1760 PermissionCacheUtil.clearCache(userId);
1761 }
1762
1763
1770 @Override
1771 public User deleteUser(long userId) throws PortalException {
1772 User user = userPersistence.findByPrimaryKey(userId);
1773
1774 return deleteUser(user);
1775 }
1776
1777
1784 @Override
1785 public User deleteUser(User user) throws PortalException {
1786 if (!PropsValues.USERS_DELETE) {
1787 throw new RequiredUserException();
1788 }
1789
1790
1791
1792 browserTrackerLocalService.deleteUserBrowserTracker(user.getUserId());
1793
1794
1795
1796 Group group = null;
1797
1798 if (!user.isDefaultUser()) {
1799 group = user.getGroup();
1800 }
1801
1802 if (group != null) {
1803 groupLocalService.deleteGroup(group);
1804 }
1805
1806
1807
1808 try {
1809 imageLocalService.deleteImage(user.getPortraitId());
1810 }
1811 catch (NoSuchImageException nsie) {
1812 if (_log.isWarnEnabled()) {
1813 _log.warn(
1814 "Unable to delete image " + user.getPortraitId(), nsie);
1815 }
1816 }
1817
1818
1819
1820 passwordPolicyRelLocalService.deletePasswordPolicyRel(
1821 User.class.getName(), user.getUserId());
1822
1823
1824
1825 passwordTrackerLocalService.deletePasswordTrackers(user.getUserId());
1826
1827
1828
1829 subscriptionLocalService.deleteSubscriptions(user.getUserId());
1830
1831
1832
1833 userIdMapperLocalService.deleteUserIdMappers(user.getUserId());
1834
1835
1836
1837 announcementsDeliveryLocalService.deleteDeliveries(user.getUserId());
1838
1839
1840
1841 assetEntryLocalService.deleteEntry(
1842 User.class.getName(), user.getUserId());
1843
1844
1845
1846 blogsStatsUserLocalService.deleteStatsUserByUserId(user.getUserId());
1847
1848
1849
1850 dlFileRankLocalService.deleteFileRanksByUserId(user.getUserId());
1851
1852
1853
1854 expandoRowLocalService.deleteRows(user.getUserId());
1855
1856
1857
1858 mbBanLocalService.deleteBansByBanUserId(user.getUserId());
1859 mbStatsUserLocalService.deleteStatsUsersByUserId(user.getUserId());
1860 mbThreadFlagLocalService.deleteThreadFlagsByUserId(user.getUserId());
1861
1862
1863
1864 membershipRequestLocalService.deleteMembershipRequestsByUserId(
1865 user.getUserId());
1866
1867
1868
1869 ratingsStatsLocalService.deleteStats(
1870 User.class.getName(), user.getUserId());
1871
1872
1873
1874 socialActivityLocalService.deleteUserActivities(user.getUserId());
1875 socialRequestLocalService.deleteReceiverUserRequests(user.getUserId());
1876 socialRequestLocalService.deleteUserRequests(user.getUserId());
1877
1878
1879
1880 mailService.deleteUser(user.getCompanyId(), user.getUserId());
1881
1882
1883
1884 Contact contact = contactLocalService.fetchContact(user.getContactId());
1885
1886 if (contact != null) {
1887 contactLocalService.deleteContact(contact);
1888 }
1889
1890
1891
1892 userGroupRoleLocalService.deleteUserGroupRolesByUserId(
1893 user.getUserId());
1894
1895
1896
1897 resourceLocalService.deleteResource(
1898 user.getCompanyId(), User.class.getName(),
1899 ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
1900
1901
1902
1903 userPersistence.remove(user);
1904
1905
1906
1907 PermissionCacheUtil.clearCache(user.getUserId());
1908
1909
1910
1911 workflowInstanceLinkLocalService.deleteWorkflowInstanceLinks(
1912 user.getCompanyId(), 0, User.class.getName(), user.getUserId());
1913
1914 return user;
1915 }
1916
1917
1924 @Override
1925 public void deleteUserGroupUser(long userGroupId, long userId)
1926 throws PortalException {
1927
1928 userGroupPersistence.removeUser(userGroupId, userId);
1929
1930 reindex(userId);
1931
1932 PermissionCacheUtil.clearCache(userId);
1933 }
1934
1935
1943 @Override
1944 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1945 public String encryptUserId(String name) throws PortalException {
1946 long userId = GetterUtil.getLong(name);
1947
1948 User user = userPersistence.findByPrimaryKey(userId);
1949
1950 Company company = companyPersistence.findByPrimaryKey(
1951 user.getCompanyId());
1952
1953 try {
1954 return Encryptor.encrypt(company.getKeyObj(), name);
1955 }
1956 catch (EncryptorException ee) {
1957 throw new SystemException(ee);
1958 }
1959 }
1960
1961
1968 @Override
1969 public User fetchUserByContactId(long contactId) {
1970 return userPersistence.fetchByContactId(contactId);
1971 }
1972
1973
1981 @Override
1982 public User fetchUserByEmailAddress(long companyId, String emailAddress) {
1983 emailAddress = getLogin(emailAddress);
1984
1985 return userPersistence.fetchByC_EA(companyId, emailAddress);
1986 }
1987
1988
1996 @Override
1997 public User fetchUserByFacebookId(long companyId, long facebookId) {
1998 return userPersistence.fetchByC_FID(companyId, facebookId);
1999 }
2000
2001
2008 @Override
2009 public User fetchUserById(long userId) {
2010 return userPersistence.fetchByPrimaryKey(userId);
2011 }
2012
2013
2021 @Override
2022 public User fetchUserByOpenId(long companyId, String openId) {
2023 return userPersistence.fetchByC_O(companyId, openId);
2024 }
2025
2026
2033 @Override
2034 public User fetchUserByPortraitId(long portraitId) {
2035 return userPersistence.fetchByPortraitId(portraitId);
2036 }
2037
2038
2046 @Override
2047 public User fetchUserByScreenName(long companyId, String screenName) {
2048 screenName = getLogin(screenName);
2049
2050 return userPersistence.fetchByC_SN(companyId, screenName);
2051 }
2052
2053
2070 @Override
2071 public List<User> getCompanyUsers(long companyId, int start, int end) {
2072 return userPersistence.findByCompanyId(companyId, start, end);
2073 }
2074
2075
2081 @Override
2082 public int getCompanyUsersCount(long companyId) {
2083 return userPersistence.countByCompanyId(companyId);
2084 }
2085
2086
2094 @Override
2095 @Skip
2096 public User getDefaultUser(long companyId) throws PortalException {
2097 User userModel = _defaultUsers.get(companyId);
2098
2099 if (userModel == null) {
2100 userModel = userLocalService.loadGetDefaultUser(companyId);
2101
2102 _defaultUsers.put(companyId, userModel);
2103 }
2104
2105 return userModel;
2106 }
2107
2108
2116 @Override
2117 @Skip
2118 public long getDefaultUserId(long companyId) throws PortalException {
2119 User user = getDefaultUser(companyId);
2120
2121 return user.getUserId();
2122 }
2123
2124
2130 @Override
2131 public long[] getGroupUserIds(long groupId) {
2132 return groupPersistence.getUserPrimaryKeys(groupId);
2133 }
2134
2135
2144 @Override
2145 public int getGroupUsersCount(long groupId, int status)
2146 throws PortalException {
2147
2148 Group group = groupPersistence.findByPrimaryKey(groupId);
2149
2150 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2151
2152 params.put("usersGroups", Long.valueOf(groupId));
2153
2154 return searchCount(group.getCompanyId(), null, status, params);
2155 }
2156
2157 @Override
2158 public List<User> getInheritedRoleUsers(
2159 long roleId, int start, int end, OrderByComparator<User> obc)
2160 throws PortalException {
2161
2162 Role role = rolePersistence.findByPrimaryKey(roleId);
2163
2164 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2165
2166 params.put("inherit", Boolean.TRUE);
2167 params.put("usersRoles", roleId);
2168
2169 return search(
2170 role.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2171 params, start, end, obc);
2172 }
2173
2174
2181 @Override
2182 public List<User> getNoAnnouncementsDeliveries(String type) {
2183 return userFinder.findByNoAnnouncementsDeliveries(type);
2184 }
2185
2186
2191 @Override
2192 public List<User> getNoContacts() {
2193 return userFinder.findByNoContacts();
2194 }
2195
2196
2202 @Override
2203 public List<User> getNoGroups() {
2204 return userFinder.findByNoGroups();
2205 }
2206
2207
2213 @Override
2214 public long[] getOrganizationUserIds(long organizationId) {
2215 return organizationPersistence.getUserPrimaryKeys(organizationId);
2216 }
2217
2218
2228 @Override
2229 public int getOrganizationUsersCount(long organizationId, int status)
2230 throws PortalException {
2231
2232 Organization organization = organizationPersistence.findByPrimaryKey(
2233 organizationId);
2234
2235 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2236
2237 params.put("usersOrgs", Long.valueOf(organizationId));
2238
2239 return searchCount(organization.getCompanyId(), null, status, params);
2240 }
2241
2242
2248 @Override
2249 public long[] getRoleUserIds(long roleId) {
2250 return rolePersistence.getUserPrimaryKeys(roleId);
2251 }
2252
2253
2262 @Override
2263 public int getRoleUsersCount(long roleId, int status)
2264 throws PortalException {
2265
2266 Role role = rolePersistence.findByPrimaryKey(roleId);
2267
2268 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2269
2270 params.put("usersRoles", Long.valueOf(roleId));
2271
2272 return searchCount(role.getCompanyId(), null, status, params);
2273 }
2274
2275
2302 @Deprecated
2303 @Override
2304 public List<User> getSocialUsers(
2305 long userId, int socialRelationType, int start, int end,
2306 OrderByComparator<User> obc)
2307 throws PortalException {
2308
2309 return getSocialUsers(
2310 userId, socialRelationType, StringPool.EQUAL, start, end, obc);
2311 }
2312
2313
2338 @Deprecated
2339 @Override
2340 public List<User> getSocialUsers(
2341 long userId, int start, int end, OrderByComparator<User> obc)
2342 throws PortalException {
2343
2344 return getSocialUsers(
2345 userId, SocialRelationConstants.TYPE_UNI_ENEMY,
2346 StringPool.NOT_EQUAL, start, end, obc);
2347 }
2348
2349 @Override
2350 public List<User> getSocialUsers(
2351 long userId, int socialRelationType,
2352 String socialRelationTypeComparator, int start, int end,
2353 OrderByComparator<User> obc)
2354 throws PortalException {
2355
2356 if (!socialRelationTypeComparator.equals(StringPool.EQUAL) &&
2357 !socialRelationTypeComparator.equals(StringPool.NOT_EQUAL)) {
2358
2359 throw new IllegalArgumentException(
2360 "Invalid social relation type comparator " +
2361 socialRelationTypeComparator);
2362 }
2363
2364 if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS)) {
2365 List<SocialRelation> socialRelations =
2366 socialRelationPersistence.findByU1_T(
2367 userId, socialRelationType);
2368
2369 if (socialRelationTypeComparator.equals(StringPool.NOT_EQUAL)) {
2370 socialRelations = ListUtil.remove(
2371 socialRelationPersistence.findByUserId1(userId),
2372 socialRelations);
2373 }
2374
2375 List<User> users = new ArrayList<>();
2376
2377 for (SocialRelation socialRelation : socialRelations) {
2378 User user = userPersistence.findByPrimaryKey(
2379 socialRelation.getUserId2());
2380
2381 if (user.isDefaultUser() ||
2382 (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {
2383
2384 continue;
2385 }
2386
2387 if (!users.contains(user)) {
2388 users.add(user);
2389 }
2390 }
2391
2392 if (obc != null) {
2393 users = ListUtil.sort(users, obc);
2394 }
2395
2396 return users;
2397 }
2398
2399 User user = userPersistence.findByPrimaryKey(userId);
2400
2401 return userFinder.findBySocialUsers(
2402 user.getCompanyId(), userId, socialRelationType,
2403 socialRelationTypeComparator, WorkflowConstants.STATUS_APPROVED,
2404 start, end, obc);
2405 }
2406
2407
2432 @Override
2433 public List<User> getSocialUsers(
2434 long userId1, long userId2, int socialRelationType, int start,
2435 int end, OrderByComparator<User> obc)
2436 throws PortalException {
2437
2438 User user1 = userPersistence.findByPrimaryKey(userId1);
2439
2440 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2441
2442 params.put(
2443 "socialMutualRelationType",
2444 new Long[] {userId1, Long.valueOf(socialRelationType), userId2,
2445 Long.valueOf(socialRelationType)
2446 });
2447
2448 return search(
2449 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2450 params, start, end, obc);
2451 }
2452
2453
2476 @Override
2477 public List<User> getSocialUsers(
2478 long userId1, long userId2, int start, int end,
2479 OrderByComparator<User> obc)
2480 throws PortalException {
2481
2482 User user1 = userPersistence.findByPrimaryKey(userId1);
2483
2484 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2485
2486 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2487
2488 return search(
2489 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2490 params, start, end, obc);
2491 }
2492
2493
2503 @Deprecated
2504 @Override
2505 public int getSocialUsersCount(long userId) throws PortalException {
2506 return getSocialUsersCount(
2507 userId, SocialRelationConstants.TYPE_UNI_ENEMY,
2508 StringPool.NOT_EQUAL);
2509 }
2510
2511
2525 @Deprecated
2526 @Override
2527 public int getSocialUsersCount(long userId, int socialRelationType)
2528 throws PortalException {
2529
2530 return getSocialUsersCount(
2531 userId, socialRelationType, StringPool.EQUAL);
2532 }
2533
2534
2543 @Override
2544 public int getSocialUsersCount(
2545 long userId, int socialRelationType,
2546 String socialRelationTypeComparator)
2547 throws PortalException {
2548
2549 User user = userPersistence.findByPrimaryKey(userId);
2550
2551 if (!socialRelationTypeComparator.equals(StringPool.EQUAL) &&
2552 !socialRelationTypeComparator.equals(StringPool.NOT_EQUAL)) {
2553
2554 throw new IllegalArgumentException(
2555 "Invalid social relation type comparator " +
2556 socialRelationTypeComparator);
2557 }
2558
2559 return userFinder.countBySocialUsers(
2560 user.getCompanyId(), user.getUserId(), socialRelationType,
2561 socialRelationTypeComparator, WorkflowConstants.STATUS_APPROVED);
2562 }
2563
2564
2573 @Override
2574 public int getSocialUsersCount(long userId1, long userId2)
2575 throws PortalException {
2576
2577 User user1 = userPersistence.findByPrimaryKey(userId1);
2578
2579 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2580
2581 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2582
2583 return searchCount(
2584 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2585 params);
2586 }
2587
2588
2600 @Override
2601 public int getSocialUsersCount(
2602 long userId1, long userId2, int socialRelationType)
2603 throws PortalException {
2604
2605 User user1 = userPersistence.findByPrimaryKey(userId1);
2606
2607 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2608
2609 params.put(
2610 "socialMutualRelationType",
2611 new Long[] {userId1, Long.valueOf(socialRelationType), userId2,
2612 Long.valueOf(socialRelationType)
2613 });
2614
2615 return searchCount(
2616 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2617 params);
2618 }
2619
2620
2627 @Override
2628 public User getUserByContactId(long contactId) throws PortalException {
2629 return userPersistence.findByContactId(contactId);
2630 }
2631
2632
2641 @Override
2642 public User getUserByEmailAddress(long companyId, String emailAddress)
2643 throws PortalException {
2644
2645 emailAddress = getLogin(emailAddress);
2646
2647 return userPersistence.findByC_EA(companyId, emailAddress);
2648 }
2649
2650
2658 @Override
2659 public User getUserByFacebookId(long companyId, long facebookId)
2660 throws PortalException {
2661
2662 return userPersistence.findByC_FID(companyId, facebookId);
2663 }
2664
2665
2672 @Override
2673 public User getUserById(long userId) throws PortalException {
2674 return userPersistence.findByPrimaryKey(userId);
2675 }
2676
2677
2686 @Override
2687 public User getUserById(long companyId, long userId)
2688 throws PortalException {
2689
2690 return userPersistence.findByC_U(companyId, userId);
2691 }
2692
2693
2701 @Override
2702 public User getUserByOpenId(long companyId, String openId)
2703 throws PortalException {
2704
2705 return userPersistence.findByC_O(companyId, openId);
2706 }
2707
2708
2715 @Override
2716 public User getUserByPortraitId(long portraitId) throws PortalException {
2717 return userPersistence.findByPortraitId(portraitId);
2718 }
2719
2720
2728 @Override
2729 public User getUserByScreenName(long companyId, String screenName)
2730 throws PortalException {
2731
2732 screenName = getLogin(screenName);
2733
2734 return userPersistence.findByC_SN(companyId, screenName);
2735 }
2736
2737
2746 @Deprecated
2747 @Override
2748 public User getUserByUuid(String uuid) throws PortalException {
2749 List<User> users = userPersistence.findByUuid(uuid);
2750
2751 if (users.isEmpty()) {
2752 throw new NoSuchUserException("{uuid=" + uuid + "}");
2753 }
2754 else {
2755 return users.get(0);
2756 }
2757 }
2758
2759
2767 @Override
2768 public User getUserByUuidAndCompanyId(String uuid, long companyId)
2769 throws PortalException {
2770
2771 List<User> users = userPersistence.findByUuid_C(uuid, companyId);
2772
2773 if (users.isEmpty()) {
2774 StringBundler sb = new StringBundler(5);
2775
2776 sb.append("{uuid=");
2777 sb.append(uuid);
2778 sb.append(", companyId=");
2779 sb.append(companyId);
2780 sb.append("}");
2781
2782 throw new NoSuchUserException(sb.toString());
2783 }
2784 else {
2785 return users.get(0);
2786 }
2787 }
2788
2789
2798 @Override
2799 public int getUserGroupUsersCount(long userGroupId, int status)
2800 throws PortalException {
2801
2802 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
2803 userGroupId);
2804
2805 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2806
2807 params.put("usersUserGroups", Long.valueOf(userGroupId));
2808
2809 return searchCount(userGroup.getCompanyId(), null, status, params);
2810 }
2811
2812
2821 @Override
2822 public long getUserIdByEmailAddress(long companyId, String emailAddress)
2823 throws PortalException {
2824
2825 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
2826
2827 User user = userPersistence.findByC_EA(companyId, emailAddress);
2828
2829 return user.getUserId();
2830 }
2831
2832
2840 @Override
2841 public long getUserIdByScreenName(long companyId, String screenName)
2842 throws PortalException {
2843
2844 screenName = getLogin(screenName);
2845
2846 User user = userPersistence.findByC_SN(companyId, screenName);
2847
2848 return user.getUserId();
2849 }
2850
2851
2860 @Override
2861 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId) {
2862 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
2863 passwordPolicyId, User.class.getName(), userId);
2864 }
2865
2866
2880 @Override
2881 public boolean hasRoleUser(
2882 long companyId, String name, long userId, boolean inherited)
2883 throws PortalException {
2884
2885 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
2886 }
2887
2888
2897 @Override
2898 public boolean isPasswordExpired(User user) throws PortalException {
2899 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2900
2901 if ((passwordPolicy != null) && passwordPolicy.getExpireable()) {
2902 Date now = new Date();
2903
2904 if (user.getPasswordModifiedDate() == null) {
2905 user.setPasswordModifiedDate(now);
2906
2907 userLocalService.updateUser(user);
2908 }
2909
2910 long passwordStartTime = user.getPasswordModifiedDate().getTime();
2911 long elapsedTime = now.getTime() - passwordStartTime;
2912
2913 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
2914 return true;
2915 }
2916 else {
2917 return false;
2918 }
2919 }
2920
2921 return false;
2922 }
2923
2924
2935 @Override
2936 public boolean isPasswordExpiringSoon(User user) throws PortalException {
2937 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2938
2939 if ((passwordPolicy != null) && passwordPolicy.isExpireable() &&
2940 (passwordPolicy.getWarningTime() > 0)) {
2941
2942 Date now = new Date();
2943
2944 if (user.getPasswordModifiedDate() == null) {
2945 user.setPasswordModifiedDate(now);
2946
2947 userLocalService.updateUser(user);
2948 }
2949
2950 long timeModified = user.getPasswordModifiedDate().getTime();
2951 long passwordExpiresOn =
2952 (passwordPolicy.getMaxAge() * 1000) + timeModified;
2953
2954 long timeStartWarning =
2955 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
2956
2957 if (now.getTime() > timeStartWarning) {
2958 return true;
2959 }
2960 else {
2961 return false;
2962 }
2963 }
2964
2965 return false;
2966 }
2967
2968
2975 @Override
2976 public User loadGetDefaultUser(long companyId) throws PortalException {
2977 return userPersistence.findByC_DU(companyId, true);
2978 }
2979
2980
3010 @Override
3011 public List<User> search(
3012 long companyId, String keywords, int status,
3013 LinkedHashMap<String, Object> params, int start, int end,
3014 OrderByComparator<User> obc) {
3015
3016 Indexer<?> indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3017
3018 if (!indexer.isIndexerEnabled() ||
3019 !PropsValues.USERS_SEARCH_WITH_INDEX || isUseCustomSQL(params)) {
3020
3021 return userFinder.findByKeywords(
3022 companyId, keywords, status, params, start, end, obc);
3023 }
3024
3025 try {
3026 return UsersAdminUtil.getUsers(
3027 search(
3028 companyId, keywords, status, params, start, end,
3029 getSorts(obc)));
3030 }
3031 catch (Exception e) {
3032 throw new SystemException(e);
3033 }
3034 }
3035
3036
3065 @Override
3066 public Hits search(
3067 long companyId, String keywords, int status,
3068 LinkedHashMap<String, Object> params, int start, int end, Sort sort) {
3069
3070 return search(
3071 companyId, keywords, status, params, start, end, new Sort[] {sort});
3072 }
3073
3074 @Override
3075 public Hits search(
3076 long companyId, String keywords, int status,
3077 LinkedHashMap<String, Object> params, int start, int end,
3078 Sort[] sorts) {
3079
3080 String firstName = null;
3081 String middleName = null;
3082 String lastName = null;
3083 String fullName = null;
3084 String screenName = null;
3085 String emailAddress = null;
3086 String street = null;
3087 String city = null;
3088 String zip = null;
3089 String region = null;
3090 String country = null;
3091 boolean andOperator = false;
3092
3093 if (Validator.isNotNull(keywords)) {
3094 firstName = keywords;
3095 middleName = keywords;
3096 lastName = keywords;
3097 fullName = keywords;
3098 screenName = keywords;
3099 emailAddress = keywords;
3100 street = keywords;
3101 city = keywords;
3102 zip = keywords;
3103 region = keywords;
3104 country = keywords;
3105 }
3106 else {
3107 andOperator = true;
3108 }
3109
3110 if (params != null) {
3111 params.put("keywords", keywords);
3112 }
3113
3114 try {
3115 Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3116 User.class);
3117
3118 SearchContext searchContext = buildSearchContext(
3119 companyId, firstName, middleName, lastName, fullName,
3120 screenName, emailAddress, street, city, zip, region, country,
3121 status, params, andOperator, start, end, sorts);
3122
3123 return indexer.search(searchContext);
3124 }
3125 catch (Exception e) {
3126 throw new SystemException(e);
3127 }
3128 }
3129
3130
3168 @Override
3169 public List<User> search(
3170 long companyId, String firstName, String middleName, String lastName,
3171 String screenName, String emailAddress, int status,
3172 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3173 int end, OrderByComparator<User> obc) {
3174
3175 Indexer<?> indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3176
3177 if (!indexer.isIndexerEnabled() ||
3178 !PropsValues.USERS_SEARCH_WITH_INDEX || isUseCustomSQL(params)) {
3179
3180 return userFinder.findByC_FN_MN_LN_SN_EA_S(
3181 companyId, firstName, middleName, lastName, screenName,
3182 emailAddress, status, params, andSearch, start, end, obc);
3183 }
3184
3185 try {
3186 return UsersAdminUtil.getUsers(
3187 search(
3188 companyId, firstName, middleName, lastName, screenName,
3189 emailAddress, status, params, andSearch, start, end,
3190 getSorts(obc)));
3191 }
3192 catch (Exception e) {
3193 throw new SystemException(e);
3194 }
3195 }
3196
3197
3234 @Override
3235 public Hits search(
3236 long companyId, String firstName, String middleName, String lastName,
3237 String screenName, String emailAddress, int status,
3238 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3239 int end, Sort sort) {
3240
3241 return search(
3242 companyId, firstName, middleName, lastName, screenName,
3243 emailAddress, status, params, andSearch, start, end,
3244 new Sort[] {sort});
3245 }
3246
3247 @Override
3248 public Hits search(
3249 long companyId, String firstName, String middleName, String lastName,
3250 String screenName, String emailAddress, int status,
3251 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3252 int end, Sort[] sorts) {
3253
3254 try {
3255 Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3256 User.class);
3257
3258 SearchContext searchContext = buildSearchContext(
3259 companyId, firstName, middleName, lastName, null, screenName,
3260 emailAddress, null, null, null, null, null, status, params,
3261 andSearch, start, end, sorts);
3262
3263 return indexer.search(searchContext);
3264 }
3265 catch (Exception e) {
3266 throw new SystemException(e);
3267 }
3268 }
3269
3270
3283 @Override
3284 public int searchCount(
3285 long companyId, String keywords, int status,
3286 LinkedHashMap<String, Object> params) {
3287
3288 Indexer<?> indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3289
3290 if (!indexer.isIndexerEnabled() ||
3291 !PropsValues.USERS_SEARCH_WITH_INDEX || isUseCustomSQL(params)) {
3292
3293 return userFinder.countByKeywords(
3294 companyId, keywords, status, params);
3295 }
3296
3297 try {
3298 String firstName = null;
3299 String middleName = null;
3300 String lastName = null;
3301 String fullName = null;
3302 String screenName = null;
3303 String emailAddress = null;
3304 String street = null;
3305 String city = null;
3306 String zip = null;
3307 String region = null;
3308 String country = null;
3309 boolean andOperator = false;
3310
3311 if (Validator.isNotNull(keywords)) {
3312 firstName = keywords;
3313 middleName = keywords;
3314 lastName = keywords;
3315 fullName = keywords;
3316 screenName = keywords;
3317 emailAddress = keywords;
3318 street = keywords;
3319 city = keywords;
3320 zip = keywords;
3321 region = keywords;
3322 country = keywords;
3323 }
3324 else {
3325 andOperator = true;
3326 }
3327
3328 if (params != null) {
3329 params.put("keywords", keywords);
3330 }
3331
3332 SearchContext searchContext = buildSearchContext(
3333 companyId, firstName, middleName, lastName, fullName,
3334 screenName, emailAddress, street, city, zip, region, country,
3335 status, params, andOperator, QueryUtil.ALL_POS,
3336 QueryUtil.ALL_POS, null);
3337
3338 return (int)indexer.searchCount(searchContext);
3339 }
3340 catch (Exception e) {
3341 throw new SystemException(e);
3342 }
3343 }
3344
3345
3366 @Override
3367 public int searchCount(
3368 long companyId, String firstName, String middleName, String lastName,
3369 String screenName, String emailAddress, int status,
3370 LinkedHashMap<String, Object> params, boolean andSearch) {
3371
3372 Indexer<?> indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3373
3374 if (!indexer.isIndexerEnabled() ||
3375 !PropsValues.USERS_SEARCH_WITH_INDEX || isUseCustomSQL(params)) {
3376
3377 return userFinder.countByC_FN_MN_LN_SN_EA_S(
3378 companyId, firstName, middleName, lastName, screenName,
3379 emailAddress, status, params, andSearch);
3380 }
3381
3382 try {
3383 FullNameGenerator fullNameGenerator =
3384 FullNameGeneratorFactory.getInstance();
3385
3386 String fullName = fullNameGenerator.getFullName(
3387 firstName, middleName, lastName);
3388
3389 SearchContext searchContext = buildSearchContext(
3390 companyId, firstName, middleName, lastName, fullName,
3391 screenName, emailAddress, null, null, null, null, null, status,
3392 params, true, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
3393
3394 return (int)indexer.searchCount(searchContext);
3395 }
3396 catch (Exception e) {
3397 throw new SystemException(e);
3398 }
3399 }
3400
3401 @Override
3402 public Map<Long, Integer> searchCounts(
3403 long companyId, int status, long[] groupIds) {
3404
3405 return userFinder.countByGroups(companyId, status, groupIds);
3406 }
3407
3408 @Override
3409 public List<User> searchSocial(
3410 long userId, int[] socialRelationTypes, String keywords, int start,
3411 int end)
3412 throws PortalException {
3413
3414 User user = userPersistence.findByPrimaryKey(userId);
3415
3416 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
3417
3418 params.put(
3419 "socialRelationType",
3420 new Long[][] {
3421 new Long[] {userId}, ArrayUtil.toLongArray(socialRelationTypes)
3422 });
3423 params.put("wildcardMode", WildcardMode.TRAILING);
3424
3425 return userFinder.findByKeywords(
3426 user.getCompanyId(), keywords, WorkflowConstants.STATUS_APPROVED,
3427 params, start, end, null);
3428 }
3429
3430 @Override
3431 public List<User> searchSocial(
3432 long companyId, long[] groupIds, String keywords, int start, int end) {
3433
3434 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
3435
3436 params.put("usersGroups", ArrayUtil.toLongArray(groupIds));
3437 params.put("wildcardMode", WildcardMode.TRAILING);
3438
3439 return userFinder.findByKeywords(
3440 companyId, keywords, WorkflowConstants.STATUS_APPROVED, params,
3441 start, end, null);
3442 }
3443
3444 @Override
3445 public List<User> searchSocial(
3446 long[] groupIds, long userId, int[] socialRelationTypes,
3447 String keywords, int start, int end)
3448 throws PortalException {
3449
3450 User user = userPersistence.findByPrimaryKey(userId);
3451
3452 LinkedHashMap<String, Object> params = new LinkedHashMap<>();
3453
3454 params.put(
3455 "socialRelationType",
3456 new Long[][] {
3457 new Long[] {userId}, ArrayUtil.toLongArray(socialRelationTypes)
3458 });
3459 params.put("socialRelationTypeUnionUserGroups", true);
3460 params.put("usersGroups", ArrayUtil.toLongArray(groupIds));
3461 params.put("wildcardMode", WildcardMode.TRAILING);
3462
3463 return userFinder.findByKeywords(
3464 user.getCompanyId(), keywords, WorkflowConstants.STATUS_APPROVED,
3465 params, start, end, null);
3466 }
3467
3468 @Override
3469 public BaseModelSearchResult<User> searchUsers(
3470 long companyId, String keywords, int status,
3471 LinkedHashMap<String, Object> params, int start, int end, Sort sort)
3472 throws PortalException {
3473
3474 return searchUsers(
3475 companyId, keywords, status, params, start, end, new Sort[] {sort});
3476 }
3477
3478 @Override
3479 public BaseModelSearchResult<User> searchUsers(
3480 long companyId, String keywords, int status,
3481 LinkedHashMap<String, Object> params, int start, int end,
3482 Sort[] sorts)
3483 throws PortalException {
3484
3485 String firstName = null;
3486 String middleName = null;
3487 String lastName = null;
3488 String fullName = null;
3489 String screenName = null;
3490 String emailAddress = null;
3491 String street = null;
3492 String city = null;
3493 String zip = null;
3494 String region = null;
3495 String country = null;
3496 boolean andOperator = false;
3497
3498 if (Validator.isNotNull(keywords)) {
3499 firstName = keywords;
3500 middleName = keywords;
3501 lastName = keywords;
3502 fullName = keywords;
3503 screenName = keywords;
3504 emailAddress = keywords;
3505 street = keywords;
3506 city = keywords;
3507 zip = keywords;
3508 region = keywords;
3509 country = keywords;
3510 }
3511 else {
3512 andOperator = true;
3513 }
3514
3515 if (params != null) {
3516 params.put("keywords", keywords);
3517 }
3518
3519 SearchContext searchContext = buildSearchContext(
3520 companyId, firstName, middleName, lastName, fullName, screenName,
3521 emailAddress, street, city, zip, region, country, status, params,
3522 andOperator, start, end, sorts);
3523
3524 return searchUsers(searchContext);
3525 }
3526
3527 @Override
3528 public BaseModelSearchResult<User> searchUsers(
3529 long companyId, String firstName, String middleName,
3530 String lastName, String screenName, String emailAddress, int status,
3531 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3532 int end, Sort sort)
3533 throws PortalException {
3534
3535 return searchUsers(
3536 companyId, firstName, middleName, lastName, screenName,
3537 emailAddress, status, params, andSearch, start, end,
3538 new Sort[] {sort});
3539 }
3540
3541 @Override
3542 public BaseModelSearchResult<User> searchUsers(
3543 long companyId, String firstName, String middleName,
3544 String lastName, String screenName, String emailAddress, int status,
3545 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3546 int end, Sort[] sorts)
3547 throws PortalException {
3548
3549 SearchContext searchContext = buildSearchContext(
3550 companyId, firstName, middleName, lastName, null, screenName,
3551 emailAddress, null, null, null, null, null, status, params,
3552 andSearch, start, end, sorts);
3553
3554 return searchUsers(searchContext);
3555 }
3556
3557
3567 @Override
3568 public void sendEmailAddressVerification(
3569 User user, String emailAddress, ServiceContext serviceContext)
3570 throws PortalException {
3571
3572 if (user.isEmailAddressVerified() &&
3573 StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
3574
3575 return;
3576 }
3577
3578 Ticket ticket = ticketLocalService.addDistinctTicket(
3579 user.getCompanyId(), User.class.getName(), user.getUserId(),
3580 TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3581 serviceContext);
3582
3583 String verifyEmailAddressURL =
3584 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3585 "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3586
3587 long plid = serviceContext.getPlid();
3588
3589 if (plid > 0) {
3590 Layout layout = layoutLocalService.fetchLayout(plid);
3591
3592 if (layout != null) {
3593 Group group = layout.getGroup();
3594
3595 if (!layout.isPrivateLayout() && !group.isUser()) {
3596 verifyEmailAddressURL +=
3597 "&p_l_id=" + serviceContext.getPlid();
3598 }
3599 }
3600 }
3601
3602 String fromName = PrefsPropsUtil.getString(
3603 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3604 String fromAddress = PrefsPropsUtil.getString(
3605 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3606
3607 String toName = user.getFullName();
3608 String toAddress = emailAddress;
3609
3610 PortletPreferences companyPortletPreferences =
3611 PrefsPropsUtil.getPreferences(user.getCompanyId(), true);
3612
3613 Map<Locale, String> localizedSubjectMap =
3614 LocalizationUtil.getLocalizationMap(
3615 companyPortletPreferences, "adminEmailVerificationSubject",
3616 PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3617 Map<Locale, String> localizedBodyMap =
3618 LocalizationUtil.getLocalizationMap(
3619 companyPortletPreferences, "adminEmailVerificationBody",
3620 PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3621
3622 SubscriptionSender subscriptionSender = new SubscriptionSender();
3623
3624 subscriptionSender.setCompanyId(user.getCompanyId());
3625 subscriptionSender.setContextAttributes(
3626 "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3627 "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3628 "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3629 "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_ID$]",
3630 user.getUserId(), "[$USER_SCREENNAME$]", user.getScreenName());
3631 subscriptionSender.setFrom(fromAddress, fromName);
3632 subscriptionSender.setHtmlFormat(true);
3633 subscriptionSender.setLocalizedBodyMap(localizedBodyMap);
3634 subscriptionSender.setLocalizedSubjectMap(localizedSubjectMap);
3635 subscriptionSender.setMailId("user", user.getUserId());
3636 subscriptionSender.setServiceContext(serviceContext);
3637
3638 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3639
3640 subscriptionSender.flushNotificationsAsync();
3641 }
3642
3643
3661 @Override
3662 public boolean sendPassword(
3663 long companyId, String emailAddress, String fromName,
3664 String fromAddress, String subject, String body,
3665 ServiceContext serviceContext)
3666 throws PortalException {
3667
3668 Company company = companyPersistence.findByPrimaryKey(companyId);
3669
3670 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3671 throw new SendPasswordException.MustBeEnabled(company);
3672 }
3673
3674 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
3675
3676 if (Validator.isNull(emailAddress)) {
3677 throw new UserEmailAddressException.MustNotBeNull();
3678 }
3679
3680 User user = userPersistence.findByC_EA(companyId, emailAddress);
3681
3682 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3683
3684 String newPassword = StringPool.BLANK;
3685 String passwordResetURL = StringPool.BLANK;
3686
3687 if (company.isSendPasswordResetLink()) {
3688 Date expirationDate = null;
3689
3690 if ((passwordPolicy != null) &&
3691 (passwordPolicy.getResetTicketMaxAge() > 0)) {
3692
3693 expirationDate = new Date(
3694 System.currentTimeMillis() +
3695 (passwordPolicy.getResetTicketMaxAge() * 1000));
3696 }
3697
3698 Ticket ticket = ticketLocalService.addDistinctTicket(
3699 companyId, User.class.getName(), user.getUserId(),
3700 TicketConstants.TYPE_PASSWORD, null, expirationDate,
3701 serviceContext);
3702
3703 passwordResetURL =
3704 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3705 "/portal/update_password?p_l_id="+
3706 serviceContext.getPlid() +
3707 "&ticketKey=" + ticket.getKey();
3708 }
3709 else {
3710 if (!Validator.equals(
3711 PasswordEncryptorUtil.getDefaultPasswordAlgorithmType(),
3712 PasswordEncryptorUtil.TYPE_NONE)) {
3713
3714 if (LDAPSettingsUtil.isPasswordPolicyEnabled(
3715 user.getCompanyId())) {
3716
3717 if (_log.isWarnEnabled()) {
3718 StringBundler sb = new StringBundler(5);
3719
3720 sb.append("When LDAP password policy is enabled, ");
3721 sb.append("it is possible that portal generated ");
3722 sb.append("passwords will not match the LDAP policy.");
3723 sb.append("Using RegExpToolkit to generate new ");
3724 sb.append("password.");
3725
3726 _log.warn(sb.toString());
3727 }
3728
3729 RegExpToolkit regExpToolkit = new RegExpToolkit();
3730
3731 newPassword = regExpToolkit.generate(null);
3732 }
3733 else {
3734 newPassword = PwdToolkitUtil.generate(passwordPolicy);
3735 }
3736
3737 boolean passwordReset = false;
3738
3739 if (passwordPolicy.getChangeable() &&
3740 passwordPolicy.getChangeRequired()) {
3741
3742 passwordReset = true;
3743 }
3744
3745 user.setPassword(PasswordEncryptorUtil.encrypt(newPassword));
3746 user.setPasswordUnencrypted(newPassword);
3747 user.setPasswordEncrypted(true);
3748 user.setPasswordReset(passwordReset);
3749 user.setPasswordModified(true);
3750 user.setPasswordModifiedDate(new Date());
3751
3752 userPersistence.update(user);
3753
3754 user.setPasswordModified(false);
3755 }
3756 else {
3757 newPassword = user.getPassword();
3758 }
3759 }
3760
3761 sendPasswordNotification(
3762 user, companyId, newPassword, passwordResetURL, fromName,
3763 fromAddress, subject, body, serviceContext);
3764
3765 return company.isSendPassword();
3766 }
3767
3768
3790 @Override
3791 public boolean sendPasswordByEmailAddress(
3792 long companyId, String emailAddress)
3793 throws PortalException {
3794
3795 User user = userPersistence.findByC_EA(companyId, emailAddress);
3796
3797 return sendPassword(
3798 user.getCompanyId(), user.getEmailAddress(), null, null, null, null,
3799 ServiceContextThreadLocal.getServiceContext());
3800 }
3801
3802
3822 @Override
3823 public boolean sendPasswordByScreenName(long companyId, String screenName)
3824 throws PortalException {
3825
3826 User user = userPersistence.findByC_SN(companyId, screenName);
3827
3828 return sendPassword(
3829 user.getCompanyId(), user.getEmailAddress(), null, null, null, null,
3830 ServiceContextThreadLocal.getServiceContext());
3831 }
3832
3833
3852 @Override
3853 public boolean sendPasswordByUserId(long userId) throws PortalException {
3854 User user = userPersistence.findByPrimaryKey(userId);
3855
3856 return sendPassword(
3857 user.getCompanyId(), user.getEmailAddress(), null, null, null, null,
3858 ServiceContextThreadLocal.getServiceContext());
3859 }
3860
3861
3869 @Override
3870 public void setRoleUsers(long roleId, long[] userIds)
3871 throws PortalException {
3872
3873 long[] oldUserIds = rolePersistence.getUserPrimaryKeys(roleId);
3874
3875 Set<Long> updatedUserIdsSet = SetUtil.symmetricDifference(
3876 userIds, oldUserIds);
3877
3878 long[] updateUserIds = ArrayUtil.toLongArray(updatedUserIdsSet);
3879
3880 rolePersistence.setUsers(roleId, userIds);
3881
3882 reindex(updateUserIds);
3883
3884 PermissionCacheUtil.clearCache(updateUserIds);
3885 }
3886
3887
3895 @Override
3896 @SuppressWarnings("deprecation")
3897 public void setUserGroupUsers(long userGroupId, long[] userIds)
3898 throws PortalException {
3899
3900 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3901 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3902 }
3903
3904 long[] oldUserIds = userGroupPersistence.getUserPrimaryKeys(
3905 userGroupId);
3906
3907 Set<Long> updatedUserIdsSet = SetUtil.symmetricDifference(
3908 userIds, oldUserIds);
3909
3910 long[] updateUserIds = ArrayUtil.toLongArray(updatedUserIdsSet);
3911
3912 userGroupPersistence.setUsers(userGroupId, userIds);
3913
3914 reindex(updateUserIds);
3915
3916 PermissionCacheUtil.clearCache(updateUserIds);
3917 }
3918
3919
3926 @Override
3927 public void unsetGroupTeamsUsers(long groupId, long[] userIds)
3928 throws PortalException {
3929
3930 List<Team> teams = teamPersistence.findByGroupId(groupId);
3931
3932 for (Team team : teams) {
3933 unsetTeamUsers(team.getTeamId(), userIds);
3934 }
3935
3936 PermissionCacheUtil.clearCache(userIds);
3937 }
3938
3939
3948 @Override
3949 public void unsetGroupUsers(
3950 final long groupId, final long[] userIds,
3951 ServiceContext serviceContext)
3952 throws PortalException {
3953
3954 userGroupRoleLocalService.deleteUserGroupRoles(
3955 userIds, groupId, RoleConstants.TYPE_SITE);
3956
3957 unsetGroupTeamsUsers(groupId, userIds);
3958
3959 groupPersistence.removeUsers(groupId, userIds);
3960
3961 reindex(userIds);
3962
3963 PermissionCacheUtil.clearCache(userIds);
3964
3965 Callable<Void> callable = new Callable<Void>() {
3966
3967 @Override
3968 public Void call() throws Exception {
3969 Message message = new Message();
3970
3971 message.put("groupId", groupId);
3972 message.put("userIds", userIds);
3973
3974 MessageBusUtil.sendMessage(
3975 DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
3976
3977 return null;
3978 }
3979
3980 };
3981
3982 TransactionCommitCallbackUtil.registerCallback(callable);
3983 }
3984
3985
3992 @Override
3993 public void unsetOrganizationUsers(
3994 long organizationId, final long[] userIds)
3995 throws PortalException {
3996
3997 Organization organization = organizationPersistence.findByPrimaryKey(
3998 organizationId);
3999
4000 final Group group = organization.getGroup();
4001
4002 userGroupRoleLocalService.deleteUserGroupRoles(
4003 userIds, group.getGroupId());
4004
4005 organizationPersistence.removeUsers(organizationId, userIds);
4006
4007 reindex(userIds);
4008
4009 PermissionCacheUtil.clearCache(userIds);
4010
4011 Callable<Void> callable = new Callable<Void>() {
4012
4013 @Override
4014 public Void call() throws Exception {
4015 Message message = new Message();
4016
4017 message.put("groupId", group.getGroupId());
4018 message.put("userIds", userIds);
4019
4020 MessageBusUtil.sendMessage(
4021 DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
4022
4023 return null;
4024 }
4025
4026 };
4027
4028 TransactionCommitCallbackUtil.registerCallback(callable);
4029 }
4030
4031
4037 @Override
4038 public void unsetPasswordPolicyUsers(
4039 long passwordPolicyId, long[] userIds) {
4040
4041 passwordPolicyRelLocalService.deletePasswordPolicyRels(
4042 passwordPolicyId, User.class.getName(), userIds);
4043 }
4044
4045
4052 @Override
4053 public void unsetRoleUsers(long roleId, List<User> users)
4054 throws PortalException {
4055
4056 Role role = rolePersistence.findByPrimaryKey(roleId);
4057
4058 String roleName = role.getName();
4059
4060 if ((roleName.equals(RoleConstants.ADMINISTRATOR) &&
4061 (getRoleUsersCount(role.getRoleId()) <= 1)) ||
4062 roleName.equals(RoleConstants.USER)) {
4063
4064 return;
4065 }
4066
4067 rolePersistence.removeUsers(roleId, users);
4068
4069 Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4070 User.class);
4071
4072 indexer.reindex(users);
4073
4074 long[] userIds = new long[users.size()];
4075
4076 for (int i = 0; i < users.size(); i++) {
4077 User user = users.get(i);
4078
4079 userIds[i] = user.getUserId();
4080 }
4081
4082 PermissionCacheUtil.clearCache(userIds);
4083 }
4084
4085
4092 @Override
4093 public void unsetRoleUsers(long roleId, long[] userIds)
4094 throws PortalException {
4095
4096 Role role = rolePersistence.findByPrimaryKey(roleId);
4097
4098 String roleName = role.getName();
4099
4100 if (roleName.equals(RoleConstants.USER) ||
4101 (roleName.equals(RoleConstants.ADMINISTRATOR) &&
4102 getRoleUsersCount(role.getRoleId()) <= 1)) {
4103
4104 return;
4105 }
4106
4107 rolePersistence.removeUsers(roleId, userIds);
4108
4109 reindex(userIds);
4110
4111 PermissionCacheUtil.clearCache(userIds);
4112 }
4113
4114
4121 @Override
4122 public void unsetTeamUsers(long teamId, long[] userIds)
4123 throws PortalException {
4124
4125 teamPersistence.removeUsers(teamId, userIds);
4126
4127 reindex(userIds);
4128
4129 PermissionCacheUtil.clearCache(userIds);
4130 }
4131
4132
4139 @Override
4140 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
4141 throws PortalException {
4142
4143 userGroupPersistence.removeUsers(userGroupId, userIds);
4144
4145 reindex(userIds);
4146
4147 PermissionCacheUtil.clearCache(userIds);
4148 }
4149
4150
4159 @Override
4160 public User updateAgreedToTermsOfUse(
4161 long userId, boolean agreedToTermsOfUse)
4162 throws PortalException {
4163
4164 User user = userPersistence.findByPrimaryKey(userId);
4165
4166 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
4167
4168 userPersistence.update(user);
4169
4170 return user;
4171 }
4172
4173
4183 @Override
4184 public void updateAsset(
4185 long userId, User user, long[] assetCategoryIds,
4186 String[] assetTagNames)
4187 throws PortalException {
4188
4189 User owner = userPersistence.findByPrimaryKey(userId);
4190
4191 Company company = companyPersistence.findByPrimaryKey(
4192 owner.getCompanyId());
4193
4194 Group companyGroup = company.getGroup();
4195
4196 assetEntryLocalService.updateEntry(
4197 userId, companyGroup.getGroupId(), user.getCreateDate(),
4198 user.getModifiedDate(), User.class.getName(), user.getUserId(),
4199 user.getUuid(), 0, assetCategoryIds, assetTagNames, false, null,
4200 null, null, null, user.getFullName(), null, null, null, null, 0, 0,
4201 null);
4202 }
4203
4204
4212 @Override
4213 public User updateCreateDate(long userId, Date createDate)
4214 throws PortalException {
4215
4216 User user = userPersistence.findByPrimaryKey(userId);
4217
4218 user.setCreateDate(createDate);
4219
4220 userPersistence.update(user);
4221
4222 return user;
4223 }
4224
4225
4235 @Override
4236 public User updateEmailAddress(
4237 long userId, String password, String emailAddress1,
4238 String emailAddress2)
4239 throws PortalException {
4240
4241 emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
4242 emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
4243
4244 User user = userPersistence.findByPrimaryKey(userId);
4245
4246 validateEmailAddress(user, emailAddress1, emailAddress2);
4247
4248 setEmailAddress(
4249 user, password, user.getFirstName(), user.getMiddleName(),
4250 user.getLastName(), emailAddress1);
4251
4252 userPersistence.update(user);
4253
4254 Contact contact = user.getContact();
4255
4256 contact.setEmailAddress(user.getEmailAddress());
4257
4258 contactPersistence.update(contact);
4259
4260 return user;
4261 }
4262
4263
4276 @Override
4277 public User updateEmailAddress(
4278 long userId, String password, String emailAddress1,
4279 String emailAddress2, ServiceContext serviceContext)
4280 throws PortalException {
4281
4282 emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
4283 emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
4284
4285 User user = userPersistence.findByPrimaryKey(userId);
4286
4287 validateEmailAddress(user, emailAddress1, emailAddress2);
4288
4289 Company company = companyPersistence.findByPrimaryKey(
4290 user.getCompanyId());
4291
4292 if (company.isStrangersVerify() &&
4293 !StringUtil.equalsIgnoreCase(
4294 emailAddress1, user.getEmailAddress())) {
4295
4296 sendEmailAddressVerification(user, emailAddress1, serviceContext);
4297 }
4298 else {
4299 setEmailAddress(
4300 user, password, user.getFirstName(), user.getMiddleName(),
4301 user.getLastName(), emailAddress1);
4302
4303 userPersistence.update(user);
4304
4305 Contact contact = user.getContact();
4306
4307 contact.setEmailAddress(user.getEmailAddress());
4308
4309 contactPersistence.update(contact);
4310 }
4311
4312 return user;
4313 }
4314
4315
4323 @Override
4324 public User updateEmailAddressVerified(
4325 long userId, boolean emailAddressVerified)
4326 throws PortalException {
4327
4328 User user = userPersistence.findByPrimaryKey(userId);
4329
4330 user.setEmailAddressVerified(emailAddressVerified);
4331
4332 userPersistence.update(user);
4333
4334 return user;
4335 }
4336
4337
4345 @Override
4346 public User updateFacebookId(long userId, long facebookId)
4347 throws PortalException {
4348
4349 User user = userPersistence.findByPrimaryKey(userId);
4350
4351 user.setFacebookId(facebookId);
4352
4353 userPersistence.update(user);
4354
4355 return user;
4356 }
4357
4358
4367 @Override
4368 public void updateGroups(
4369 long userId, long[] newGroupIds, ServiceContext serviceContext)
4370 throws PortalException {
4371
4372 boolean indexingEnabled = true;
4373
4374 if (serviceContext != null) {
4375 indexingEnabled = serviceContext.isIndexingEnabled();
4376 }
4377
4378 updateGroups(userId, newGroupIds, serviceContext, indexingEnabled);
4379 }
4380
4381
4419 @Override
4420 public User updateIncompleteUser(
4421 long creatorUserId, long companyId, boolean autoPassword,
4422 String password1, String password2, boolean autoScreenName,
4423 String screenName, String emailAddress, long facebookId,
4424 String openId, Locale locale, String firstName, String middleName,
4425 String lastName, long prefixId, long suffixId, boolean male,
4426 int birthdayMonth, int birthdayDay, int birthdayYear,
4427 String jobTitle, boolean updateUserInformation, boolean sendEmail,
4428 ServiceContext serviceContext)
4429 throws PortalException {
4430
4431 User user = getUserByEmailAddress(companyId, emailAddress);
4432
4433 if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
4434 throw new PortalException("Invalid user status");
4435 }
4436
4437 User defaultUser = getDefaultUser(companyId);
4438
4439 if (facebookId > 0) {
4440 autoPassword = false;
4441
4442 if ((password1 == null) || (password2 == null)) {
4443 password1 = PwdGenerator.getPassword();
4444 password2 = password1;
4445 }
4446
4447 sendEmail = false;
4448 }
4449
4450 if (updateUserInformation) {
4451 autoScreenName = false;
4452
4453 if (PrefsPropsUtil.getBoolean(
4454 companyId,
4455 PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
4456
4457 autoScreenName = true;
4458 }
4459
4460 validate(
4461 companyId, user.getUserId(), autoPassword, password1, password2,
4462 autoScreenName, screenName, emailAddress, openId, firstName,
4463 middleName, lastName, null, locale);
4464
4465 if (!autoPassword) {
4466 if (Validator.isNull(password1) ||
4467 Validator.isNull(password2)) {
4468 throw new UserPasswordException.MustNotBeNull(
4469 user.getUserId());
4470 }
4471 }
4472
4473 if (autoScreenName) {
4474 ScreenNameGenerator screenNameGenerator =
4475 ScreenNameGeneratorFactory.getInstance();
4476
4477 try {
4478 screenName = screenNameGenerator.generate(
4479 companyId, user.getUserId(), emailAddress);
4480 }
4481 catch (Exception e) {
4482 throw new SystemException(e);
4483 }
4484 }
4485
4486 FullNameGenerator fullNameGenerator =
4487 FullNameGeneratorFactory.getInstance();
4488
4489 String fullName = fullNameGenerator.getFullName(
4490 firstName, middleName, lastName);
4491
4492 String greeting = LanguageUtil.format(
4493 locale, "welcome-x", fullName, false);
4494
4495 if (Validator.isNotNull(password1)) {
4496 user.setPassword(PasswordEncryptorUtil.encrypt(password1));
4497 user.setPasswordUnencrypted(password1);
4498 }
4499
4500 user.setPasswordEncrypted(true);
4501
4502 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
4503
4504 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
4505 passwordPolicy.isChangeRequired()) {
4506
4507 user.setPasswordReset(true);
4508 }
4509 else {
4510 user.setPasswordReset(false);
4511 }
4512
4513 user.setScreenName(screenName);
4514 user.setFacebookId(facebookId);
4515 user.setOpenId(openId);
4516 user.setLanguageId(locale.toString());
4517 user.setTimeZoneId(defaultUser.getTimeZoneId());
4518 user.setGreeting(greeting);
4519 user.setFirstName(firstName);
4520 user.setMiddleName(middleName);
4521 user.setLastName(lastName);
4522 user.setJobTitle(jobTitle);
4523 user.setExpandoBridgeAttributes(serviceContext);
4524
4525 Date birthday = getBirthday(
4526 birthdayMonth, birthdayDay, birthdayYear);
4527
4528 Contact contact = user.getContact();
4529
4530 contact.setFirstName(firstName);
4531 contact.setMiddleName(middleName);
4532 contact.setLastName(lastName);
4533 contact.setPrefixId(prefixId);
4534 contact.setSuffixId(suffixId);
4535 contact.setMale(male);
4536 contact.setBirthday(birthday);
4537 contact.setJobTitle(jobTitle);
4538
4539 contactPersistence.update(contact, serviceContext);
4540
4541
4542
4543 Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4544 User.class);
4545
4546 indexer.reindex(user);
4547 }
4548
4549 user.setStatus(WorkflowConstants.STATUS_DRAFT);
4550
4551 userPersistence.update(user, serviceContext);
4552
4553
4554
4555 long workflowUserId = creatorUserId;
4556
4557 if (workflowUserId == user.getUserId()) {
4558 workflowUserId = defaultUser.getUserId();
4559 }
4560
4561 ServiceContext workflowServiceContext = serviceContext;
4562
4563 if (workflowServiceContext == null) {
4564 workflowServiceContext = new ServiceContext();
4565 }
4566
4567 workflowServiceContext.setAttribute("autoPassword", autoPassword);
4568 workflowServiceContext.setAttribute("passwordUnencrypted", password1);
4569 workflowServiceContext.setAttribute("sendEmail", sendEmail);
4570
4571 WorkflowHandlerRegistryUtil.startWorkflowInstance(
4572 companyId, workflowUserId, User.class.getName(), user.getUserId(),
4573 user, workflowServiceContext);
4574
4575 return getUserByEmailAddress(companyId, emailAddress);
4576 }
4577
4578
4587 @Override
4588 public User updateJobTitle(long userId, String jobTitle)
4589 throws PortalException {
4590
4591 User user = userPersistence.findByPrimaryKey(userId);
4592
4593 user.setJobTitle(jobTitle);
4594
4595 userPersistence.update(user);
4596
4597 Contact contact = contactPersistence.findByPrimaryKey(
4598 user.getContactId());
4599
4600 contact.setJobTitle(jobTitle);
4601
4602 contactPersistence.update(contact);
4603
4604 return user;
4605 }
4606
4607
4615 @Override
4616 public User updateLastLogin(long userId, String loginIP)
4617 throws PortalException {
4618
4619 User user = userPersistence.findByPrimaryKey(userId);
4620
4621 Date lastLoginDate = user.getLoginDate();
4622
4623 if (lastLoginDate == null) {
4624 lastLoginDate = new Date();
4625 }
4626
4627 String lastLoginIP = user.getLoginIP();
4628
4629 if (lastLoginIP == null) {
4630 lastLoginIP = loginIP;
4631 }
4632
4633 user.setLoginDate(new Date());
4634 user.setLoginIP(loginIP);
4635 user.setLastLoginDate(lastLoginDate);
4636 user.setLastLoginIP(lastLoginIP);
4637
4638 resetFailedLoginAttempts(user, true);
4639
4640 return user;
4641 }
4642
4643
4651 @Override
4652 public User updateLockout(User user, boolean lockout)
4653 throws PortalException {
4654
4655 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
4656
4657 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
4658 return user;
4659 }
4660
4661 Date lockoutDate = null;
4662
4663 if (lockout) {
4664 lockoutDate = new Date();
4665 }
4666
4667 user.setLockout(lockout);
4668 user.setLockoutDate(lockoutDate);
4669
4670 if (!lockout) {
4671 user.setFailedLoginAttempts(0);
4672 }
4673
4674 userPersistence.update(user);
4675
4676 return user;
4677 }
4678
4679
4689 @Override
4690 public User updateLockoutByEmailAddress(
4691 long companyId, String emailAddress, boolean lockout)
4692 throws PortalException {
4693
4694 User user = getUserByEmailAddress(companyId, emailAddress);
4695
4696 return updateLockout(user, lockout);
4697 }
4698
4699
4707 @Override
4708 public User updateLockoutById(long userId, boolean lockout)
4709 throws PortalException {
4710
4711 User user = userPersistence.findByPrimaryKey(userId);
4712
4713 return updateLockout(user, lockout);
4714 }
4715
4716
4725 @Override
4726 public User updateLockoutByScreenName(
4727 long companyId, String screenName, boolean lockout)
4728 throws PortalException {
4729
4730 User user = getUserByScreenName(companyId, screenName);
4731
4732 return updateLockout(user, lockout);
4733 }
4734
4735
4743 @Override
4744 public User updateModifiedDate(long userId, Date modifiedDate)
4745 throws PortalException {
4746
4747 User user = userPersistence.findByPrimaryKey(userId);
4748
4749 userPersistence.update(user);
4750
4751 return user;
4752 }
4753
4754
4762 @Override
4763 public User updateOpenId(long userId, String openId)
4764 throws PortalException {
4765
4766 openId = openId.trim();
4767
4768 User user = userPersistence.findByPrimaryKey(userId);
4769
4770 user.setOpenId(openId);
4771
4772 userPersistence.update(user);
4773
4774 return user;
4775 }
4776
4777
4787 @Override
4788 public void updateOrganizations(
4789 long userId, long[] newOrganizationIds,
4790 ServiceContext serviceContext)
4791 throws PortalException {
4792
4793 updateOrganizations(
4794 userId, newOrganizationIds, serviceContext.isIndexingEnabled());
4795 }
4796
4797
4808 @Override
4809 public User updatePassword(
4810 long userId, String password1, String password2,
4811 boolean passwordReset)
4812 throws PortalException {
4813
4814 return updatePassword(
4815 userId, password1, password2, passwordReset, false);
4816 }
4817
4818
4832 @Override
4833 public User updatePassword(
4834 long userId, String password1, String password2,
4835 boolean passwordReset, boolean silentUpdate)
4836 throws PortalException {
4837
4838 User user = userPersistence.findByPrimaryKey(userId);
4839
4840 if (!silentUpdate) {
4841 validatePassword(user.getCompanyId(), userId, password1, password2);
4842 }
4843
4844 String oldEncPwd = user.getPassword();
4845
4846 if (!user.isPasswordEncrypted()) {
4847 oldEncPwd = PasswordEncryptorUtil.encrypt(user.getPassword());
4848 }
4849
4850 String newEncPwd = PasswordEncryptorUtil.encrypt(password1);
4851
4852 if (user.hasCompanyMx()) {
4853 mailService.updatePassword(user.getCompanyId(), userId, password1);
4854 }
4855
4856 user.setPassword(newEncPwd);
4857 user.setPasswordUnencrypted(password1);
4858 user.setPasswordEncrypted(true);
4859 user.setPasswordReset(passwordReset);
4860
4861 if (!silentUpdate || (user.getPasswordModifiedDate() == null)) {
4862 user.setPasswordModifiedDate(new Date());
4863 }
4864
4865 user.setDigest(StringPool.BLANK);
4866 user.setGraceLoginCount(0);
4867
4868 if (!silentUpdate) {
4869 user.setPasswordModified(true);
4870 }
4871
4872 try {
4873 userPersistence.update(user);
4874 }
4875 catch (ModelListenerException mle) {
4876 String msg = GetterUtil.getString(mle.getCause().getMessage());
4877
4878 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
4879 String passwordHistory = PrefsPropsUtil.getString(
4880 user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
4881
4882 if (msg.contains(passwordHistory)) {
4883 throw new UserPasswordException.MustNotBeRecentlyUsed(
4884 userId);
4885 }
4886 }
4887
4888 throw new UserPasswordException.MustComplyWithModelListeners(
4889 userId, mle);
4890 }
4891
4892 if (!silentUpdate) {
4893 user.setPasswordModified(false);
4894
4895 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
4896 }
4897
4898 if (!silentUpdate && (PrincipalThreadLocal.getUserId() != userId)) {
4899 sendPasswordNotification(
4900 user, user.getCompanyId(), password1, null, null, null, null,
4901 null, ServiceContextThreadLocal.getServiceContext());
4902 }
4903
4904 return user;
4905 }
4906
4907
4920 @Override
4921 public User updatePasswordManually(
4922 long userId, String password, boolean passwordEncrypted,
4923 boolean passwordReset, Date passwordModifiedDate)
4924 throws PortalException {
4925
4926
4927
4928 User user = userPersistence.findByPrimaryKey(userId);
4929
4930 user.setPassword(password);
4931 user.setPasswordEncrypted(passwordEncrypted);
4932 user.setPasswordReset(passwordReset);
4933 user.setPasswordModifiedDate(passwordModifiedDate);
4934 user.setDigest(StringPool.BLANK);
4935
4936 userPersistence.update(user);
4937
4938 return user;
4939 }
4940
4941
4951 @Override
4952 public User updatePasswordReset(long userId, boolean passwordReset)
4953 throws PortalException {
4954
4955 User user = userPersistence.findByPrimaryKey(userId);
4956
4957 user.setPasswordReset(passwordReset);
4958
4959 userPersistence.update(user);
4960
4961 return user;
4962 }
4963
4964
4973 @Override
4974 public User updatePortrait(long userId, byte[] bytes)
4975 throws PortalException {
4976
4977 User user = userPersistence.findByPrimaryKey(userId);
4978
4979 PortalUtil.updateImageId(
4980 user, true, bytes, "portraitId",
4981 PrefsPropsUtil.getLong(PropsKeys.USERS_IMAGE_MAX_SIZE),
4982 PropsValues.USERS_IMAGE_MAX_HEIGHT,
4983 PropsValues.USERS_IMAGE_MAX_WIDTH);
4984
4985 return userPersistence.update(user);
4986 }
4987
4988
4998 @Override
4999 public User updateReminderQuery(long userId, String question, String answer)
5000 throws PortalException {
5001
5002 validateReminderQuery(question, answer);
5003
5004 User user = userPersistence.findByPrimaryKey(userId);
5005
5006 user.setReminderQueryQuestion(question);
5007 user.setReminderQueryAnswer(answer);
5008
5009 userPersistence.update(user);
5010
5011 return user;
5012 }
5013
5014
5023 @Override
5024 public User updateScreenName(long userId, String screenName)
5025 throws PortalException {
5026
5027
5028
5029 User user = userPersistence.findByPrimaryKey(userId);
5030
5031 screenName = getLogin(screenName);
5032
5033 validateScreenName(user.getCompanyId(), userId, screenName);
5034
5035 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
5036 user.setDigest(StringPool.BLANK);
5037 }
5038
5039 user.setScreenName(screenName);
5040
5041 userPersistence.update(user);
5042
5043
5044
5045 Group group = groupLocalService.getUserGroup(
5046 user.getCompanyId(), userId);
5047
5048 group.setFriendlyURL(StringPool.SLASH + screenName);
5049
5050 groupPersistence.update(group);
5051
5052 return user;
5053 }
5054
5055
5066 @Deprecated
5067 @Override
5068 public User updateStatus(long userId, int status) throws PortalException {
5069 return updateStatus(userId, status, new ServiceContext());
5070 }
5071
5072
5083 @Override
5084 public User updateStatus(
5085 long userId, int status, ServiceContext serviceContext)
5086 throws PortalException {
5087
5088 User user = userPersistence.findByPrimaryKey(userId);
5089
5090 if ((status == WorkflowConstants.STATUS_APPROVED) &&
5091 (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {
5092
5093 validateCompanyMaxUsers(user.getCompanyId());
5094 }
5095
5096 String passwordUnencrypted = (String)serviceContext.getAttribute(
5097 "passwordUnencrypted");
5098
5099 if (Validator.isNotNull(passwordUnencrypted)) {
5100 user.setPasswordUnencrypted(passwordUnencrypted);
5101 }
5102
5103 user.setStatus(status);
5104
5105 userPersistence.update(user);
5106
5107 reindex(user);
5108
5109 return user;
5110 }
5111
5112
5168 @Override
5169 @SuppressWarnings("deprecation")
5170 public User updateUser(
5171 long userId, String oldPassword, String newPassword1,
5172 String newPassword2, boolean passwordReset,
5173 String reminderQueryQuestion, String reminderQueryAnswer,
5174 String screenName, String emailAddress, long facebookId,
5175 String openId, boolean portrait, byte[] portraitBytes,
5176 String languageId, String timeZoneId, String greeting,
5177 String comments, String firstName, String middleName,
5178 String lastName, long prefixId, long suffixId, boolean male,
5179 int birthdayMonth, int birthdayDay, int birthdayYear, String smsSn,
5180 String aimSn, String facebookSn, String icqSn, String jabberSn,
5181 String mySpaceSn, String skypeSn, String twitterSn, String ymSn,
5182 String jobTitle, long[] groupIds, long[] organizationIds,
5183 long[] roleIds, List<UserGroupRole> userGroupRoles,
5184 long[] userGroupIds, ServiceContext serviceContext)
5185 throws PortalException {
5186
5187
5188
5189 User user = userPersistence.findByPrimaryKey(userId);
5190 Company company = companyPersistence.findByPrimaryKey(
5191 user.getCompanyId());
5192 String password = oldPassword;
5193 screenName = getLogin(screenName);
5194 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
5195 openId = openId.trim();
5196 String oldFullName = user.getFullName();
5197 aimSn = StringUtil.toLowerCase(aimSn.trim());
5198 facebookSn = StringUtil.toLowerCase(facebookSn.trim());
5199 icqSn = StringUtil.toLowerCase(icqSn.trim());
5200 jabberSn = StringUtil.toLowerCase(jabberSn.trim());
5201 mySpaceSn = StringUtil.toLowerCase(mySpaceSn.trim());
5202 skypeSn = StringUtil.toLowerCase(skypeSn.trim());
5203 twitterSn = StringUtil.toLowerCase(twitterSn.trim());
5204 ymSn = StringUtil.toLowerCase(ymSn.trim());
5205
5206 EmailAddressGenerator emailAddressGenerator =
5207 EmailAddressGeneratorFactory.getInstance();
5208
5209 if (emailAddressGenerator.isGenerated(emailAddress)) {
5210 emailAddress = StringPool.BLANK;
5211 }
5212
5213 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
5214 Validator.isNull(emailAddress)) {
5215
5216 emailAddress = emailAddressGenerator.generate(
5217 user.getCompanyId(), userId);
5218 }
5219
5220 Locale locale = LocaleUtil.fromLanguageId(languageId);
5221
5222 validate(
5223 userId, screenName, emailAddress, openId, firstName, middleName,
5224 lastName, smsSn, locale);
5225
5226 if (Validator.isNotNull(newPassword1) ||
5227 Validator.isNotNull(newPassword2)) {
5228
5229 user = updatePassword(
5230 userId, newPassword1, newPassword2, passwordReset);
5231
5232 password = newPassword1;
5233
5234 user.setDigest(StringPool.BLANK);
5235 }
5236
5237 if (user.getContactId() <= 0) {
5238 user.setContactId(counterLocalService.increment());
5239 }
5240
5241 user.setPasswordReset(passwordReset);
5242
5243 if (Validator.isNotNull(reminderQueryQuestion) &&
5244 Validator.isNotNull(reminderQueryAnswer)) {
5245
5246 user.setReminderQueryQuestion(reminderQueryQuestion);
5247 user.setReminderQueryAnswer(reminderQueryAnswer);
5248 }
5249
5250 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
5251 user.setScreenName(screenName);
5252
5253 user.setDigest(StringPool.BLANK);
5254 }
5255
5256 boolean sendEmailAddressVerification = false;
5257
5258 if (company.isStrangersVerify() &&
5259 !StringUtil.equalsIgnoreCase(
5260 emailAddress, user.getEmailAddress())) {
5261
5262 sendEmailAddressVerification = true;
5263 }
5264 else {
5265 setEmailAddress(
5266 user, password, firstName, middleName, lastName, emailAddress);
5267 }
5268
5269 if (serviceContext != null) {
5270 String uuid = serviceContext.getUuid();
5271
5272 if (Validator.isNotNull(uuid)) {
5273 user.setUuid(uuid);
5274 }
5275 }
5276
5277 user.setFacebookId(facebookId);
5278
5279 Long ldapServerId = null;
5280
5281 if (serviceContext != null) {
5282 ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
5283 }
5284
5285 if (ldapServerId != null) {
5286 user.setLdapServerId(ldapServerId);
5287 }
5288
5289 user.setOpenId(openId);
5290
5291 PortalUtil.updateImageId(
5292 user, portrait, portraitBytes, "portraitId",
5293 PrefsPropsUtil.getLong(PropsKeys.USERS_IMAGE_MAX_SIZE),
5294 PropsValues.USERS_IMAGE_MAX_HEIGHT,
5295 PropsValues.USERS_IMAGE_MAX_WIDTH);
5296
5297 user.setLanguageId(languageId);
5298 user.setTimeZoneId(timeZoneId);
5299 user.setGreeting(greeting);
5300 user.setComments(comments);
5301 user.setFirstName(firstName);
5302 user.setMiddleName(middleName);
5303 user.setLastName(lastName);
5304 user.setJobTitle(jobTitle);
5305 user.setExpandoBridgeAttributes(serviceContext);
5306
5307 userPersistence.update(user, serviceContext);
5308
5309
5310
5311 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
5312
5313 long contactId = user.getContactId();
5314
5315 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
5316
5317 if (contact == null) {
5318 contact = contactPersistence.create(contactId);
5319
5320 contact.setCompanyId(user.getCompanyId());
5321 contact.setUserName(StringPool.BLANK);
5322 contact.setClassName(User.class.getName());
5323 contact.setClassPK(user.getUserId());
5324 contact.setAccountId(company.getAccountId());
5325 contact.setParentContactId(
5326 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
5327 }
5328
5329 contact.setEmailAddress(user.getEmailAddress());
5330 contact.setFirstName(firstName);
5331 contact.setMiddleName(middleName);
5332 contact.setLastName(lastName);
5333 contact.setPrefixId(prefixId);
5334 contact.setSuffixId(suffixId);
5335 contact.setMale(male);
5336 contact.setBirthday(birthday);
5337 contact.setSmsSn(smsSn);
5338 contact.setAimSn(aimSn);
5339 contact.setFacebookSn(facebookSn);
5340 contact.setIcqSn(icqSn);
5341 contact.setJabberSn(jabberSn);
5342 contact.setMySpaceSn(mySpaceSn);
5343 contact.setSkypeSn(skypeSn);
5344 contact.setTwitterSn(twitterSn);
5345 contact.setYmSn(ymSn);
5346 contact.setJobTitle(jobTitle);
5347
5348 contactPersistence.update(contact, serviceContext);
5349
5350
5351
5352 Group group = groupLocalService.getUserGroup(
5353 user.getCompanyId(), userId);
5354
5355 group.setFriendlyURL(StringPool.SLASH + screenName);
5356
5357 groupPersistence.update(group);
5358
5359
5360
5361
5362
5363
5364
5365 List<UserGroupRole> previousUserGroupRoles =
5366 userGroupRolePersistence.findByUserId(userId);
5367
5368 updateGroups(userId, groupIds, serviceContext, false);
5369 updateOrganizations(userId, organizationIds, false);
5370
5371
5372
5373 if (roleIds != null) {
5374 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
5375
5376 userPersistence.setRoles(userId, roleIds);
5377 }
5378
5379
5380
5381 updateUserGroupRoles(
5382 user, groupIds, organizationIds, userGroupRoles,
5383 previousUserGroupRoles);
5384
5385
5386
5387 if (userGroupIds != null) {
5388 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
5389 userGroupLocalService.copyUserGroupLayouts(
5390 userGroupIds, userId);
5391 }
5392
5393 userPersistence.setUserGroups(userId, userGroupIds);
5394 }
5395
5396
5397
5398 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
5399
5400
5401
5402 if (serviceContext != null) {
5403 updateAsset(
5404 userId, user, serviceContext.getAssetCategoryIds(),
5405 serviceContext.getAssetTagNames());
5406 }
5407
5408
5409
5410 if (GetterUtil.getBoolean(
5411 PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
5412 !oldFullName.equals(user.getFullName())) {
5413
5414 mbMessageLocalService.updateUserName(userId, user.getFullName());
5415 }
5416
5417
5418
5419 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
5420 Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5421 User.class);
5422
5423 indexer.reindex(user);
5424 }
5425
5426
5427
5428 if ((serviceContext != null) && sendEmailAddressVerification) {
5429 sendEmailAddressVerification(user, emailAddress, serviceContext);
5430 }
5431
5432
5433
5434 PermissionCacheUtil.clearCache(userId);
5435
5436 return user;
5437 }
5438
5439
5500 @Deprecated
5501 @Override
5502 public User updateUser(
5503 long userId, String oldPassword, String newPassword1,
5504 String newPassword2, boolean passwordReset,
5505 String reminderQueryQuestion, String reminderQueryAnswer,
5506 String screenName, String emailAddress, long facebookId,
5507 String openId, String languageId, String timeZoneId,
5508 String greeting, String comments, String firstName,
5509 String middleName, String lastName, long prefixId, long suffixId,
5510 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
5511 String smsSn, String aimSn, String facebookSn, String icqSn,
5512 String jabberSn, String mySpaceSn, String skypeSn, String twitterSn,
5513 String ymSn, String jobTitle, long[] groupIds,
5514 long[] organizationIds, long[] roleIds,
5515 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
5516 ServiceContext serviceContext)
5517 throws PortalException {
5518
5519 return updateUser(
5520 userId, oldPassword, newPassword1, newPassword2, passwordReset,
5521 reminderQueryQuestion, reminderQueryAnswer, screenName,
5522 emailAddress, facebookId, openId, true, null, languageId,
5523 timeZoneId, greeting, comments, firstName, middleName, lastName,
5524 prefixId, suffixId, male, birthdayMonth, birthdayDay, birthdayYear,
5525 smsSn, aimSn, facebookSn, icqSn, jabberSn, mySpaceSn, skypeSn,
5526 twitterSn, ymSn, jobTitle, groupIds, organizationIds, roleIds,
5527 userGroupRoles, userGroupIds, serviceContext);
5528 }
5529
5530
5538 @Override
5539 public void verifyEmailAddress(String ticketKey) throws PortalException {
5540 Ticket ticket = ticketLocalService.getTicket(ticketKey);
5541
5542 if (ticket.isExpired() ||
5543 (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
5544
5545 throw new NoSuchTicketException("{ticketKey=" + ticketKey + "}");
5546 }
5547
5548 User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
5549
5550 String emailAddress = ticket.getExtraInfo();
5551
5552 emailAddress = StringUtil.toLowerCase(emailAddress).trim();
5553
5554 if (!emailAddress.equals(user.getEmailAddress())) {
5555 if (userPersistence.fetchByC_EA(
5556 user.getCompanyId(), emailAddress) != null) {
5557
5558 throw new UserEmailAddressException.MustNotBeDuplicate(
5559 user.getUserId(), emailAddress);
5560 }
5561
5562 setEmailAddress(
5563 user, StringPool.BLANK, user.getFirstName(),
5564 user.getMiddleName(), user.getLastName(), emailAddress);
5565
5566 Contact contact = user.getContact();
5567
5568 contact.setEmailAddress(user.getEmailAddress());
5569
5570 contactPersistence.update(contact);
5571 }
5572
5573 user.setEmailAddressVerified(true);
5574
5575 userPersistence.update(user);
5576
5577 ticketLocalService.deleteTicket(ticket);
5578 }
5579
5580 protected void addDefaultRolesAndTeams(long groupId, long[] userIds)
5581 throws PortalException {
5582
5583 List<Role> defaultSiteRoles = new ArrayList<>();
5584
5585 Group group = groupLocalService.getGroup(groupId);
5586
5587 UnicodeProperties typeSettingsProperties =
5588 group.getTypeSettingsProperties();
5589
5590 long[] defaultSiteRoleIds = StringUtil.split(
5591 typeSettingsProperties.getProperty("defaultSiteRoleIds"), 0L);
5592
5593 for (long defaultSiteRoleId : defaultSiteRoleIds) {
5594 Role defaultSiteRole = rolePersistence.fetchByPrimaryKey(
5595 defaultSiteRoleId);
5596
5597 if (defaultSiteRole == null) {
5598 if (_log.isWarnEnabled()) {
5599 _log.warn("Unable to find role " + defaultSiteRoleId);
5600 }
5601
5602 continue;
5603 }
5604
5605 defaultSiteRoles.add(defaultSiteRole);
5606 }
5607
5608 List<Team> defaultTeams = new ArrayList<>();
5609
5610 long[] defaultTeamIds = StringUtil.split(
5611 typeSettingsProperties.getProperty("defaultTeamIds"), 0L);
5612
5613 for (long defaultTeamId : defaultTeamIds) {
5614 Team defaultTeam = teamPersistence.findByPrimaryKey(defaultTeamId);
5615
5616 if (defaultTeam == null) {
5617 if (_log.isWarnEnabled()) {
5618 _log.warn("Unable to find team " + defaultTeamId);
5619 }
5620
5621 continue;
5622 }
5623
5624 defaultTeams.add(defaultTeam);
5625 }
5626
5627 for (long userId : userIds) {
5628 Set<Long> userRoleIdsSet = new HashSet<>();
5629
5630 for (Role role : defaultSiteRoles) {
5631 if (!userPersistence.containsRole(userId, role.getRoleId())) {
5632 userRoleIdsSet.add(role.getRoleId());
5633 }
5634 }
5635
5636 long[] userRoleIds = ArrayUtil.toArray(
5637 userRoleIdsSet.toArray(new Long[userRoleIdsSet.size()]));
5638
5639 userGroupRoleLocalService.addUserGroupRoles(
5640 userId, groupId, userRoleIds);
5641
5642 Set<Long> userTeamIdsSet = new HashSet<>();
5643
5644 for (Team team : defaultTeams) {
5645 if (!userPersistence.containsTeam(userId, team.getTeamId())) {
5646 userTeamIdsSet.add(team.getTeamId());
5647 }
5648 }
5649
5650 long[] userTeamIds = ArrayUtil.toArray(
5651 userTeamIdsSet.toArray(new Long[userTeamIdsSet.size()]));
5652
5653 userPersistence.addTeams(userId, userTeamIds);
5654 }
5655 }
5656
5657
5700 protected int authenticate(
5701 long companyId, String login, String password, String authType,
5702 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
5703 Map<String, Object> resultsMap)
5704 throws PortalException {
5705
5706 if (PropsValues.AUTH_LOGIN_DISABLED) {
5707 return Authenticator.FAILURE;
5708 }
5709
5710 login = StringUtil.toLowerCase(login.trim());
5711
5712 long userId = GetterUtil.getLong(login);
5713
5714
5715
5716 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5717 if (Validator.isNull(login)) {
5718 throw new UserEmailAddressException.MustNotBeNull();
5719 }
5720 }
5721 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5722 if (Validator.isNull(login)) {
5723 throw new UserScreenNameException.MustNotBeNull();
5724 }
5725 }
5726 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5727 if (Validator.isNull(login)) {
5728 throw new UserIdException.MustNotBeNull();
5729 }
5730 }
5731
5732 if (Validator.isNull(password)) {
5733 throw new UserPasswordException.MustNotBeNull(userId);
5734 }
5735
5736 int authResult = Authenticator.FAILURE;
5737
5738
5739
5740 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5741 authResult = AuthPipeline.authenticateByEmailAddress(
5742 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5743 headerMap, parameterMap);
5744 }
5745 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5746 authResult = AuthPipeline.authenticateByScreenName(
5747 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5748 headerMap, parameterMap);
5749 }
5750 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5751 authResult = AuthPipeline.authenticateByUserId(
5752 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
5753 headerMap, parameterMap);
5754 }
5755
5756
5757
5758 User user = null;
5759
5760 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5761 user = fetchUserByEmailAddress(companyId, login);
5762 }
5763 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5764 user = fetchUserByScreenName(companyId, login);
5765 }
5766 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5767 user = userPersistence.fetchByPrimaryKey(GetterUtil.getLong(login));
5768 }
5769
5770 if (user == null) {
5771 return Authenticator.DNE;
5772 }
5773
5774 if (!isUserAllowedToAuthenticate(user)) {
5775 return Authenticator.FAILURE;
5776 }
5777
5778 if (!user.isPasswordEncrypted()) {
5779 user.setPassword(PasswordEncryptorUtil.encrypt(user.getPassword()));
5780 user.setPasswordEncrypted(true);
5781
5782 userPersistence.update(user);
5783 }
5784
5785
5786
5787 boolean skipLiferayCheck = false;
5788
5789 if (authResult == Authenticator.SKIP_LIFERAY_CHECK) {
5790 authResult = Authenticator.SUCCESS;
5791
5792 skipLiferayCheck = true;
5793 }
5794 else if ((authResult == Authenticator.SUCCESS) &&
5795 PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5796
5797 boolean authenticated = PwdAuthenticator.authenticate(
5798 login, password, user.getPassword());
5799
5800 if (authenticated) {
5801 authResult = Authenticator.SUCCESS;
5802 }
5803 else {
5804 authResult = Authenticator.FAILURE;
5805 }
5806 }
5807
5808
5809
5810 if (authResult == Authenticator.SUCCESS) {
5811 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5812 authResult = AuthPipeline.authenticateByEmailAddress(
5813 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5814 headerMap, parameterMap);
5815 }
5816 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5817 authResult = AuthPipeline.authenticateByScreenName(
5818 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5819 headerMap, parameterMap);
5820 }
5821 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5822 authResult = AuthPipeline.authenticateByUserId(
5823 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5824 headerMap, parameterMap);
5825 }
5826 }
5827
5828 if (resultsMap != null) {
5829 resultsMap.put("userId", user.getUserId());
5830 }
5831
5832 if (authResult == Authenticator.SUCCESS) {
5833
5834
5835
5836 if (skipLiferayCheck ||
5837 !PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK ||
5838 Validator.isNull(user.getDigest())) {
5839
5840 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5841
5842 String digest = user.getDigest(password);
5843
5844 user.setDigest(digest);
5845
5846 userPersistence.update(user);
5847 }
5848 }
5849
5850
5851
5852 if (authResult == Authenticator.FAILURE) {
5853 authResult = handleAuthenticationFailure(
5854 login, authType, user, headerMap, parameterMap);
5855 }
5856 else {
5857 resetFailedLoginAttempts(user);
5858 }
5859
5860
5861
5862 return authResult;
5863 }
5864
5865 protected SearchContext buildSearchContext(
5866 long companyId, String firstName, String middleName, String lastName,
5867 String fullName, String screenName, String emailAddress, String street,
5868 String city, String zip, String region, String country, int status,
5869 LinkedHashMap<String, Object> params, boolean andSearch, int start,
5870 int end, Sort[] sorts) {
5871
5872 SearchContext searchContext = new SearchContext();
5873
5874 searchContext.setAndSearch(andSearch);
5875
5876 Map<String, Serializable> attributes = new HashMap<>();
5877
5878 attributes.put("city", city);
5879 attributes.put("country", country);
5880 attributes.put("emailAddress", emailAddress);
5881 attributes.put("firstName", firstName);
5882 attributes.put("fullName", fullName);
5883 attributes.put("lastName", lastName);
5884 attributes.put("middleName", middleName);
5885 attributes.put("params", params);
5886 attributes.put("region", region);
5887 attributes.put("screenName", screenName);
5888 attributes.put("street", street);
5889 attributes.put("status", status);
5890 attributes.put("zip", zip);
5891
5892 searchContext.setAttributes(attributes);
5893
5894 searchContext.setCompanyId(companyId);
5895 searchContext.setEnd(end);
5896
5897 if (params != null) {
5898 String keywords = (String)params.remove("keywords");
5899
5900 if (Validator.isNotNull(keywords)) {
5901 searchContext.setKeywords(keywords);
5902 }
5903 }
5904
5905 if (sorts != null) {
5906 searchContext.setSorts(sorts);
5907 }
5908
5909 searchContext.setStart(start);
5910
5911 QueryConfig queryConfig = searchContext.getQueryConfig();
5912
5913 queryConfig.setHighlightEnabled(false);
5914 queryConfig.setScoreEnabled(false);
5915
5916 return searchContext;
5917 }
5918
5919 protected Date getBirthday(
5920 int birthdayMonth, int birthdayDay, int birthdayYear)
5921 throws PortalException {
5922
5923 Date birthday = PortalUtil.getDate(
5924 birthdayMonth, birthdayDay, birthdayYear,
5925 ContactBirthdayException.class);
5926
5927 if (birthday.after(new Date())) {
5928 throw new ContactBirthdayException();
5929 }
5930
5931 return birthday;
5932 }
5933
5934 protected String getLogin(String login) {
5935 return StringUtil.lowerCase(StringUtil.trim(login));
5936 }
5937
5938 protected Sort[] getSorts(OrderByComparator<User> obc) {
5939 if (obc == null) {
5940 return new Sort[0];
5941 }
5942
5943 String[] orderByClauses = StringUtil.split(obc.getOrderBy());
5944 String[] orderByFields = obc.getOrderByFields();
5945
5946 Sort[] sorts = new Sort[orderByFields.length];
5947
5948 for (int i = 0; i < orderByFields.length; i++) {
5949 boolean reverse = orderByClauses[i].contains("DESC");
5950
5951 sorts[i] = new Sort(orderByFields[i], reverse);
5952 }
5953
5954 return sorts;
5955 }
5956
5957 protected int handleAuthenticationFailure(
5958 String login, String authType, User user,
5959 Map<String, String[]> headerMap, Map<String, String[]> parameterMap) {
5960
5961 if (user == null) {
5962 return Authenticator.DNE;
5963 }
5964
5965 try {
5966 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5967 AuthPipeline.onFailureByEmailAddress(
5968 PropsKeys.AUTH_FAILURE, user.getCompanyId(), login,
5969 headerMap, parameterMap);
5970 }
5971 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5972 AuthPipeline.onFailureByScreenName(
5973 PropsKeys.AUTH_FAILURE, user.getCompanyId(), login,
5974 headerMap, parameterMap);
5975 }
5976 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5977 AuthPipeline.onFailureByUserId(
5978 PropsKeys.AUTH_FAILURE, user.getCompanyId(),
5979 user.getUserId(), headerMap, parameterMap);
5980 }
5981
5982 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5983
5984 if (user == null) {
5985 return Authenticator.DNE;
5986 }
5987
5988
5989
5990 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5991 user.getCompanyId())) {
5992
5993 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5994
5995 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5996
5997 int failedLoginAttempts = user.getFailedLoginAttempts();
5998 int maxFailures = passwordPolicy.getMaxFailure();
5999
6000 if ((failedLoginAttempts >= maxFailures) &&
6001 (maxFailures != 0)) {
6002
6003 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
6004 AuthPipeline.onMaxFailuresByEmailAddress(
6005 PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
6006 login, headerMap, parameterMap);
6007 }
6008 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
6009 AuthPipeline.onMaxFailuresByScreenName(
6010 PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
6011 login, headerMap, parameterMap);
6012 }
6013 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
6014 AuthPipeline.onMaxFailuresByUserId(
6015 PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
6016 user.getUserId(), headerMap, parameterMap);
6017 }
6018 }
6019 }
6020 }
6021 catch (Exception e) {
6022 _log.error(e, e);
6023 }
6024
6025 return Authenticator.FAILURE;
6026 }
6027
6028 protected boolean isUseCustomSQL(LinkedHashMap<String, Object> params) {
6029 if (MapUtil.isEmpty(params)) {
6030 return false;
6031 }
6032
6033 for (String key : params.keySet()) {
6034 if (!key.equals("inherit") && !key.equals("usersGroups") &&
6035 !key.equals("usersOrgs") && !key.equals("usersOrgsCount") &&
6036 !key.equals("usersRoles") && !key.equals("usersTeams") &&
6037 !key.equals("usersUserGroups")) {
6038
6039 return true;
6040 }
6041 }
6042
6043 Boolean inherit = (Boolean)params.get("inherit");
6044
6045 if ((inherit != null) && inherit) {
6046 return true;
6047 }
6048
6049 return false;
6050 }
6051
6052 protected boolean isUserAllowedToAuthenticate(User user)
6053 throws PortalException {
6054
6055 if (user.isDefaultUser()) {
6056 if (_log.isInfoEnabled()) {
6057 _log.info("Authentication is disabled for the default user");
6058 }
6059
6060 return false;
6061 }
6062 else if (!user.isActive()) {
6063 if (_log.isInfoEnabled()) {
6064 _log.info(
6065 "Authentication is disabled for inactive user " +
6066 user.getUserId());
6067 }
6068
6069 return false;
6070 }
6071
6072
6073
6074
6075 checkLockout(user);
6076
6077 checkPasswordExpired(user);
6078
6079 return true;
6080 }
6081
6082 protected void notifyUser(
6083 User user, String password, ServiceContext serviceContext) {
6084
6085 if (!PrefsPropsUtil.getBoolean(
6086 user.getCompanyId(),
6087 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
6088
6089 return;
6090 }
6091
6092 String fromName = PrefsPropsUtil.getString(
6093 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
6094 String fromAddress = PrefsPropsUtil.getString(
6095 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
6096
6097 String toName = user.getFullName();
6098 String toAddress = user.getEmailAddress();
6099
6100 PortletPreferences companyPortletPreferences =
6101 PrefsPropsUtil.getPreferences(user.getCompanyId(), true);
6102
6103 Map<Locale, String> localizedSubjectMap =
6104 LocalizationUtil.getLocalizationMap(
6105 companyPortletPreferences, "adminEmailUserAddedSubject",
6106 PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
6107
6108 Map<Locale, String> localizedBodyMap = null;
6109
6110 if (Validator.isNotNull(password)) {
6111 localizedBodyMap = LocalizationUtil.getLocalizationMap(
6112 companyPortletPreferences, "adminEmailUserAddedBody",
6113 PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
6114 }
6115 else {
6116 localizedBodyMap = LocalizationUtil.getLocalizationMap(
6117 companyPortletPreferences, "adminEmailUserAddedNoPasswordBody",
6118 PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
6119 }
6120
6121 SubscriptionSender subscriptionSender = new SubscriptionSender();
6122
6123 subscriptionSender.setCompanyId(user.getCompanyId());
6124 subscriptionSender.setContextAttributes(
6125 "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
6126 "[$USER_SCREENNAME$]", user.getScreenName());
6127 subscriptionSender.setFrom(fromAddress, fromName);
6128 subscriptionSender.setHtmlFormat(true);
6129 subscriptionSender.setLocalizedBodyMap(localizedBodyMap);
6130 subscriptionSender.setLocalizedSubjectMap(localizedSubjectMap);
6131 subscriptionSender.setMailId("user", user.getUserId());
6132 subscriptionSender.setServiceContext(serviceContext);
6133
6134 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
6135
6136 subscriptionSender.flushNotificationsAsync();
6137 }
6138
6139 protected void reindex(long userId) throws SearchException {
6140 Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6141 User.class);
6142
6143 User user = userLocalService.fetchUser(userId);
6144
6145 indexer.reindex(user);
6146 }
6147
6148 protected void reindex(long[] userIds) throws SearchException {
6149 Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6150 User.class);
6151
6152 List<User> users = new ArrayList<>(userIds.length);
6153
6154 for (Long userId : userIds) {
6155 User user = userLocalService.fetchUser(userId);
6156
6157 users.add(user);
6158 }
6159
6160 indexer.reindex(users);
6161 }
6162
6163 protected void reindex(final User user) throws SearchException {
6164 Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6165 User.class);
6166
6167 indexer.reindex(user);
6168 }
6169
6170 protected void resetFailedLoginAttempts(User user) {
6171 resetFailedLoginAttempts(user, false);
6172 }
6173
6174 protected void resetFailedLoginAttempts(User user, boolean forceUpdate) {
6175 if (forceUpdate || (user.getFailedLoginAttempts() > 0)) {
6176 user.setFailedLoginAttempts(0);
6177
6178 userPersistence.update(user);
6179 }
6180 }
6181
6182 protected BaseModelSearchResult<User> searchUsers(
6183 SearchContext searchContext)
6184 throws PortalException {
6185
6186 Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6187 User.class);
6188
6189 for (int i = 0; i < 10; i++) {
6190 Hits hits = indexer.search(searchContext);
6191
6192 List<User> users = UsersAdminUtil.getUsers(hits);
6193
6194 if (users != null) {
6195 return new BaseModelSearchResult<>(users, hits.getLength());
6196 }
6197 }
6198
6199 throw new SearchException(
6200 "Unable to fix the search index after 10 attempts");
6201 }
6202
6203 protected void sendPasswordNotification(
6204 User user, long companyId, String newPassword, String passwordResetURL,
6205 String fromName, String fromAddress, String subject, String body,
6206 ServiceContext serviceContext) {
6207
6208 if (Validator.isNull(fromName)) {
6209 fromName = PrefsPropsUtil.getString(
6210 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
6211 }
6212
6213 if (Validator.isNull(fromAddress)) {
6214 fromAddress = PrefsPropsUtil.getString(
6215 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
6216 }
6217
6218 String toName = user.getFullName();
6219 String toAddress = user.getEmailAddress();
6220
6221 PortletPreferences companyPortletPreferences =
6222 PrefsPropsUtil.getPreferences(companyId, true);
6223
6224 Map<Locale, String> localizedSubjectMap = null;
6225 Map<Locale, String> localizedBodyMap = null;
6226
6227 String bodyProperty = null;
6228 String prefix = null;
6229 String subjectProperty = null;
6230
6231 if (Validator.isNotNull(passwordResetURL)) {
6232 bodyProperty = PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY;
6233 prefix = "adminEmailPasswordReset";
6234 subjectProperty = PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT;
6235 }
6236 else {
6237 bodyProperty = PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY;
6238 prefix = "adminEmailPasswordSent";
6239 subjectProperty = PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT;
6240 }
6241
6242 if (Validator.isNull(body)) {
6243 localizedBodyMap = LocalizationUtil.getLocalizationMap(
6244 companyPortletPreferences, prefix + "Body", bodyProperty);
6245 }
6246
6247 if (Validator.isNull(subject)) {
6248 localizedSubjectMap = LocalizationUtil.getLocalizationMap(
6249 companyPortletPreferences, prefix + "Subject", subjectProperty);
6250 }
6251
6252 SubscriptionSender subscriptionSender = new SubscriptionSender();
6253
6254 subscriptionSender.setCompanyId(companyId);
6255 subscriptionSender.setContextAttributes(
6256 "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
6257 serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
6258 serviceContext.getRemoteHost(), "[$USER_ID$]", user.getUserId(),
6259 "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
6260 user.getScreenName());
6261 subscriptionSender.setFrom(fromAddress, fromName);
6262 subscriptionSender.setHtmlFormat(true);
6263 subscriptionSender.setLocalizedBodyMap(localizedBodyMap);
6264 subscriptionSender.setLocalizedSubjectMap(localizedSubjectMap);
6265 subscriptionSender.setMailId("user", user.getUserId());
6266 subscriptionSender.setServiceContext(serviceContext);
6267
6268 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
6269
6270 subscriptionSender.flushNotificationsAsync();
6271 }
6272
6273 protected void setEmailAddress(
6274 User user, String password, String firstName, String middleName,
6275 String lastName, String emailAddress)
6276 throws PortalException {
6277
6278 if (StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
6279 return;
6280 }
6281
6282 long userId = user.getUserId();
6283
6284
6285
6286 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
6287 Validator.isNotNull(password)) {
6288
6289 mailService.addUser(
6290 user.getCompanyId(), userId, password, firstName, middleName,
6291 lastName, emailAddress);
6292 }
6293
6294
6295
6296 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
6297 mailService.updateEmailAddress(
6298 user.getCompanyId(), userId, emailAddress);
6299 }
6300
6301
6302
6303 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
6304 mailService.deleteEmailAddress(user.getCompanyId(), userId);
6305 }
6306
6307 user.setEmailAddress(emailAddress);
6308 user.setDigest(StringPool.BLANK);
6309 }
6310
6311 protected void updateGroups(
6312 long userId, long[] newGroupIds, ServiceContext serviceContext,
6313 boolean indexingEnabled)
6314 throws PortalException {
6315
6316 if (newGroupIds == null) {
6317 return;
6318 }
6319
6320 long[] oldGroupIds = getGroupPrimaryKeys(userId);
6321
6322 for (long oldGroupId : oldGroupIds) {
6323 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
6324 unsetGroupUsers(
6325 oldGroupId, new long[] {userId}, serviceContext);
6326 }
6327 }
6328
6329 for (long newGroupId : newGroupIds) {
6330 if (!ArrayUtil.contains(oldGroupIds, newGroupId)) {
6331 addGroupUsers(newGroupId, new long[] {userId});
6332 }
6333 }
6334
6335 if (indexingEnabled) {
6336 reindex(userId);
6337 }
6338
6339 PermissionCacheUtil.clearCache(userId);
6340 }
6341
6342 protected void updateOrganizations(
6343 long userId, long[] newOrganizationIds, boolean indexingEnabled)
6344 throws PortalException {
6345
6346 if (newOrganizationIds == null) {
6347 return;
6348 }
6349
6350 long[] oldOrganizationIds = getOrganizationPrimaryKeys(userId);
6351
6352 for (long oldOrganizationId : oldOrganizationIds) {
6353 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
6354 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
6355 }
6356 }
6357
6358 for (long newOrganizationId : newOrganizationIds) {
6359 if (!ArrayUtil.contains(oldOrganizationIds, newOrganizationId)) {
6360 addOrganizationUsers(newOrganizationId, new long[] {userId});
6361 }
6362 }
6363
6364 if (indexingEnabled) {
6365 reindex(userId);
6366 }
6367
6368 PermissionCacheUtil.clearCache(userId);
6369 }
6370
6371 protected void updateUserGroupRoles(
6372 User user, long[] groupIds, long[] organizationIds,
6373 List<UserGroupRole> userGroupRoles,
6374 List<UserGroupRole> previousUserGroupRoles)
6375 throws PortalException {
6376
6377 if (userGroupRoles == null) {
6378 return;
6379 }
6380
6381 userGroupRoles = new ArrayList<>(userGroupRoles);
6382
6383 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
6384 if (userGroupRoles.contains(userGroupRole)) {
6385 userGroupRoles.remove(userGroupRole);
6386 }
6387 else {
6388 userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
6389 }
6390 }
6391
6392 if (ListUtil.isEmpty(userGroupRoles)) {
6393 return;
6394 }
6395
6396 long[] validGroupIds = null;
6397
6398 if (groupIds != null) {
6399 validGroupIds = ArrayUtil.clone(groupIds);
6400 }
6401 else {
6402 validGroupIds = user.getGroupIds();
6403 }
6404
6405 if (organizationIds == null) {
6406 organizationIds = user.getOrganizationIds();
6407 }
6408
6409 for (long organizationId : organizationIds) {
6410 Organization organization =
6411 organizationPersistence.findByPrimaryKey(organizationId);
6412
6413 validGroupIds = ArrayUtil.append(
6414 validGroupIds, organization.getGroupId());
6415 }
6416
6417 Arrays.sort(validGroupIds);
6418
6419 for (UserGroupRole userGroupRole : userGroupRoles) {
6420 if (Arrays.binarySearch(
6421 validGroupIds, userGroupRole.getGroupId()) >= 0) {
6422
6423 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
6424 }
6425 }
6426 }
6427
6428 protected void validate(
6429 long companyId, long userId, boolean autoPassword, String password1,
6430 String password2, boolean autoScreenName, String screenName,
6431 String emailAddress, String openId, String firstName,
6432 String middleName, String lastName, long[] organizationIds,
6433 Locale locale)
6434 throws PortalException {
6435
6436 validateCompanyMaxUsers(companyId);
6437
6438 if (!autoScreenName) {
6439 validateScreenName(companyId, userId, screenName);
6440 }
6441
6442 if (!autoPassword) {
6443 PasswordPolicy passwordPolicy =
6444 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
6445
6446 PwdToolkitUtil.validate(
6447 companyId, 0, password1, password2, passwordPolicy);
6448 }
6449
6450 validateEmailAddress(companyId, emailAddress);
6451
6452 if (Validator.isNotNull(emailAddress)) {
6453 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
6454
6455 if ((user != null) && (user.getUserId() != userId)) {
6456 throw new UserEmailAddressException.MustNotBeDuplicate(
6457 userId, emailAddress);
6458 }
6459 }
6460
6461 validateOpenId(companyId, userId, openId);
6462
6463 validateFullName(companyId, firstName, middleName, lastName, locale);
6464
6465 if (organizationIds != null) {
6466 for (long organizationId : organizationIds) {
6467 Organization organization =
6468 organizationPersistence.fetchByPrimaryKey(organizationId);
6469
6470 if (organization == null) {
6471 throw new NoSuchOrganizationException(
6472 "{organizationId=" + organizationId + "}");
6473 }
6474 }
6475 }
6476 }
6477
6478 protected void validate(
6479 long userId, String screenName, String emailAddress, String openId,
6480 String firstName, String middleName, String lastName, String smsSn,
6481 Locale locale)
6482 throws PortalException {
6483
6484 User user = userPersistence.findByPrimaryKey(userId);
6485
6486 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
6487 validateScreenName(user.getCompanyId(), userId, screenName);
6488 }
6489
6490 validateEmailAddress(user.getCompanyId(), emailAddress);
6491
6492 validateOpenId(user.getCompanyId(), userId, openId);
6493
6494 if (!user.isDefaultUser()) {
6495 if (Validator.isNotNull(emailAddress) &&
6496 !StringUtil.equalsIgnoreCase(
6497 user.getEmailAddress(), emailAddress)) {
6498
6499 if (userPersistence.fetchByC_EA(
6500 user.getCompanyId(), emailAddress) != null) {
6501
6502 throw new UserEmailAddressException.MustNotBeDuplicate(
6503 userId, emailAddress);
6504 }
6505 }
6506
6507 validateFullName(
6508 user.getCompanyId(), firstName, middleName, lastName, locale);
6509 }
6510
6511 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
6512 throw new UserSmsException.MustBeEmailAddress(smsSn);
6513 }
6514 }
6515
6516 protected void validateCompanyMaxUsers(long companyId)
6517 throws PortalException {
6518
6519 Company company = companyPersistence.findByPrimaryKey(companyId);
6520
6521 if (company.isSystem() || (company.getMaxUsers() == 0)) {
6522 return;
6523 }
6524
6525 int userCount = searchCount(
6526 companyId, null, WorkflowConstants.STATUS_APPROVED, null);
6527
6528 if (userCount >= company.getMaxUsers()) {
6529 throw new CompanyMaxUsersException();
6530 }
6531 }
6532
6533 protected void validateEmailAddress(long companyId, String emailAddress)
6534 throws PortalException {
6535
6536 if (Validator.isNull(emailAddress) &&
6537 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
6538
6539 return;
6540 }
6541
6542 EmailAddressValidator emailAddressValidator =
6543 EmailAddressValidatorFactory.getInstance();
6544
6545 if (!emailAddressValidator.validate(companyId, emailAddress)) {
6546 throw new UserEmailAddressException.MustValidate(
6547 emailAddress, emailAddressValidator);
6548 }
6549
6550 String pop3User = PrefsPropsUtil.getString(
6551 PropsKeys.MAIL_SESSION_MAIL_POP3_USER,
6552 PropsValues.MAIL_SESSION_MAIL_POP3_USER);
6553
6554 if (StringUtil.equalsIgnoreCase(emailAddress, pop3User)) {
6555 throw new UserEmailAddressException.MustNotBePOP3User(emailAddress);
6556 }
6557
6558 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
6559 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
6560 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
6561
6562 for (String reservedEmailAddress : reservedEmailAddresses) {
6563 if (StringUtil.equalsIgnoreCase(
6564 emailAddress, reservedEmailAddress)) {
6565
6566 throw new UserEmailAddressException.MustNotBeReserved(
6567 emailAddress, reservedEmailAddresses);
6568 }
6569 }
6570 }
6571
6572 protected void validateEmailAddress(
6573 User user, String emailAddress1, String emailAddress2)
6574 throws PortalException {
6575
6576 if (!emailAddress1.equals(emailAddress2)) {
6577 throw new UserEmailAddressException.MustBeEqual(
6578 user, emailAddress1, emailAddress2);
6579 }
6580
6581 validateEmailAddress(user.getCompanyId(), emailAddress1);
6582 validateEmailAddress(user.getCompanyId(), emailAddress2);
6583
6584 if (!StringUtil.equalsIgnoreCase(
6585 emailAddress1, user.getEmailAddress())) {
6586
6587 if (userPersistence.fetchByC_EA(
6588 user.getCompanyId(), emailAddress1) != null) {
6589
6590 throw new UserEmailAddressException.MustNotBeDuplicate(
6591 user.getUserId(), emailAddress1);
6592 }
6593 }
6594 }
6595
6596 protected void validateFullName(
6597 long companyId, String firstName, String middleName,
6598 String lastName, Locale locale)
6599 throws PortalException {
6600
6601 FullNameDefinition fullNameDefinition =
6602 FullNameDefinitionFactory.getInstance(locale);
6603
6604 if (Validator.isNull(firstName)) {
6605 throw new ContactNameException.MustHaveFirstName();
6606 }
6607 else if (Validator.isNull(middleName) &&
6608 fullNameDefinition.isFieldRequired("middle-name")) {
6609
6610 throw new ContactNameException.MustHaveMiddleName();
6611 }
6612 else if (Validator.isNull(lastName) &&
6613 fullNameDefinition.isFieldRequired("last-name")) {
6614
6615 throw new ContactNameException.MustHaveLastName();
6616 }
6617
6618 FullNameValidator fullNameValidator =
6619 FullNameValidatorFactory.getInstance();
6620
6621 if (!fullNameValidator.validate(
6622 companyId, firstName, middleName, lastName)) {
6623
6624 throw new ContactNameException.MustHaveValidFullName(
6625 fullNameValidator);
6626 }
6627 }
6628
6629 protected void validateOpenId(long companyId, long userId, String openId)
6630 throws PortalException {
6631
6632 if (Validator.isNull(openId)) {
6633 return;
6634 }
6635
6636 User user = userPersistence.fetchByC_O(companyId, openId);
6637
6638 if ((user != null) && (user.getUserId() != userId)) {
6639 throw new DuplicateOpenIdException("{userId=" + userId + "}");
6640 }
6641 }
6642
6643 protected void validatePassword(
6644 long companyId, long userId, String password1, String password2)
6645 throws PortalException {
6646
6647 if (Validator.isNull(password1) || Validator.isNull(password2)) {
6648 throw new UserPasswordException.MustNotBeNull(userId);
6649 }
6650
6651 if (!password1.equals(password2)) {
6652 throw new UserPasswordException.MustMatch(userId);
6653 }
6654
6655 PasswordPolicy passwordPolicy =
6656 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
6657
6658 PwdToolkitUtil.validate(
6659 companyId, userId, password1, password2, passwordPolicy);
6660 }
6661
6662 protected void validateReminderQuery(String question, String answer)
6663 throws PortalException {
6664
6665 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
6666 return;
6667 }
6668
6669 if (Validator.isNull(question)) {
6670 throw new UserReminderQueryException("Question is null");
6671 }
6672
6673 if (Validator.isNull(answer)) {
6674 throw new UserReminderQueryException("Answer is null");
6675 }
6676 }
6677
6678 protected void validateScreenName(
6679 long companyId, long userId, String screenName)
6680 throws PortalException {
6681
6682 if (Validator.isNull(screenName)) {
6683 throw new UserScreenNameException.MustNotBeNull(userId);
6684 }
6685
6686 ScreenNameValidator screenNameValidator =
6687 ScreenNameValidatorFactory.getInstance();
6688
6689 if (!screenNameValidator.validate(companyId, screenName)) {
6690 throw new UserScreenNameException.MustValidate(
6691 userId, screenName, screenNameValidator);
6692 }
6693
6694 if (Validator.isNumber(screenName)) {
6695 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
6696 throw new UserScreenNameException.MustNotBeNumeric(
6697 userId, screenName);
6698 }
6699
6700 if (!screenName.equals(String.valueOf(userId))) {
6701 Group group = groupPersistence.fetchByPrimaryKey(
6702 GetterUtil.getLong(screenName));
6703
6704 if (group != null) {
6705 throw new UserScreenNameException.MustNotBeUsedByGroup(
6706 userId, screenName, group);
6707 }
6708 }
6709 }
6710
6711 String[] anonymousNames = BaseServiceImpl.ANONYMOUS_NAMES;
6712
6713 for (String anonymousName : anonymousNames) {
6714 if (StringUtil.equalsIgnoreCase(screenName, anonymousName)) {
6715 throw new UserScreenNameException.MustNotBeReservedForAnonymous(
6716 userId, screenName, anonymousNames);
6717 }
6718 }
6719
6720 User user = userPersistence.fetchByC_SN(companyId, screenName);
6721
6722 if ((user != null) && (user.getUserId() != userId)) {
6723 throw new UserScreenNameException.MustNotBeDuplicate(
6724 user.getUserId(), screenName);
6725 }
6726
6727 String friendlyURL = StringPool.SLASH + screenName;
6728
6729 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
6730
6731 if ((group != null) && (group.getClassPK() != userId)) {
6732 GroupFriendlyURLException gfurle = new GroupFriendlyURLException(
6733 GroupFriendlyURLException.DUPLICATE);
6734
6735 gfurle.setDuplicateClassPK(group.getGroupId());
6736 gfurle.setDuplicateClassName(Group.class.getName());
6737
6738 throw gfurle;
6739 }
6740
6741 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
6742
6743 if (exceptionType != -1) {
6744 throw new UserScreenNameException.MustProduceValidFriendlyURL(
6745 userId, screenName, exceptionType);
6746 }
6747
6748 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
6749 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
6750 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
6751
6752 for (String reservedScreenName : reservedScreenNames) {
6753 if (StringUtil.equalsIgnoreCase(screenName, reservedScreenName)) {
6754 throw new UserScreenNameException.MustNotBeReserved(
6755 userId, screenName, reservedScreenNames);
6756 }
6757 }
6758 }
6759
6760 private static final Log _log = LogFactoryUtil.getLog(
6761 UserLocalServiceImpl.class);
6762
6763 private final Map<Long, User> _defaultUsers = new ConcurrentHashMap<>();
6764
6765 }