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.ContactFirstNameException;
020 import com.liferay.portal.ContactFullNameException;
021 import com.liferay.portal.ContactLastNameException;
022 import com.liferay.portal.DuplicateUserEmailAddressException;
023 import com.liferay.portal.DuplicateUserScreenNameException;
024 import com.liferay.portal.GroupFriendlyURLException;
025 import com.liferay.portal.ModelListenerException;
026 import com.liferay.portal.NoSuchContactException;
027 import com.liferay.portal.NoSuchGroupException;
028 import com.liferay.portal.NoSuchOrganizationException;
029 import com.liferay.portal.NoSuchRoleException;
030 import com.liferay.portal.NoSuchTicketException;
031 import com.liferay.portal.NoSuchUserException;
032 import com.liferay.portal.NoSuchUserGroupException;
033 import com.liferay.portal.PasswordExpiredException;
034 import com.liferay.portal.RequiredUserException;
035 import com.liferay.portal.ReservedUserEmailAddressException;
036 import com.liferay.portal.ReservedUserScreenNameException;
037 import com.liferay.portal.UserEmailAddressException;
038 import com.liferay.portal.UserIdException;
039 import com.liferay.portal.UserLockoutException;
040 import com.liferay.portal.UserPasswordException;
041 import com.liferay.portal.UserPortraitSizeException;
042 import com.liferay.portal.UserPortraitTypeException;
043 import com.liferay.portal.UserReminderQueryException;
044 import com.liferay.portal.UserScreenNameException;
045 import com.liferay.portal.UserSmsException;
046 import com.liferay.portal.kernel.exception.PortalException;
047 import com.liferay.portal.kernel.exception.SystemException;
048 import com.liferay.portal.kernel.image.ImageBag;
049 import com.liferay.portal.kernel.image.ImageToolUtil;
050 import com.liferay.portal.kernel.language.LanguageUtil;
051 import com.liferay.portal.kernel.log.Log;
052 import com.liferay.portal.kernel.log.LogFactoryUtil;
053 import com.liferay.portal.kernel.search.Hits;
054 import com.liferay.portal.kernel.search.Indexer;
055 import com.liferay.portal.kernel.search.IndexerRegistryUtil;
056 import com.liferay.portal.kernel.search.QueryConfig;
057 import com.liferay.portal.kernel.search.SearchContext;
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.TransactionCommitCallbackRegistryUtil;
062 import com.liferay.portal.kernel.transaction.Transactional;
063 import com.liferay.portal.kernel.util.ArrayUtil;
064 import com.liferay.portal.kernel.util.CharPool;
065 import com.liferay.portal.kernel.util.Digester;
066 import com.liferay.portal.kernel.util.DigesterUtil;
067 import com.liferay.portal.kernel.util.GetterUtil;
068 import com.liferay.portal.kernel.util.KeyValuePair;
069 import com.liferay.portal.kernel.util.OrderByComparator;
070 import com.liferay.portal.kernel.util.ParamUtil;
071 import com.liferay.portal.kernel.util.PropsKeys;
072 import com.liferay.portal.kernel.util.StringBundler;
073 import com.liferay.portal.kernel.util.StringPool;
074 import com.liferay.portal.kernel.util.StringUtil;
075 import com.liferay.portal.kernel.util.UnicodeProperties;
076 import com.liferay.portal.kernel.util.Validator;
077 import com.liferay.portal.kernel.workflow.WorkflowConstants;
078 import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil;
079 import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
080 import com.liferay.portal.model.Account;
081 import com.liferay.portal.model.Company;
082 import com.liferay.portal.model.CompanyConstants;
083 import com.liferay.portal.model.Contact;
084 import com.liferay.portal.model.ContactConstants;
085 import com.liferay.portal.model.Group;
086 import com.liferay.portal.model.GroupConstants;
087 import com.liferay.portal.model.Layout;
088 import com.liferay.portal.model.Organization;
089 import com.liferay.portal.model.PasswordPolicy;
090 import com.liferay.portal.model.ResourceConstants;
091 import com.liferay.portal.model.Role;
092 import com.liferay.portal.model.RoleConstants;
093 import com.liferay.portal.model.Team;
094 import com.liferay.portal.model.Ticket;
095 import com.liferay.portal.model.TicketConstants;
096 import com.liferay.portal.model.User;
097 import com.liferay.portal.model.UserGroup;
098 import com.liferay.portal.model.UserGroupRole;
099 import com.liferay.portal.model.impl.LayoutImpl;
100 import com.liferay.portal.security.auth.AuthPipeline;
101 import com.liferay.portal.security.auth.Authenticator;
102 import com.liferay.portal.security.auth.EmailAddressGenerator;
103 import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
104 import com.liferay.portal.security.auth.EmailAddressValidator;
105 import com.liferay.portal.security.auth.EmailAddressValidatorFactory;
106 import com.liferay.portal.security.auth.FullNameGenerator;
107 import com.liferay.portal.security.auth.FullNameGeneratorFactory;
108 import com.liferay.portal.security.auth.FullNameValidator;
109 import com.liferay.portal.security.auth.FullNameValidatorFactory;
110 import com.liferay.portal.security.auth.PrincipalException;
111 import com.liferay.portal.security.auth.ScreenNameGenerator;
112 import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
113 import com.liferay.portal.security.auth.ScreenNameValidator;
114 import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
115 import com.liferay.portal.security.ldap.LDAPSettingsUtil;
116 import com.liferay.portal.security.permission.PermissionCacheUtil;
117 import com.liferay.portal.security.pwd.PwdAuthenticator;
118 import com.liferay.portal.security.pwd.PwdEncryptor;
119 import com.liferay.portal.security.pwd.PwdToolkitUtil;
120 import com.liferay.portal.security.pwd.RegExpToolkit;
121 import com.liferay.portal.service.BaseServiceImpl;
122 import com.liferay.portal.service.ServiceContext;
123 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
124 import com.liferay.portal.util.PortalUtil;
125 import com.liferay.portal.util.PrefsPropsUtil;
126 import com.liferay.portal.util.PropsValues;
127 import com.liferay.portal.util.SubscriptionSender;
128 import com.liferay.portlet.documentlibrary.ImageSizeException;
129 import com.liferay.portlet.messageboards.model.MBMessage;
130 import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
131 import com.liferay.util.Encryptor;
132 import com.liferay.util.EncryptorException;
133
134 import java.awt.image.RenderedImage;
135
136 import java.io.IOException;
137 import java.io.Serializable;
138
139 import java.util.ArrayList;
140 import java.util.Arrays;
141 import java.util.Calendar;
142 import java.util.Date;
143 import java.util.HashMap;
144 import java.util.HashSet;
145 import java.util.LinkedHashMap;
146 import java.util.List;
147 import java.util.Locale;
148 import java.util.Map;
149 import java.util.Set;
150 import java.util.concurrent.Callable;
151 import java.util.concurrent.ConcurrentHashMap;
152
153
164 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
165
166
180 public User addDefaultAdminUser(
181 long companyId, String screenName, String emailAddress,
182 Locale locale, String firstName, String middleName, String lastName)
183 throws PortalException, SystemException {
184
185 long creatorUserId = 0;
186 boolean autoPassword = false;
187 String password1 = PropsValues.DEFAULT_ADMIN_PASSWORD;
188 String password2 = password1;
189 boolean autoScreenName = false;
190
191 screenName = getScreenName(screenName);
192
193 for (int i = 1;; i++) {
194 User screenNameUser = userPersistence.fetchByC_SN(
195 companyId, screenName);
196
197 if (screenNameUser == null) {
198 break;
199 }
200
201 screenName = screenName + i;
202 }
203
204 long facebookId = 0;
205 String openId = StringPool.BLANK;
206 int prefixId = 0;
207 int suffixId = 0;
208 boolean male = true;
209 int birthdayMonth = Calendar.JANUARY;
210 int birthdayDay = 1;
211 int birthdayYear = 1970;
212 String jobTitle = StringPool.BLANK;
213
214 Group guestGroup = groupLocalService.getGroup(
215 companyId, GroupConstants.GUEST);
216
217 long[] groupIds = {guestGroup.getGroupId()};
218
219 long[] organizationIds = null;
220
221 Role adminRole = roleLocalService.getRole(
222 companyId, RoleConstants.ADMINISTRATOR);
223
224 Role powerUserRole = roleLocalService.getRole(
225 companyId, RoleConstants.POWER_USER);
226
227 long[] roleIds = {adminRole.getRoleId(), powerUserRole.getRoleId()};
228
229 long[] userGroupIds = null;
230 boolean sendEmail = false;
231 ServiceContext serviceContext = new ServiceContext();
232
233 User defaultAdminUser = addUser(
234 creatorUserId, companyId, autoPassword, password1, password2,
235 autoScreenName, screenName, emailAddress, facebookId, openId,
236 locale, firstName, middleName, lastName, prefixId, suffixId, male,
237 birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
238 organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
239
240 updateEmailAddressVerified(defaultAdminUser.getUserId(), true);
241
242 updateLastLogin(
243 defaultAdminUser.getUserId(), defaultAdminUser.getLoginIP());
244
245 updatePasswordReset(defaultAdminUser.getUserId(), false);
246
247 return defaultAdminUser;
248 }
249
250
260 public void addDefaultGroups(long userId)
261 throws PortalException, SystemException {
262
263 User user = userPersistence.findByPrimaryKey(userId);
264
265 Set<Long> groupIdsSet = new HashSet<Long>();
266
267 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
268 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
269 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
270
271 for (String defaultGroupName : defaultGroupNames) {
272 Company company = companyPersistence.findByPrimaryKey(
273 user.getCompanyId());
274
275 Account account = company.getAccount();
276
277 if (defaultGroupName.equalsIgnoreCase(account.getName())) {
278 defaultGroupName = GroupConstants.GUEST;
279 }
280
281 try {
282 Group group = groupPersistence.findByC_N(
283 user.getCompanyId(), defaultGroupName);
284
285 if (!userPersistence.containsGroup(
286 userId, group.getGroupId())) {
287
288 groupIdsSet.add(group.getGroupId());
289 }
290 }
291 catch (NoSuchGroupException nsge) {
292 }
293 }
294
295 String[] defaultOrganizationGroupNames = PrefsPropsUtil.getStringArray(
296 user.getCompanyId(),
297 PropsKeys.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES,
298 StringPool.NEW_LINE,
299 PropsValues.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES);
300
301 for (String defaultOrganizationGroupName :
302 defaultOrganizationGroupNames) {
303
304 defaultOrganizationGroupName +=
305 GroupLocalServiceImpl.ORGANIZATION_NAME_SUFFIX;
306
307 try {
308 Group group = groupPersistence.findByC_N(
309 user.getCompanyId(), defaultOrganizationGroupName);
310
311 if (!userPersistence.containsGroup(
312 userId, group.getGroupId())) {
313
314 groupIdsSet.add(group.getGroupId());
315 }
316 }
317 catch (NoSuchGroupException nsge) {
318 }
319 }
320
321 long[] groupIds = ArrayUtil.toArray(
322 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
323
324 groupLocalService.addUserGroups(userId, groupIds);
325 }
326
327
337 public void addDefaultRoles(long userId)
338 throws PortalException, SystemException {
339
340 User user = userPersistence.findByPrimaryKey(userId);
341
342 Set<Long> roleIdSet = new HashSet<Long>();
343
344 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
345 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
346 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
347
348 for (String defaultRoleName : defaultRoleNames) {
349 try {
350 Role role = rolePersistence.findByC_N(
351 user.getCompanyId(), defaultRoleName);
352
353 if (!userPersistence.containsRole(userId, role.getRoleId())) {
354 roleIdSet.add(role.getRoleId());
355 }
356 }
357 catch (NoSuchRoleException nsre) {
358 }
359 }
360
361 long[] roleIds = ArrayUtil.toArray(
362 roleIdSet.toArray(new Long[roleIdSet.size()]));
363
364 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
365
366 userPersistence.addRoles(userId, roleIds);
367 }
368
369
379 @SuppressWarnings("deprecation")
380 public void addDefaultUserGroups(long userId)
381 throws PortalException, SystemException {
382
383 User user = userPersistence.findByPrimaryKey(userId);
384
385 Set<Long> userGroupIdSet = new HashSet<Long>();
386
387 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
388 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
389 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
390
391 for (String defaultUserGroupName : defaultUserGroupNames) {
392 try {
393 UserGroup userGroup = userGroupPersistence.findByC_N(
394 user.getCompanyId(), defaultUserGroupName);
395
396 if (!userPersistence.containsUserGroup(
397 userId, userGroup.getUserGroupId())) {
398
399 userGroupIdSet.add(userGroup.getUserGroupId());
400 }
401 }
402 catch (NoSuchUserGroupException nsuge) {
403 }
404 }
405
406 long[] userGroupIds = ArrayUtil.toArray(
407 userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
408
409 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
410 for (long userGroupId : userGroupIds) {
411 userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
412 }
413 }
414
415 userPersistence.addUserGroups(userId, userGroupIds);
416 }
417
418
427 public void addGroupUsers(long groupId, long[] userIds)
428 throws PortalException, SystemException {
429
430 groupPersistence.addUsers(groupId, userIds);
431
432 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
433
434 indexer.reindex(userIds);
435
436 PermissionCacheUtil.clearCache();
437
438 addDefaultRolesAndTeams(groupId, userIds);
439 }
440
441
450 public void addOrganizationUsers(long organizationId, long[] userIds)
451 throws PortalException, SystemException {
452
453 organizationPersistence.addUsers(organizationId, userIds);
454
455 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
456
457 indexer.reindex(userIds);
458
459 PermissionCacheUtil.clearCache();
460 }
461
462
470 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
471 throws SystemException {
472
473 passwordPolicyRelLocalService.addPasswordPolicyRels(
474 passwordPolicyId, User.class.getName(), userIds);
475 }
476
477
486 public void addRoleUsers(long roleId, long[] userIds)
487 throws PortalException, SystemException {
488
489 rolePersistence.addUsers(roleId, userIds);
490
491 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
492
493 indexer.reindex(userIds);
494
495 PermissionCacheUtil.clearCache();
496 }
497
498
507 public void addTeamUsers(long teamId, long[] userIds)
508 throws PortalException, SystemException {
509
510 teamPersistence.addUsers(teamId, userIds);
511
512 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
513
514 indexer.reindex(userIds);
515
516 PermissionCacheUtil.clearCache();
517 }
518
519
567 public User addUser(
568 long creatorUserId, long companyId, boolean autoPassword,
569 String password1, String password2, boolean autoScreenName,
570 String screenName, String emailAddress, long facebookId,
571 String openId, Locale locale, String firstName, String middleName,
572 String lastName, int prefixId, int suffixId, boolean male,
573 int birthdayMonth, int birthdayDay, int birthdayYear,
574 String jobTitle, long[] groupIds, long[] organizationIds,
575 long[] roleIds, long[] userGroupIds, boolean sendEmail,
576 ServiceContext serviceContext)
577 throws PortalException, SystemException {
578
579 boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
580
581 try {
582 WorkflowThreadLocal.setEnabled(false);
583
584 return addUserWithWorkflow(
585 creatorUserId, companyId, autoPassword, password1, password2,
586 autoScreenName, screenName, emailAddress, facebookId, openId,
587 locale, firstName, middleName, lastName, prefixId, suffixId,
588 male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
589 groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
590 serviceContext);
591 }
592 finally {
593 WorkflowThreadLocal.setEnabled(workflowEnabled);
594 }
595 }
596
597
606 @SuppressWarnings("deprecation")
607 public void addUserGroupUsers(long userGroupId, long[] userIds)
608 throws PortalException, SystemException {
609
610 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
611 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
612 }
613
614 userGroupPersistence.addUsers(userGroupId, userIds);
615
616 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
617
618 indexer.reindex(userIds);
619
620 PermissionCacheUtil.clearCache();
621 }
622
623
671 @SuppressWarnings("deprecation")
672 public User addUserWithWorkflow(
673 long creatorUserId, long companyId, boolean autoPassword,
674 String password1, String password2, boolean autoScreenName,
675 String screenName, String emailAddress, long facebookId,
676 String openId, Locale locale, String firstName, String middleName,
677 String lastName, int prefixId, int suffixId, boolean male,
678 int birthdayMonth, int birthdayDay, int birthdayYear,
679 String jobTitle, long[] groupIds, long[] organizationIds,
680 long[] roleIds, long[] userGroupIds, boolean sendEmail,
681 ServiceContext serviceContext)
682 throws PortalException, SystemException {
683
684
685
686 Company company = companyPersistence.findByPrimaryKey(companyId);
687 screenName = getScreenName(screenName);
688 emailAddress = emailAddress.trim().toLowerCase();
689 openId = openId.trim();
690 Date now = new Date();
691
692 if (PrefsPropsUtil.getBoolean(
693 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
694
695 autoScreenName = true;
696 }
697
698
699
700 long userId = counterLocalService.increment();
701
702 EmailAddressGenerator emailAddressGenerator =
703 EmailAddressGeneratorFactory.getInstance();
704
705 if (emailAddressGenerator.isGenerated(emailAddress)) {
706 emailAddress = StringPool.BLANK;
707 }
708
709 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
710 Validator.isNull(emailAddress)) {
711
712 emailAddress = emailAddressGenerator.generate(companyId, userId);
713 }
714
715 validate(
716 companyId, userId, autoPassword, password1, password2,
717 autoScreenName, screenName, emailAddress, firstName, middleName,
718 lastName, organizationIds);
719
720 if (!autoPassword) {
721 if (Validator.isNull(password1) || Validator.isNull(password2)) {
722 throw new UserPasswordException(
723 UserPasswordException.PASSWORD_INVALID);
724 }
725 }
726
727 if (autoScreenName) {
728 ScreenNameGenerator screenNameGenerator =
729 ScreenNameGeneratorFactory.getInstance();
730
731 try {
732 screenName = screenNameGenerator.generate(
733 companyId, userId, emailAddress);
734 }
735 catch (Exception e) {
736 throw new SystemException(e);
737 }
738 }
739
740 User defaultUser = getDefaultUser(companyId);
741
742 FullNameGenerator fullNameGenerator =
743 FullNameGeneratorFactory.getInstance();
744
745 String fullName = fullNameGenerator.getFullName(
746 firstName, middleName, lastName);
747
748 String greeting = LanguageUtil.format(
749 locale, "welcome-x", " " + fullName, false);
750
751 User user = userPersistence.create(userId);
752
753 if (serviceContext != null) {
754 String uuid = serviceContext.getUuid();
755
756 if (Validator.isNotNull(uuid)) {
757 user.setUuid(uuid);
758 }
759 }
760
761 user.setCompanyId(companyId);
762 user.setCreateDate(now);
763 user.setModifiedDate(now);
764 user.setDefaultUser(false);
765 user.setContactId(counterLocalService.increment());
766
767 if (Validator.isNotNull(password1)) {
768 user.setPassword(PwdEncryptor.encrypt(password1));
769 user.setPasswordUnencrypted(password1);
770 }
771
772 user.setPasswordEncrypted(true);
773
774 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
775
776 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
777 passwordPolicy.isChangeRequired()) {
778
779 user.setPasswordReset(true);
780 }
781 else {
782 user.setPasswordReset(false);
783 }
784
785 user.setDigest(StringPool.BLANK);
786 user.setScreenName(screenName);
787 user.setEmailAddress(emailAddress);
788 user.setFacebookId(facebookId);
789 user.setOpenId(openId);
790 user.setLanguageId(locale.toString());
791 user.setTimeZoneId(defaultUser.getTimeZoneId());
792 user.setGreeting(greeting);
793 user.setFirstName(firstName);
794 user.setMiddleName(middleName);
795 user.setLastName(lastName);
796 user.setJobTitle(jobTitle);
797 user.setStatus(WorkflowConstants.STATUS_DRAFT);
798 user.setExpandoBridgeAttributes(serviceContext);
799
800 userPersistence.update(user, serviceContext);
801
802
803
804 String creatorUserName = StringPool.BLANK;
805
806 if (creatorUserId <= 0) {
807 creatorUserId = user.getUserId();
808
809
810
811
812
813 }
814 else {
815 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
816
817 creatorUserName = creatorUser.getFullName();
818 }
819
820 resourceLocalService.addResources(
821 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
822 false, false, false);
823
824
825
826 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
827
828 Contact contact = contactPersistence.create(user.getContactId());
829
830 contact.setCompanyId(user.getCompanyId());
831 contact.setUserId(creatorUserId);
832 contact.setUserName(creatorUserName);
833 contact.setCreateDate(now);
834 contact.setModifiedDate(now);
835 contact.setClassName(User.class.getName());
836 contact.setClassPK(user.getUserId());
837 contact.setAccountId(company.getAccountId());
838 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
839 contact.setEmailAddress(user.getEmailAddress());
840 contact.setFirstName(firstName);
841 contact.setMiddleName(middleName);
842 contact.setLastName(lastName);
843 contact.setPrefixId(prefixId);
844 contact.setSuffixId(suffixId);
845 contact.setMale(male);
846 contact.setBirthday(birthday);
847 contact.setJobTitle(jobTitle);
848
849 contactPersistence.update(contact, serviceContext);
850
851
852
853 groupLocalService.addGroup(
854 user.getUserId(), GroupConstants.DEFAULT_PARENT_GROUP_ID,
855 User.class.getName(), user.getUserId(), null, null, 0,
856 StringPool.SLASH + screenName, false, true, null);
857
858
859
860 if (groupIds != null) {
861 groupLocalService.addUserGroups(userId, groupIds);
862 }
863
864 addDefaultGroups(userId);
865
866
867
868 updateOrganizations(userId, organizationIds, false);
869
870
871
872 if (roleIds != null) {
873 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
874
875 userPersistence.setRoles(userId, roleIds);
876 }
877
878 addDefaultRoles(userId);
879
880
881
882 if (userGroupIds != null) {
883 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
884 for (long userGroupId : userGroupIds) {
885 userGroupLocalService.copyUserGroupLayouts(
886 userGroupId, new long[] {userId});
887 }
888 }
889
890 userPersistence.setUserGroups(userId, userGroupIds);
891 }
892
893 addDefaultUserGroups(userId);
894
895
896
897 if (serviceContext != null) {
898 updateAsset(
899 creatorUserId, user, serviceContext.getAssetCategoryIds(),
900 serviceContext.getAssetTagNames());
901 }
902
903
904
905 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
906 reindex(user);
907 }
908
909
910
911 long workflowUserId = creatorUserId;
912
913 if (workflowUserId == userId) {
914 workflowUserId = defaultUser.getUserId();
915 }
916
917 ServiceContext workflowServiceContext = serviceContext;
918
919 if (workflowServiceContext == null) {
920 workflowServiceContext = new ServiceContext();
921 }
922
923 workflowServiceContext.setAttribute("autoPassword", autoPassword);
924 workflowServiceContext.setAttribute("sendEmail", sendEmail);
925
926 WorkflowHandlerRegistryUtil.startWorkflowInstance(
927 companyId, workflowUserId, User.class.getName(), userId, user,
928 workflowServiceContext);
929
930 if (serviceContext != null) {
931 String passwordUnencrypted = (String)serviceContext.getAttribute(
932 "passwordUnencrypted");
933
934 if (Validator.isNotNull(passwordUnencrypted)) {
935 user.setPasswordUnencrypted(passwordUnencrypted);
936 }
937 }
938
939 return user;
940 }
941
942
966 public int authenticateByEmailAddress(
967 long companyId, String emailAddress, String password,
968 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
969 Map<String, Object> resultsMap)
970 throws PortalException, SystemException {
971
972 return authenticate(
973 companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
974 headerMap, parameterMap, resultsMap);
975 }
976
977
1001 public int authenticateByScreenName(
1002 long companyId, String screenName, String password,
1003 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1004 Map<String, Object> resultsMap)
1005 throws PortalException, SystemException {
1006
1007 return authenticate(
1008 companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
1009 headerMap, parameterMap, resultsMap);
1010 }
1011
1012
1036 public int authenticateByUserId(
1037 long companyId, long userId, String password,
1038 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1039 Map<String, Object> resultsMap)
1040 throws PortalException, SystemException {
1041
1042 return authenticate(
1043 companyId, String.valueOf(userId), password,
1044 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap, resultsMap);
1045 }
1046
1047
1087 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1088 public long authenticateForBasic(
1089 long companyId, String authType, String login, String password)
1090 throws PortalException, SystemException {
1091
1092 if (PropsValues.AUTH_LOGIN_DISABLED) {
1093 return 0;
1094 }
1095
1096 try {
1097 User user = null;
1098
1099 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1100 user = getUserByEmailAddress(companyId, login);
1101 }
1102 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1103 user = getUserByScreenName(companyId, login);
1104 }
1105 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1106 user = getUserById(companyId, GetterUtil.getLong(login));
1107 }
1108
1109 if (user.isDefaultUser()) {
1110 if (_log.isInfoEnabled()) {
1111 _log.info(
1112 "Basic authentication is disabled for the default " +
1113 "user");
1114 }
1115
1116 return 0;
1117 }
1118 else if (!user.isActive()) {
1119 if (_log.isInfoEnabled()) {
1120 _log.info(
1121 "Basic authentication is disabled for inactive user " +
1122 user.getUserId());
1123 }
1124
1125 return 0;
1126 }
1127
1128 if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
1129 return user.getUserId();
1130 }
1131
1132 String userPassword = user.getPassword();
1133
1134 if (!user.isPasswordEncrypted()) {
1135 userPassword = PwdEncryptor.encrypt(userPassword);
1136 }
1137
1138 String encPassword = PwdEncryptor.encrypt(password);
1139
1140 if (userPassword.equals(password) ||
1141 userPassword.equals(encPassword)) {
1142
1143 return user.getUserId();
1144 }
1145 }
1146 catch (NoSuchUserException nsue) {
1147 }
1148
1149 return 0;
1150 }
1151
1152
1170 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1171 public long authenticateForDigest(
1172 long companyId, String username, String realm, String nonce,
1173 String method, String uri, String response)
1174 throws PortalException, SystemException {
1175
1176 if (PropsValues.AUTH_LOGIN_DISABLED) {
1177 return 0;
1178 }
1179
1180
1181
1182 User user = null;
1183
1184 try {
1185 user = getUserByEmailAddress(companyId, username);
1186 }
1187 catch (NoSuchUserException nsue) {
1188 try {
1189 user = getUserByScreenName(companyId, username);
1190 }
1191 catch (NoSuchUserException nsue2) {
1192 try {
1193 user = getUserById(GetterUtil.getLong(username));
1194 }
1195 catch (NoSuchUserException nsue3) {
1196 return 0;
1197 }
1198 }
1199 }
1200
1201 if (user.isDefaultUser()) {
1202 if (_log.isInfoEnabled()) {
1203 _log.info(
1204 "Digest authentication is disabled for the default user");
1205 }
1206
1207 return 0;
1208 }
1209 else if (!user.isActive()) {
1210 if (_log.isInfoEnabled()) {
1211 _log.info(
1212 "Digest authentication is disabled for inactive user " +
1213 user.getUserId());
1214 }
1215
1216 return 0;
1217 }
1218
1219
1220
1221 String digest = user.getDigest();
1222
1223 if (Validator.isNull(digest)) {
1224 _log.error(
1225 "User must first login through the portal " + user.getUserId());
1226
1227 return 0;
1228 }
1229
1230 String[] digestArray = StringUtil.split(user.getDigest());
1231
1232 for (String ha1 : digestArray) {
1233 String ha2 = DigesterUtil.digestHex(Digester.MD5, method, uri);
1234
1235 String curResponse = DigesterUtil.digestHex(
1236 Digester.MD5, ha1, nonce, ha2);
1237
1238 if (response.equals(curResponse)) {
1239 return user.getUserId();
1240 }
1241 }
1242
1243 return 0;
1244 }
1245
1246
1255 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1256 public boolean authenticateForJAAS(long userId, String encPassword) {
1257 if (PropsValues.AUTH_LOGIN_DISABLED) {
1258 return false;
1259 }
1260
1261 try {
1262 User user = userPersistence.findByPrimaryKey(userId);
1263
1264 if (user.isDefaultUser()) {
1265 if (_log.isInfoEnabled()) {
1266 _log.info(
1267 "JAAS authentication is disabled for the default user");
1268 }
1269
1270 return false;
1271 }
1272 else if (!user.isActive()) {
1273 if (_log.isInfoEnabled()) {
1274 _log.info(
1275 "JAAS authentication is disabled for inactive user " +
1276 userId);
1277 }
1278
1279 return false;
1280 }
1281
1282 String password = user.getPassword();
1283
1284 if (user.isPasswordEncrypted()) {
1285 if (password.equals(encPassword)) {
1286 return true;
1287 }
1288
1289 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1290 encPassword = PwdEncryptor.encrypt(encPassword, password);
1291
1292 if (password.equals(encPassword)) {
1293 return true;
1294 }
1295 }
1296 }
1297 else {
1298 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1299 if (password.equals(encPassword)) {
1300 return true;
1301 }
1302 }
1303
1304 password = PwdEncryptor.encrypt(password);
1305
1306 if (password.equals(encPassword)) {
1307 return true;
1308 }
1309 }
1310 }
1311 catch (Exception e) {
1312 _log.error(e);
1313 }
1314
1315 return false;
1316 }
1317
1318
1326 public void checkLockout(User user)
1327 throws PortalException, SystemException {
1328
1329 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1330 return;
1331 }
1332
1333 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1334
1335 if (passwordPolicy.isLockout()) {
1336
1337
1338
1339 Date now = new Date();
1340 int failedLoginAttempts = user.getFailedLoginAttempts();
1341
1342 if (failedLoginAttempts > 0) {
1343 long failedLoginTime = user.getLastFailedLoginDate().getTime();
1344 long elapsedTime = now.getTime() - failedLoginTime;
1345 long requiredElapsedTime =
1346 passwordPolicy.getResetFailureCount() * 1000;
1347
1348 if ((requiredElapsedTime != 0) &&
1349 (elapsedTime > requiredElapsedTime)) {
1350
1351 user.setLastFailedLoginDate(null);
1352 user.setFailedLoginAttempts(0);
1353
1354 userPersistence.update(user);
1355 }
1356 }
1357
1358
1359
1360 if (user.isLockout()) {
1361 long lockoutTime = user.getLockoutDate().getTime();
1362 long elapsedTime = now.getTime() - lockoutTime;
1363 long requiredElapsedTime =
1364 passwordPolicy.getLockoutDuration() * 1000;
1365
1366 if ((requiredElapsedTime != 0) &&
1367 (elapsedTime > requiredElapsedTime)) {
1368
1369 user.setLockout(false);
1370 user.setLockoutDate(null);
1371
1372 userPersistence.update(user);
1373 }
1374 }
1375
1376 if (user.isLockout()) {
1377 throw new UserLockoutException();
1378 }
1379 }
1380 }
1381
1382
1389 public void checkLoginFailure(User user) throws SystemException {
1390 Date now = new Date();
1391
1392 int failedLoginAttempts = user.getFailedLoginAttempts();
1393
1394 user.setLastFailedLoginDate(now);
1395 user.setFailedLoginAttempts(++failedLoginAttempts);
1396
1397 userPersistence.update(user);
1398 }
1399
1400
1410 public void checkLoginFailureByEmailAddress(
1411 long companyId, String emailAddress)
1412 throws PortalException, SystemException {
1413
1414 User user = getUserByEmailAddress(companyId, emailAddress);
1415
1416 checkLoginFailure(user);
1417 }
1418
1419
1427 public void checkLoginFailureById(long userId)
1428 throws PortalException, SystemException {
1429
1430 User user = userPersistence.findByPrimaryKey(userId);
1431
1432 checkLoginFailure(user);
1433 }
1434
1435
1444 public void checkLoginFailureByScreenName(long companyId, String screenName)
1445 throws PortalException, SystemException {
1446
1447 User user = getUserByScreenName(companyId, screenName);
1448
1449 checkLoginFailure(user);
1450 }
1451
1452
1462 public void checkPasswordExpired(User user)
1463 throws PortalException, SystemException {
1464
1465 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1466 return;
1467 }
1468
1469 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1470
1471
1472
1473 if (isPasswordExpired(user)) {
1474 int graceLoginCount = user.getGraceLoginCount();
1475
1476 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
1477 user.setGraceLoginCount(++graceLoginCount);
1478
1479 userPersistence.update(user);
1480 }
1481 else {
1482 user.setDigest(StringPool.BLANK);
1483
1484 userPersistence.update(user);
1485
1486 throw new PasswordExpiredException();
1487 }
1488 }
1489
1490
1491
1492 if (passwordPolicy.isChangeable() &&
1493 passwordPolicy.isChangeRequired()) {
1494
1495 if (user.getLastLoginDate() == null) {
1496 user.setPasswordReset(true);
1497
1498 userPersistence.update(user);
1499 }
1500 }
1501 }
1502
1503
1509 public void clearOrganizationUsers(long organizationId)
1510 throws SystemException {
1511
1512 organizationPersistence.clearUsers(organizationId);
1513
1514 PermissionCacheUtil.clearCache();
1515 }
1516
1517
1523 public void clearUserGroupUsers(long userGroupId) throws SystemException {
1524 userGroupPersistence.clearUsers(userGroupId);
1525
1526 PermissionCacheUtil.clearCache();
1527 }
1528
1529
1541 public void completeUserRegistration(
1542 User user, ServiceContext serviceContext)
1543 throws PortalException, SystemException {
1544
1545 boolean autoPassword = ParamUtil.getBoolean(
1546 serviceContext, "autoPassword");
1547
1548 String password = null;
1549
1550 if (autoPassword) {
1551 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1552 if (_log.isWarnEnabled()) {
1553 StringBundler sb = new StringBundler(4);
1554
1555 sb.append("When LDAP password policy is enabled, it is ");
1556 sb.append("possible that portal generated passwords will ");
1557 sb.append("not match the LDAP policy. Using ");
1558 sb.append("RegExpToolkit to generate new password.");
1559
1560 _log.warn(sb.toString());
1561 }
1562
1563 RegExpToolkit regExpToolkit = new RegExpToolkit();
1564
1565 password = regExpToolkit.generate(null);
1566 }
1567 else {
1568 PasswordPolicy passwordPolicy =
1569 passwordPolicyLocalService.getPasswordPolicy(
1570 user.getCompanyId(), user.getOrganizationIds());
1571
1572 password = PwdToolkitUtil.generate(passwordPolicy);
1573 }
1574
1575 user.setPassword(PwdEncryptor.encrypt(password));
1576 user.setPasswordEncrypted(true);
1577 user.setPasswordUnencrypted(password);
1578
1579 userPersistence.update(user);
1580 }
1581
1582 if (user.hasCompanyMx()) {
1583 String mailPassword = password;
1584
1585 if (Validator.isNull(mailPassword)) {
1586 mailPassword = user.getPasswordUnencrypted();
1587 }
1588
1589 mailService.addUser(
1590 user.getCompanyId(), user.getUserId(), mailPassword,
1591 user.getFirstName(), user.getMiddleName(), user.getLastName(),
1592 user.getEmailAddress());
1593 }
1594
1595 boolean sendEmail = ParamUtil.getBoolean(serviceContext, "sendEmail");
1596
1597 if (sendEmail) {
1598 sendEmail(user, password, serviceContext);
1599 }
1600
1601 Company company = companyPersistence.findByPrimaryKey(
1602 user.getCompanyId());
1603
1604 if (company.isStrangersVerify() && (serviceContext.getPlid() > 0)) {
1605 sendEmailAddressVerification(
1606 user, user.getEmailAddress(), serviceContext);
1607 }
1608 }
1609
1610
1623 public KeyValuePair decryptUserId(
1624 long companyId, String name, String password)
1625 throws PortalException, SystemException {
1626
1627 Company company = companyPersistence.findByPrimaryKey(companyId);
1628
1629 try {
1630 name = Encryptor.decrypt(company.getKeyObj(), name);
1631 }
1632 catch (EncryptorException ee) {
1633 throw new SystemException(ee);
1634 }
1635
1636 long userId = GetterUtil.getLong(name);
1637
1638 User user = userPersistence.findByPrimaryKey(userId);
1639
1640 try {
1641 password = Encryptor.decrypt(company.getKeyObj(), password);
1642 }
1643 catch (EncryptorException ee) {
1644 throw new SystemException(ee);
1645 }
1646
1647 String encPassword = PwdEncryptor.encrypt(password);
1648
1649 if (user.getPassword().equals(encPassword)) {
1650 if (isPasswordExpired(user)) {
1651 user.setPasswordReset(true);
1652
1653 userPersistence.update(user);
1654 }
1655
1656 return new KeyValuePair(name, password);
1657 }
1658 else {
1659 throw new PrincipalException();
1660 }
1661 }
1662
1663
1671 public void deletePortrait(long userId)
1672 throws PortalException, SystemException {
1673
1674 User user = userPersistence.findByPrimaryKey(userId);
1675
1676 long portraitId = user.getPortraitId();
1677
1678 if (portraitId > 0) {
1679 user.setPortraitId(0);
1680
1681 userPersistence.update(user);
1682
1683 imageLocalService.deleteImage(portraitId);
1684 }
1685 }
1686
1687
1696 public void deleteRoleUser(long roleId, long userId)
1697 throws PortalException, SystemException {
1698
1699 rolePersistence.removeUser(roleId, userId);
1700
1701 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1702
1703 indexer.reindex(userId);
1704
1705 PermissionCacheUtil.clearCache();
1706 }
1707
1708
1716 @Override
1717 public User deleteUser(long userId)
1718 throws PortalException, SystemException {
1719
1720 User user = userPersistence.findByPrimaryKey(userId);
1721
1722 return deleteUser(user);
1723 }
1724
1725
1733 @Override
1734 public User deleteUser(User user) throws PortalException, SystemException {
1735 if (!PropsValues.USERS_DELETE) {
1736 throw new RequiredUserException();
1737 }
1738
1739
1740
1741 browserTrackerLocalService.deleteUserBrowserTracker(user.getUserId());
1742
1743
1744
1745 Group group = user.getGroup();
1746
1747 if (group != null) {
1748 groupLocalService.deleteGroup(group);
1749 }
1750
1751
1752
1753 imageLocalService.deleteImage(user.getPortraitId());
1754
1755
1756
1757 passwordPolicyRelLocalService.deletePasswordPolicyRel(
1758 User.class.getName(), user.getUserId());
1759
1760
1761
1762 passwordTrackerLocalService.deletePasswordTrackers(user.getUserId());
1763
1764
1765
1766 subscriptionLocalService.deleteSubscriptions(user.getUserId());
1767
1768
1769
1770 userIdMapperLocalService.deleteUserIdMappers(user.getUserId());
1771
1772
1773
1774 announcementsDeliveryLocalService.deleteDeliveries(user.getUserId());
1775
1776
1777
1778 assetEntryLocalService.deleteEntry(
1779 User.class.getName(), user.getUserId());
1780
1781
1782
1783 blogsStatsUserLocalService.deleteStatsUserByUserId(user.getUserId());
1784
1785
1786
1787 dlFileRankLocalService.deleteFileRanksByUserId(user.getUserId());
1788
1789
1790
1791 expandoValueLocalService.deleteValues(
1792 User.class.getName(), user.getUserId());
1793
1794
1795
1796 mbBanLocalService.deleteBansByBanUserId(user.getUserId());
1797 mbStatsUserLocalService.deleteStatsUsersByUserId(user.getUserId());
1798 mbThreadFlagLocalService.deleteThreadFlagsByUserId(user.getUserId());
1799
1800
1801
1802 membershipRequestLocalService.deleteMembershipRequestsByUserId(
1803 user.getUserId());
1804
1805
1806
1807 shoppingCartLocalService.deleteUserCarts(user.getUserId());
1808
1809
1810
1811 socialActivityLocalService.deleteUserActivities(user.getUserId());
1812 socialRequestLocalService.deleteReceiverUserRequests(user.getUserId());
1813 socialRequestLocalService.deleteUserRequests(user.getUserId());
1814
1815
1816
1817 mailService.deleteUser(user.getCompanyId(), user.getUserId());
1818
1819
1820
1821 try {
1822 contactLocalService.deleteContact(user.getContactId());
1823 }
1824 catch (NoSuchContactException nsce) {
1825 }
1826
1827
1828
1829 resourceLocalService.deleteResource(
1830 user.getCompanyId(), User.class.getName(),
1831 ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
1832
1833
1834
1835 userGroupRoleLocalService.deleteUserGroupRolesByUserId(
1836 user.getUserId());
1837
1838
1839
1840 userPersistence.remove(user);
1841
1842
1843
1844 PermissionCacheUtil.clearCache();
1845
1846
1847
1848 workflowInstanceLinkLocalService.deleteWorkflowInstanceLinks(
1849 user.getCompanyId(), 0, User.class.getName(), user.getUserId());
1850
1851 return user;
1852 }
1853
1854
1862 public void deleteUserGroupUser(long userGroupId, long userId)
1863 throws PortalException, SystemException {
1864
1865 userGroupPersistence.removeUser(userGroupId, userId);
1866
1867 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1868
1869 indexer.reindex(userId);
1870
1871 PermissionCacheUtil.clearCache();
1872 }
1873
1874
1883 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1884 public String encryptUserId(String name)
1885 throws PortalException, SystemException {
1886
1887 long userId = GetterUtil.getLong(name);
1888
1889 User user = userPersistence.findByPrimaryKey(userId);
1890
1891 Company company = companyPersistence.findByPrimaryKey(
1892 user.getCompanyId());
1893
1894 try {
1895 return Encryptor.encrypt(company.getKeyObj(), name);
1896 }
1897 catch (EncryptorException ee) {
1898 throw new SystemException(ee);
1899 }
1900 }
1901
1902
1911 public User fetchUserByEmailAddress(long companyId, String emailAddress)
1912 throws SystemException {
1913
1914 return userPersistence.fetchByC_EA(companyId, emailAddress);
1915 }
1916
1917
1925 public User fetchUserById(long userId) throws SystemException {
1926 return userPersistence.fetchByPrimaryKey(userId);
1927 }
1928
1929
1938 public User fetchUserByScreenName(long companyId, String screenName)
1939 throws SystemException {
1940
1941 screenName = getScreenName(screenName);
1942
1943 return userPersistence.fetchByC_SN(companyId, screenName);
1944 }
1945
1946
1965 public List<User> getCompanyUsers(long companyId, int start, int end)
1966 throws SystemException {
1967
1968 return userPersistence.findByCompanyId(companyId, start, end);
1969 }
1970
1971
1978 public int getCompanyUsersCount(long companyId) throws SystemException {
1979 return userPersistence.countByCompanyId(companyId);
1980 }
1981
1982
1991 @Skip
1992 public User getDefaultUser(long companyId)
1993 throws PortalException, SystemException {
1994
1995 User userModel = _defaultUsers.get(companyId);
1996
1997 if (userModel == null) {
1998 userModel = userLocalService.loadGetDefaultUser(companyId);
1999
2000 _defaultUsers.put(companyId, userModel);
2001 }
2002
2003 return userModel;
2004 }
2005
2006
2015 @Skip
2016 public long getDefaultUserId(long companyId)
2017 throws PortalException, SystemException {
2018
2019 User user = getDefaultUser(companyId);
2020
2021 return user.getUserId();
2022 }
2023
2024
2031 public long[] getGroupUserIds(long groupId) throws SystemException {
2032 return getUserIds(getGroupUsers(groupId));
2033 }
2034
2035
2042 public List<User> getGroupUsers(long groupId) throws SystemException {
2043 return groupPersistence.getUsers(groupId);
2044 }
2045
2046
2053 public int getGroupUsersCount(long groupId) throws SystemException {
2054 return groupPersistence.getUsersSize(groupId);
2055 }
2056
2057
2067 public int getGroupUsersCount(long groupId, int status)
2068 throws PortalException, SystemException {
2069
2070 Group group = groupPersistence.findByPrimaryKey(groupId);
2071
2072 LinkedHashMap<String, Object> params =
2073 new LinkedHashMap<String, Object>();
2074
2075 params.put("usersGroups", new Long(groupId));
2076
2077 return searchCount(group.getCompanyId(), null, status, params);
2078 }
2079
2080
2088 public List<User> getNoAnnouncementsDeliveries(String type)
2089 throws SystemException {
2090
2091 return userFinder.findByNoAnnouncementsDeliveries(type);
2092 }
2093
2094
2100 public List<User> getNoContacts() throws SystemException {
2101 return userFinder.findByNoContacts();
2102 }
2103
2104
2111 public List<User> getNoGroups() throws SystemException {
2112 return userFinder.findByNoGroups();
2113 }
2114
2115
2122 public long[] getOrganizationUserIds(long organizationId)
2123 throws SystemException {
2124
2125 return getUserIds(getOrganizationUsers(organizationId));
2126 }
2127
2128
2135 public List<User> getOrganizationUsers(long organizationId)
2136 throws SystemException {
2137
2138 return organizationPersistence.getUsers(organizationId);
2139 }
2140
2141
2148 public int getOrganizationUsersCount(long organizationId)
2149 throws SystemException {
2150
2151 return organizationPersistence.getUsersSize(organizationId);
2152 }
2153
2154
2165 public int getOrganizationUsersCount(long organizationId, int status)
2166 throws PortalException, SystemException {
2167
2168 Organization organization = organizationPersistence.findByPrimaryKey(
2169 organizationId);
2170
2171 LinkedHashMap<String, Object> params =
2172 new LinkedHashMap<String, Object>();
2173
2174 params.put("usersOrgs", new Long(organizationId));
2175
2176 return searchCount(organization.getCompanyId(), null, status, params);
2177 }
2178
2179
2186 public long[] getRoleUserIds(long roleId) throws SystemException {
2187 return getUserIds(getRoleUsers(roleId));
2188 }
2189
2190
2197 public List<User> getRoleUsers(long roleId) throws SystemException {
2198 return rolePersistence.getUsers(roleId);
2199 }
2200
2201
2220 public List<User> getRoleUsers(long roleId, int start, int end)
2221 throws SystemException {
2222
2223 return rolePersistence.getUsers(roleId, start, end);
2224 }
2225
2226
2233 public int getRoleUsersCount(long roleId) throws SystemException {
2234 return rolePersistence.getUsersSize(roleId);
2235 }
2236
2237
2247 public int getRoleUsersCount(long roleId, int status)
2248 throws PortalException, SystemException {
2249
2250 Role role = rolePersistence.findByPrimaryKey(roleId);
2251
2252 LinkedHashMap<String, Object> params =
2253 new LinkedHashMap<String, Object>();
2254
2255 params.put("usersRoles", new Long(roleId));
2256
2257 return searchCount(role.getCompanyId(), null, status, params);
2258 }
2259
2260
2287 public List<User> getSocialUsers(
2288 long userId, int type, int start, int end, OrderByComparator obc)
2289 throws PortalException, SystemException {
2290
2291 User user = userPersistence.findByPrimaryKey(userId);
2292
2293 LinkedHashMap<String, Object> params =
2294 new LinkedHashMap<String, Object>();
2295
2296 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2297
2298 return search(
2299 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2300 params, start, end, obc);
2301 }
2302
2303
2326 public List<User> getSocialUsers(
2327 long userId, int start, int end, OrderByComparator obc)
2328 throws PortalException, SystemException {
2329
2330 User user = userPersistence.findByPrimaryKey(userId);
2331
2332 LinkedHashMap<String, Object> params =
2333 new LinkedHashMap<String, Object>();
2334
2335 params.put("socialRelation", new Long[] {userId});
2336
2337 return search(
2338 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2339 params, start, end, obc);
2340 }
2341
2342
2370 public List<User> getSocialUsers(
2371 long userId1, long userId2, int type, int start, int end,
2372 OrderByComparator obc)
2373 throws PortalException, SystemException {
2374
2375 User user1 = userPersistence.findByPrimaryKey(userId1);
2376
2377 LinkedHashMap<String, Object> params =
2378 new LinkedHashMap<String, Object>();
2379
2380 params.put(
2381 "socialMutualRelationType",
2382 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2383
2384 return search(
2385 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2386 params, start, end, obc);
2387 }
2388
2389
2414 public List<User> getSocialUsers(
2415 long userId1, long userId2, int start, int end,
2416 OrderByComparator obc)
2417 throws PortalException, SystemException {
2418
2419 User user1 = userPersistence.findByPrimaryKey(userId1);
2420
2421 LinkedHashMap<String, Object> params =
2422 new LinkedHashMap<String, Object>();
2423
2424 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2425
2426 return search(
2427 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2428 params, start, end, obc);
2429 }
2430
2431
2439 public int getSocialUsersCount(long userId)
2440 throws PortalException, SystemException {
2441
2442 User user = userPersistence.findByPrimaryKey(userId);
2443
2444 LinkedHashMap<String, Object> params =
2445 new LinkedHashMap<String, Object>();
2446
2447 params.put("socialRelation", new Long[] {userId});
2448
2449 return searchCount(
2450 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2451 params);
2452 }
2453
2454
2467 public int getSocialUsersCount(long userId, int type)
2468 throws PortalException, SystemException {
2469
2470 User user = userPersistence.findByPrimaryKey(userId);
2471
2472 LinkedHashMap<String, Object> params =
2473 new LinkedHashMap<String, Object>();
2474
2475 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2476
2477 return searchCount(
2478 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2479 params);
2480 }
2481
2482
2492 public int getSocialUsersCount(long userId1, long userId2)
2493 throws PortalException, SystemException {
2494
2495 User user1 = userPersistence.findByPrimaryKey(userId1);
2496
2497 LinkedHashMap<String, Object> params =
2498 new LinkedHashMap<String, Object>();
2499
2500 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2501
2502 return searchCount(
2503 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2504 params);
2505 }
2506
2507
2521 public int getSocialUsersCount(long userId1, long userId2, int type)
2522 throws PortalException, SystemException {
2523
2524 User user1 = userPersistence.findByPrimaryKey(userId1);
2525
2526 LinkedHashMap<String, Object> params =
2527 new LinkedHashMap<String, Object>();
2528
2529 params.put(
2530 "socialMutualRelationType",
2531 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2532
2533 return searchCount(
2534 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2535 params);
2536 }
2537
2538
2546 public User getUserByContactId(long contactId)
2547 throws PortalException, SystemException {
2548
2549 return userPersistence.findByContactId(contactId);
2550 }
2551
2552
2562 public User getUserByEmailAddress(long companyId, String emailAddress)
2563 throws PortalException, SystemException {
2564
2565 emailAddress = emailAddress.trim().toLowerCase();
2566
2567 return userPersistence.findByC_EA(companyId, emailAddress);
2568 }
2569
2570
2579 public User getUserByFacebookId(long companyId, long facebookId)
2580 throws PortalException, SystemException {
2581
2582 return userPersistence.findByC_FID(companyId, facebookId);
2583 }
2584
2585
2593 public User getUserById(long userId)
2594 throws PortalException, SystemException {
2595
2596 return userPersistence.findByPrimaryKey(userId);
2597 }
2598
2599
2609 public User getUserById(long companyId, long userId)
2610 throws PortalException, SystemException {
2611
2612 return userPersistence.findByC_U(companyId, userId);
2613 }
2614
2615
2624 public User getUserByOpenId(long companyId, String openId)
2625 throws PortalException, SystemException {
2626
2627 return userPersistence.findByC_O(companyId, openId);
2628 }
2629
2630
2638 public User getUserByPortraitId(long portraitId)
2639 throws PortalException, SystemException {
2640
2641 return userPersistence.findByPortraitId(portraitId);
2642 }
2643
2644
2653 public User getUserByScreenName(long companyId, String screenName)
2654 throws PortalException, SystemException {
2655
2656 screenName = getScreenName(screenName);
2657
2658 return userPersistence.findByC_SN(companyId, screenName);
2659 }
2660
2661
2671 public User getUserByUuid(String uuid)
2672 throws PortalException, SystemException {
2673
2674 List<User> users = userPersistence.findByUuid(uuid);
2675
2676 if (users.isEmpty()) {
2677 throw new NoSuchUserException();
2678 }
2679 else {
2680 return users.get(0);
2681 }
2682 }
2683
2684
2694 public User getUserByUuidAndCompanyId(String uuid, long companyId)
2695 throws PortalException, SystemException {
2696
2697 List<User> users = userPersistence.findByUuid_C(uuid, companyId);
2698
2699 if (users.isEmpty()) {
2700 throw new NoSuchUserException();
2701 }
2702 else {
2703 return users.get(0);
2704 }
2705 }
2706
2707
2714 public List<User> getUserGroupUsers(long userGroupId)
2715 throws SystemException {
2716
2717 return userGroupPersistence.getUsers(userGroupId);
2718 }
2719
2720
2727 public int getUserGroupUsersCount(long userGroupId) throws SystemException {
2728 return userGroupPersistence.getUsersSize(userGroupId);
2729 }
2730
2731
2741 public int getUserGroupUsersCount(long userGroupId, int status)
2742 throws PortalException, SystemException {
2743
2744 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
2745 userGroupId);
2746
2747 LinkedHashMap<String, Object> params =
2748 new LinkedHashMap<String, Object>();
2749
2750 params.put("usersUserGroups", new Long(userGroupId));
2751
2752 return searchCount(userGroup.getCompanyId(), null, status, params);
2753 }
2754
2755
2765 public long getUserIdByEmailAddress(long companyId, String emailAddress)
2766 throws PortalException, SystemException {
2767
2768 emailAddress = emailAddress.trim().toLowerCase();
2769
2770 User user = userPersistence.findByC_EA(companyId, emailAddress);
2771
2772 return user.getUserId();
2773 }
2774
2775
2784 public long getUserIdByScreenName(long companyId, String screenName)
2785 throws PortalException, SystemException {
2786
2787 screenName = getScreenName(screenName);
2788
2789 User user = userPersistence.findByC_SN(companyId, screenName);
2790
2791 return user.getUserId();
2792 }
2793
2794
2803 public boolean hasGroupUser(long groupId, long userId)
2804 throws SystemException {
2805
2806 return groupPersistence.containsUser(groupId, userId);
2807 }
2808
2809
2818 public boolean hasOrganizationUser(long organizationId, long userId)
2819 throws SystemException {
2820
2821 return organizationPersistence.containsUser(organizationId, userId);
2822 }
2823
2824
2834 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
2835 throws SystemException {
2836
2837 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
2838 passwordPolicyId, User.class.getName(), userId);
2839 }
2840
2841
2850 public boolean hasRoleUser(long roleId, long userId)
2851 throws SystemException {
2852
2853 return rolePersistence.containsUser(roleId, userId);
2854 }
2855
2856
2871 public boolean hasRoleUser(
2872 long companyId, String name, long userId, boolean inherited)
2873 throws PortalException, SystemException {
2874
2875 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
2876 }
2877
2878
2887 public boolean hasTeamUser(long teamId, long userId)
2888 throws SystemException {
2889
2890 return teamPersistence.containsUser(teamId, userId);
2891 }
2892
2893
2902 public boolean hasUserGroupUser(long userGroupId, long userId)
2903 throws SystemException {
2904
2905 return userGroupPersistence.containsUser(userGroupId, userId);
2906 }
2907
2908
2918 public boolean isPasswordExpired(User user)
2919 throws PortalException, SystemException {
2920
2921 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2922
2923 if ((passwordPolicy != null) && passwordPolicy.getExpireable()) {
2924 Date now = new Date();
2925
2926 if (user.getPasswordModifiedDate() == null) {
2927 user.setPasswordModifiedDate(now);
2928
2929 userLocalService.updateUser(user);
2930 }
2931
2932 long passwordStartTime = user.getPasswordModifiedDate().getTime();
2933 long elapsedTime = now.getTime() - passwordStartTime;
2934
2935 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
2936 return true;
2937 }
2938 else {
2939 return false;
2940 }
2941 }
2942
2943 return false;
2944 }
2945
2946
2958 public boolean isPasswordExpiringSoon(User user)
2959 throws PortalException, SystemException {
2960
2961 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2962
2963 if ((passwordPolicy != null) && passwordPolicy.isExpireable() &&
2964 (passwordPolicy.getWarningTime() > 0)) {
2965
2966 Date now = new Date();
2967
2968 if (user.getPasswordModifiedDate() == null) {
2969 user.setPasswordModifiedDate(now);
2970
2971 userLocalService.updateUser(user);
2972 }
2973
2974 long timeModified = user.getPasswordModifiedDate().getTime();
2975 long passwordExpiresOn =
2976 (passwordPolicy.getMaxAge() * 1000) + timeModified;
2977
2978 long timeStartWarning =
2979 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
2980
2981 if (now.getTime() > timeStartWarning) {
2982 return true;
2983 }
2984 else {
2985 return false;
2986 }
2987 }
2988
2989 return false;
2990 }
2991
2992
3000 public User loadGetDefaultUser(long companyId)
3001 throws PortalException, SystemException {
3002
3003 return userPersistence.findByC_DU(companyId, true);
3004 }
3005
3006
3038 public List<User> search(
3039 long companyId, String keywords, int status,
3040 LinkedHashMap<String, Object> params, int start, int end,
3041 OrderByComparator obc)
3042 throws SystemException {
3043
3044 return userFinder.findByKeywords(
3045 companyId, keywords, status, params, start, end, obc);
3046 }
3047
3048
3079 public Hits search(
3080 long companyId, String keywords, int status,
3081 LinkedHashMap<String, Object> params, int start, int end, Sort sort)
3082 throws SystemException {
3083
3084 String firstName = null;
3085 String middleName = null;
3086 String lastName = null;
3087 String fullName = null;
3088 String screenName = null;
3089 String emailAddress = null;
3090 String street = null;
3091 String city = null;
3092 String zip = null;
3093 String region = null;
3094 String country = null;
3095 boolean andOperator = false;
3096
3097 if (Validator.isNotNull(keywords)) {
3098 firstName = keywords;
3099 middleName = keywords;
3100 lastName = keywords;
3101 fullName = keywords;
3102 screenName = keywords;
3103 emailAddress = keywords;
3104 street = keywords;
3105 city = keywords;
3106 zip = keywords;
3107 region = keywords;
3108 country = keywords;
3109 }
3110 else {
3111 andOperator = true;
3112 }
3113
3114 if (params != null) {
3115 params.put("keywords", keywords);
3116 }
3117
3118 return search(
3119 companyId, firstName, middleName, lastName, fullName, screenName,
3120 emailAddress, street, city, zip, region, country, status, params,
3121 andOperator, start, end, sort);
3122 }
3123
3124
3164 public List<User> search(
3165 long companyId, String firstName, String middleName,
3166 String lastName, String screenName, String emailAddress, int status,
3167 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3168 int end, OrderByComparator obc)
3169 throws SystemException {
3170
3171 return userFinder.findByC_FN_MN_LN_SN_EA_S(
3172 companyId, firstName, middleName, lastName, screenName,
3173 emailAddress, status, params, andSearch, start, end, obc);
3174 }
3175
3176
3215 public Hits search(
3216 long companyId, String firstName, String middleName,
3217 String lastName, String screenName, String emailAddress, int status,
3218 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3219 int end, Sort sort)
3220 throws SystemException {
3221
3222 return search(
3223 companyId, firstName, middleName, lastName, null, screenName,
3224 emailAddress, null, null, null, null, null, status, params,
3225 andSearch, start, end, sort);
3226 }
3227
3228
3242 public int searchCount(
3243 long companyId, String keywords, int status,
3244 LinkedHashMap<String, Object> params)
3245 throws SystemException {
3246
3247 return userFinder.countByKeywords(companyId, keywords, status, params);
3248 }
3249
3250
3272 public int searchCount(
3273 long companyId, String firstName, String middleName,
3274 String lastName, String screenName, String emailAddress, int status,
3275 LinkedHashMap<String, Object> params, boolean andSearch)
3276 throws SystemException {
3277
3278 return userFinder.countByC_FN_MN_LN_SN_EA_S(
3279 companyId, firstName, middleName, lastName, screenName,
3280 emailAddress, status, params, andSearch);
3281 }
3282
3283
3294 public void sendEmailAddressVerification(
3295 User user, String emailAddress, ServiceContext serviceContext)
3296 throws PortalException, SystemException {
3297
3298 if (user.isEmailAddressVerified() &&
3299 emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
3300
3301 return;
3302 }
3303
3304 Ticket ticket = ticketLocalService.addTicket(
3305 user.getCompanyId(), User.class.getName(), user.getUserId(),
3306 TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3307 serviceContext);
3308
3309 String verifyEmailAddressURL =
3310 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3311 "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3312
3313 Layout layout = layoutLocalService.getLayout(serviceContext.getPlid());
3314
3315 Group group = layout.getGroup();
3316
3317 if (!layout.isPrivateLayout() && !group.isUser()) {
3318 verifyEmailAddressURL += "&p_l_id=" + serviceContext.getPlid();
3319 }
3320
3321 String fromName = PrefsPropsUtil.getString(
3322 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3323 String fromAddress = PrefsPropsUtil.getString(
3324 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3325
3326 String toName = user.getFullName();
3327 String toAddress = emailAddress;
3328
3329 String subject = PrefsPropsUtil.getContent(
3330 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3331
3332 String body = PrefsPropsUtil.getContent(
3333 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3334
3335 SubscriptionSender subscriptionSender = new SubscriptionSender();
3336
3337 subscriptionSender.setBody(body);
3338 subscriptionSender.setCompanyId(user.getCompanyId());
3339 subscriptionSender.setContextAttributes(
3340 "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3341 "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3342 "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3343 "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_ID$]",
3344 user.getUserId(), "[$USER_SCREENNAME$]", user.getScreenName());
3345 subscriptionSender.setFrom(fromAddress, fromName);
3346 subscriptionSender.setHtmlFormat(true);
3347 subscriptionSender.setMailId("user", user.getUserId());
3348 subscriptionSender.setServiceContext(serviceContext);
3349 subscriptionSender.setSubject(subject);
3350 subscriptionSender.setUserId(user.getUserId());
3351
3352 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3353
3354 subscriptionSender.flushNotificationsAsync();
3355 }
3356
3357
3376 public void sendPassword(
3377 long companyId, String emailAddress, String fromName,
3378 String fromAddress, String subject, String body,
3379 ServiceContext serviceContext)
3380 throws PortalException, SystemException {
3381
3382 Company company = companyPersistence.findByPrimaryKey(companyId);
3383
3384 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3385 return;
3386 }
3387
3388 emailAddress = emailAddress.trim().toLowerCase();
3389
3390 if (Validator.isNull(emailAddress)) {
3391 throw new UserEmailAddressException();
3392 }
3393
3394 User user = userPersistence.findByC_EA(companyId, emailAddress);
3395
3396 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3397
3398 String newPassword = StringPool.BLANK;
3399 String passwordResetURL = StringPool.BLANK;
3400
3401 if (company.isSendPasswordResetLink()) {
3402 Date expirationDate = null;
3403
3404 if ((passwordPolicy != null) &&
3405 (passwordPolicy.getResetTicketMaxAge() > 0)) {
3406 expirationDate = new Date(
3407 System.currentTimeMillis() +
3408 (passwordPolicy.getResetTicketMaxAge() * 1000));
3409 }
3410
3411 Ticket ticket = ticketLocalService.addTicket(
3412 companyId, User.class.getName(), user.getUserId(),
3413 TicketConstants.TYPE_PASSWORD, null, expirationDate,
3414 serviceContext);
3415
3416 passwordResetURL =
3417 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3418 "/portal/update_password?p_l_id="+
3419 serviceContext.getPlid() +
3420 "&ticketKey=" + ticket.getKey();
3421 }
3422 else {
3423 if (!PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
3424 PwdEncryptor.TYPE_NONE)) {
3425
3426 if (LDAPSettingsUtil.isPasswordPolicyEnabled(
3427 user.getCompanyId())) {
3428
3429 if (_log.isWarnEnabled()) {
3430 StringBundler sb = new StringBundler(5);
3431
3432 sb.append("When LDAP password policy is enabled, ");
3433 sb.append("it is possible that portal generated ");
3434 sb.append("passwords will not match the LDAP policy.");
3435 sb.append("Using RegExpToolkit to generate new ");
3436 sb.append("password.");
3437
3438 _log.warn(sb.toString());
3439 }
3440
3441 RegExpToolkit regExpToolkit = new RegExpToolkit();
3442
3443 newPassword = regExpToolkit.generate(null);
3444 }
3445 else {
3446 newPassword = PwdToolkitUtil.generate(passwordPolicy);
3447 }
3448
3449 boolean passwordReset = false;
3450
3451 if (passwordPolicy.getChangeable() &&
3452 passwordPolicy.getChangeRequired()) {
3453
3454 passwordReset = true;
3455 }
3456
3457 user.setPassword(PwdEncryptor.encrypt(newPassword));
3458 user.setPasswordUnencrypted(newPassword);
3459 user.setPasswordEncrypted(true);
3460 user.setPasswordReset(passwordReset);
3461 user.setPasswordModified(true);
3462 user.setPasswordModifiedDate(new Date());
3463
3464 userPersistence.update(user);
3465
3466 user.setPasswordModified(false);
3467 }
3468 else {
3469 newPassword = user.getPassword();
3470 }
3471 }
3472
3473 if (Validator.isNull(fromName)) {
3474 fromName = PrefsPropsUtil.getString(
3475 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3476 }
3477
3478 if (Validator.isNull(fromAddress)) {
3479 fromAddress = PrefsPropsUtil.getString(
3480 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3481 }
3482
3483 String toName = user.getFullName();
3484 String toAddress = user.getEmailAddress();
3485
3486 if (Validator.isNull(subject)) {
3487 if (company.isSendPasswordResetLink()) {
3488 subject = PrefsPropsUtil.getContent(
3489 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
3490 }
3491 else {
3492 subject = PrefsPropsUtil.getContent(
3493 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
3494 }
3495 }
3496
3497 if (Validator.isNull(body)) {
3498 if (company.isSendPasswordResetLink()) {
3499 body = PrefsPropsUtil.getContent(
3500 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
3501 }
3502 else {
3503 body = PrefsPropsUtil.getContent(
3504 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
3505 }
3506 }
3507
3508 SubscriptionSender subscriptionSender = new SubscriptionSender();
3509
3510 subscriptionSender.setBody(body);
3511 subscriptionSender.setCompanyId(companyId);
3512 subscriptionSender.setContextAttributes(
3513 "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
3514 serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
3515 serviceContext.getRemoteHost(), "[$USER_ID$]", user.getUserId(),
3516 "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
3517 user.getScreenName());
3518 subscriptionSender.setFrom(fromAddress, fromName);
3519 subscriptionSender.setHtmlFormat(true);
3520 subscriptionSender.setMailId("user", user.getUserId());
3521 subscriptionSender.setServiceContext(serviceContext);
3522 subscriptionSender.setSubject(subject);
3523 subscriptionSender.setUserId(user.getUserId());
3524
3525 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3526
3527 subscriptionSender.flushNotificationsAsync();
3528 }
3529
3530
3539 public void setRoleUsers(long roleId, long[] userIds)
3540 throws PortalException, SystemException {
3541
3542 rolePersistence.setUsers(roleId, userIds);
3543
3544 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3545
3546 indexer.reindex(userIds);
3547
3548 PermissionCacheUtil.clearCache();
3549 }
3550
3551
3560 @SuppressWarnings("deprecation")
3561 public void setUserGroupUsers(long userGroupId, long[] userIds)
3562 throws PortalException, SystemException {
3563
3564 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3565 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3566 }
3567
3568 userGroupPersistence.setUsers(userGroupId, userIds);
3569
3570 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3571
3572 indexer.reindex(userIds);
3573
3574 PermissionCacheUtil.clearCache();
3575 }
3576
3577
3585 public void unsetGroupTeamsUsers(long groupId, long[] userIds)
3586 throws PortalException, SystemException {
3587
3588 List<Team> teams = teamPersistence.findByGroupId(groupId);
3589
3590 for (Team team : teams) {
3591 unsetTeamUsers(team.getTeamId(), userIds);
3592 }
3593
3594 PermissionCacheUtil.clearCache();
3595 }
3596
3597
3606 public void unsetGroupUsers(
3607 long groupId, long[] userIds, ServiceContext serviceContext)
3608 throws PortalException, SystemException {
3609
3610 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
3611
3612 userLocalService.unsetGroupTeamsUsers(groupId, userIds);
3613
3614 groupPersistence.removeUsers(groupId, userIds);
3615
3616 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3617
3618 indexer.reindex(userIds);
3619
3620 PermissionCacheUtil.clearCache();
3621 }
3622
3623
3631 public void unsetOrganizationUsers(long organizationId, long[] userIds)
3632 throws PortalException, SystemException {
3633
3634 Organization organization = organizationPersistence.findByPrimaryKey(
3635 organizationId);
3636
3637 Group group = organization.getGroup();
3638
3639 long groupId = group.getGroupId();
3640
3641 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
3642
3643 organizationPersistence.removeUsers(organizationId, userIds);
3644
3645 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3646
3647 indexer.reindex(userIds);
3648
3649 PermissionCacheUtil.clearCache();
3650 }
3651
3652
3659 public void unsetPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
3660 throws SystemException {
3661
3662 passwordPolicyRelLocalService.deletePasswordPolicyRels(
3663 passwordPolicyId, User.class.getName(), userIds);
3664 }
3665
3666
3674 public void unsetRoleUsers(long roleId, List<User> users)
3675 throws PortalException, SystemException {
3676
3677 Role role = rolePersistence.findByPrimaryKey(roleId);
3678
3679 if (role.getName().equals(RoleConstants.USER)) {
3680 return;
3681 }
3682
3683 rolePersistence.removeUsers(roleId, users);
3684
3685 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3686
3687 indexer.reindex(users);
3688
3689 PermissionCacheUtil.clearCache();
3690 }
3691
3692
3700 public void unsetRoleUsers(long roleId, long[] userIds)
3701 throws PortalException, SystemException {
3702
3703 Role role = rolePersistence.findByPrimaryKey(roleId);
3704
3705 if (role.getName().equals(RoleConstants.USER)) {
3706 return;
3707 }
3708
3709 rolePersistence.removeUsers(roleId, userIds);
3710
3711 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3712
3713 indexer.reindex(userIds);
3714
3715 PermissionCacheUtil.clearCache();
3716 }
3717
3718
3726 public void unsetTeamUsers(long teamId, long[] userIds)
3727 throws PortalException, SystemException {
3728
3729 teamPersistence.removeUsers(teamId, userIds);
3730
3731 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3732
3733 indexer.reindex(userIds);
3734
3735 PermissionCacheUtil.clearCache();
3736 }
3737
3738
3746 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
3747 throws PortalException, SystemException {
3748
3749 userGroupPersistence.removeUsers(userGroupId, userIds);
3750
3751 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3752
3753 indexer.reindex(userIds);
3754
3755 PermissionCacheUtil.clearCache();
3756 }
3757
3758
3768 public User updateAgreedToTermsOfUse(
3769 long userId, boolean agreedToTermsOfUse)
3770 throws PortalException, SystemException {
3771
3772 User user = userPersistence.findByPrimaryKey(userId);
3773
3774 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
3775
3776 userPersistence.update(user);
3777
3778 return user;
3779 }
3780
3781
3792 public void updateAsset(
3793 long userId, User user, long[] assetCategoryIds,
3794 String[] assetTagNames)
3795 throws PortalException, SystemException {
3796
3797 User owner = userPersistence.findByPrimaryKey(userId);
3798
3799 Company company = companyPersistence.findByPrimaryKey(
3800 owner.getCompanyId());
3801
3802 Group companyGroup = company.getGroup();
3803
3804 assetEntryLocalService.updateEntry(
3805 userId, companyGroup.getGroupId(), user.getCreateDate(),
3806 user.getModifiedDate(), User.class.getName(), user.getUserId(),
3807 user.getUuid(), 0, assetCategoryIds, assetTagNames, false, null,
3808 null, null, null, user.getFullName(), null, null, null, null, 0, 0,
3809 null, false);
3810 }
3811
3812
3821 public User updateCreateDate(long userId, Date createDate)
3822 throws PortalException, SystemException {
3823
3824 User user = userPersistence.findByPrimaryKey(userId);
3825
3826 user.setCreateDate(createDate);
3827
3828 userPersistence.update(user);
3829
3830 return user;
3831 }
3832
3833
3844 public User updateEmailAddress(
3845 long userId, String password, String emailAddress1,
3846 String emailAddress2)
3847 throws PortalException, SystemException {
3848
3849 emailAddress1 = emailAddress1.trim().toLowerCase();
3850 emailAddress2 = emailAddress2.trim().toLowerCase();
3851
3852 User user = userPersistence.findByPrimaryKey(userId);
3853
3854 validateEmailAddress(user, emailAddress1, emailAddress2);
3855
3856 setEmailAddress(
3857 user, password, user.getFirstName(), user.getMiddleName(),
3858 user.getLastName(), emailAddress1);
3859
3860 userPersistence.update(user);
3861
3862 Contact contact = user.getContact();
3863
3864 contact.setEmailAddress(user.getEmailAddress());
3865
3866 contactPersistence.update(contact);
3867
3868 return user;
3869 }
3870
3871
3885 public User updateEmailAddress(
3886 long userId, String password, String emailAddress1,
3887 String emailAddress2, ServiceContext serviceContext)
3888 throws PortalException, SystemException {
3889
3890 emailAddress1 = emailAddress1.trim().toLowerCase();
3891 emailAddress2 = emailAddress2.trim().toLowerCase();
3892
3893 User user = userPersistence.findByPrimaryKey(userId);
3894
3895 validateEmailAddress(user, emailAddress1, emailAddress2);
3896
3897 Company company = companyPersistence.findByPrimaryKey(
3898 user.getCompanyId());
3899
3900 if (!company.isStrangersVerify()) {
3901 setEmailAddress(
3902 user, password, user.getFirstName(), user.getMiddleName(),
3903 user.getLastName(), emailAddress1);
3904
3905 userPersistence.update(user);
3906
3907 Contact contact = user.getContact();
3908
3909 contact.setEmailAddress(user.getEmailAddress());
3910
3911 contactPersistence.update(contact);
3912 }
3913 else {
3914 sendEmailAddressVerification(user, emailAddress1, serviceContext);
3915 }
3916
3917 return user;
3918 }
3919
3920
3929 public User updateEmailAddressVerified(
3930 long userId, boolean emailAddressVerified)
3931 throws PortalException, SystemException {
3932
3933 User user = userPersistence.findByPrimaryKey(userId);
3934
3935 user.setEmailAddressVerified(emailAddressVerified);
3936
3937 userPersistence.update(user);
3938
3939 return user;
3940 }
3941
3942
3951 public User updateFacebookId(long userId, long facebookId)
3952 throws PortalException, SystemException {
3953
3954 User user = userPersistence.findByPrimaryKey(userId);
3955
3956 user.setFacebookId(facebookId);
3957
3958 userPersistence.update(user);
3959
3960 return user;
3961 }
3962
3963
3972 public void updateGroups(
3973 long userId, long[] newGroupIds, ServiceContext serviceContext)
3974 throws PortalException, SystemException {
3975
3976 updateGroups(
3977 userId, newGroupIds, serviceContext,
3978 serviceContext.isIndexingEnabled());
3979 }
3980
3981
4020 public User updateIncompleteUser(
4021 long creatorUserId, long companyId, boolean autoPassword,
4022 String password1, String password2, boolean autoScreenName,
4023 String screenName, String emailAddress, long facebookId,
4024 String openId, Locale locale, String firstName, String middleName,
4025 String lastName, int prefixId, int suffixId, boolean male,
4026 int birthdayMonth, int birthdayDay, int birthdayYear,
4027 String jobTitle, boolean updateUserInformation, boolean sendEmail,
4028 ServiceContext serviceContext)
4029 throws PortalException, SystemException {
4030
4031 User user = getUserByEmailAddress(companyId, emailAddress);
4032
4033 if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
4034 throw new PortalException("Invalid user status");
4035 }
4036
4037 User defaultUser = getDefaultUser(companyId);
4038
4039 if (updateUserInformation) {
4040 autoScreenName = false;
4041
4042 if (PrefsPropsUtil.getBoolean(
4043 companyId,
4044 PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
4045
4046 autoScreenName = true;
4047 }
4048
4049 validate(
4050 companyId, user.getUserId(), autoPassword, password1, password2,
4051 autoScreenName, screenName, emailAddress, firstName, middleName,
4052 lastName, null);
4053
4054 if (!autoPassword) {
4055 if (Validator.isNull(password1) ||
4056 Validator.isNull(password2)) {
4057 throw new UserPasswordException(
4058 UserPasswordException.PASSWORD_INVALID);
4059 }
4060 }
4061
4062 if (autoScreenName) {
4063 ScreenNameGenerator screenNameGenerator =
4064 ScreenNameGeneratorFactory.getInstance();
4065
4066 try {
4067 screenName = screenNameGenerator.generate(
4068 companyId, user.getUserId(), emailAddress);
4069 }
4070 catch (Exception e) {
4071 throw new SystemException(e);
4072 }
4073 }
4074
4075 FullNameGenerator fullNameGenerator =
4076 FullNameGeneratorFactory.getInstance();
4077
4078 String fullName = fullNameGenerator.getFullName(
4079 firstName, middleName, lastName);
4080
4081 String greeting = LanguageUtil.format(
4082 locale, "welcome-x", " " + fullName, false);
4083
4084 if (Validator.isNotNull(password1)) {
4085 user.setPassword(PwdEncryptor.encrypt(password1));
4086 user.setPasswordUnencrypted(password1);
4087 }
4088
4089 user.setPasswordEncrypted(true);
4090
4091 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
4092
4093 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
4094 passwordPolicy.isChangeRequired()) {
4095
4096 user.setPasswordReset(true);
4097 }
4098 else {
4099 user.setPasswordReset(false);
4100 }
4101
4102 user.setScreenName(screenName);
4103 user.setFacebookId(facebookId);
4104 user.setOpenId(openId);
4105 user.setLanguageId(locale.toString());
4106 user.setTimeZoneId(defaultUser.getTimeZoneId());
4107 user.setGreeting(greeting);
4108 user.setFirstName(firstName);
4109 user.setMiddleName(middleName);
4110 user.setLastName(lastName);
4111 user.setJobTitle(jobTitle);
4112 user.setExpandoBridgeAttributes(serviceContext);
4113
4114 Date birthday = getBirthday(
4115 birthdayMonth, birthdayDay, birthdayYear);
4116
4117 Contact contact = user.getContact();
4118
4119 contact.setFirstName(firstName);
4120 contact.setMiddleName(middleName);
4121 contact.setLastName(lastName);
4122 contact.setPrefixId(prefixId);
4123 contact.setSuffixId(suffixId);
4124 contact.setMale(male);
4125 contact.setBirthday(birthday);
4126 contact.setJobTitle(jobTitle);
4127
4128 contactPersistence.update(contact, serviceContext);
4129
4130
4131
4132 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4133 User.class);
4134
4135 indexer.reindex(user);
4136 }
4137
4138 user.setStatus(WorkflowConstants.STATUS_DRAFT);
4139
4140 userPersistence.update(user, serviceContext);
4141
4142
4143
4144 long workflowUserId = creatorUserId;
4145
4146 if (workflowUserId == user.getUserId()) {
4147 workflowUserId = defaultUser.getUserId();
4148 }
4149
4150 ServiceContext workflowServiceContext = serviceContext;
4151
4152 if (workflowServiceContext == null) {
4153 workflowServiceContext = new ServiceContext();
4154 }
4155
4156 workflowServiceContext.setAttribute("autoPassword", autoPassword);
4157 workflowServiceContext.setAttribute("sendEmail", sendEmail);
4158
4159 WorkflowHandlerRegistryUtil.startWorkflowInstance(
4160 companyId, workflowUserId, User.class.getName(), user.getUserId(),
4161 user, workflowServiceContext);
4162
4163 return getUserByEmailAddress(companyId, emailAddress);
4164 }
4165
4166
4176 public User updateJobTitle(long userId, String jobTitle)
4177 throws PortalException, SystemException {
4178
4179 User user = userPersistence.findByPrimaryKey(userId);
4180
4181 user.setJobTitle(jobTitle);
4182
4183 userPersistence.update(user);
4184
4185 Contact contact = contactPersistence.findByPrimaryKey(
4186 user.getContactId());
4187
4188 contact.setJobTitle(jobTitle);
4189
4190 contactPersistence.update(contact);
4191
4192 return user;
4193 }
4194
4195
4204 public User updateLastLogin(long userId, String loginIP)
4205 throws PortalException, SystemException {
4206
4207 User user = userPersistence.findByPrimaryKey(userId);
4208
4209 Date lastLoginDate = user.getLoginDate();
4210
4211 if (lastLoginDate == null) {
4212 lastLoginDate = new Date();
4213 }
4214
4215 user.setLoginDate(new Date());
4216 user.setLoginIP(loginIP);
4217 user.setLastLoginDate(lastLoginDate);
4218 user.setLastLoginIP(user.getLoginIP());
4219 user.setLastFailedLoginDate(null);
4220 user.setFailedLoginAttempts(0);
4221
4222 userPersistence.update(user);
4223
4224 return user;
4225 }
4226
4227
4236 public User updateLockout(User user, boolean lockout)
4237 throws PortalException, SystemException {
4238
4239 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
4240
4241 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
4242 return user;
4243 }
4244
4245 Date lockoutDate = null;
4246
4247 if (lockout) {
4248 lockoutDate = new Date();
4249 }
4250
4251 user.setLockout(lockout);
4252 user.setLockoutDate(lockoutDate);
4253
4254 if (!lockout) {
4255 user.setLastFailedLoginDate(lockoutDate);
4256 user.setFailedLoginAttempts(0);
4257 }
4258
4259 userPersistence.update(user);
4260
4261 return user;
4262 }
4263
4264
4275 public User updateLockoutByEmailAddress(
4276 long companyId, String emailAddress, boolean lockout)
4277 throws PortalException, SystemException {
4278
4279 User user = getUserByEmailAddress(companyId, emailAddress);
4280
4281 return updateLockout(user, lockout);
4282 }
4283
4284
4293 public User updateLockoutById(long userId, boolean lockout)
4294 throws PortalException, SystemException {
4295
4296 User user = userPersistence.findByPrimaryKey(userId);
4297
4298 return updateLockout(user, lockout);
4299 }
4300
4301
4311 public User updateLockoutByScreenName(
4312 long companyId, String screenName, boolean lockout)
4313 throws PortalException, SystemException {
4314
4315 User user = getUserByScreenName(companyId, screenName);
4316
4317 return updateLockout(user, lockout);
4318 }
4319
4320
4329 public User updateModifiedDate(long userId, Date modifiedDate)
4330 throws PortalException, SystemException {
4331
4332 User user = userPersistence.findByPrimaryKey(userId);
4333
4334 user.setModifiedDate(modifiedDate);
4335
4336 userPersistence.update(user);
4337
4338 return user;
4339 }
4340
4341
4350 public User updateOpenId(long userId, String openId)
4351 throws PortalException, SystemException {
4352
4353 openId = openId.trim();
4354
4355 User user = userPersistence.findByPrimaryKey(userId);
4356
4357 user.setOpenId(openId);
4358
4359 userPersistence.update(user);
4360
4361 return user;
4362 }
4363
4364
4375 public void updateOrganizations(
4376 long userId, long[] newOrganizationIds,
4377 ServiceContext serviceContext)
4378 throws PortalException, SystemException {
4379
4380 updateOrganizations(
4381 userId, newOrganizationIds, serviceContext.isIndexingEnabled());
4382 }
4383
4384
4396 public User updatePassword(
4397 long userId, String password1, String password2,
4398 boolean passwordReset)
4399 throws PortalException, SystemException {
4400
4401 return updatePassword(
4402 userId, password1, password2, passwordReset, false);
4403 }
4404
4405
4420 public User updatePassword(
4421 long userId, String password1, String password2,
4422 boolean passwordReset, boolean silentUpdate)
4423 throws PortalException, SystemException {
4424
4425 User user = userPersistence.findByPrimaryKey(userId);
4426
4427 if (!silentUpdate) {
4428 validatePassword(user.getCompanyId(), userId, password1, password2);
4429 }
4430
4431 String oldEncPwd = user.getPassword();
4432
4433 if (!user.isPasswordEncrypted()) {
4434 oldEncPwd = PwdEncryptor.encrypt(user.getPassword());
4435 }
4436
4437 String newEncPwd = PwdEncryptor.encrypt(password1);
4438
4439 if (user.hasCompanyMx()) {
4440 mailService.updatePassword(user.getCompanyId(), userId, password1);
4441 }
4442
4443 user.setPassword(newEncPwd);
4444 user.setPasswordUnencrypted(password1);
4445 user.setPasswordEncrypted(true);
4446 user.setPasswordReset(passwordReset);
4447 user.setPasswordModifiedDate(new Date());
4448 user.setDigest(StringPool.BLANK);
4449 user.setGraceLoginCount(0);
4450
4451 if (!silentUpdate) {
4452 user.setPasswordModified(true);
4453 }
4454
4455 try {
4456 userPersistence.update(user);
4457 }
4458 catch (ModelListenerException mle) {
4459 String msg = GetterUtil.getString(mle.getCause().getMessage());
4460
4461 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
4462 String passwordHistory = PrefsPropsUtil.getString(
4463 user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
4464
4465 if (msg.contains(passwordHistory)) {
4466 throw new UserPasswordException(
4467 UserPasswordException.PASSWORD_ALREADY_USED);
4468 }
4469 }
4470
4471 throw new UserPasswordException(
4472 UserPasswordException.PASSWORD_INVALID);
4473 }
4474
4475 if (!silentUpdate) {
4476 user.setPasswordModified(false);
4477
4478 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
4479 }
4480
4481 return user;
4482 }
4483
4484
4498 public User updatePasswordManually(
4499 long userId, String password, boolean passwordEncrypted,
4500 boolean passwordReset, Date passwordModifiedDate)
4501 throws PortalException, SystemException {
4502
4503
4504
4505 User user = userPersistence.findByPrimaryKey(userId);
4506
4507 user.setPassword(password);
4508 user.setPasswordEncrypted(passwordEncrypted);
4509 user.setPasswordReset(passwordReset);
4510 user.setPasswordModifiedDate(passwordModifiedDate);
4511 user.setDigest(StringPool.BLANK);
4512
4513 userPersistence.update(user);
4514
4515 return user;
4516 }
4517
4518
4529 public User updatePasswordReset(long userId, boolean passwordReset)
4530 throws PortalException, SystemException {
4531
4532 User user = userPersistence.findByPrimaryKey(userId);
4533
4534 user.setPasswordReset(passwordReset);
4535
4536 userPersistence.update(user);
4537
4538 return user;
4539 }
4540
4541
4551 public User updatePortrait(long userId, byte[] bytes)
4552 throws PortalException, SystemException {
4553
4554 User user = userPersistence.findByPrimaryKey(userId);
4555
4556 long imageMaxSize = PrefsPropsUtil.getLong(
4557 PropsKeys.USERS_IMAGE_MAX_SIZE);
4558
4559 if ((imageMaxSize > 0) &&
4560 ((bytes == null) || (bytes.length > imageMaxSize))) {
4561
4562 throw new UserPortraitSizeException();
4563 }
4564
4565 long portraitId = user.getPortraitId();
4566
4567 if (portraitId <= 0) {
4568 portraitId = counterLocalService.increment();
4569
4570 user.setPortraitId(portraitId);
4571 }
4572
4573 try {
4574 ImageBag imageBag = ImageToolUtil.read(bytes);
4575
4576 RenderedImage renderedImage = imageBag.getRenderedImage();
4577
4578 if (renderedImage == null) {
4579 throw new UserPortraitTypeException();
4580 }
4581
4582 renderedImage = ImageToolUtil.scale(
4583 renderedImage, PropsValues.USERS_IMAGE_MAX_HEIGHT,
4584 PropsValues.USERS_IMAGE_MAX_WIDTH);
4585
4586 String contentType = imageBag.getType();
4587
4588 imageLocalService.updateImage(
4589 portraitId,
4590 ImageToolUtil.getBytes(renderedImage, contentType));
4591 }
4592 catch (IOException ioe) {
4593 throw new ImageSizeException(ioe);
4594 }
4595
4596 userPersistence.update(user);
4597
4598 return user;
4599 }
4600
4601
4612 public User updateReminderQuery(long userId, String question, String answer)
4613 throws PortalException, SystemException {
4614
4615 validateReminderQuery(question, answer);
4616
4617 User user = userPersistence.findByPrimaryKey(userId);
4618
4619 user.setReminderQueryQuestion(question);
4620 user.setReminderQueryAnswer(answer);
4621
4622 userPersistence.update(user);
4623
4624 return user;
4625 }
4626
4627
4637 public User updateScreenName(long userId, String screenName)
4638 throws PortalException, SystemException {
4639
4640
4641
4642 User user = userPersistence.findByPrimaryKey(userId);
4643
4644 screenName = getScreenName(screenName);
4645
4646 validateScreenName(user.getCompanyId(), userId, screenName);
4647
4648 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
4649 user.setDigest(StringPool.BLANK);
4650 }
4651
4652 user.setScreenName(screenName);
4653
4654 userPersistence.update(user);
4655
4656
4657
4658 Group group = groupLocalService.getUserGroup(
4659 user.getCompanyId(), userId);
4660
4661 group.setFriendlyURL(StringPool.SLASH + screenName);
4662
4663 groupPersistence.update(group);
4664
4665 return user;
4666 }
4667
4668
4677 public User updateStatus(long userId, int status)
4678 throws PortalException, SystemException {
4679
4680 User user = userPersistence.findByPrimaryKey(userId);
4681
4682 user.setStatus(status);
4683
4684 userPersistence.update(user);
4685
4686 reindex(user);
4687
4688 return user;
4689 }
4690
4691
4747 @SuppressWarnings("deprecation")
4748 public User updateUser(
4749 long userId, String oldPassword, String newPassword1,
4750 String newPassword2, boolean passwordReset,
4751 String reminderQueryQuestion, String reminderQueryAnswer,
4752 String screenName, String emailAddress, long facebookId,
4753 String openId, String languageId, String timeZoneId,
4754 String greeting, String comments, String firstName,
4755 String middleName, String lastName, int prefixId, int suffixId,
4756 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
4757 String smsSn, String aimSn, String facebookSn, String icqSn,
4758 String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
4759 String twitterSn, String ymSn, String jobTitle, long[] groupIds,
4760 long[] organizationIds, long[] roleIds,
4761 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
4762 ServiceContext serviceContext)
4763 throws PortalException, SystemException {
4764
4765
4766
4767 User user = userPersistence.findByPrimaryKey(userId);
4768 Company company = companyPersistence.findByPrimaryKey(
4769 user.getCompanyId());
4770 String password = oldPassword;
4771 screenName = getScreenName(screenName);
4772 emailAddress = emailAddress.trim().toLowerCase();
4773 openId = openId.trim();
4774 String oldFullName = user.getFullName();
4775 aimSn = aimSn.trim().toLowerCase();
4776 facebookSn = facebookSn.trim().toLowerCase();
4777 icqSn = icqSn.trim().toLowerCase();
4778 jabberSn = jabberSn.trim().toLowerCase();
4779 msnSn = msnSn.trim().toLowerCase();
4780 mySpaceSn = mySpaceSn.trim().toLowerCase();
4781 skypeSn = skypeSn.trim().toLowerCase();
4782 twitterSn = twitterSn.trim().toLowerCase();
4783 ymSn = ymSn.trim().toLowerCase();
4784 Date now = new Date();
4785
4786 EmailAddressGenerator emailAddressGenerator =
4787 EmailAddressGeneratorFactory.getInstance();
4788
4789 if (emailAddressGenerator.isGenerated(emailAddress)) {
4790 emailAddress = StringPool.BLANK;
4791 }
4792
4793 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
4794 Validator.isNull(emailAddress)) {
4795
4796 emailAddress = emailAddressGenerator.generate(
4797 user.getCompanyId(), userId);
4798 }
4799
4800 validate(
4801 userId, screenName, emailAddress, firstName, middleName, lastName,
4802 smsSn);
4803
4804 if (Validator.isNotNull(newPassword1) ||
4805 Validator.isNotNull(newPassword2)) {
4806
4807 user = updatePassword(
4808 userId, newPassword1, newPassword2, passwordReset);
4809
4810 password = newPassword1;
4811
4812 user.setDigest(StringPool.BLANK);
4813 }
4814
4815 user.setModifiedDate(now);
4816
4817 if (user.getContactId() <= 0) {
4818 user.setContactId(counterLocalService.increment());
4819 }
4820
4821 user.setPasswordReset(passwordReset);
4822
4823 if (Validator.isNotNull(reminderQueryQuestion) &&
4824 Validator.isNotNull(reminderQueryAnswer)) {
4825
4826 user.setReminderQueryQuestion(reminderQueryQuestion);
4827 user.setReminderQueryAnswer(reminderQueryAnswer);
4828 }
4829
4830 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
4831 user.setScreenName(screenName);
4832
4833 user.setDigest(StringPool.BLANK);
4834 }
4835
4836 boolean sendEmailAddressVerification = false;
4837
4838 if (!company.isStrangersVerify()) {
4839 setEmailAddress(
4840 user, password, firstName, middleName, lastName, emailAddress);
4841 }
4842 else {
4843 sendEmailAddressVerification = true;
4844 }
4845
4846 if (serviceContext != null) {
4847 String uuid = serviceContext.getUuid();
4848
4849 if (Validator.isNotNull(uuid)) {
4850 user.setUuid(uuid);
4851 }
4852 }
4853
4854 user.setFacebookId(facebookId);
4855 user.setOpenId(openId);
4856 user.setLanguageId(languageId);
4857 user.setTimeZoneId(timeZoneId);
4858 user.setGreeting(greeting);
4859 user.setComments(comments);
4860 user.setFirstName(firstName);
4861 user.setMiddleName(middleName);
4862 user.setLastName(lastName);
4863 user.setJobTitle(jobTitle);
4864 user.setExpandoBridgeAttributes(serviceContext);
4865
4866 userPersistence.update(user, serviceContext);
4867
4868
4869
4870 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
4871
4872 long contactId = user.getContactId();
4873
4874 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
4875
4876 if (contact == null) {
4877 contact = contactPersistence.create(contactId);
4878
4879 contact.setCompanyId(user.getCompanyId());
4880 contact.setUserName(StringPool.BLANK);
4881 contact.setCreateDate(now);
4882 contact.setClassName(User.class.getName());
4883 contact.setClassPK(user.getUserId());
4884 contact.setAccountId(company.getAccountId());
4885 contact.setParentContactId(
4886 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
4887 }
4888
4889 contact.setModifiedDate(now);
4890 contact.setEmailAddress(user.getEmailAddress());
4891 contact.setFirstName(firstName);
4892 contact.setMiddleName(middleName);
4893 contact.setLastName(lastName);
4894 contact.setPrefixId(prefixId);
4895 contact.setSuffixId(suffixId);
4896 contact.setMale(male);
4897 contact.setBirthday(birthday);
4898 contact.setSmsSn(smsSn);
4899 contact.setAimSn(aimSn);
4900 contact.setFacebookSn(facebookSn);
4901 contact.setIcqSn(icqSn);
4902 contact.setJabberSn(jabberSn);
4903 contact.setMsnSn(msnSn);
4904 contact.setMySpaceSn(mySpaceSn);
4905 contact.setSkypeSn(skypeSn);
4906 contact.setTwitterSn(twitterSn);
4907 contact.setYmSn(ymSn);
4908 contact.setJobTitle(jobTitle);
4909
4910 contactPersistence.update(contact, serviceContext);
4911
4912
4913
4914 Group group = groupLocalService.getUserGroup(
4915 user.getCompanyId(), userId);
4916
4917 group.setFriendlyURL(StringPool.SLASH + screenName);
4918
4919 groupPersistence.update(group);
4920
4921
4922
4923 updateGroups(userId, groupIds, serviceContext, false);
4924 updateOrganizations(userId, organizationIds, false);
4925
4926
4927
4928 if (roleIds != null) {
4929 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
4930
4931 userPersistence.setRoles(userId, roleIds);
4932 }
4933
4934
4935
4936 updateUserGroupRoles(user, groupIds, organizationIds, userGroupRoles);
4937
4938
4939
4940 if (userGroupIds != null) {
4941 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
4942 userGroupLocalService.copyUserGroupLayouts(
4943 userGroupIds, userId);
4944 }
4945
4946 userPersistence.setUserGroups(userId, userGroupIds);
4947 }
4948
4949
4950
4951 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
4952
4953
4954
4955 if (serviceContext != null) {
4956 updateAsset(
4957 userId, user, serviceContext.getAssetCategoryIds(),
4958 serviceContext.getAssetTagNames());
4959 }
4960
4961
4962
4963 if (GetterUtil.getBoolean(
4964 PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
4965 !oldFullName.equals(user.getFullName())) {
4966
4967 mbMessageLocalService.updateUserName(userId, user.getFullName());
4968 }
4969
4970
4971
4972 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
4973 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4974 User.class);
4975
4976 indexer.reindex(user);
4977 }
4978
4979
4980
4981 if ((serviceContext != null) && sendEmailAddressVerification) {
4982 sendEmailAddressVerification(user, emailAddress, serviceContext);
4983 }
4984
4985
4986
4987 PermissionCacheUtil.clearCache();
4988
4989 return user;
4990 }
4991
4992
5001 public void verifyEmailAddress(String ticketKey)
5002 throws PortalException, SystemException {
5003
5004 Ticket ticket = ticketLocalService.getTicket(ticketKey);
5005
5006 if (ticket.isExpired() ||
5007 (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
5008
5009 throw new NoSuchTicketException();
5010 }
5011
5012 User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
5013
5014 String emailAddress = ticket.getExtraInfo();
5015
5016 emailAddress = emailAddress.toLowerCase().trim();
5017
5018 if (!emailAddress.equals(user.getEmailAddress())) {
5019 if (userPersistence.fetchByC_EA(
5020 user.getCompanyId(), emailAddress) != null) {
5021
5022 throw new DuplicateUserEmailAddressException();
5023 }
5024
5025 setEmailAddress(
5026 user, StringPool.BLANK, user.getFirstName(),
5027 user.getMiddleName(), user.getLastName(), emailAddress);
5028
5029 Contact contact = user.getContact();
5030
5031 contact.setEmailAddress(user.getEmailAddress());
5032
5033 contactPersistence.update(contact);
5034 }
5035
5036 user.setEmailAddressVerified(true);
5037
5038 userPersistence.update(user);
5039
5040 ticketLocalService.deleteTicket(ticket);
5041 }
5042
5043 protected void addDefaultRolesAndTeams(long groupId, long[] userIds)
5044 throws PortalException, SystemException {
5045
5046 List<Role> defaultSiteRoles = new ArrayList<Role>();
5047
5048 Group group = groupLocalService.getGroup(groupId);
5049
5050 UnicodeProperties typeSettingsProperties =
5051 group.getTypeSettingsProperties();
5052
5053 long[] defaultSiteRoleIds = StringUtil.split(
5054 typeSettingsProperties.getProperty("defaultSiteRoleIds"), 0L);
5055
5056 for (long defaultSiteRoleId : defaultSiteRoleIds) {
5057 Role defaultSiteRole = rolePersistence.fetchByPrimaryKey(
5058 defaultSiteRoleId);
5059
5060 if (defaultSiteRole == null) {
5061 if (_log.isWarnEnabled()) {
5062 _log.warn("Unable to find role " + defaultSiteRoleId);
5063 }
5064
5065 continue;
5066 }
5067
5068 defaultSiteRoles.add(defaultSiteRole);
5069 }
5070
5071 List<Team> defaultTeams = new ArrayList<Team>();
5072
5073 long[] defaultTeamIds = StringUtil.split(
5074 typeSettingsProperties.getProperty("defaultTeamIds"), 0L);
5075
5076 for (long defaultTeamId : defaultTeamIds) {
5077 Team defaultTeam = teamPersistence.findByPrimaryKey(defaultTeamId);
5078
5079 if (defaultTeam == null) {
5080 if (_log.isWarnEnabled()) {
5081 _log.warn("Unable to find team " + defaultTeamId);
5082 }
5083
5084 continue;
5085 }
5086
5087 defaultTeams.add(defaultTeam);
5088 }
5089
5090 for (long userId : userIds) {
5091 Set<Long> userRoleIdsSet = new HashSet<Long>();
5092
5093 for (Role role : defaultSiteRoles) {
5094 if (!userPersistence.containsRole(userId, role.getRoleId())) {
5095 userRoleIdsSet.add(role.getRoleId());
5096 }
5097 }
5098
5099 long[] userRoleIds = ArrayUtil.toArray(
5100 userRoleIdsSet.toArray(new Long[userRoleIdsSet.size()]));
5101
5102 userGroupRoleLocalService.addUserGroupRoles(
5103 userId, groupId, userRoleIds);
5104
5105 Set<Long> userTeamIdsSet = new HashSet<Long>();
5106
5107 for (Team team : defaultTeams) {
5108 if (!userPersistence.containsTeam(userId, team.getTeamId())) {
5109 userTeamIdsSet.add(team.getTeamId());
5110 }
5111 }
5112
5113 long[] userTeamIds = ArrayUtil.toArray(
5114 userTeamIdsSet.toArray(new Long[userTeamIdsSet.size()]));
5115
5116 userPersistence.addTeams(userId, userTeamIds);
5117 }
5118 }
5119
5120
5166 protected int authenticate(
5167 long companyId, String login, String password, String authType,
5168 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
5169 Map<String, Object> resultsMap)
5170 throws PortalException, SystemException {
5171
5172 if (PropsValues.AUTH_LOGIN_DISABLED) {
5173 return Authenticator.FAILURE;
5174 }
5175
5176 login = login.trim().toLowerCase();
5177
5178 long userId = GetterUtil.getLong(login);
5179
5180
5181
5182 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5183 if (Validator.isNull(login)) {
5184 throw new UserEmailAddressException();
5185 }
5186 }
5187 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5188 if (Validator.isNull(login)) {
5189 throw new UserScreenNameException();
5190 }
5191 }
5192 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5193 if (Validator.isNull(login)) {
5194 throw new UserIdException();
5195 }
5196 }
5197
5198 if (Validator.isNull(password)) {
5199 throw new UserPasswordException(
5200 UserPasswordException.PASSWORD_INVALID);
5201 }
5202
5203 int authResult = Authenticator.FAILURE;
5204
5205
5206
5207 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5208 authResult = AuthPipeline.authenticateByEmailAddress(
5209 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5210 headerMap, parameterMap);
5211 }
5212 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5213 authResult = AuthPipeline.authenticateByScreenName(
5214 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5215 headerMap, parameterMap);
5216 }
5217 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5218 authResult = AuthPipeline.authenticateByUserId(
5219 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
5220 headerMap, parameterMap);
5221 }
5222
5223
5224
5225 User user = null;
5226
5227 try {
5228 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5229 user = userPersistence.findByC_EA(companyId, login);
5230 }
5231 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5232 user = userPersistence.findByC_SN(companyId, login);
5233 }
5234 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5235 user = userPersistence.findByC_U(
5236 companyId, GetterUtil.getLong(login));
5237 }
5238 }
5239 catch (NoSuchUserException nsue) {
5240 return Authenticator.DNE;
5241 }
5242
5243 if (user.isDefaultUser()) {
5244 if (_log.isInfoEnabled()) {
5245 _log.info("Authentication is disabled for the default user");
5246 }
5247
5248 return Authenticator.DNE;
5249 }
5250 else if (!user.isActive()) {
5251 if (_log.isInfoEnabled()) {
5252 _log.info(
5253 "Authentication is disabled for inactive user " +
5254 user.getUserId());
5255 }
5256
5257 return Authenticator.FAILURE;
5258 }
5259
5260 if (!user.isPasswordEncrypted()) {
5261 user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
5262 user.setPasswordEncrypted(true);
5263
5264 userPersistence.update(user);
5265 }
5266
5267
5268
5269
5270 checkLockout(user);
5271
5272 checkPasswordExpired(user);
5273
5274
5275
5276 if ((authResult == Authenticator.SUCCESS) &&
5277 PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5278
5279 boolean authenticated = PwdAuthenticator.authenticate(
5280 login, password, user.getPassword());
5281
5282 if (authenticated) {
5283 authResult = Authenticator.SUCCESS;
5284 }
5285 else {
5286 authResult = Authenticator.FAILURE;
5287 }
5288 }
5289
5290
5291
5292 if (authResult == Authenticator.SUCCESS) {
5293 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5294 authResult = AuthPipeline.authenticateByEmailAddress(
5295 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5296 headerMap, parameterMap);
5297 }
5298 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5299 authResult = AuthPipeline.authenticateByScreenName(
5300 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5301 headerMap, parameterMap);
5302 }
5303 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5304 authResult = AuthPipeline.authenticateByUserId(
5305 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5306 headerMap, parameterMap);
5307 }
5308 }
5309
5310 if (authResult == Authenticator.SUCCESS) {
5311 if (resultsMap != null) {
5312 resultsMap.put("userId", user.getUserId());
5313 }
5314
5315
5316
5317 boolean updateDigest = true;
5318
5319 if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5320 if (Validator.isNotNull(user.getDigest())) {
5321 updateDigest = false;
5322 }
5323 }
5324
5325 if (updateDigest) {
5326 String digest = user.getDigest(password);
5327
5328 user.setDigest(digest);
5329
5330 userPersistence.update(user);
5331 }
5332 }
5333
5334
5335
5336 if (authResult == Authenticator.FAILURE) {
5337 try {
5338 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5339 AuthPipeline.onFailureByEmailAddress(
5340 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5341 parameterMap);
5342 }
5343 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5344 AuthPipeline.onFailureByScreenName(
5345 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5346 parameterMap);
5347 }
5348 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5349 AuthPipeline.onFailureByUserId(
5350 PropsKeys.AUTH_FAILURE, companyId, userId, headerMap,
5351 parameterMap);
5352 }
5353
5354 try {
5355 user = userPersistence.findByPrimaryKey(user.getUserId());
5356 }
5357 catch (NoSuchUserException nsue) {
5358 return Authenticator.DNE;
5359 }
5360
5361
5362
5363 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5364 user.getCompanyId())) {
5365
5366 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5367
5368 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5369
5370 int failedLoginAttempts = user.getFailedLoginAttempts();
5371 int maxFailures = passwordPolicy.getMaxFailure();
5372
5373 if ((failedLoginAttempts >= maxFailures) &&
5374 (maxFailures != 0)) {
5375
5376 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5377 AuthPipeline.onMaxFailuresByEmailAddress(
5378 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5379 headerMap, parameterMap);
5380 }
5381 else if (authType.equals(
5382 CompanyConstants.AUTH_TYPE_SN)) {
5383
5384 AuthPipeline.onMaxFailuresByScreenName(
5385 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5386 headerMap, parameterMap);
5387 }
5388 else if (authType.equals(
5389 CompanyConstants.AUTH_TYPE_ID)) {
5390
5391 AuthPipeline.onMaxFailuresByUserId(
5392 PropsKeys.AUTH_MAX_FAILURES, companyId, userId,
5393 headerMap, parameterMap);
5394 }
5395 }
5396 }
5397 }
5398 catch (Exception e) {
5399 _log.error(e, e);
5400 }
5401 }
5402
5403
5404
5405 return authResult;
5406 }
5407
5408 protected Date getBirthday(
5409 int birthdayMonth, int birthdayDay, int birthdayYear)
5410 throws PortalException {
5411
5412 Date birthday = PortalUtil.getDate(
5413 birthdayMonth, birthdayDay, birthdayYear,
5414 ContactBirthdayException.class);
5415
5416 Date now = new Date();
5417
5418 if (birthday.after(now)) {
5419 throw new ContactBirthdayException();
5420 }
5421
5422 return birthday;
5423 }
5424
5425 protected String getScreenName(String screenName) {
5426 return StringUtil.lowerCase(StringUtil.trim(screenName));
5427 }
5428
5429 protected long[] getUserIds(List<User> users) {
5430 long[] userIds = new long[users.size()];
5431
5432 for (int i = 0; i < users.size(); i++) {
5433 User user = users.get(i);
5434
5435 userIds[i] = user.getUserId();
5436 }
5437
5438 return userIds;
5439 }
5440
5441 protected void reindex(final User user) {
5442 final Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5443 User.class);
5444
5445 Callable<Void> callable = new Callable<Void>() {
5446
5447 public Void call() throws Exception {
5448 indexer.reindex(user);
5449
5450 return null;
5451 }
5452
5453 };
5454
5455 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
5456 }
5457
5458 protected Hits search(
5459 long companyId, String firstName, String middleName,
5460 String lastName, String fullName, String screenName,
5461 String emailAddress, String street, String city, String zip,
5462 String region, String country, int status,
5463 LinkedHashMap<String, Object> params, boolean andSearch, int start,
5464 int end, Sort sort)
5465 throws SystemException {
5466
5467 try {
5468 SearchContext searchContext = new SearchContext();
5469
5470 searchContext.setAndSearch(andSearch);
5471
5472 Map<String, Serializable> attributes =
5473 new HashMap<String, Serializable>();
5474
5475 attributes.put("city", city);
5476 attributes.put("country", country);
5477 attributes.put("emailAddress", emailAddress);
5478 attributes.put("firstName", firstName);
5479 attributes.put("fullName", fullName);
5480 attributes.put("lastName", lastName);
5481 attributes.put("middleName", middleName);
5482 attributes.put("params", params);
5483 attributes.put("region", region);
5484 attributes.put("screenName", screenName);
5485 attributes.put("street", street);
5486 attributes.put("status", status);
5487 attributes.put("zip", zip);
5488
5489 searchContext.setAttributes(attributes);
5490
5491 searchContext.setCompanyId(companyId);
5492 searchContext.setEnd(end);
5493
5494 if (params != null) {
5495 String keywords = (String)params.remove("keywords");
5496
5497 if (Validator.isNotNull(keywords)) {
5498 searchContext.setKeywords(keywords);
5499 }
5500 }
5501
5502 QueryConfig queryConfig = new QueryConfig();
5503
5504 queryConfig.setHighlightEnabled(false);
5505 queryConfig.setScoreEnabled(false);
5506
5507 searchContext.setQueryConfig(queryConfig);
5508
5509 if (sort != null) {
5510 searchContext.setSorts(new Sort[] {sort});
5511 }
5512
5513 searchContext.setStart(start);
5514
5515 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5516 User.class);
5517
5518 return indexer.search(searchContext);
5519 }
5520 catch (Exception e) {
5521 throw new SystemException(e);
5522 }
5523 }
5524
5525 protected void sendEmail(
5526 User user, String password, ServiceContext serviceContext)
5527 throws SystemException {
5528
5529 if (!PrefsPropsUtil.getBoolean(
5530 user.getCompanyId(),
5531 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
5532
5533 return;
5534 }
5535
5536 String fromName = PrefsPropsUtil.getString(
5537 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
5538 String fromAddress = PrefsPropsUtil.getString(
5539 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
5540
5541 String toName = user.getFullName();
5542 String toAddress = user.getEmailAddress();
5543
5544 String subject = PrefsPropsUtil.getContent(
5545 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
5546
5547 String body = null;
5548
5549 if (Validator.isNotNull(password)) {
5550 body = PrefsPropsUtil.getContent(
5551 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
5552 }
5553 else {
5554 body = PrefsPropsUtil.getContent(
5555 user.getCompanyId(),
5556 PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
5557 }
5558
5559 SubscriptionSender subscriptionSender = new SubscriptionSender();
5560
5561 subscriptionSender.setBody(body);
5562 subscriptionSender.setCompanyId(user.getCompanyId());
5563 subscriptionSender.setContextAttributes(
5564 "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
5565 "[$USER_SCREENNAME$]", user.getScreenName());
5566 subscriptionSender.setFrom(fromAddress, fromName);
5567 subscriptionSender.setHtmlFormat(true);
5568 subscriptionSender.setMailId("user", user.getUserId());
5569 subscriptionSender.setServiceContext(serviceContext);
5570 subscriptionSender.setSubject(subject);
5571 subscriptionSender.setUserId(user.getUserId());
5572
5573 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
5574
5575 subscriptionSender.flushNotificationsAsync();
5576 }
5577
5578 protected void setEmailAddress(
5579 User user, String password, String firstName, String middleName,
5580 String lastName, String emailAddress)
5581 throws PortalException, SystemException {
5582
5583 if (emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
5584 return;
5585 }
5586
5587 long userId = user.getUserId();
5588
5589
5590
5591 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
5592 Validator.isNotNull(password)) {
5593
5594 mailService.addUser(
5595 user.getCompanyId(), userId, password, firstName, middleName,
5596 lastName, emailAddress);
5597 }
5598
5599
5600
5601 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
5602 mailService.updateEmailAddress(
5603 user.getCompanyId(), userId, emailAddress);
5604 }
5605
5606
5607
5608 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
5609 mailService.deleteEmailAddress(user.getCompanyId(), userId);
5610 }
5611
5612 user.setEmailAddress(emailAddress);
5613 user.setDigest(StringPool.BLANK);
5614 }
5615
5616 protected void updateGroups(
5617 long userId, long[] newGroupIds, ServiceContext serviceContext,
5618 boolean indexingEnabled)
5619 throws PortalException, SystemException {
5620
5621 if (newGroupIds == null) {
5622 return;
5623 }
5624
5625 List<Group> oldGroups = userPersistence.getGroups(userId);
5626
5627 Set<Long> oldGroupIds = new HashSet<Long>(oldGroups.size());
5628
5629 for (Group oldGroup : oldGroups) {
5630 long oldGroupId = oldGroup.getGroupId();
5631
5632 oldGroupIds.add(oldGroupId);
5633
5634 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
5635 unsetGroupUsers(
5636 oldGroupId, new long[] {userId}, serviceContext);
5637 }
5638 }
5639
5640 for (long newGroupId : newGroupIds) {
5641 if (!oldGroupIds.contains(newGroupId)) {
5642 addGroupUsers(newGroupId, new long[] {userId});
5643 }
5644 }
5645
5646 if (indexingEnabled) {
5647 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5648 User.class);
5649
5650 indexer.reindex(new long[] {userId});
5651 }
5652
5653 PermissionCacheUtil.clearCache();
5654 }
5655
5656 protected void updateOrganizations(
5657 long userId, long[] newOrganizationIds, boolean indexingEnabled)
5658 throws PortalException, SystemException {
5659
5660 if (newOrganizationIds == null) {
5661 return;
5662 }
5663
5664 List<Organization> oldOrganizations = userPersistence.getOrganizations(
5665 userId);
5666
5667 Set<Long> oldOrganizationIds = new HashSet<Long>(
5668 oldOrganizations.size());
5669
5670 for (Organization oldOrganization : oldOrganizations) {
5671 long oldOrganizationId = oldOrganization.getOrganizationId();
5672
5673 oldOrganizationIds.add(oldOrganizationId);
5674
5675 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
5676 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
5677 }
5678 }
5679
5680 for (long newOrganizationId : newOrganizationIds) {
5681 if (!oldOrganizationIds.contains(newOrganizationId)) {
5682 addOrganizationUsers(newOrganizationId, new long[] {userId});
5683 }
5684 }
5685
5686 if (indexingEnabled) {
5687 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5688 User.class);
5689
5690 indexer.reindex(new long[] {userId});
5691 }
5692
5693 PermissionCacheUtil.clearCache();
5694 }
5695
5696 protected void updateUserGroupRoles(
5697 User user, long[] groupIds, long[] organizationIds,
5698 List<UserGroupRole> userGroupRoles)
5699 throws PortalException, SystemException {
5700
5701 if (userGroupRoles == null) {
5702 return;
5703 }
5704
5705 List<UserGroupRole> previousUserGroupRoles =
5706 userGroupRolePersistence.findByUserId(user.getUserId());
5707
5708 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
5709 if (userGroupRoles.contains(userGroupRole)) {
5710 userGroupRoles.remove(userGroupRole);
5711 }
5712 else {
5713 userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
5714 }
5715 }
5716
5717 long[] validGroupIds = null;
5718
5719 if (groupIds != null) {
5720 validGroupIds = ArrayUtil.clone(groupIds);
5721 }
5722 else {
5723 validGroupIds = user.getGroupIds();
5724 }
5725
5726 if (organizationIds == null) {
5727 organizationIds = user.getOrganizationIds();
5728 }
5729
5730 long[] organizationGroupIds = new long[organizationIds.length];
5731
5732 for (int i = 0; i < organizationIds.length; i++) {
5733 long organizationId = organizationIds[i];
5734
5735 Organization organization =
5736 organizationPersistence.findByPrimaryKey(organizationId);
5737
5738 Group organizationGroup = organization.getGroup();
5739
5740 organizationGroupIds[i] = organizationGroup.getGroupId();
5741 }
5742
5743 validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
5744
5745 Arrays.sort(validGroupIds);
5746
5747 for (UserGroupRole userGroupRole : userGroupRoles) {
5748 if (Arrays.binarySearch(
5749 validGroupIds, userGroupRole.getGroupId()) >= 0) {
5750
5751 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
5752 }
5753 }
5754 }
5755
5756 protected void validate(
5757 long companyId, long userId, boolean autoPassword, String password1,
5758 String password2, boolean autoScreenName, String screenName,
5759 String emailAddress, String firstName, String middleName,
5760 String lastName, long[] organizationIds)
5761 throws PortalException, SystemException {
5762
5763 Company company = companyPersistence.findByPrimaryKey(companyId);
5764
5765 if (company.isSystem()) {
5766 return;
5767 }
5768
5769 if ((company.getMaxUsers() > 0) &&
5770 (company.getMaxUsers() <=
5771 searchCount(
5772 companyId, null, WorkflowConstants.STATUS_APPROVED,
5773 null))) {
5774
5775 throw new CompanyMaxUsersException();
5776 }
5777
5778 if (!autoScreenName) {
5779 validateScreenName(companyId, userId, screenName);
5780 }
5781
5782 if (!autoPassword) {
5783 PasswordPolicy passwordPolicy =
5784 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
5785
5786 PwdToolkitUtil.validate(
5787 companyId, 0, password1, password2, passwordPolicy);
5788 }
5789
5790 validateEmailAddress(companyId, emailAddress);
5791
5792 if (Validator.isNotNull(emailAddress)) {
5793 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
5794
5795 if ((user != null) && (user.getUserId() != userId)) {
5796 throw new DuplicateUserEmailAddressException();
5797 }
5798 }
5799
5800 validateFullName(companyId, firstName, middleName, lastName);
5801
5802 if (organizationIds != null) {
5803 for (long organizationId : organizationIds) {
5804 Organization organization =
5805 organizationPersistence.fetchByPrimaryKey(organizationId);
5806
5807 if (organization == null) {
5808 throw new NoSuchOrganizationException();
5809 }
5810 }
5811 }
5812 }
5813
5814 protected void validate(
5815 long userId, String screenName, String emailAddress,
5816 String firstName, String middleName, String lastName, String smsSn)
5817 throws PortalException, SystemException {
5818
5819 User user = userPersistence.findByPrimaryKey(userId);
5820
5821 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
5822 validateScreenName(user.getCompanyId(), userId, screenName);
5823 }
5824
5825 validateEmailAddress(user.getCompanyId(), emailAddress);
5826
5827 if (!user.isDefaultUser()) {
5828 if (Validator.isNotNull(emailAddress) &&
5829 !user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
5830
5831 if (userPersistence.fetchByC_EA(
5832 user.getCompanyId(), emailAddress) != null) {
5833
5834 throw new DuplicateUserEmailAddressException();
5835 }
5836 }
5837
5838 validateFullName(
5839 user.getCompanyId(), firstName, middleName, lastName);
5840 }
5841
5842 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
5843 throw new UserSmsException();
5844 }
5845 }
5846
5847 protected void validateEmailAddress(long companyId, String emailAddress)
5848 throws PortalException, SystemException {
5849
5850 if (Validator.isNull(emailAddress) &&
5851 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
5852
5853 return;
5854 }
5855
5856 EmailAddressValidator emailAddressValidator =
5857 EmailAddressValidatorFactory.getInstance();
5858
5859 if (!emailAddressValidator.validate(companyId, emailAddress)) {
5860 throw new UserEmailAddressException();
5861 }
5862
5863 String pop3User = PrefsPropsUtil.getString(
5864 PropsKeys.MAIL_SESSION_MAIL_POP3_USER,
5865 PropsValues.MAIL_SESSION_MAIL_POP3_USER);
5866
5867 if (emailAddress.equalsIgnoreCase(pop3User)) {
5868 throw new ReservedUserEmailAddressException();
5869 }
5870
5871 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
5872 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
5873 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
5874
5875 for (String reservedEmailAddress : reservedEmailAddresses) {
5876 if (emailAddress.equalsIgnoreCase(reservedEmailAddress)) {
5877 throw new ReservedUserEmailAddressException();
5878 }
5879 }
5880 }
5881
5882 protected void validateEmailAddress(
5883 User user, String emailAddress1, String emailAddress2)
5884 throws PortalException, SystemException {
5885
5886 if (!emailAddress1.equals(emailAddress2)) {
5887 throw new UserEmailAddressException();
5888 }
5889
5890 validateEmailAddress(user.getCompanyId(), emailAddress1);
5891 validateEmailAddress(user.getCompanyId(), emailAddress2);
5892
5893 if (!emailAddress1.equalsIgnoreCase(user.getEmailAddress())) {
5894 if (userPersistence.fetchByC_EA(
5895 user.getCompanyId(), emailAddress1) != null) {
5896
5897 throw new DuplicateUserEmailAddressException();
5898 }
5899 }
5900 }
5901
5902 protected void validateFullName(
5903 long companyId, String firstName, String middleName,
5904 String lastName)
5905 throws PortalException, SystemException {
5906
5907 if (Validator.isNull(firstName)) {
5908 throw new ContactFirstNameException();
5909 }
5910 else if (Validator.isNull(lastName) &&
5911 PrefsPropsUtil.getBoolean(
5912 companyId, PropsKeys.USERS_LAST_NAME_REQUIRED,
5913 PropsValues.USERS_LAST_NAME_REQUIRED)) {
5914
5915 throw new ContactLastNameException();
5916 }
5917
5918 FullNameValidator fullNameValidator =
5919 FullNameValidatorFactory.getInstance();
5920
5921 if (!fullNameValidator.validate(
5922 companyId, firstName, middleName, lastName)) {
5923
5924 throw new ContactFullNameException();
5925 }
5926 }
5927
5928 protected void validatePassword(
5929 long companyId, long userId, String password1, String password2)
5930 throws PortalException, SystemException {
5931
5932 if (Validator.isNull(password1) || Validator.isNull(password2)) {
5933 throw new UserPasswordException(
5934 UserPasswordException.PASSWORD_INVALID);
5935 }
5936
5937 if (!password1.equals(password2)) {
5938 throw new UserPasswordException(
5939 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
5940 }
5941
5942 PasswordPolicy passwordPolicy =
5943 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
5944
5945 PwdToolkitUtil.validate(
5946 companyId, userId, password1, password2, passwordPolicy);
5947 }
5948
5949 protected void validateReminderQuery(String question, String answer)
5950 throws PortalException {
5951
5952 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
5953 return;
5954 }
5955
5956 if (Validator.isNull(question)) {
5957 throw new UserReminderQueryException("Question cannot be null");
5958 }
5959
5960 if (Validator.isNull(answer)) {
5961 throw new UserReminderQueryException("Answer cannot be null");
5962 }
5963 }
5964
5965 protected void validateScreenName(
5966 long companyId, long userId, String screenName)
5967 throws PortalException, SystemException {
5968
5969 if (Validator.isNull(screenName)) {
5970 throw new UserScreenNameException();
5971 }
5972
5973 ScreenNameValidator screenNameValidator =
5974 ScreenNameValidatorFactory.getInstance();
5975
5976 if (!screenNameValidator.validate(companyId, screenName)) {
5977 throw new UserScreenNameException();
5978 }
5979
5980 if (Validator.isNumber(screenName)) {
5981 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
5982 throw new UserScreenNameException();
5983 }
5984
5985 if (!screenName.equals(String.valueOf(userId))) {
5986 Group group = groupPersistence.fetchByPrimaryKey(
5987 GetterUtil.getLong(screenName));
5988
5989 if (group != null) {
5990 throw new UserScreenNameException();
5991 }
5992 }
5993 }
5994
5995 for (char c : screenName.toCharArray()) {
5996 if (!Validator.isChar(c) && !Validator.isDigit(c) &&
5997 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
5998 (c != CharPool.UNDERLINE)) {
5999
6000 throw new UserScreenNameException();
6001 }
6002 }
6003
6004 String[] anonymousNames = BaseServiceImpl.ANONYMOUS_NAMES;
6005
6006 for (String anonymousName : anonymousNames) {
6007 if (screenName.equalsIgnoreCase(anonymousName)) {
6008 throw new UserScreenNameException();
6009 }
6010 }
6011
6012 User user = userPersistence.fetchByC_SN(companyId, screenName);
6013
6014 if ((user != null) && (user.getUserId() != userId)) {
6015 throw new DuplicateUserScreenNameException();
6016 }
6017
6018 String friendlyURL = StringPool.SLASH + screenName;
6019
6020 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
6021
6022 if ((group != null) && (group.getClassPK() != userId)) {
6023 throw new GroupFriendlyURLException(
6024 GroupFriendlyURLException.DUPLICATE);
6025 }
6026
6027 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
6028
6029 if (exceptionType != -1) {
6030 throw new UserScreenNameException(
6031 new GroupFriendlyURLException(exceptionType));
6032 }
6033
6034 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
6035 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
6036 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
6037
6038 for (String reservedScreenName : reservedScreenNames) {
6039 if (screenName.equalsIgnoreCase(reservedScreenName)) {
6040 throw new ReservedUserScreenNameException();
6041 }
6042 }
6043 }
6044
6045 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
6046
6047 private static Map<Long, User> _defaultUsers =
6048 new ConcurrentHashMap<Long, User>();
6049
6050 }