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.NoSuchRoleException;
029 import com.liferay.portal.NoSuchTicketException;
030 import com.liferay.portal.NoSuchUserException;
031 import com.liferay.portal.NoSuchUserGroupException;
032 import com.liferay.portal.PasswordExpiredException;
033 import com.liferay.portal.RequiredUserException;
034 import com.liferay.portal.ReservedUserEmailAddressException;
035 import com.liferay.portal.ReservedUserScreenNameException;
036 import com.liferay.portal.UserEmailAddressException;
037 import com.liferay.portal.UserIdException;
038 import com.liferay.portal.UserLockoutException;
039 import com.liferay.portal.UserPasswordException;
040 import com.liferay.portal.UserPortraitSizeException;
041 import com.liferay.portal.UserPortraitTypeException;
042 import com.liferay.portal.UserReminderQueryException;
043 import com.liferay.portal.UserScreenNameException;
044 import com.liferay.portal.UserSmsException;
045 import com.liferay.portal.kernel.exception.PortalException;
046 import com.liferay.portal.kernel.exception.SystemException;
047 import com.liferay.portal.kernel.image.ImageBag;
048 import com.liferay.portal.kernel.image.ImageProcessorUtil;
049 import com.liferay.portal.kernel.language.LanguageUtil;
050 import com.liferay.portal.kernel.log.Log;
051 import com.liferay.portal.kernel.log.LogFactoryUtil;
052 import com.liferay.portal.kernel.search.Hits;
053 import com.liferay.portal.kernel.search.Indexer;
054 import com.liferay.portal.kernel.search.IndexerRegistryUtil;
055 import com.liferay.portal.kernel.search.QueryConfig;
056 import com.liferay.portal.kernel.search.SearchContext;
057 import com.liferay.portal.kernel.search.Sort;
058 import com.liferay.portal.kernel.spring.aop.Skip;
059 import com.liferay.portal.kernel.transaction.Propagation;
060 import com.liferay.portal.kernel.transaction.Transactional;
061 import com.liferay.portal.kernel.util.ArrayUtil;
062 import com.liferay.portal.kernel.util.CharPool;
063 import com.liferay.portal.kernel.util.Digester;
064 import com.liferay.portal.kernel.util.DigesterUtil;
065 import com.liferay.portal.kernel.util.GetterUtil;
066 import com.liferay.portal.kernel.util.KeyValuePair;
067 import com.liferay.portal.kernel.util.OrderByComparator;
068 import com.liferay.portal.kernel.util.PropsKeys;
069 import com.liferay.portal.kernel.util.StringPool;
070 import com.liferay.portal.kernel.util.StringUtil;
071 import com.liferay.portal.kernel.util.Validator;
072 import com.liferay.portal.kernel.workflow.WorkflowConstants;
073 import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil;
074 import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
075 import com.liferay.portal.model.Account;
076 import com.liferay.portal.model.Company;
077 import com.liferay.portal.model.CompanyConstants;
078 import com.liferay.portal.model.Contact;
079 import com.liferay.portal.model.ContactConstants;
080 import com.liferay.portal.model.Group;
081 import com.liferay.portal.model.GroupConstants;
082 import com.liferay.portal.model.Layout;
083 import com.liferay.portal.model.Organization;
084 import com.liferay.portal.model.PasswordPolicy;
085 import com.liferay.portal.model.ResourceConstants;
086 import com.liferay.portal.model.Role;
087 import com.liferay.portal.model.RoleConstants;
088 import com.liferay.portal.model.Ticket;
089 import com.liferay.portal.model.TicketConstants;
090 import com.liferay.portal.model.User;
091 import com.liferay.portal.model.UserGroup;
092 import com.liferay.portal.model.UserGroupRole;
093 import com.liferay.portal.model.impl.LayoutImpl;
094 import com.liferay.portal.security.auth.AuthPipeline;
095 import com.liferay.portal.security.auth.Authenticator;
096 import com.liferay.portal.security.auth.EmailAddressGenerator;
097 import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
098 import com.liferay.portal.security.auth.FullNameGenerator;
099 import com.liferay.portal.security.auth.FullNameGeneratorFactory;
100 import com.liferay.portal.security.auth.FullNameValidator;
101 import com.liferay.portal.security.auth.FullNameValidatorFactory;
102 import com.liferay.portal.security.auth.PrincipalException;
103 import com.liferay.portal.security.auth.ScreenNameGenerator;
104 import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
105 import com.liferay.portal.security.auth.ScreenNameValidator;
106 import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
107 import com.liferay.portal.security.ldap.LDAPSettingsUtil;
108 import com.liferay.portal.security.permission.PermissionCacheUtil;
109 import com.liferay.portal.security.pwd.PwdAuthenticator;
110 import com.liferay.portal.security.pwd.PwdEncryptor;
111 import com.liferay.portal.security.pwd.PwdToolkitUtil;
112 import com.liferay.portal.service.ServiceContext;
113 import com.liferay.portal.service.base.PrincipalBean;
114 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
115 import com.liferay.portal.util.PortalUtil;
116 import com.liferay.portal.util.PrefsPropsUtil;
117 import com.liferay.portal.util.PropsValues;
118 import com.liferay.portal.util.SubscriptionSender;
119 import com.liferay.portlet.documentlibrary.ImageSizeException;
120 import com.liferay.portlet.messageboards.model.MBMessage;
121 import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
122 import com.liferay.util.Encryptor;
123 import com.liferay.util.EncryptorException;
124
125 import java.awt.image.RenderedImage;
126
127 import java.io.IOException;
128 import java.io.Serializable;
129
130 import java.util.ArrayList;
131 import java.util.Arrays;
132 import java.util.Date;
133 import java.util.HashMap;
134 import java.util.HashSet;
135 import java.util.LinkedHashMap;
136 import java.util.List;
137 import java.util.Locale;
138 import java.util.Map;
139 import java.util.Set;
140 import java.util.concurrent.ConcurrentHashMap;
141
142
153 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
154
155
165 public void addDefaultGroups(long userId)
166 throws PortalException, SystemException {
167
168 User user = userPersistence.findByPrimaryKey(userId);
169
170 Set<Long> groupIdsSet = new HashSet<Long>();
171
172 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
173 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
174 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
175
176 for (String defaultGroupName : defaultGroupNames) {
177 Company company = companyPersistence.findByPrimaryKey(
178 user.getCompanyId());
179
180 Account account = company.getAccount();
181
182 if (defaultGroupName.equalsIgnoreCase(account.getName())) {
183 defaultGroupName = GroupConstants.GUEST;
184 }
185
186 try {
187 Group group = groupPersistence.findByC_N(
188 user.getCompanyId(), defaultGroupName);
189
190 if (!userPersistence.containsGroup(
191 userId, group.getGroupId())) {
192
193 groupIdsSet.add(group.getGroupId());
194 }
195 }
196 catch (NoSuchGroupException nsge) {
197 }
198 }
199
200 long[] groupIds = ArrayUtil.toArray(
201 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
202
203 groupLocalService.addUserGroups(userId, groupIds);
204 }
205
206
216 public void addDefaultRoles(long userId)
217 throws PortalException, SystemException {
218
219 User user = userPersistence.findByPrimaryKey(userId);
220
221 Set<Long> roleIdSet = new HashSet<Long>();
222
223 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
224 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
225 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
226
227 for (String defaultRoleName : defaultRoleNames) {
228 try {
229 Role role = rolePersistence.findByC_N(
230 user.getCompanyId(), defaultRoleName);
231
232 if (!userPersistence.containsRole(userId, role.getRoleId())) {
233 roleIdSet.add(role.getRoleId());
234 }
235 }
236 catch (NoSuchRoleException nsre) {
237 }
238 }
239
240 long[] roleIds = ArrayUtil.toArray(
241 roleIdSet.toArray(new Long[roleIdSet.size()]));
242
243 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
244
245 userPersistence.addRoles(userId, roleIds);
246 }
247
248
258 @SuppressWarnings("deprecation")
259 public void addDefaultUserGroups(long userId)
260 throws PortalException, SystemException {
261
262 User user = userPersistence.findByPrimaryKey(userId);
263
264 Set<Long> userGroupIdSet = new HashSet<Long>();
265
266 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
267 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
268 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
269
270 for (String defaultUserGroupName : defaultUserGroupNames) {
271 try {
272 UserGroup userGroup = userGroupPersistence.findByC_N(
273 user.getCompanyId(), defaultUserGroupName);
274
275 if (!userPersistence.containsUserGroup(
276 userId, userGroup.getUserGroupId())) {
277
278 userGroupIdSet.add(userGroup.getUserGroupId());
279 }
280 }
281 catch (NoSuchUserGroupException nsuge) {
282 }
283 }
284
285 long[] userGroupIds = ArrayUtil.toArray(
286 userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
287
288 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
289 for (long userGroupId : userGroupIds) {
290 userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
291 }
292 }
293
294 userPersistence.addUserGroups(userId, userGroupIds);
295 }
296
297
306 public void addGroupUsers(long groupId, long[] userIds)
307 throws PortalException, SystemException {
308
309 groupPersistence.addUsers(groupId, userIds);
310
311 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
312
313 indexer.reindex(userIds);
314
315 PermissionCacheUtil.clearCache();
316 }
317
318
327 public void addOrganizationUsers(long organizationId, long[] userIds)
328 throws PortalException, SystemException {
329
330 organizationPersistence.addUsers(organizationId, userIds);
331
332 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
333
334 indexer.reindex(userIds);
335
336 PermissionCacheUtil.clearCache();
337 }
338
339
347 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
348 throws SystemException {
349
350 passwordPolicyRelLocalService.addPasswordPolicyRels(
351 passwordPolicyId, User.class.getName(), userIds);
352 }
353
354
363 public void addRoleUsers(long roleId, long[] userIds)
364 throws PortalException, SystemException {
365
366 rolePersistence.addUsers(roleId, userIds);
367
368 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
369
370 indexer.reindex(userIds);
371
372 PermissionCacheUtil.clearCache();
373 }
374
375
384 public void addTeamUsers(long teamId, long[] userIds)
385 throws PortalException, SystemException {
386
387 teamPersistence.addUsers(teamId, userIds);
388
389 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
390
391 indexer.reindex(userIds);
392
393 PermissionCacheUtil.clearCache();
394 }
395
396
444 public User addUser(
445 long creatorUserId, long companyId, boolean autoPassword,
446 String password1, String password2, boolean autoScreenName,
447 String screenName, String emailAddress, long facebookId,
448 String openId, Locale locale, String firstName, String middleName,
449 String lastName, int prefixId, int suffixId, boolean male,
450 int birthdayMonth, int birthdayDay, int birthdayYear,
451 String jobTitle, long[] groupIds, long[] organizationIds,
452 long[] roleIds, long[] userGroupIds, boolean sendEmail,
453 ServiceContext serviceContext)
454 throws PortalException, SystemException {
455
456 boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
457
458 try {
459 WorkflowThreadLocal.setEnabled(false);
460
461 return addUserWithWorkflow(
462 creatorUserId, companyId, autoPassword, password1, password2,
463 autoScreenName, screenName, emailAddress, facebookId, openId,
464 locale, firstName, middleName, lastName, prefixId, suffixId,
465 male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
466 groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
467 serviceContext);
468 }
469 finally {
470 WorkflowThreadLocal.setEnabled(workflowEnabled);
471 }
472 }
473
474
483 @SuppressWarnings("deprecation")
484 public void addUserGroupUsers(long userGroupId, long[] userIds)
485 throws PortalException, SystemException {
486
487 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
488 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
489 }
490
491 userGroupPersistence.addUsers(userGroupId, userIds);
492
493 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
494
495 indexer.reindex(userIds);
496
497 PermissionCacheUtil.clearCache();
498 }
499
500
548 @SuppressWarnings("deprecation")
549 public User addUserWithWorkflow(
550 long creatorUserId, long companyId, boolean autoPassword,
551 String password1, String password2, boolean autoScreenName,
552 String screenName, String emailAddress, long facebookId,
553 String openId, Locale locale, String firstName, String middleName,
554 String lastName, int prefixId, int suffixId, boolean male,
555 int birthdayMonth, int birthdayDay, int birthdayYear,
556 String jobTitle, long[] groupIds, long[] organizationIds,
557 long[] roleIds, long[] userGroupIds, boolean sendEmail,
558 ServiceContext serviceContext)
559 throws PortalException, SystemException {
560
561
562
563 Company company = companyPersistence.findByPrimaryKey(companyId);
564 screenName = getScreenName(screenName);
565 emailAddress = emailAddress.trim().toLowerCase();
566 openId = openId.trim();
567 Date now = new Date();
568
569 if (PrefsPropsUtil.getBoolean(
570 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
571
572 autoScreenName = true;
573 }
574
575 long userId = counterLocalService.increment();
576
577 EmailAddressGenerator emailAddressGenerator =
578 EmailAddressGeneratorFactory.getInstance();
579
580 if (emailAddressGenerator.isGenerated(emailAddress)) {
581 emailAddress = StringPool.BLANK;
582 }
583
584 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
585 Validator.isNull(emailAddress)) {
586
587 emailAddress = emailAddressGenerator.generate(companyId, userId);
588 }
589
590 validate(
591 companyId, userId, autoPassword, password1, password2,
592 autoScreenName, screenName, emailAddress, firstName, middleName,
593 lastName, organizationIds);
594
595 if (!autoPassword) {
596 if (Validator.isNull(password1) || Validator.isNull(password2)) {
597 throw new UserPasswordException(
598 UserPasswordException.PASSWORD_INVALID);
599 }
600 }
601
602 if (autoScreenName) {
603 ScreenNameGenerator screenNameGenerator =
604 ScreenNameGeneratorFactory.getInstance();
605
606 try {
607 screenName = screenNameGenerator.generate(
608 companyId, userId, emailAddress);
609 }
610 catch (Exception e) {
611 throw new SystemException(e);
612 }
613 }
614
615 User defaultUser = getDefaultUser(companyId);
616
617 FullNameGenerator fullNameGenerator =
618 FullNameGeneratorFactory.getInstance();
619
620 String fullName = fullNameGenerator.getFullName(
621 firstName, middleName, lastName);
622
623 String greeting = LanguageUtil.format(
624 locale, "welcome-x", " " + fullName, false);
625
626 User user = userPersistence.create(userId);
627
628 if (serviceContext != null) {
629 String uuid = serviceContext.getUuid();
630
631 if (Validator.isNotNull(uuid)) {
632 user.setUuid(uuid);
633 }
634 }
635
636 user.setCompanyId(companyId);
637 user.setCreateDate(now);
638 user.setModifiedDate(now);
639 user.setDefaultUser(false);
640 user.setContactId(counterLocalService.increment());
641
642 if (Validator.isNotNull(password1)) {
643 user.setPassword(PwdEncryptor.encrypt(password1));
644 user.setPasswordUnencrypted(password1);
645 }
646
647 user.setPasswordEncrypted(true);
648
649 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
650
651 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
652 passwordPolicy.isChangeRequired()) {
653
654 user.setPasswordReset(true);
655 }
656 else {
657 user.setPasswordReset(false);
658 }
659
660 user.setDigest(StringPool.BLANK);
661 user.setScreenName(screenName);
662 user.setEmailAddress(emailAddress);
663 user.setFacebookId(facebookId);
664 user.setOpenId(openId);
665 user.setLanguageId(locale.toString());
666 user.setTimeZoneId(defaultUser.getTimeZoneId());
667 user.setGreeting(greeting);
668 user.setFirstName(firstName);
669 user.setMiddleName(middleName);
670 user.setLastName(lastName);
671 user.setJobTitle(jobTitle);
672 user.setStatus(WorkflowConstants.STATUS_DRAFT);
673
674 userPersistence.update(user, false, serviceContext);
675
676
677
678 String creatorUserName = StringPool.BLANK;
679
680 if (creatorUserId <= 0) {
681 creatorUserId = user.getUserId();
682
683
684
685
686
687 }
688 else {
689 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
690
691 creatorUserName = creatorUser.getFullName();
692 }
693
694 resourceLocalService.addResources(
695 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
696 false, false, false);
697
698
699
700 Date birthday = PortalUtil.getDate(
701 birthdayMonth, birthdayDay, birthdayYear,
702 new ContactBirthdayException());
703
704 Contact contact = contactPersistence.create(user.getContactId());
705
706 contact.setCompanyId(user.getCompanyId());
707 contact.setUserId(creatorUserId);
708 contact.setUserName(creatorUserName);
709 contact.setCreateDate(now);
710 contact.setModifiedDate(now);
711 contact.setAccountId(company.getAccountId());
712 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
713 contact.setFirstName(firstName);
714 contact.setMiddleName(middleName);
715 contact.setLastName(lastName);
716 contact.setPrefixId(prefixId);
717 contact.setSuffixId(suffixId);
718 contact.setMale(male);
719 contact.setBirthday(birthday);
720 contact.setJobTitle(jobTitle);
721
722 contactPersistence.update(contact, false, serviceContext);
723
724
725
726 groupLocalService.addGroup(
727 user.getUserId(), User.class.getName(), user.getUserId(), null,
728 null, 0, StringPool.SLASH + screenName, false, true, null);
729
730
731
732 if (groupIds != null) {
733 groupLocalService.addUserGroups(userId, groupIds);
734 }
735
736 addDefaultGroups(userId);
737
738
739
740 boolean indexingEnabled = serviceContext.isIndexingEnabled();
741
742 serviceContext.setIndexingEnabled(false);
743
744 try {
745 updateOrganizations(userId, organizationIds, serviceContext);
746 }
747 finally {
748 serviceContext.setIndexingEnabled(indexingEnabled);
749 }
750
751
752
753 if (roleIds != null) {
754 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
755
756 userPersistence.setRoles(userId, roleIds);
757 }
758
759 addDefaultRoles(userId);
760
761
762
763 if (userGroupIds != null) {
764 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
765 for (long userGroupId : userGroupIds) {
766 userGroupLocalService.copyUserGroupLayouts(
767 userGroupId, new long[] {userId});
768 }
769 }
770
771 userPersistence.setUserGroups(userId, userGroupIds);
772 }
773
774 addDefaultUserGroups(userId);
775
776
777
778 if (serviceContext != null) {
779 updateAsset(
780 creatorUserId, user, serviceContext.getAssetCategoryIds(),
781 serviceContext.getAssetTagNames());
782 }
783
784
785
786 user.setExpandoBridgeAttributes(serviceContext);
787
788
789
790 if (serviceContext.isIndexingEnabled()) {
791 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
792
793 indexer.reindex(user);
794 }
795
796
797
798 long workflowUserId = creatorUserId;
799
800 if (workflowUserId == userId) {
801 workflowUserId = defaultUser.getUserId();
802 }
803
804 serviceContext.setAttribute("autoPassword", autoPassword);
805 serviceContext.setAttribute("sendEmail", sendEmail);
806
807 WorkflowHandlerRegistryUtil.startWorkflowInstance(
808 companyId, workflowUserId, User.class.getName(), userId, user,
809 serviceContext);
810
811 String passwordUnencrypted =
812 (String) serviceContext.getAttribute("passwordUnencrypted");
813
814 if (Validator.isNotNull(passwordUnencrypted)) {
815 user.setPasswordUnencrypted(passwordUnencrypted);
816 }
817
818 return user;
819 }
820
821
845 public int authenticateByEmailAddress(
846 long companyId, String emailAddress, String password,
847 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
848 Map<String, Object> resultsMap)
849 throws PortalException, SystemException {
850
851 return authenticate(
852 companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
853 headerMap, parameterMap, resultsMap);
854 }
855
856
880 public int authenticateByScreenName(
881 long companyId, String screenName, String password,
882 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
883 Map<String, Object> resultsMap)
884 throws PortalException, SystemException {
885
886 return authenticate(
887 companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
888 headerMap, parameterMap, resultsMap);
889 }
890
891
915 public int authenticateByUserId(
916 long companyId, long userId, String password,
917 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
918 Map<String, Object> resultsMap)
919 throws PortalException, SystemException {
920
921 return authenticate(
922 companyId, String.valueOf(userId), password,
923 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap, resultsMap);
924 }
925
926
966 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
967 public long authenticateForBasic(
968 long companyId, String authType, String login, String password)
969 throws PortalException, SystemException {
970
971 if (PropsValues.AUTH_LOGIN_DISABLED) {
972 return 0;
973 }
974
975 try {
976 User user = null;
977
978 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
979 user = getUserByEmailAddress(companyId, login);
980 }
981 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
982 user = getUserByScreenName(companyId, login);
983 }
984 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
985 user = getUserById(companyId, GetterUtil.getLong(login));
986 }
987
988 if (user.isDefaultUser()) {
989 if (_log.isInfoEnabled()) {
990 _log.info(
991 "Basic authentication is disabled for the default " +
992 "user");
993 }
994
995 return 0;
996 }
997 else if (!user.isActive()) {
998 if (_log.isInfoEnabled()) {
999 _log.info(
1000 "Basic authentication is disabled for inactive user " +
1001 user.getUserId());
1002 }
1003
1004 return 0;
1005 }
1006
1007 if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
1008 return user.getUserId();
1009 }
1010
1011 String userPassword = user.getPassword();
1012
1013 if (!user.isPasswordEncrypted()) {
1014 userPassword = PwdEncryptor.encrypt(userPassword);
1015 }
1016
1017 String encPassword = PwdEncryptor.encrypt(password);
1018
1019 if (userPassword.equals(password) ||
1020 userPassword.equals(encPassword)) {
1021
1022 return user.getUserId();
1023 }
1024 }
1025 catch (NoSuchUserException nsue) {
1026 }
1027
1028 return 0;
1029 }
1030
1031
1049 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1050 public long authenticateForDigest(
1051 long companyId, String username, String realm, String nonce,
1052 String method, String uri, String response)
1053 throws PortalException, SystemException {
1054
1055 if (PropsValues.AUTH_LOGIN_DISABLED) {
1056 return 0;
1057 }
1058
1059
1060
1061 User user = null;
1062
1063 try {
1064 user = getUserByEmailAddress(companyId, username);
1065 }
1066 catch (NoSuchUserException nsue) {
1067 try {
1068 user = getUserByScreenName(companyId, username);
1069 }
1070 catch (NoSuchUserException nsue2) {
1071 try {
1072 user = getUserById(GetterUtil.getLong(username));
1073 }
1074 catch (NoSuchUserException nsue3) {
1075 return 0;
1076 }
1077 }
1078 }
1079
1080 if (user.isDefaultUser()) {
1081 if (_log.isInfoEnabled()) {
1082 _log.info(
1083 "Digest authentication is disabled for the default user");
1084 }
1085
1086 return 0;
1087 }
1088 else if (!user.isActive()) {
1089 if (_log.isInfoEnabled()) {
1090 _log.info(
1091 "Digest authentication is disabled for inactive user " +
1092 user.getUserId());
1093 }
1094
1095 return 0;
1096 }
1097
1098
1099
1100 String digest = user.getDigest();
1101
1102 if (Validator.isNull(digest)) {
1103 _log.error(
1104 "User must first login through the portal " + user.getUserId());
1105
1106 return 0;
1107 }
1108
1109 String[] digestArray = StringUtil.split(user.getDigest());
1110
1111 for (String ha1 : digestArray) {
1112 String ha2 = DigesterUtil.digestHex(Digester.MD5, method, uri);
1113
1114 String curResponse = DigesterUtil.digestHex(
1115 Digester.MD5, ha1, nonce, ha2);
1116
1117 if (response.equals(curResponse)) {
1118 return user.getUserId();
1119 }
1120 }
1121
1122 return 0;
1123 }
1124
1125
1134 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1135 public boolean authenticateForJAAS(long userId, String encPassword) {
1136 if (PropsValues.AUTH_LOGIN_DISABLED) {
1137 return false;
1138 }
1139
1140 try {
1141 User user = userPersistence.findByPrimaryKey(userId);
1142
1143 if (user.isDefaultUser()) {
1144 if (_log.isInfoEnabled()) {
1145 _log.info(
1146 "JAAS authentication is disabled for the default user");
1147 }
1148
1149 return false;
1150 }
1151 else if (!user.isActive()) {
1152 if (_log.isInfoEnabled()) {
1153 _log.info(
1154 "JAAS authentication is disabled for inactive user " +
1155 userId);
1156 }
1157
1158 return false;
1159 }
1160
1161 String password = user.getPassword();
1162
1163 if (user.isPasswordEncrypted()) {
1164 if (password.equals(encPassword)) {
1165 return true;
1166 }
1167
1168 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1169 encPassword = PwdEncryptor.encrypt(encPassword, password);
1170
1171 if (password.equals(encPassword)) {
1172 return true;
1173 }
1174 }
1175 }
1176 else {
1177 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1178 if (password.equals(encPassword)) {
1179 return true;
1180 }
1181 }
1182
1183 password = PwdEncryptor.encrypt(password);
1184
1185 if (password.equals(encPassword)) {
1186 return true;
1187 }
1188 }
1189 }
1190 catch (Exception e) {
1191 _log.error(e);
1192 }
1193
1194 return false;
1195 }
1196
1197
1205 public void checkLockout(User user)
1206 throws PortalException, SystemException {
1207
1208 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1209 return;
1210 }
1211
1212 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1213
1214 if (passwordPolicy.isLockout()) {
1215
1216
1217
1218 Date now = new Date();
1219 int failedLoginAttempts = user.getFailedLoginAttempts();
1220
1221 if (failedLoginAttempts > 0) {
1222 long failedLoginTime = user.getLastFailedLoginDate().getTime();
1223 long elapsedTime = now.getTime() - failedLoginTime;
1224 long requiredElapsedTime =
1225 passwordPolicy.getResetFailureCount() * 1000;
1226
1227 if ((requiredElapsedTime != 0) &&
1228 (elapsedTime > requiredElapsedTime)) {
1229
1230 user.setLastFailedLoginDate(null);
1231 user.setFailedLoginAttempts(0);
1232
1233 userPersistence.update(user, false);
1234 }
1235 }
1236
1237
1238
1239 if (user.isLockout()) {
1240 long lockoutTime = user.getLockoutDate().getTime();
1241 long elapsedTime = now.getTime() - lockoutTime;
1242 long requiredElapsedTime =
1243 passwordPolicy.getLockoutDuration() * 1000;
1244
1245 if ((requiredElapsedTime != 0) &&
1246 (elapsedTime > requiredElapsedTime)) {
1247
1248 user.setLockout(false);
1249 user.setLockoutDate(null);
1250
1251 userPersistence.update(user, false);
1252 }
1253 }
1254
1255 if (user.isLockout()) {
1256 throw new UserLockoutException();
1257 }
1258 }
1259 }
1260
1261
1268 public void checkLoginFailure(User user) throws SystemException {
1269 Date now = new Date();
1270
1271 int failedLoginAttempts = user.getFailedLoginAttempts();
1272
1273 user.setLastFailedLoginDate(now);
1274 user.setFailedLoginAttempts(++failedLoginAttempts);
1275
1276 userPersistence.update(user, false);
1277 }
1278
1279
1289 public void checkLoginFailureByEmailAddress(
1290 long companyId, String emailAddress)
1291 throws PortalException, SystemException {
1292
1293 User user = getUserByEmailAddress(companyId, emailAddress);
1294
1295 checkLoginFailure(user);
1296 }
1297
1298
1306 public void checkLoginFailureById(long userId)
1307 throws PortalException, SystemException {
1308
1309 User user = userPersistence.findByPrimaryKey(userId);
1310
1311 checkLoginFailure(user);
1312 }
1313
1314
1323 public void checkLoginFailureByScreenName(long companyId, String screenName)
1324 throws PortalException, SystemException {
1325
1326 User user = getUserByScreenName(companyId, screenName);
1327
1328 checkLoginFailure(user);
1329 }
1330
1331
1341 public void checkPasswordExpired(User user)
1342 throws PortalException, SystemException {
1343
1344 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1345 return;
1346 }
1347
1348 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1349
1350
1351
1352 if (isPasswordExpired(user)) {
1353 int graceLoginCount = user.getGraceLoginCount();
1354
1355 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
1356 user.setGraceLoginCount(++graceLoginCount);
1357
1358 userPersistence.update(user, false);
1359 }
1360 else {
1361 user.setDigest(StringPool.BLANK);
1362
1363 userPersistence.update(user, false);
1364
1365 throw new PasswordExpiredException();
1366 }
1367 }
1368
1369
1370
1371 if (isPasswordExpiringSoon(user)) {
1372 user.setPasswordReset(true);
1373
1374 userPersistence.update(user, false);
1375 }
1376
1377
1378
1379 if (passwordPolicy.isChangeable() &&
1380 passwordPolicy.isChangeRequired()) {
1381
1382 if ((user.getLastLoginDate() == null)) {
1383 user.setPasswordReset(true);
1384
1385 userPersistence.update(user, false);
1386 }
1387 }
1388 }
1389
1390
1396 public void clearOrganizationUsers(long organizationId)
1397 throws SystemException {
1398
1399 organizationPersistence.clearUsers(organizationId);
1400
1401 PermissionCacheUtil.clearCache();
1402 }
1403
1404
1410 public void clearUserGroupUsers(long userGroupId) throws SystemException {
1411 userGroupPersistence.clearUsers(userGroupId);
1412
1413 PermissionCacheUtil.clearCache();
1414 }
1415
1416
1428 public void completeUserRegistration(
1429 User user, ServiceContext serviceContext)
1430 throws PortalException, SystemException {
1431
1432 boolean autoPassword = GetterUtil.getBoolean(
1433 serviceContext.getAttribute("autoPassword"));
1434
1435 String password = null;
1436
1437 if (autoPassword) {
1438 PasswordPolicy passwordPolicy =
1439 passwordPolicyLocalService.getPasswordPolicy(
1440 user.getCompanyId(), user.getOrganizationIds());
1441
1442 password = PwdToolkitUtil.generate(passwordPolicy);
1443
1444 user.setPassword(PwdEncryptor.encrypt(password));
1445 user.setPasswordEncrypted(true);
1446 user.setPasswordUnencrypted(password);
1447
1448 userPersistence.update(user, false);
1449
1450 }
1451
1452 if (user.hasCompanyMx()) {
1453 String mailPassword = password;
1454
1455 if (Validator.isNull(mailPassword)) {
1456 mailPassword = user.getPasswordUnencrypted();
1457 }
1458
1459 mailService.addUser(
1460 user.getCompanyId(), user.getUserId(), mailPassword,
1461 user.getFirstName(), user.getMiddleName(),
1462 user.getLastName(), user.getEmailAddress());
1463 }
1464
1465 boolean sendEmail = GetterUtil.getBoolean(
1466 serviceContext.getAttribute("sendEmail"));
1467
1468 if (sendEmail) {
1469 sendEmail(user, password, serviceContext);
1470 }
1471
1472 Company company = companyPersistence.findByPrimaryKey(
1473 user.getCompanyId());
1474
1475 if (company.isStrangersVerify() && (serviceContext.getPlid() > 0)) {
1476 sendEmailAddressVerification(
1477 user, user.getEmailAddress(), serviceContext);
1478 }
1479 }
1480
1481
1494 public KeyValuePair decryptUserId(
1495 long companyId, String name, String password)
1496 throws PortalException, SystemException {
1497
1498 Company company = companyPersistence.findByPrimaryKey(companyId);
1499
1500 try {
1501 name = Encryptor.decrypt(company.getKeyObj(), name);
1502 }
1503 catch (EncryptorException ee) {
1504 throw new SystemException(ee);
1505 }
1506
1507 long userId = GetterUtil.getLong(name);
1508
1509 User user = userPersistence.findByPrimaryKey(userId);
1510
1511 try {
1512 password = Encryptor.decrypt(company.getKeyObj(), password);
1513 }
1514 catch (EncryptorException ee) {
1515 throw new SystemException(ee);
1516 }
1517
1518 String encPassword = PwdEncryptor.encrypt(password);
1519
1520 if (user.getPassword().equals(encPassword)) {
1521 if (isPasswordExpired(user)) {
1522 user.setPasswordReset(true);
1523
1524 userPersistence.update(user, false);
1525 }
1526
1527 return new KeyValuePair(name, password);
1528 }
1529 else {
1530 throw new PrincipalException();
1531 }
1532 }
1533
1534
1542 public void deletePortrait(long userId)
1543 throws PortalException, SystemException {
1544
1545 User user = userPersistence.findByPrimaryKey(userId);
1546
1547 long portraitId = user.getPortraitId();
1548
1549 if (portraitId > 0) {
1550 user.setPortraitId(0);
1551
1552 userPersistence.update(user, false);
1553
1554 imageLocalService.deleteImage(portraitId);
1555 }
1556 }
1557
1558
1567 public void deleteRoleUser(long roleId, long userId)
1568 throws PortalException, SystemException {
1569
1570 rolePersistence.removeUser(roleId, userId);
1571
1572 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1573
1574 indexer.reindex(userId);
1575
1576 PermissionCacheUtil.clearCache();
1577 }
1578
1579
1586 @Override
1587 public void deleteUser(long userId)
1588 throws PortalException, SystemException {
1589
1590 User user = userPersistence.findByPrimaryKey(userId);
1591
1592 deleteUser(user);
1593 }
1594
1595
1602 @Override
1603 public void deleteUser(User user) throws PortalException, SystemException {
1604 if (!PropsValues.USERS_DELETE) {
1605 throw new RequiredUserException();
1606 }
1607
1608
1609
1610 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1611
1612 indexer.delete(user);
1613
1614
1615
1616 browserTrackerLocalService.deleteUserBrowserTracker(user.getUserId());
1617
1618
1619
1620 Group group = user.getGroup();
1621
1622 if (group != null) {
1623 groupLocalService.deleteGroup(group);
1624 }
1625
1626
1627
1628 imageLocalService.deleteImage(user.getPortraitId());
1629
1630
1631
1632 passwordPolicyRelLocalService.deletePasswordPolicyRel(
1633 User.class.getName(), user.getUserId());
1634
1635
1636
1637 passwordTrackerLocalService.deletePasswordTrackers(user.getUserId());
1638
1639
1640
1641 subscriptionLocalService.deleteSubscriptions(user.getUserId());
1642
1643
1644
1645 userIdMapperLocalService.deleteUserIdMappers(user.getUserId());
1646
1647
1648
1649 announcementsDeliveryLocalService.deleteDeliveries(user.getUserId());
1650
1651
1652
1653 assetEntryLocalService.deleteEntry(
1654 User.class.getName(), user.getUserId());
1655
1656
1657
1658 blogsStatsUserLocalService.deleteStatsUserByUserId(user.getUserId());
1659
1660
1661
1662 dlFileRankLocalService.deleteFileRanksByUserId(user.getUserId());
1663
1664
1665
1666 expandoValueLocalService.deleteValues(
1667 User.class.getName(), user.getUserId());
1668
1669
1670
1671 mbBanLocalService.deleteBansByBanUserId(user.getUserId());
1672 mbStatsUserLocalService.deleteStatsUsersByUserId(user.getUserId());
1673 mbThreadFlagLocalService.deleteThreadFlagsByUserId(user.getUserId());
1674
1675
1676
1677 membershipRequestLocalService.deleteMembershipRequestsByUserId(
1678 user.getUserId());
1679
1680
1681
1682 shoppingCartLocalService.deleteUserCarts(user.getUserId());
1683
1684
1685
1686 socialActivityLocalService.deleteUserActivities(user.getUserId());
1687 socialRequestLocalService.deleteReceiverUserRequests(user.getUserId());
1688 socialRequestLocalService.deleteUserRequests(user.getUserId());
1689
1690
1691
1692 mailService.deleteUser(user.getCompanyId(), user.getUserId());
1693
1694
1695
1696 try {
1697 contactLocalService.deleteContact(user.getContactId());
1698 }
1699 catch (NoSuchContactException nsce) {
1700 }
1701
1702
1703
1704 resourceLocalService.deleteResource(
1705 user.getCompanyId(), User.class.getName(),
1706 ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
1707
1708
1709
1710 userGroupRoleLocalService.deleteUserGroupRolesByUserId(
1711 user.getUserId());
1712
1713
1714
1715 userPersistence.remove(user);
1716
1717
1718
1719 PermissionCacheUtil.clearCache();
1720
1721
1722
1723 workflowInstanceLinkLocalService.deleteWorkflowInstanceLinks(
1724 user.getCompanyId(), 0, User.class.getName(), user.getUserId());
1725 }
1726
1727
1735 public void deleteUserGroupUser(long userGroupId, long userId)
1736 throws PortalException, SystemException {
1737
1738 userGroupPersistence.removeUser(userGroupId, userId);
1739
1740 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1741
1742 indexer.reindex(userId);
1743
1744 PermissionCacheUtil.clearCache();
1745 }
1746
1747
1756 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1757 public String encryptUserId(String name)
1758 throws PortalException, SystemException {
1759
1760 long userId = GetterUtil.getLong(name);
1761
1762 User user = userPersistence.findByPrimaryKey(userId);
1763
1764 Company company = companyPersistence.findByPrimaryKey(
1765 user.getCompanyId());
1766
1767 try {
1768 return Encryptor.encrypt(company.getKeyObj(), name);
1769 }
1770 catch (EncryptorException ee) {
1771 throw new SystemException(ee);
1772 }
1773 }
1774
1775
1784 public User fetchUserByScreenName(long companyId, String screenName)
1785 throws SystemException {
1786
1787 screenName = getScreenName(screenName);
1788
1789 return userPersistence.fetchByC_SN(companyId, screenName);
1790 }
1791
1792
1800 public User fetchUserById(long userId) throws SystemException {
1801 return userPersistence.fetchByPrimaryKey(userId);
1802 }
1803
1804
1823 public List<User> getCompanyUsers(long companyId, int start, int end)
1824 throws SystemException {
1825
1826 return userPersistence.findByCompanyId(companyId, start, end);
1827 }
1828
1829
1836 public int getCompanyUsersCount(long companyId) throws SystemException {
1837 return userPersistence.countByCompanyId(companyId);
1838 }
1839
1840
1849 @Skip
1850 public User getDefaultUser(long companyId)
1851 throws PortalException, SystemException {
1852
1853 User userModel = _defaultUsers.get(companyId);
1854
1855 if (userModel == null) {
1856 userModel = userLocalService.loadGetDefaultUser(companyId);
1857
1858 _defaultUsers.put(companyId, userModel);
1859 }
1860
1861 return userModel;
1862 }
1863
1864
1873 @Skip
1874 public long getDefaultUserId(long companyId)
1875 throws PortalException, SystemException {
1876
1877 User user = getDefaultUser(companyId);
1878
1879 return user.getUserId();
1880 }
1881
1882
1889 public long[] getGroupUserIds(long groupId) throws SystemException {
1890 return getUserIds(getGroupUsers(groupId));
1891 }
1892
1893
1900 public List<User> getGroupUsers(long groupId) throws SystemException {
1901 return groupPersistence.getUsers(groupId);
1902 }
1903
1904
1911 public int getGroupUsersCount(long groupId) throws SystemException {
1912 return groupPersistence.getUsersSize(groupId);
1913 }
1914
1915
1925 public int getGroupUsersCount(long groupId, int status)
1926 throws PortalException, SystemException {
1927
1928 Group group = groupPersistence.findByPrimaryKey(groupId);
1929
1930 LinkedHashMap<String, Object> params =
1931 new LinkedHashMap<String, Object>();
1932
1933 params.put("usersGroups", new Long(groupId));
1934
1935 return searchCount(group.getCompanyId(), null, status, params);
1936 }
1937
1938
1946 public List<User> getNoAnnouncementsDeliveries(String type)
1947 throws SystemException {
1948
1949 return userFinder.findByNoAnnouncementsDeliveries(type);
1950 }
1951
1952
1958 public List<User> getNoContacts() throws SystemException {
1959 return userFinder.findByNoContacts();
1960 }
1961
1962
1969 public List<User> getNoGroups() throws SystemException {
1970 return userFinder.findByNoGroups();
1971 }
1972
1973
1980 public long[] getOrganizationUserIds(long organizationId)
1981 throws SystemException {
1982
1983 return getUserIds(getOrganizationUsers(organizationId));
1984 }
1985
1986
1993 public List<User> getOrganizationUsers(long organizationId)
1994 throws SystemException {
1995
1996 return organizationPersistence.getUsers(organizationId);
1997 }
1998
1999
2006 public int getOrganizationUsersCount(long organizationId)
2007 throws SystemException {
2008
2009 return organizationPersistence.getUsersSize(organizationId);
2010 }
2011
2012
2023 public int getOrganizationUsersCount(long organizationId, int status)
2024 throws PortalException, SystemException {
2025
2026 Organization organization = organizationPersistence.findByPrimaryKey(
2027 organizationId);
2028
2029 LinkedHashMap<String, Object> params =
2030 new LinkedHashMap<String, Object>();
2031
2032 params.put("usersOrgs", new Long(organizationId));
2033
2034 return searchCount(organization.getCompanyId(), null, status, params);
2035 }
2036
2037
2044 public long[] getRoleUserIds(long roleId) throws SystemException {
2045 return getUserIds(getRoleUsers(roleId));
2046 }
2047
2048
2055 public List<User> getRoleUsers(long roleId) throws SystemException {
2056 return rolePersistence.getUsers(roleId);
2057 }
2058
2059
2078 public List<User> getRoleUsers(long roleId, int start, int end)
2079 throws SystemException {
2080
2081 return rolePersistence.getUsers(roleId, start, end);
2082 }
2083
2084
2091 public int getRoleUsersCount(long roleId) throws SystemException {
2092 return rolePersistence.getUsersSize(roleId);
2093 }
2094
2095
2105 public int getRoleUsersCount(long roleId, int status)
2106 throws PortalException, SystemException {
2107
2108 Role role = rolePersistence.findByPrimaryKey(roleId);
2109
2110 LinkedHashMap<String, Object> params =
2111 new LinkedHashMap<String, Object>();
2112
2113 params.put("usersRoles", new Long(roleId));
2114
2115 return searchCount(role.getCompanyId(), null, status, params);
2116 }
2117
2118
2145 public List<User> getSocialUsers(
2146 long userId, int type, int start, int end, OrderByComparator obc)
2147 throws PortalException, SystemException {
2148
2149 User user = userPersistence.findByPrimaryKey(userId);
2150
2151 LinkedHashMap<String, Object> params =
2152 new LinkedHashMap<String, Object>();
2153
2154 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2155
2156 return search(
2157 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2158 params, start, end, obc);
2159 }
2160
2161
2184 public List<User> getSocialUsers(
2185 long userId, int start, int end, OrderByComparator obc)
2186 throws PortalException, SystemException {
2187
2188 User user = userPersistence.findByPrimaryKey(userId);
2189
2190 LinkedHashMap<String, Object> params =
2191 new LinkedHashMap<String, Object>();
2192
2193 params.put("socialRelation", new Long[] {userId});
2194
2195 return search(
2196 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2197 params, start, end, obc);
2198 }
2199
2200
2228 public List<User> getSocialUsers(
2229 long userId1, long userId2, int type, int start, int end,
2230 OrderByComparator obc)
2231 throws PortalException, SystemException {
2232
2233 User user1 = userPersistence.findByPrimaryKey(userId1);
2234
2235 LinkedHashMap<String, Object> params =
2236 new LinkedHashMap<String, Object>();
2237
2238 params.put(
2239 "socialMutualRelationType",
2240 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2241
2242 return search(
2243 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2244 params, start, end, obc);
2245 }
2246
2247
2272 public List<User> getSocialUsers(
2273 long userId1, long userId2, int start, int end,
2274 OrderByComparator obc)
2275 throws PortalException, SystemException {
2276
2277 User user1 = userPersistence.findByPrimaryKey(userId1);
2278
2279 LinkedHashMap<String, Object> params =
2280 new LinkedHashMap<String, Object>();
2281
2282 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2283
2284 return search(
2285 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2286 params, start, end, obc);
2287 }
2288
2289
2297 public int getSocialUsersCount(long userId)
2298 throws PortalException, SystemException {
2299
2300 User user = userPersistence.findByPrimaryKey(userId);
2301
2302 LinkedHashMap<String, Object> params =
2303 new LinkedHashMap<String, Object>();
2304
2305 params.put("socialRelation", new Long[] {userId});
2306
2307 return searchCount(user.getCompanyId(), null,
2308 WorkflowConstants.STATUS_APPROVED, params);
2309 }
2310
2311
2324 public int getSocialUsersCount(long userId, int type)
2325 throws PortalException, SystemException {
2326
2327 User user = userPersistence.findByPrimaryKey(userId);
2328
2329 LinkedHashMap<String, Object> params =
2330 new LinkedHashMap<String, Object>();
2331
2332 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2333
2334 return searchCount(user.getCompanyId(), null,
2335 WorkflowConstants.STATUS_APPROVED, params);
2336 }
2337
2338
2348 public int getSocialUsersCount(long userId1, long userId2)
2349 throws PortalException, SystemException {
2350
2351 User user1 = userPersistence.findByPrimaryKey(userId1);
2352
2353 LinkedHashMap<String, Object> params =
2354 new LinkedHashMap<String, Object>();
2355
2356 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2357
2358 return searchCount(user1.getCompanyId(), null,
2359 WorkflowConstants.STATUS_APPROVED, params);
2360 }
2361
2362
2376 public int getSocialUsersCount(long userId1, long userId2, int type)
2377 throws PortalException, SystemException {
2378
2379 User user1 = userPersistence.findByPrimaryKey(userId1);
2380
2381 LinkedHashMap<String, Object> params =
2382 new LinkedHashMap<String, Object>();
2383
2384 params.put(
2385 "socialMutualRelationType",
2386 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2387
2388 return searchCount(user1.getCompanyId(), null,
2389 WorkflowConstants.STATUS_APPROVED, params);
2390 }
2391
2392
2400 public User getUserByContactId(long contactId)
2401 throws PortalException, SystemException {
2402
2403 return userPersistence.findByContactId(contactId);
2404 }
2405
2406
2416 public User getUserByEmailAddress(long companyId, String emailAddress)
2417 throws PortalException, SystemException {
2418
2419 emailAddress = emailAddress.trim().toLowerCase();
2420
2421 return userPersistence.findByC_EA(companyId, emailAddress);
2422 }
2423
2424
2433 public User getUserByFacebookId(long companyId, long facebookId)
2434 throws PortalException, SystemException {
2435
2436 return userPersistence.findByC_FID(companyId, facebookId);
2437 }
2438
2439
2447 public User getUserById(long userId)
2448 throws PortalException, SystemException {
2449
2450 return userPersistence.findByPrimaryKey(userId);
2451 }
2452
2453
2463 public User getUserById(long companyId, long userId)
2464 throws PortalException, SystemException {
2465
2466 return userPersistence.findByC_U(companyId, userId);
2467 }
2468
2469
2478 public User getUserByOpenId(long companyId, String openId)
2479 throws PortalException, SystemException {
2480
2481 return userPersistence.findByC_O(companyId, openId);
2482 }
2483
2484
2492 public User getUserByPortraitId(long portraitId)
2493 throws PortalException, SystemException {
2494
2495 return userPersistence.findByPortraitId(portraitId);
2496 }
2497
2498
2507 public User getUserByScreenName(long companyId, String screenName)
2508 throws PortalException, SystemException {
2509
2510 screenName = getScreenName(screenName);
2511
2512 return userPersistence.findByC_SN(companyId, screenName);
2513 }
2514
2515
2524 public User getUserByUuid(String uuid)
2525 throws PortalException, SystemException {
2526
2527 List<User> users = userPersistence.findByUuid(uuid);
2528
2529 if (users.isEmpty()) {
2530 throw new NoSuchUserException();
2531 }
2532 else {
2533 return users.get(0);
2534 }
2535 }
2536
2537
2544 public List<User> getUserGroupUsers(long userGroupId)
2545 throws SystemException {
2546
2547 return userGroupPersistence.getUsers(userGroupId);
2548 }
2549
2550
2557 public int getUserGroupUsersCount(long userGroupId) throws SystemException {
2558 return userGroupPersistence.getUsersSize(userGroupId);
2559 }
2560
2561
2571 public int getUserGroupUsersCount(long userGroupId, int status)
2572 throws PortalException, SystemException {
2573
2574 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
2575 userGroupId);
2576
2577 LinkedHashMap<String, Object> params =
2578 new LinkedHashMap<String, Object>();
2579
2580 params.put("usersUserGroups", new Long(userGroupId));
2581
2582 return searchCount(userGroup.getCompanyId(), null, status, params);
2583 }
2584
2585
2595 public long getUserIdByEmailAddress(long companyId, String emailAddress)
2596 throws PortalException, SystemException {
2597
2598 emailAddress = emailAddress.trim().toLowerCase();
2599
2600 User user = userPersistence.findByC_EA(companyId, emailAddress);
2601
2602 return user.getUserId();
2603 }
2604
2605
2614 public long getUserIdByScreenName(long companyId, String screenName)
2615 throws PortalException, SystemException {
2616
2617 screenName = getScreenName(screenName);
2618
2619 User user = userPersistence.findByC_SN(companyId, screenName);
2620
2621 return user.getUserId();
2622 }
2623
2624
2633 public boolean hasGroupUser(long groupId, long userId)
2634 throws SystemException {
2635
2636 return groupPersistence.containsUser(groupId, userId);
2637 }
2638
2639
2648 public boolean hasOrganizationUser(long organizationId, long userId)
2649 throws SystemException {
2650
2651 return organizationPersistence.containsUser(organizationId, userId);
2652 }
2653
2654
2664 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
2665 throws SystemException {
2666
2667 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
2668 passwordPolicyId, User.class.getName(), userId);
2669 }
2670
2671
2680 public boolean hasRoleUser(long roleId, long userId)
2681 throws SystemException {
2682
2683 return rolePersistence.containsUser(roleId, userId);
2684 }
2685
2686
2701 public boolean hasRoleUser(
2702 long companyId, String name, long userId, boolean inherited)
2703 throws PortalException, SystemException {
2704
2705 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
2706 }
2707
2708
2717 public boolean hasTeamUser(long teamId, long userId)
2718 throws SystemException {
2719
2720 return teamPersistence.containsUser(teamId, userId);
2721 }
2722
2723
2732 public boolean hasUserGroupUser(long userGroupId, long userId)
2733 throws SystemException {
2734
2735 return userGroupPersistence.containsUser(userGroupId, userId);
2736 }
2737
2738
2748 public boolean isPasswordExpired(User user)
2749 throws PortalException, SystemException {
2750
2751 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2752
2753 if (passwordPolicy.getExpireable()) {
2754 Date now = new Date();
2755
2756 if (user.getPasswordModifiedDate() == null) {
2757 user.setPasswordModifiedDate(now);
2758
2759 userLocalService.updateUser(user, false);
2760 }
2761
2762 long passwordStartTime = user.getPasswordModifiedDate().getTime();
2763 long elapsedTime = now.getTime() - passwordStartTime;
2764
2765 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
2766 return true;
2767 }
2768 else {
2769 return false;
2770 }
2771 }
2772
2773 return false;
2774 }
2775
2776
2786 public boolean isPasswordExpiringSoon(User user)
2787 throws PortalException, SystemException {
2788
2789 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2790
2791 if (passwordPolicy.isExpireable()) {
2792 Date now = new Date();
2793
2794 if (user.getPasswordModifiedDate() == null) {
2795 user.setPasswordModifiedDate(now);
2796
2797 userLocalService.updateUser(user, false);
2798 }
2799
2800 long timeModified = user.getPasswordModifiedDate().getTime();
2801 long passwordExpiresOn =
2802 (passwordPolicy.getMaxAge() * 1000) + timeModified;
2803
2804 long timeStartWarning =
2805 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
2806
2807 if (now.getTime() > timeStartWarning) {
2808 return true;
2809 }
2810 else {
2811 return false;
2812 }
2813 }
2814
2815 return false;
2816 }
2817
2818 public User loadGetDefaultUser(long companyId)
2819 throws PortalException, SystemException {
2820
2821 return userPersistence.findByC_DU(companyId, true);
2822 }
2823
2824
2863 public User updateIncompleteUser(
2864 long creatorUserId, long companyId, boolean autoPassword,
2865 String password1, String password2, boolean autoScreenName,
2866 String screenName, String emailAddress, long facebookId,
2867 String openId, Locale locale, String firstName, String middleName,
2868 String lastName, int prefixId, int suffixId, boolean male,
2869 int birthdayMonth, int birthdayDay, int birthdayYear,
2870 String jobTitle, boolean updateUserInformation, boolean sendEmail,
2871 ServiceContext serviceContext)
2872 throws PortalException, SystemException {
2873
2874 User user = getUserByEmailAddress(companyId, emailAddress);
2875
2876 if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
2877 throw new PortalException("Invalid user status");
2878 }
2879
2880 User defaultUser = getDefaultUser(companyId);
2881
2882 if (updateUserInformation) {
2883 autoScreenName = false;
2884
2885 if (PrefsPropsUtil.getBoolean(
2886 companyId,
2887 PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
2888
2889 autoScreenName = true;
2890 }
2891
2892 validate(
2893 companyId, user.getUserId(), autoPassword, password1, password2,
2894 autoScreenName, screenName, emailAddress, firstName, middleName,
2895 lastName, null);
2896
2897 if (!autoPassword) {
2898 if (Validator.isNull(password1) ||
2899 Validator.isNull(password2)) {
2900 throw new UserPasswordException(
2901 UserPasswordException.PASSWORD_INVALID);
2902 }
2903 }
2904
2905 if (autoScreenName) {
2906 ScreenNameGenerator screenNameGenerator =
2907 ScreenNameGeneratorFactory.getInstance();
2908
2909 try {
2910 screenName = screenNameGenerator.generate(
2911 companyId, user.getUserId(), emailAddress);
2912 }
2913 catch (Exception e) {
2914 throw new SystemException(e);
2915 }
2916 }
2917
2918 FullNameGenerator fullNameGenerator =
2919 FullNameGeneratorFactory.getInstance();
2920
2921 String fullName = fullNameGenerator.getFullName(
2922 firstName, middleName, lastName);
2923
2924 String greeting = LanguageUtil.format(
2925 locale, "welcome-x", " " + fullName, false);
2926
2927 if (Validator.isNotNull(password1)) {
2928 user.setPassword(PwdEncryptor.encrypt(password1));
2929 user.setPasswordUnencrypted(password1);
2930 }
2931
2932 user.setPasswordEncrypted(true);
2933
2934 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
2935
2936 if (passwordPolicy.isChangeable() &&
2937 passwordPolicy.isChangeRequired()) {
2938
2939 user.setPasswordReset(true);
2940 }
2941 else {
2942 user.setPasswordReset(false);
2943 }
2944
2945 user.setScreenName(screenName);
2946 user.setFacebookId(facebookId);
2947 user.setOpenId(openId);
2948 user.setLanguageId(locale.toString());
2949 user.setTimeZoneId(defaultUser.getTimeZoneId());
2950 user.setGreeting(greeting);
2951 user.setFirstName(firstName);
2952 user.setMiddleName(middleName);
2953 user.setLastName(lastName);
2954 user.setJobTitle(jobTitle);
2955
2956 Date birthday = PortalUtil.getDate(
2957 birthdayMonth, birthdayDay, birthdayYear,
2958 new ContactBirthdayException());
2959
2960 Contact contact = user.getContact();
2961
2962 contact.setFirstName(firstName);
2963 contact.setMiddleName(middleName);
2964 contact.setLastName(lastName);
2965 contact.setPrefixId(prefixId);
2966 contact.setSuffixId(suffixId);
2967 contact.setMale(male);
2968 contact.setBirthday(birthday);
2969 contact.setJobTitle(jobTitle);
2970
2971 contactPersistence.update(contact, false, serviceContext);
2972
2973
2974
2975 user.setExpandoBridgeAttributes(serviceContext);
2976
2977
2978
2979 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
2980
2981 indexer.reindex(user);
2982 }
2983
2984 user.setStatus(WorkflowConstants.STATUS_DRAFT);
2985
2986 userPersistence.update(user, false, serviceContext);
2987
2988
2989
2990 long workflowUserId = creatorUserId;
2991
2992 if (workflowUserId == user.getUserId()) {
2993 workflowUserId = defaultUser.getUserId();
2994 }
2995
2996 serviceContext.setAttribute("autoPassword", autoPassword);
2997 serviceContext.setAttribute("sendEmail", sendEmail);
2998
2999 WorkflowHandlerRegistryUtil.startWorkflowInstance(
3000 companyId, workflowUserId, User.class.getName(), user.getUserId(),
3001 user, serviceContext);
3002
3003 return getUserByEmailAddress(companyId, emailAddress);
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 params.put("keywords", keywords);
3115
3116 return search(
3117 companyId, firstName, middleName, lastName, fullName, screenName,
3118 emailAddress, street, city, zip, region, country, status, params,
3119 andOperator, start, end, sort);
3120 }
3121
3122
3162 public List<User> search(
3163 long companyId, String firstName, String middleName,
3164 String lastName, String screenName, String emailAddress,
3165 int status, LinkedHashMap<String, Object> params,
3166 boolean andSearch, int start, int end, OrderByComparator obc)
3167 throws SystemException {
3168
3169 return userFinder.findByC_FN_MN_LN_SN_EA_S(
3170 companyId, firstName, middleName, lastName, screenName,
3171 emailAddress, status, params, andSearch, start, end, obc);
3172 }
3173
3174
3213 public Hits search(
3214 long companyId, String firstName, String middleName,
3215 String lastName, String screenName, String emailAddress,
3216 int status, LinkedHashMap<String, Object> params,
3217 boolean andSearch, int start, int end, Sort sort)
3218 throws SystemException {
3219
3220 return search(
3221 companyId, firstName, middleName, lastName, null, screenName,
3222 emailAddress, null, null, null, null, null, status, params,
3223 andSearch, start, end, sort);
3224 }
3225
3226
3240 public int searchCount(
3241 long companyId, String keywords, int status,
3242 LinkedHashMap<String, Object> params)
3243 throws SystemException {
3244
3245 return userFinder.countByKeywords(companyId, keywords, status, params);
3246 }
3247
3248
3270 public int searchCount(
3271 long companyId, String firstName, String middleName,
3272 String lastName, String screenName, String emailAddress,
3273 int status, LinkedHashMap<String, Object> params,
3274 boolean andSearch)
3275 throws SystemException {
3276
3277 return userFinder.countByC_FN_MN_LN_SN_EA_S(
3278 companyId, firstName, middleName, lastName, screenName,
3279 emailAddress, status, params, andSearch);
3280 }
3281
3282
3293 public void sendEmailAddressVerification(
3294 User user, String emailAddress, ServiceContext serviceContext)
3295 throws PortalException, SystemException {
3296
3297 if (user.isEmailAddressVerified() &&
3298 emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
3299
3300 return;
3301 }
3302
3303 Ticket ticket = ticketLocalService.addTicket(
3304 user.getCompanyId(), User.class.getName(), user.getUserId(),
3305 TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3306 serviceContext);
3307
3308 String verifyEmailAddressURL =
3309 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3310 "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3311
3312 Layout layout = layoutLocalService.getLayout(serviceContext.getPlid());
3313
3314 Group group = layout.getGroup();
3315
3316 if (!layout.isPrivateLayout() && !group.isUser()) {
3317 verifyEmailAddressURL += "&p_l_id=" + serviceContext.getPlid();
3318 }
3319
3320 String fromName = PrefsPropsUtil.getString(
3321 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3322 String fromAddress = PrefsPropsUtil.getString(
3323 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3324
3325 String toName = user.getFullName();
3326 String toAddress = emailAddress;
3327
3328 String subject = PrefsPropsUtil.getContent(
3329 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3330
3331 String body = PrefsPropsUtil.getContent(
3332 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3333
3334 SubscriptionSender subscriptionSender = new SubscriptionSender();
3335
3336 subscriptionSender.setBody(body);
3337 subscriptionSender.setCompanyId(user.getCompanyId());
3338 subscriptionSender.setContextAttributes(
3339 "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3340 "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3341 "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3342 "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_AGENT$]",
3343 serviceContext.getUserAgent(), "[$USER_ID$]", user.getUserId(),
3344 "[$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 = new Date(
3403 System.currentTimeMillis() +
3404 (passwordPolicy.getResetTicketMaxAge() * 1000));
3405
3406 Ticket ticket = ticketLocalService.addTicket(
3407 companyId, User.class.getName(), user.getUserId(),
3408 TicketConstants.TYPE_PASSWORD, null, expirationDate,
3409 serviceContext);
3410
3411 passwordResetURL =
3412 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3413 "/portal/update_password?p_l_id="+
3414 serviceContext.getPlid() +
3415 "&ticketKey=" + ticket.getKey();
3416 }
3417 else {
3418 if (!PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
3419 PwdEncryptor.TYPE_NONE)) {
3420
3421 newPassword = PwdToolkitUtil.generate(passwordPolicy);
3422
3423 boolean passwordReset = false;
3424
3425 if (passwordPolicy.getChangeable() &&
3426 passwordPolicy.getChangeRequired()) {
3427
3428 passwordReset = true;
3429 }
3430
3431 user.setPassword(PwdEncryptor.encrypt(newPassword));
3432 user.setPasswordUnencrypted(newPassword);
3433 user.setPasswordEncrypted(true);
3434 user.setPasswordReset(passwordReset);
3435 user.setPasswordModified(true);
3436 user.setPasswordModifiedDate(new Date());
3437
3438 userPersistence.update(user, false);
3439
3440 user.setPasswordModified(false);
3441 }
3442 else {
3443 newPassword = user.getPassword();
3444 }
3445 }
3446
3447 if (Validator.isNull(fromName)) {
3448 fromName = PrefsPropsUtil.getString(
3449 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3450 }
3451
3452 if (Validator.isNull(fromAddress)) {
3453 fromAddress = PrefsPropsUtil.getString(
3454 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3455 }
3456
3457 String toName = user.getFullName();
3458 String toAddress = user.getEmailAddress();
3459
3460 if (Validator.isNull(subject)) {
3461 if (company.isSendPasswordResetLink()) {
3462 subject = PrefsPropsUtil.getContent(
3463 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
3464 }
3465 else {
3466 subject = PrefsPropsUtil.getContent(
3467 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
3468 }
3469 }
3470
3471 if (Validator.isNull(body)) {
3472 if (company.isSendPasswordResetLink()) {
3473 body = PrefsPropsUtil.getContent(
3474 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
3475 }
3476 else {
3477 body = PrefsPropsUtil.getContent(
3478 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
3479 }
3480 }
3481
3482 SubscriptionSender subscriptionSender = new SubscriptionSender();
3483
3484 subscriptionSender.setBody(body);
3485 subscriptionSender.setCompanyId(companyId);
3486 subscriptionSender.setContextAttributes(
3487 "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
3488 serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
3489 serviceContext.getRemoteHost(), "[$USER_AGENT$]",
3490 serviceContext.getUserAgent(), "[$USER_ID$]", user.getUserId(),
3491 "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
3492 user.getScreenName());
3493 subscriptionSender.setFrom(fromAddress, fromName);
3494 subscriptionSender.setHtmlFormat(true);
3495 subscriptionSender.setMailId("user", user.getUserId());
3496 subscriptionSender.setServiceContext(serviceContext);
3497 subscriptionSender.setSubject(subject);
3498 subscriptionSender.setUserId(user.getUserId());
3499
3500 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3501
3502 subscriptionSender.flushNotificationsAsync();
3503 }
3504
3505
3514 public void setRoleUsers(long roleId, long[] userIds)
3515 throws PortalException, SystemException {
3516
3517 rolePersistence.setUsers(roleId, userIds);
3518
3519 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3520
3521 indexer.reindex(userIds);
3522
3523 PermissionCacheUtil.clearCache();
3524 }
3525
3526
3535 @SuppressWarnings("deprecation")
3536 public void setUserGroupUsers(long userGroupId, long[] userIds)
3537 throws PortalException, SystemException {
3538
3539 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3540 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3541 }
3542
3543 userGroupPersistence.setUsers(userGroupId, userIds);
3544
3545 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3546
3547 indexer.reindex(userIds);
3548
3549 PermissionCacheUtil.clearCache();
3550 }
3551
3552
3560 public void unsetGroupUsers(
3561 long groupId, long[] userIds, ServiceContext serviceContext)
3562 throws PortalException, SystemException {
3563
3564 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
3565
3566 groupPersistence.removeUsers(groupId, userIds);
3567
3568 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3569
3570 indexer.reindex(userIds);
3571
3572 PermissionCacheUtil.clearCache();
3573 }
3574
3575
3583 public void unsetOrganizationUsers(long organizationId, long[] userIds)
3584 throws PortalException, SystemException {
3585
3586 Organization organization = organizationPersistence.findByPrimaryKey(
3587 organizationId);
3588
3589 Group group = organization.getGroup();
3590
3591 long groupId = group.getGroupId();
3592
3593 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
3594
3595 organizationPersistence.removeUsers(organizationId, userIds);
3596
3597 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3598
3599 indexer.reindex(userIds);
3600
3601 PermissionCacheUtil.clearCache();
3602 }
3603
3604
3611 public void unsetPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
3612 throws SystemException {
3613
3614 passwordPolicyRelLocalService.deletePasswordPolicyRels(
3615 passwordPolicyId, User.class.getName(), userIds);
3616 }
3617
3618
3626 public void unsetRoleUsers(long roleId, List<User> users)
3627 throws PortalException, SystemException {
3628
3629 Role role = rolePersistence.findByPrimaryKey(roleId);
3630
3631 if (role.getName().equals(RoleConstants.USER)) {
3632 return;
3633 }
3634
3635 rolePersistence.removeUsers(roleId, users);
3636
3637 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3638
3639 indexer.reindex(users);
3640
3641 PermissionCacheUtil.clearCache();
3642 }
3643
3644
3652 public void unsetRoleUsers(long roleId, long[] userIds)
3653 throws PortalException, SystemException {
3654
3655 Role role = rolePersistence.findByPrimaryKey(roleId);
3656
3657 if (role.getName().equals(RoleConstants.USER)) {
3658 return;
3659 }
3660
3661 rolePersistence.removeUsers(roleId, userIds);
3662
3663 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3664
3665 indexer.reindex(userIds);
3666
3667 PermissionCacheUtil.clearCache();
3668 }
3669
3670
3678 public void unsetTeamUsers(long teamId, long[] userIds)
3679 throws PortalException, SystemException {
3680
3681 teamPersistence.removeUsers(teamId, userIds);
3682
3683 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3684
3685 indexer.reindex(userIds);
3686
3687 PermissionCacheUtil.clearCache();
3688 }
3689
3690
3698 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
3699 throws PortalException, SystemException {
3700
3701 userGroupPersistence.removeUsers(userGroupId, userIds);
3702
3703 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3704
3705 indexer.reindex(userIds);
3706
3707 PermissionCacheUtil.clearCache();
3708 }
3709
3710
3720 public User updateAgreedToTermsOfUse(
3721 long userId, boolean agreedToTermsOfUse)
3722 throws PortalException, SystemException {
3723
3724 User user = userPersistence.findByPrimaryKey(userId);
3725
3726 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
3727
3728 userPersistence.update(user, false);
3729
3730 return user;
3731 }
3732
3733
3744 public void updateAsset(
3745 long userId, User user, long[] assetCategoryIds,
3746 String[] assetTagNames)
3747 throws PortalException, SystemException {
3748
3749 User owner = userPersistence.findByPrimaryKey(userId);
3750
3751 Company company = companyPersistence.findByPrimaryKey(
3752 owner.getCompanyId());
3753
3754 Group companyGroup = company.getGroup();
3755
3756 assetEntryLocalService.updateEntry(
3757 userId, companyGroup.getGroupId(), User.class.getName(),
3758 user.getUserId(), user.getUuid(), 0, assetCategoryIds,
3759 assetTagNames, false, null, null, null, null, null,
3760 user.getFullName(), null, null, null, null, 0, 0, null, false);
3761 }
3762
3763
3772 public User updateCreateDate(long userId, Date createDate)
3773 throws PortalException, SystemException {
3774
3775 User user = userPersistence.findByPrimaryKey(userId);
3776
3777 user.setCreateDate(createDate);
3778
3779 userPersistence.update(user, false);
3780
3781 return user;
3782 }
3783
3784
3795 public User updateEmailAddress(
3796 long userId, String password, String emailAddress1,
3797 String emailAddress2)
3798 throws PortalException, SystemException {
3799
3800 emailAddress1 = emailAddress1.trim().toLowerCase();
3801 emailAddress2 = emailAddress2.trim().toLowerCase();
3802
3803 User user = userPersistence.findByPrimaryKey(userId);
3804
3805 validateEmailAddress(user, emailAddress1, emailAddress2);
3806
3807 setEmailAddress(
3808 user, password, user.getFirstName(), user.getMiddleName(),
3809 user.getLastName(), emailAddress1);
3810
3811 userPersistence.update(user, false);
3812
3813 return user;
3814 }
3815
3816
3827 public User updateEmailAddress(
3828 long userId, String password, String emailAddress1,
3829 String emailAddress2, ServiceContext serviceContext)
3830 throws PortalException, SystemException {
3831
3832 emailAddress1 = emailAddress1.trim().toLowerCase();
3833 emailAddress2 = emailAddress2.trim().toLowerCase();
3834
3835 User user = userPersistence.findByPrimaryKey(userId);
3836
3837 validateEmailAddress(user, emailAddress1, emailAddress2);
3838
3839 Company company = companyPersistence.findByPrimaryKey(
3840 user.getCompanyId());
3841
3842 if (!company.isStrangersVerify()) {
3843 setEmailAddress(
3844 user, password, user.getFirstName(), user.getMiddleName(),
3845 user.getLastName(), emailAddress1);
3846
3847 userPersistence.update(user, false);
3848 }
3849 else {
3850 sendEmailAddressVerification(user, emailAddress1, serviceContext);
3851 }
3852
3853 return user;
3854 }
3855
3856
3865 public User updateEmailAddressVerified(
3866 long userId, boolean emailAddressVerified)
3867 throws PortalException, SystemException {
3868
3869 User user = userPersistence.findByPrimaryKey(userId);
3870
3871 user.setEmailAddressVerified(emailAddressVerified);
3872
3873 userPersistence.update(user, false);
3874
3875 return user;
3876 }
3877
3878
3887 public User updateFacebookId(long userId, long facebookId)
3888 throws PortalException, SystemException {
3889
3890 User user = userPersistence.findByPrimaryKey(userId);
3891
3892 user.setFacebookId(facebookId);
3893
3894 userPersistence.update(user, false);
3895
3896 return user;
3897 }
3898
3899
3907 public void updateGroups(
3908 long userId, long[] newGroupIds, ServiceContext serviceContext)
3909 throws PortalException, SystemException {
3910
3911 if (newGroupIds == null) {
3912 return;
3913 }
3914
3915 List<Group> oldGroups = userPersistence.getGroups(userId);
3916
3917 List<Long> oldGroupIds = new ArrayList<Long>(oldGroups.size());
3918
3919 for (Group oldGroup : oldGroups) {
3920 long oldGroupId = oldGroup.getGroupId();
3921
3922 oldGroupIds.add(oldGroupId);
3923
3924 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
3925 unsetGroupUsers(
3926 oldGroupId, new long[] {userId}, serviceContext);
3927 }
3928 }
3929
3930 for (long newGroupId : newGroupIds) {
3931 if (!oldGroupIds.contains(newGroupId)) {
3932 addGroupUsers(newGroupId, new long[] {userId});
3933 }
3934 }
3935
3936 if (serviceContext.isIndexingEnabled()) {
3937 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3938
3939 indexer.reindex(new long[] {userId});
3940 }
3941
3942 PermissionCacheUtil.clearCache();
3943 }
3944
3945
3955 public User updateJobTitle(long userId, String jobTitle)
3956 throws PortalException, SystemException {
3957
3958 User user = userPersistence.findByPrimaryKey(userId);
3959
3960 user.setJobTitle(jobTitle);
3961
3962 userPersistence.update(user, false);
3963
3964 Contact contact = contactPersistence.findByPrimaryKey(
3965 user.getContactId());
3966
3967 contact.setJobTitle(jobTitle);
3968
3969 contactPersistence.update(contact, false);
3970
3971 return user;
3972 }
3973
3974
3983 public User updateLastLogin(long userId, String loginIP)
3984 throws PortalException, SystemException {
3985
3986 User user = userPersistence.findByPrimaryKey(userId);
3987
3988 Date lastLoginDate = user.getLoginDate();
3989
3990 if (lastLoginDate == null) {
3991 lastLoginDate = new Date();
3992 }
3993
3994 user.setLoginDate(new Date());
3995 user.setLoginIP(loginIP);
3996 user.setLastLoginDate(lastLoginDate);
3997 user.setLastLoginIP(user.getLoginIP());
3998 user.setLastFailedLoginDate(null);
3999 user.setFailedLoginAttempts(0);
4000
4001 userPersistence.update(user, false);
4002
4003 return user;
4004 }
4005
4006
4015 public User updateLockout(User user, boolean lockout)
4016 throws PortalException, SystemException {
4017
4018 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
4019
4020 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
4021 return user;
4022 }
4023
4024 Date lockoutDate = null;
4025
4026 if (lockout) {
4027 lockoutDate = new Date();
4028 }
4029
4030 user.setLockout(lockout);
4031 user.setLockoutDate(lockoutDate);
4032
4033 if (!lockout) {
4034 user.setLastFailedLoginDate(lockoutDate);
4035 user.setFailedLoginAttempts(0);
4036 }
4037
4038 userPersistence.update(user, false);
4039
4040 return user;
4041 }
4042
4043
4054 public User updateLockoutByEmailAddress(
4055 long companyId, String emailAddress, boolean lockout)
4056 throws PortalException, SystemException {
4057
4058 User user = getUserByEmailAddress(companyId, emailAddress);
4059
4060 return updateLockout(user, lockout);
4061 }
4062
4063
4072 public User updateLockoutById(long userId, boolean lockout)
4073 throws PortalException, SystemException {
4074
4075 User user = userPersistence.findByPrimaryKey(userId);
4076
4077 return updateLockout(user, lockout);
4078 }
4079
4080
4090 public User updateLockoutByScreenName(
4091 long companyId, String screenName, boolean lockout)
4092 throws PortalException, SystemException {
4093
4094 User user = getUserByScreenName(companyId, screenName);
4095
4096 return updateLockout(user, lockout);
4097 }
4098
4099
4108 public User updateModifiedDate(long userId, Date modifiedDate)
4109 throws PortalException, SystemException {
4110
4111 User user = userPersistence.findByPrimaryKey(userId);
4112
4113 user.setModifiedDate(modifiedDate);
4114
4115 userPersistence.update(user, false);
4116
4117 return user;
4118 }
4119
4120
4129 public User updateOpenId(long userId, String openId)
4130 throws PortalException, SystemException {
4131
4132 openId = openId.trim();
4133
4134 User user = userPersistence.findByPrimaryKey(userId);
4135
4136 user.setOpenId(openId);
4137
4138 userPersistence.update(user, false);
4139
4140 return user;
4141 }
4142
4143
4152 public void updateOrganizations(
4153 long userId, long[] newOrganizationIds,
4154 ServiceContext serviceContext)
4155 throws PortalException, SystemException {
4156
4157 if (newOrganizationIds == null) {
4158 return;
4159 }
4160
4161 List<Organization> oldOrganizations = userPersistence.getOrganizations(
4162 userId);
4163
4164 List<Long> oldOrganizationIds = new ArrayList<Long>(
4165 oldOrganizations.size());
4166
4167 for (Organization oldOrganization : oldOrganizations) {
4168 long oldOrganizationId = oldOrganization.getOrganizationId();
4169
4170 oldOrganizationIds.add(oldOrganizationId);
4171
4172 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
4173 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
4174 }
4175 }
4176
4177 for (long newOrganizationId : newOrganizationIds) {
4178 if (!oldOrganizationIds.contains(newOrganizationId)) {
4179 addOrganizationUsers(newOrganizationId, new long[] {userId});
4180 }
4181 }
4182
4183 if (serviceContext.isIndexingEnabled()) {
4184 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
4185
4186 indexer.reindex(new long[] {userId});
4187 }
4188
4189 PermissionCacheUtil.clearCache();
4190 }
4191
4192
4204 public User updatePassword(
4205 long userId, String password1, String password2,
4206 boolean passwordReset)
4207 throws PortalException, SystemException {
4208
4209 return updatePassword(
4210 userId, password1, password2, passwordReset, false);
4211 }
4212
4213
4228 public User updatePassword(
4229 long userId, String password1, String password2,
4230 boolean passwordReset, boolean silentUpdate)
4231 throws PortalException, SystemException {
4232
4233 User user = userPersistence.findByPrimaryKey(userId);
4234
4235 if (!silentUpdate) {
4236 validatePassword(user.getCompanyId(), userId, password1, password2);
4237 }
4238
4239 String oldEncPwd = user.getPassword();
4240
4241 if (!user.isPasswordEncrypted()) {
4242 oldEncPwd = PwdEncryptor.encrypt(user.getPassword());
4243 }
4244
4245 String newEncPwd = PwdEncryptor.encrypt(password1);
4246
4247 if (user.hasCompanyMx()) {
4248 mailService.updatePassword(user.getCompanyId(), userId, password1);
4249 }
4250
4251 user.setPassword(newEncPwd);
4252 user.setPasswordUnencrypted(password1);
4253 user.setPasswordEncrypted(true);
4254 user.setPasswordReset(passwordReset);
4255 user.setPasswordModifiedDate(new Date());
4256 user.setDigest(StringPool.BLANK);
4257 user.setGraceLoginCount(0);
4258
4259 if (!silentUpdate) {
4260 user.setPasswordModified(true);
4261 }
4262
4263 try {
4264 userPersistence.update(user, false);
4265 }
4266 catch (ModelListenerException mle) {
4267 String msg = GetterUtil.getString(mle.getCause().getMessage());
4268
4269 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
4270 String passwordHistory = PrefsPropsUtil.getString(
4271 user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
4272
4273 if (msg.indexOf(passwordHistory) != -1) {
4274 throw new UserPasswordException(
4275 UserPasswordException.PASSWORD_ALREADY_USED);
4276 }
4277 }
4278
4279 throw new UserPasswordException(
4280 UserPasswordException.PASSWORD_INVALID);
4281 }
4282
4283 if (!silentUpdate) {
4284 user.setPasswordModified(false);
4285
4286 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
4287 }
4288
4289 return user;
4290 }
4291
4292
4306 public User updatePasswordManually(
4307 long userId, String password, boolean passwordEncrypted,
4308 boolean passwordReset, Date passwordModifiedDate)
4309 throws PortalException, SystemException {
4310
4311
4312
4313 User user = userPersistence.findByPrimaryKey(userId);
4314
4315 user.setPassword(password);
4316 user.setPasswordEncrypted(passwordEncrypted);
4317 user.setPasswordReset(passwordReset);
4318 user.setPasswordModifiedDate(passwordModifiedDate);
4319 user.setDigest(StringPool.BLANK);
4320
4321 userPersistence.update(user, false);
4322
4323 return user;
4324 }
4325
4326
4337 public User updatePasswordReset(long userId, boolean passwordReset)
4338 throws PortalException, SystemException {
4339
4340 User user = userPersistence.findByPrimaryKey(userId);
4341
4342 user.setPasswordReset(passwordReset);
4343
4344 userPersistence.update(user, false);
4345
4346 return user;
4347 }
4348
4349
4359 public User updatePortrait(long userId, byte[] bytes)
4360 throws PortalException, SystemException {
4361
4362 User user = userPersistence.findByPrimaryKey(userId);
4363
4364 long imageMaxSize = PrefsPropsUtil.getLong(
4365 PropsKeys.USERS_IMAGE_MAX_SIZE);
4366
4367 if ((imageMaxSize > 0) &&
4368 ((bytes == null) || (bytes.length > imageMaxSize))) {
4369
4370 throw new UserPortraitSizeException();
4371 }
4372
4373 long portraitId = user.getPortraitId();
4374
4375 if (portraitId <= 0) {
4376 portraitId = counterLocalService.increment();
4377
4378 user.setPortraitId(portraitId);
4379 }
4380
4381 try {
4382 ImageBag imageBag = ImageProcessorUtil.read(bytes);
4383
4384 RenderedImage renderedImage = imageBag.getRenderedImage();
4385
4386 if (renderedImage == null) {
4387 throw new UserPortraitTypeException();
4388 }
4389
4390 renderedImage = ImageProcessorUtil.scale(
4391 renderedImage, PropsValues.USERS_IMAGE_MAX_HEIGHT,
4392 PropsValues.USERS_IMAGE_MAX_WIDTH);
4393
4394 String contentType = imageBag.getType();
4395
4396 imageLocalService.updateImage(
4397 portraitId,
4398 ImageProcessorUtil.getBytes(renderedImage, contentType));
4399 }
4400 catch (IOException ioe) {
4401 throw new ImageSizeException(ioe);
4402 }
4403
4404 userPersistence.update(user, false);
4405
4406 return user;
4407 }
4408
4409
4420 public User updateReminderQuery(long userId, String question, String answer)
4421 throws PortalException, SystemException {
4422
4423 validateReminderQuery(question, answer) ;
4424
4425 User user = userPersistence.findByPrimaryKey(userId);
4426
4427 user.setReminderQueryQuestion(question);
4428 user.setReminderQueryAnswer(answer);
4429
4430 userPersistence.update(user, false);
4431
4432 return user;
4433 }
4434
4435
4445 public User updateScreenName(long userId, String screenName)
4446 throws PortalException, SystemException {
4447
4448
4449
4450 User user = userPersistence.findByPrimaryKey(userId);
4451
4452 screenName = getScreenName(screenName);
4453
4454 validateScreenName(user.getCompanyId(), userId, screenName);
4455
4456 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
4457 user.setDigest(StringPool.BLANK);
4458 }
4459
4460 user.setScreenName(screenName);
4461
4462 userPersistence.update(user, false);
4463
4464
4465
4466 Group group = groupLocalService.getUserGroup(
4467 user.getCompanyId(), userId);
4468
4469 group.setFriendlyURL(StringPool.SLASH + screenName);
4470
4471 groupPersistence.update(group, false);
4472
4473 return user;
4474 }
4475
4476
4485 public User updateStatus(long userId, int status)
4486 throws PortalException, SystemException {
4487
4488 User user = userPersistence.findByPrimaryKey(userId);
4489
4490 user.setStatus(status);
4491
4492 userPersistence.update(user, false);
4493
4494 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
4495
4496 indexer.reindex(user);
4497
4498 return user;
4499 }
4500
4501
4557 @SuppressWarnings("deprecation")
4558 public User updateUser(
4559 long userId, String oldPassword, String newPassword1,
4560 String newPassword2, boolean passwordReset,
4561 String reminderQueryQuestion, String reminderQueryAnswer,
4562 String screenName, String emailAddress, long facebookId,
4563 String openId, String languageId, String timeZoneId,
4564 String greeting, String comments, String firstName,
4565 String middleName, String lastName, int prefixId, int suffixId,
4566 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
4567 String smsSn, String aimSn, String facebookSn, String icqSn,
4568 String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
4569 String twitterSn, String ymSn, String jobTitle, long[] groupIds,
4570 long[] organizationIds, long[] roleIds,
4571 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
4572 ServiceContext serviceContext)
4573 throws PortalException, SystemException {
4574
4575
4576
4577 User user = userPersistence.findByPrimaryKey(userId);
4578 Company company = companyPersistence.findByPrimaryKey(
4579 user.getCompanyId());
4580 String password = oldPassword;
4581 screenName = getScreenName(screenName);
4582 emailAddress = emailAddress.trim().toLowerCase();
4583 openId = openId.trim();
4584 String oldFullName = user.getFullName();
4585 aimSn = aimSn.trim().toLowerCase();
4586 facebookSn = facebookSn.trim().toLowerCase();
4587 icqSn = icqSn.trim().toLowerCase();
4588 jabberSn = jabberSn.trim().toLowerCase();
4589 msnSn = msnSn.trim().toLowerCase();
4590 mySpaceSn = mySpaceSn.trim().toLowerCase();
4591 skypeSn = skypeSn.trim().toLowerCase();
4592 twitterSn = twitterSn.trim().toLowerCase();
4593 ymSn = ymSn.trim().toLowerCase();
4594 Date now = new Date();
4595
4596 EmailAddressGenerator emailAddressGenerator =
4597 EmailAddressGeneratorFactory.getInstance();
4598
4599 if (emailAddressGenerator.isGenerated(emailAddress)) {
4600 emailAddress = StringPool.BLANK;
4601 }
4602
4603 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
4604 Validator.isNull(emailAddress)) {
4605
4606 emailAddress = emailAddressGenerator.generate(
4607 user.getCompanyId(), userId);
4608 }
4609
4610 validate(
4611 userId, screenName, emailAddress, firstName, middleName, lastName,
4612 smsSn);
4613
4614 if (Validator.isNotNull(newPassword1) ||
4615 Validator.isNotNull(newPassword2)) {
4616
4617 user = updatePassword(
4618 userId, newPassword1, newPassword2, passwordReset);
4619
4620 password = newPassword1;
4621
4622 user.setDigest(StringPool.BLANK);
4623 }
4624
4625 user.setModifiedDate(now);
4626
4627 if (user.getContactId() <= 0) {
4628 user.setContactId(counterLocalService.increment());
4629 }
4630
4631 user.setPasswordReset(passwordReset);
4632
4633 if (Validator.isNotNull(reminderQueryQuestion) &&
4634 Validator.isNotNull(reminderQueryAnswer)) {
4635
4636 user.setReminderQueryQuestion(reminderQueryQuestion);
4637 user.setReminderQueryAnswer(reminderQueryAnswer);
4638 }
4639
4640 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
4641 user.setScreenName(screenName);
4642
4643 user.setDigest(StringPool.BLANK);
4644 }
4645
4646 boolean sendEmailAddressVerification = false;
4647
4648 if (!company.isStrangersVerify()) {
4649 setEmailAddress(
4650 user, password, firstName, middleName, lastName, emailAddress);
4651 }
4652 else {
4653 sendEmailAddressVerification = true;
4654 }
4655
4656 if (serviceContext != null) {
4657 String uuid = serviceContext.getUuid();
4658
4659 if (Validator.isNotNull(uuid)) {
4660 user.setUuid(uuid);
4661 }
4662 }
4663
4664 user.setFacebookId(facebookId);
4665 user.setOpenId(openId);
4666 user.setLanguageId(languageId);
4667 user.setTimeZoneId(timeZoneId);
4668 user.setGreeting(greeting);
4669 user.setComments(comments);
4670 user.setFirstName(firstName);
4671 user.setMiddleName(middleName);
4672 user.setLastName(lastName);
4673 user.setJobTitle(jobTitle);
4674
4675 userPersistence.update(user, false, serviceContext);
4676
4677
4678
4679 Date birthday = PortalUtil.getDate(
4680 birthdayMonth, birthdayDay, birthdayYear,
4681 new ContactBirthdayException());
4682
4683 long contactId = user.getContactId();
4684
4685 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
4686
4687 if (contact == null) {
4688 contact = contactPersistence.create(contactId);
4689
4690 contact.setCompanyId(user.getCompanyId());
4691 contact.setUserName(StringPool.BLANK);
4692 contact.setCreateDate(now);
4693 contact.setAccountId(company.getAccountId());
4694 contact.setParentContactId(
4695 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
4696 }
4697
4698 contact.setModifiedDate(now);
4699 contact.setFirstName(firstName);
4700 contact.setMiddleName(middleName);
4701 contact.setLastName(lastName);
4702 contact.setPrefixId(prefixId);
4703 contact.setSuffixId(suffixId);
4704 contact.setMale(male);
4705 contact.setBirthday(birthday);
4706 contact.setSmsSn(smsSn);
4707 contact.setAimSn(aimSn);
4708 contact.setFacebookSn(facebookSn);
4709 contact.setIcqSn(icqSn);
4710 contact.setJabberSn(jabberSn);
4711 contact.setMsnSn(msnSn);
4712 contact.setMySpaceSn(mySpaceSn);
4713 contact.setSkypeSn(skypeSn);
4714 contact.setTwitterSn(twitterSn);
4715 contact.setYmSn(ymSn);
4716 contact.setJobTitle(jobTitle);
4717
4718 contactPersistence.update(contact, false, serviceContext);
4719
4720
4721
4722 Group group = groupLocalService.getUserGroup(
4723 user.getCompanyId(), userId);
4724
4725 group.setFriendlyURL(StringPool.SLASH + screenName);
4726
4727 groupPersistence.update(group, false);
4728
4729
4730
4731 boolean indexingEnabled = serviceContext.isIndexingEnabled();
4732
4733 serviceContext.setIndexingEnabled(false);
4734
4735 try {
4736 updateGroups(userId, groupIds, serviceContext);
4737 updateOrganizations(userId, organizationIds, serviceContext);
4738 }
4739 finally {
4740 serviceContext.setIndexingEnabled(indexingEnabled);
4741 }
4742
4743
4744
4745 if (roleIds != null) {
4746 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
4747
4748 userPersistence.setRoles(userId, roleIds);
4749 }
4750
4751
4752
4753 updateUserGroupRoles(user, groupIds, organizationIds, userGroupRoles);
4754
4755
4756
4757 if (userGroupIds != null) {
4758 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
4759 userGroupLocalService.copyUserGroupLayouts(
4760 userGroupIds, userId);
4761 }
4762
4763 userPersistence.setUserGroups(userId, userGroupIds);
4764 }
4765
4766
4767
4768 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
4769
4770
4771
4772 if (serviceContext != null) {
4773 updateAsset(
4774 userId, user, serviceContext.getAssetCategoryIds(),
4775 serviceContext.getAssetTagNames());
4776 }
4777
4778
4779
4780 user.setExpandoBridgeAttributes(serviceContext);
4781
4782
4783
4784 if (GetterUtil.getBoolean(
4785 PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
4786 !oldFullName.equals(user.getFullName())) {
4787
4788 mbMessageLocalService.updateUserName(userId, user.getFullName());
4789 }
4790
4791
4792
4793 if (serviceContext.isIndexingEnabled()) {
4794 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
4795
4796 indexer.reindex(user);
4797 }
4798
4799
4800
4801 if (sendEmailAddressVerification) {
4802 sendEmailAddressVerification(user, emailAddress, serviceContext);
4803 }
4804
4805
4806
4807 PermissionCacheUtil.clearCache();
4808
4809 return user;
4810 }
4811
4812
4821 public void verifyEmailAddress(String ticketKey)
4822 throws PortalException, SystemException {
4823
4824 Ticket ticket = ticketLocalService.getTicket(ticketKey);
4825
4826 if (ticket.isExpired() ||
4827 (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
4828
4829 throw new NoSuchTicketException();
4830 }
4831
4832 User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
4833
4834 String emailAddress = ticket.getExtraInfo();
4835
4836 emailAddress = emailAddress.toLowerCase().trim();
4837
4838 if (!emailAddress.equals(user.getEmailAddress())) {
4839 if (userPersistence.fetchByC_EA(
4840 user.getCompanyId(), emailAddress) != null) {
4841
4842 throw new DuplicateUserEmailAddressException();
4843 }
4844
4845 setEmailAddress(
4846 user, StringPool.BLANK, user.getFirstName(),
4847 user.getMiddleName(), user.getLastName(), emailAddress);
4848 }
4849
4850 user.setEmailAddressVerified(true);
4851
4852 userPersistence.update(user, false);
4853
4854 ticketLocalService.deleteTicket(ticket);
4855 }
4856
4857
4903 protected int authenticate(
4904 long companyId, String login, String password, String authType,
4905 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
4906 Map<String, Object> resultsMap)
4907 throws PortalException, SystemException {
4908
4909 if (PropsValues.AUTH_LOGIN_DISABLED) {
4910 return Authenticator.FAILURE;
4911 }
4912
4913 login = login.trim().toLowerCase();
4914
4915 long userId = GetterUtil.getLong(login);
4916
4917
4918
4919 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
4920 if (Validator.isNull(login)) {
4921 throw new UserEmailAddressException();
4922 }
4923 }
4924 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
4925 if (Validator.isNull(login)) {
4926 throw new UserScreenNameException();
4927 }
4928 }
4929 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
4930 if (Validator.isNull(login)) {
4931 throw new UserIdException();
4932 }
4933 }
4934
4935 if (Validator.isNull(password)) {
4936 throw new UserPasswordException(
4937 UserPasswordException.PASSWORD_INVALID);
4938 }
4939
4940 int authResult = Authenticator.FAILURE;
4941
4942
4943
4944 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
4945 authResult = AuthPipeline.authenticateByEmailAddress(
4946 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
4947 headerMap, parameterMap);
4948 }
4949 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
4950 authResult = AuthPipeline.authenticateByScreenName(
4951 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
4952 headerMap, parameterMap);
4953 }
4954 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
4955 authResult = AuthPipeline.authenticateByUserId(
4956 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
4957 headerMap, parameterMap);
4958 }
4959
4960
4961
4962 User user = null;
4963
4964 try {
4965 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
4966 user = userPersistence.findByC_EA(companyId, login);
4967 }
4968 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
4969 user = userPersistence.findByC_SN(companyId, login);
4970 }
4971 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
4972 user = userPersistence.findByC_U(
4973 companyId, GetterUtil.getLong(login));
4974 }
4975 }
4976 catch (NoSuchUserException nsue) {
4977 return Authenticator.DNE;
4978 }
4979
4980 if (user.isDefaultUser()) {
4981 if (_log.isInfoEnabled()) {
4982 _log.info("Authentication is disabled for the default user");
4983 }
4984
4985 return Authenticator.DNE;
4986 }
4987 else if (!user.isActive()) {
4988 if (_log.isInfoEnabled()) {
4989 _log.info(
4990 "Authentication is disabled for inactive user " +
4991 user.getUserId());
4992 }
4993
4994 return Authenticator.FAILURE;
4995 }
4996
4997 if (!user.isPasswordEncrypted()) {
4998 user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
4999 user.setPasswordEncrypted(true);
5000
5001 userPersistence.update(user, false);
5002 }
5003
5004
5005
5006
5007 checkLockout(user);
5008
5009 checkPasswordExpired(user);
5010
5011
5012
5013 if (authResult == Authenticator.SUCCESS) {
5014 if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5015 boolean authenticated = PwdAuthenticator.authenticate(
5016 login, password, user.getPassword());
5017
5018 if (authenticated) {
5019 authResult = Authenticator.SUCCESS;
5020 }
5021 else {
5022 authResult = Authenticator.FAILURE;
5023 }
5024 }
5025 }
5026
5027
5028
5029 if (authResult == Authenticator.SUCCESS) {
5030 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5031 authResult = AuthPipeline.authenticateByEmailAddress(
5032 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5033 headerMap, parameterMap);
5034 }
5035 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5036 authResult = AuthPipeline.authenticateByScreenName(
5037 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5038 headerMap, parameterMap);
5039 }
5040 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5041 authResult = AuthPipeline.authenticateByUserId(
5042 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5043 headerMap, parameterMap);
5044 }
5045 }
5046
5047 if (authResult == Authenticator.SUCCESS) {
5048 if (resultsMap != null) {
5049 resultsMap.put("userId", user.getUserId());
5050 }
5051
5052
5053
5054 boolean updateDigest = true;
5055
5056 if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5057 if (Validator.isNotNull(user.getDigest())) {
5058 updateDigest = false;
5059 }
5060 }
5061
5062 if (updateDigest) {
5063 String digest = user.getDigest(password);
5064
5065 user.setDigest(digest);
5066
5067 userPersistence.update(user, false);
5068 }
5069 }
5070
5071
5072
5073 if (authResult == Authenticator.FAILURE) {
5074 try {
5075 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5076 AuthPipeline.onFailureByEmailAddress(
5077 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5078 parameterMap);
5079 }
5080 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5081 AuthPipeline.onFailureByScreenName(
5082 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5083 parameterMap);
5084 }
5085 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5086 AuthPipeline.onFailureByUserId(
5087 PropsKeys.AUTH_FAILURE, companyId, userId, headerMap,
5088 parameterMap);
5089 }
5090
5091
5092
5093 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5094 user.getCompanyId())) {
5095
5096 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5097
5098 int failedLoginAttempts = user.getFailedLoginAttempts();
5099 int maxFailures = passwordPolicy.getMaxFailure();
5100
5101 if ((failedLoginAttempts >= maxFailures) &&
5102 (maxFailures != 0)) {
5103
5104 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5105 AuthPipeline.onMaxFailuresByEmailAddress(
5106 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5107 headerMap, parameterMap);
5108 }
5109 else if (authType.equals(
5110 CompanyConstants.AUTH_TYPE_SN)) {
5111
5112 AuthPipeline.onMaxFailuresByScreenName(
5113 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5114 headerMap, parameterMap);
5115 }
5116 else if (authType.equals(
5117 CompanyConstants.AUTH_TYPE_ID)) {
5118
5119 AuthPipeline.onMaxFailuresByUserId(
5120 PropsKeys.AUTH_MAX_FAILURES, companyId, userId,
5121 headerMap, parameterMap);
5122 }
5123 }
5124 }
5125 }
5126 catch (Exception e) {
5127 _log.error(e, e);
5128 }
5129 }
5130
5131 return authResult;
5132 }
5133
5134 protected String getScreenName(String screenName) {
5135 return StringUtil.lowerCase(StringUtil.trim(screenName));
5136 }
5137
5138 protected long[] getUserIds(List<User> users) {
5139 long[] userIds = new long[users.size()];
5140
5141 for (int i = 0; i < users.size(); i++) {
5142 User user = users.get(i);
5143
5144 userIds[i] = user.getUserId();
5145 }
5146
5147 return userIds;
5148 }
5149
5150 protected void sendEmail(
5151 User user, String password, ServiceContext serviceContext)
5152 throws SystemException {
5153
5154 if (!PrefsPropsUtil.getBoolean(
5155 user.getCompanyId(),
5156 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
5157
5158 return;
5159 }
5160
5161 String fromName = PrefsPropsUtil.getString(
5162 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
5163 String fromAddress = PrefsPropsUtil.getString(
5164 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
5165
5166 String toName = user.getFullName();
5167 String toAddress = user.getEmailAddress();
5168
5169 String subject = PrefsPropsUtil.getContent(
5170 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
5171
5172 String body = null;
5173
5174 if (Validator.isNotNull(password)) {
5175 body = PrefsPropsUtil.getContent(
5176 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
5177 }
5178 else {
5179 body = PrefsPropsUtil.getContent(
5180 user.getCompanyId(),
5181 PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
5182 }
5183
5184 SubscriptionSender subscriptionSender = new SubscriptionSender();
5185
5186 subscriptionSender.setBody(body);
5187 subscriptionSender.setCompanyId(user.getCompanyId());
5188 subscriptionSender.setContextAttributes(
5189 "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
5190 "[$USER_SCREENNAME$]", user.getScreenName());
5191 subscriptionSender.setFrom(fromAddress, fromName);
5192 subscriptionSender.setHtmlFormat(true);
5193 subscriptionSender.setMailId("user", user.getUserId());
5194 subscriptionSender.setServiceContext(serviceContext);
5195 subscriptionSender.setSubject(subject);
5196 subscriptionSender.setUserId(user.getUserId());
5197
5198 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
5199
5200 subscriptionSender.flushNotificationsAsync();
5201 }
5202
5203 protected Hits search(
5204 long companyId, String firstName, String middleName,
5205 String lastName, String fullName, String screenName,
5206 String emailAddress, String street, String city, String zip,
5207 String region, String country, int status,
5208 LinkedHashMap<String, Object> params, boolean andSearch, int start,
5209 int end, Sort sort)
5210 throws SystemException {
5211
5212 try {
5213 Map<String, Serializable> attributes =
5214 new HashMap<String, Serializable>();
5215
5216 attributes.put("city", city);
5217 attributes.put("country", country);
5218 attributes.put("emailAddress", emailAddress);
5219 attributes.put("firstName", firstName);
5220 attributes.put("fullName", fullName);
5221 attributes.put("lastName", lastName);
5222 attributes.put("middleName", middleName);
5223 attributes.put("params", params);
5224 attributes.put("region", region);
5225 attributes.put("screenName", screenName);
5226 attributes.put("street", street);
5227 attributes.put("status", status);
5228 attributes.put("zip", zip);
5229
5230 SearchContext searchContext = new SearchContext();
5231
5232 searchContext.setAndSearch(andSearch);
5233 searchContext.setAttributes(attributes);
5234 searchContext.setCompanyId(companyId);
5235 searchContext.setEnd(end);
5236
5237 String keywords = (String)params.remove("keywords");
5238
5239 if (Validator.isNotNull(keywords)) {
5240 searchContext.setKeywords(keywords);
5241 }
5242
5243 searchContext.setSorts(new Sort[] {sort});
5244
5245 QueryConfig queryConfig = new QueryConfig();
5246
5247 queryConfig.setHighlightEnabled(false);
5248 queryConfig.setScoreEnabled(false);
5249
5250 searchContext.setQueryConfig(queryConfig);
5251
5252 searchContext.setStart(start);
5253
5254 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
5255
5256 return indexer.search(searchContext);
5257 }
5258 catch (Exception e) {
5259 throw new SystemException(e);
5260 }
5261 }
5262
5263 protected void setEmailAddress(
5264 User user, String password, String firstName, String middleName,
5265 String lastName, String emailAddress)
5266 throws PortalException, SystemException {
5267
5268 if (emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
5269 return;
5270 }
5271
5272 long userId = user.getUserId();
5273
5274
5275
5276 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
5277 Validator.isNotNull(password)) {
5278
5279 mailService.addUser(
5280 user.getCompanyId(), userId, password, firstName, middleName,
5281 lastName, emailAddress);
5282 }
5283
5284
5285
5286 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
5287 mailService.updateEmailAddress(
5288 user.getCompanyId(), userId, emailAddress);
5289 }
5290
5291
5292
5293 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
5294 mailService.deleteEmailAddress(user.getCompanyId(), userId);
5295 }
5296
5297 user.setEmailAddress(emailAddress);
5298 user.setDigest(StringPool.BLANK);
5299 }
5300
5301 protected void updateUserGroupRoles(
5302 User user, long[] groupIds, long[] organizationIds,
5303 List<UserGroupRole> userGroupRoles)
5304 throws PortalException, SystemException {
5305
5306 if (userGroupRoles == null) {
5307 return;
5308 }
5309
5310 List<UserGroupRole> previousUserGroupRoles =
5311 userGroupRolePersistence.findByUserId(user.getUserId());
5312
5313 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
5314 if (userGroupRoles.contains(userGroupRole)) {
5315 userGroupRoles.remove(userGroupRole);
5316 }
5317 else {
5318 userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
5319 }
5320 }
5321
5322 long[] validGroupIds = null;
5323
5324 if (groupIds != null) {
5325 validGroupIds = ArrayUtil.clone(groupIds);
5326 }
5327 else {
5328 validGroupIds = user.getGroupIds();
5329 }
5330
5331 if (organizationIds == null) {
5332 organizationIds = user.getOrganizationIds();
5333 }
5334
5335 long[] organizationGroupIds = new long[organizationIds.length];
5336
5337 for (int i = 0; i < organizationIds.length; i++) {
5338 long organizationId = organizationIds[i];
5339
5340 Organization organization =
5341 organizationPersistence.findByPrimaryKey(organizationId);
5342
5343 Group organizationGroup = organization.getGroup();
5344
5345 organizationGroupIds[i] = organizationGroup.getGroupId();
5346 }
5347
5348 validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
5349
5350 Arrays.sort(validGroupIds);
5351
5352 for (UserGroupRole userGroupRole : userGroupRoles) {
5353 if (Arrays.binarySearch(
5354 validGroupIds, userGroupRole.getGroupId()) >= 0) {
5355
5356 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
5357 }
5358 }
5359 }
5360
5361 protected void validate(
5362 long companyId, long userId, boolean autoPassword, String password1,
5363 String password2, boolean autoScreenName, String screenName,
5364 String emailAddress, String firstName, String middleName,
5365 String lastName, long[] organizationIds)
5366 throws PortalException, SystemException {
5367
5368 Company company = companyPersistence.findByPrimaryKey(companyId);
5369
5370 if (company.isSystem()) {
5371 return;
5372 }
5373
5374 if ((company.getMaxUsers() > 0) &&
5375 (company.getMaxUsers() <=
5376 searchCount(
5377 companyId, null, WorkflowConstants.STATUS_APPROVED,
5378 null))) {
5379
5380 throw new CompanyMaxUsersException();
5381 }
5382
5383 if (!autoScreenName) {
5384 validateScreenName(companyId, userId, screenName);
5385 }
5386
5387 if (!autoPassword) {
5388 PasswordPolicy passwordPolicy =
5389 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
5390
5391 PwdToolkitUtil.validate(
5392 companyId, 0, password1, password2, passwordPolicy);
5393 }
5394
5395 validateEmailAddress(companyId, emailAddress);
5396
5397 if (Validator.isNotNull(emailAddress)) {
5398 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
5399
5400 if ((user != null) && (user.getUserId() != userId)) {
5401 throw new DuplicateUserEmailAddressException();
5402 }
5403 }
5404
5405 validateFullName(companyId, firstName, middleName, lastName);
5406 }
5407
5408 protected void validate(
5409 long userId, String screenName, String emailAddress,
5410 String firstName, String middleName, String lastName, String smsSn)
5411 throws PortalException, SystemException {
5412
5413 User user = userPersistence.findByPrimaryKey(userId);
5414
5415 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
5416 validateScreenName(user.getCompanyId(), userId, screenName);
5417 }
5418
5419 validateEmailAddress(user.getCompanyId(), emailAddress);
5420
5421 if (!user.isDefaultUser()) {
5422 if (Validator.isNotNull(emailAddress) &&
5423 !user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
5424
5425 if (userPersistence.fetchByC_EA(
5426 user.getCompanyId(), emailAddress) != null) {
5427
5428 throw new DuplicateUserEmailAddressException();
5429 }
5430 }
5431
5432 validateFullName(
5433 user.getCompanyId(), firstName, middleName, lastName);
5434 }
5435
5436 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
5437 throw new UserSmsException();
5438 }
5439 }
5440
5441 protected void validateEmailAddress(long companyId, String emailAddress)
5442 throws PortalException, SystemException {
5443
5444 if (Validator.isNull(emailAddress) &&
5445 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
5446
5447 return;
5448 }
5449
5450 if (!Validator.isEmailAddress(emailAddress) ||
5451 emailAddress.startsWith("root@") ||
5452 emailAddress.startsWith("postmaster@")) {
5453
5454 throw new UserEmailAddressException();
5455 }
5456
5457 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
5458 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
5459 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
5460
5461 for (String reservedEmailAddress : reservedEmailAddresses) {
5462 if (emailAddress.equalsIgnoreCase(reservedEmailAddress)) {
5463 throw new ReservedUserEmailAddressException();
5464 }
5465 }
5466 }
5467
5468 protected void validateEmailAddress(
5469 User user, String emailAddress1, String emailAddress2)
5470 throws PortalException, SystemException {
5471
5472 if (!emailAddress1.equals(emailAddress2)) {
5473 throw new UserEmailAddressException();
5474 }
5475
5476 validateEmailAddress(user.getCompanyId(), emailAddress1);
5477 validateEmailAddress(user.getCompanyId(), emailAddress2);
5478
5479 if (!emailAddress1.equalsIgnoreCase(user.getEmailAddress())) {
5480 if (userPersistence.fetchByC_EA(
5481 user.getCompanyId(), emailAddress1) != null) {
5482
5483 throw new DuplicateUserEmailAddressException();
5484 }
5485 }
5486 }
5487
5488 protected void validateFullName(
5489 long companyId, String firstName, String middleName,
5490 String lastName)
5491 throws PortalException, SystemException {
5492
5493 if (Validator.isNull(firstName)) {
5494 throw new ContactFirstNameException();
5495 }
5496 else if (Validator.isNull(lastName) &&
5497 PrefsPropsUtil.getBoolean(
5498 companyId, PropsKeys.USERS_LAST_NAME_REQUIRED,
5499 PropsValues.USERS_LAST_NAME_REQUIRED)) {
5500
5501 throw new ContactLastNameException();
5502 }
5503
5504 FullNameValidator fullNameValidator =
5505 FullNameValidatorFactory.getInstance();
5506
5507 if (!fullNameValidator.validate(
5508 companyId, firstName, middleName, lastName)) {
5509
5510 throw new ContactFullNameException();
5511 }
5512 }
5513
5514 protected void validatePassword(
5515 long companyId, long userId, String password1, String password2)
5516 throws PortalException, SystemException {
5517
5518 if (Validator.isNull(password1) || Validator.isNull(password2)) {
5519 throw new UserPasswordException(
5520 UserPasswordException.PASSWORD_INVALID);
5521 }
5522
5523 if (!password1.equals(password2)) {
5524 throw new UserPasswordException(
5525 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
5526 }
5527
5528 PasswordPolicy passwordPolicy =
5529 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
5530
5531 PwdToolkitUtil.validate(
5532 companyId, userId, password1, password2, passwordPolicy);
5533 }
5534
5535 protected void validateReminderQuery(String question, String answer)
5536 throws PortalException {
5537
5538 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
5539 return;
5540 }
5541
5542 if (Validator.isNull(question)) {
5543 throw new UserReminderQueryException("Question cannot be null");
5544 }
5545
5546 if (Validator.isNull(answer)) {
5547 throw new UserReminderQueryException("Answer cannot be null");
5548 }
5549 }
5550
5551 protected void validateScreenName(
5552 long companyId, long userId, String screenName)
5553 throws PortalException, SystemException {
5554
5555 if (Validator.isNull(screenName)) {
5556 throw new UserScreenNameException();
5557 }
5558
5559 ScreenNameValidator screenNameValidator =
5560 ScreenNameValidatorFactory.getInstance();
5561
5562 if (!screenNameValidator.validate(companyId, screenName)) {
5563 throw new UserScreenNameException();
5564 }
5565
5566 if (Validator.isNumber(screenName)) {
5567 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
5568 throw new UserScreenNameException();
5569 }
5570
5571 if (!screenName.equals(String.valueOf(userId))) {
5572 Group group = groupPersistence.fetchByPrimaryKey(
5573 GetterUtil.getLong(screenName));
5574
5575 if (group != null) {
5576 throw new UserScreenNameException();
5577 }
5578 }
5579 }
5580
5581 for (char c : screenName.toCharArray()) {
5582 if ((!Validator.isChar(c)) && (!Validator.isDigit(c)) &&
5583 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
5584 (c != CharPool.UNDERLINE)) {
5585
5586 throw new UserScreenNameException();
5587 }
5588 }
5589
5590 String[] anonymousNames = PrincipalBean.ANONYMOUS_NAMES;
5591
5592 for (String anonymousName : anonymousNames) {
5593 if (screenName.equalsIgnoreCase(anonymousName)) {
5594 throw new UserScreenNameException();
5595 }
5596 }
5597
5598 User user = userPersistence.fetchByC_SN(companyId, screenName);
5599
5600 if ((user != null) && (user.getUserId() != userId)) {
5601 throw new DuplicateUserScreenNameException();
5602 }
5603
5604 String friendlyURL = StringPool.SLASH + screenName;
5605
5606 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
5607
5608 if ((group != null) && (group.getClassPK() != userId)) {
5609 throw new GroupFriendlyURLException(
5610 GroupFriendlyURLException.DUPLICATE);
5611 }
5612
5613 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
5614
5615 if (exceptionType != -1) {
5616 throw new UserScreenNameException(
5617 new GroupFriendlyURLException(exceptionType));
5618 }
5619
5620 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
5621 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
5622 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
5623
5624 for (String reservedScreenName : reservedScreenNames) {
5625 if (screenName.equalsIgnoreCase(reservedScreenName)) {
5626 throw new ReservedUserScreenNameException();
5627 }
5628 }
5629 }
5630
5631 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
5632
5633 private static Map<Long, User> _defaultUsers =
5634 new ConcurrentHashMap<Long, User>();
5635
5636 }