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.ImageToolUtil;
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.spring.transaction.TransactionCommitCallbackUtil;
116 import com.liferay.portal.util.PortalUtil;
117 import com.liferay.portal.util.PrefsPropsUtil;
118 import com.liferay.portal.util.PropsValues;
119 import com.liferay.portal.util.SubscriptionSender;
120 import com.liferay.portlet.documentlibrary.ImageSizeException;
121 import com.liferay.portlet.messageboards.model.MBMessage;
122 import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
123 import com.liferay.util.Encryptor;
124 import com.liferay.util.EncryptorException;
125
126 import java.awt.image.RenderedImage;
127
128 import java.io.IOException;
129 import java.io.Serializable;
130
131 import java.util.ArrayList;
132 import java.util.Arrays;
133 import java.util.Date;
134 import java.util.HashMap;
135 import java.util.HashSet;
136 import java.util.LinkedHashMap;
137 import java.util.List;
138 import java.util.Locale;
139 import java.util.Map;
140 import java.util.Set;
141 import java.util.concurrent.Callable;
142 import java.util.concurrent.ConcurrentHashMap;
143
144
155 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
156
157
167 public void addDefaultGroups(long userId)
168 throws PortalException, SystemException {
169
170 User user = userPersistence.findByPrimaryKey(userId);
171
172 Set<Long> groupIdsSet = new HashSet<Long>();
173
174 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
175 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
176 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
177
178 for (String defaultGroupName : defaultGroupNames) {
179 Company company = companyPersistence.findByPrimaryKey(
180 user.getCompanyId());
181
182 Account account = company.getAccount();
183
184 if (defaultGroupName.equalsIgnoreCase(account.getName())) {
185 defaultGroupName = GroupConstants.GUEST;
186 }
187
188 try {
189 Group group = groupPersistence.findByC_N(
190 user.getCompanyId(), defaultGroupName);
191
192 if (!userPersistence.containsGroup(
193 userId, group.getGroupId())) {
194
195 groupIdsSet.add(group.getGroupId());
196 }
197 }
198 catch (NoSuchGroupException nsge) {
199 }
200 }
201
202 long[] groupIds = ArrayUtil.toArray(
203 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
204
205 groupLocalService.addUserGroups(userId, groupIds);
206 }
207
208
218 public void addDefaultRoles(long userId)
219 throws PortalException, SystemException {
220
221 User user = userPersistence.findByPrimaryKey(userId);
222
223 Set<Long> roleIdSet = new HashSet<Long>();
224
225 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
226 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
227 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
228
229 for (String defaultRoleName : defaultRoleNames) {
230 try {
231 Role role = rolePersistence.findByC_N(
232 user.getCompanyId(), defaultRoleName);
233
234 if (!userPersistence.containsRole(userId, role.getRoleId())) {
235 roleIdSet.add(role.getRoleId());
236 }
237 }
238 catch (NoSuchRoleException nsre) {
239 }
240 }
241
242 long[] roleIds = ArrayUtil.toArray(
243 roleIdSet.toArray(new Long[roleIdSet.size()]));
244
245 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
246
247 userPersistence.addRoles(userId, roleIds);
248 }
249
250
260 @SuppressWarnings("deprecation")
261 public void addDefaultUserGroups(long userId)
262 throws PortalException, SystemException {
263
264 User user = userPersistence.findByPrimaryKey(userId);
265
266 Set<Long> userGroupIdSet = new HashSet<Long>();
267
268 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
269 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
270 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
271
272 for (String defaultUserGroupName : defaultUserGroupNames) {
273 try {
274 UserGroup userGroup = userGroupPersistence.findByC_N(
275 user.getCompanyId(), defaultUserGroupName);
276
277 if (!userPersistence.containsUserGroup(
278 userId, userGroup.getUserGroupId())) {
279
280 userGroupIdSet.add(userGroup.getUserGroupId());
281 }
282 }
283 catch (NoSuchUserGroupException nsuge) {
284 }
285 }
286
287 long[] userGroupIds = ArrayUtil.toArray(
288 userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
289
290 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
291 for (long userGroupId : userGroupIds) {
292 userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
293 }
294 }
295
296 userPersistence.addUserGroups(userId, userGroupIds);
297 }
298
299
308 public void addGroupUsers(long groupId, long[] userIds)
309 throws PortalException, SystemException {
310
311 groupPersistence.addUsers(groupId, userIds);
312
313 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
314
315 indexer.reindex(userIds);
316
317 PermissionCacheUtil.clearCache();
318 }
319
320
329 public void addOrganizationUsers(long organizationId, long[] userIds)
330 throws PortalException, SystemException {
331
332 organizationPersistence.addUsers(organizationId, userIds);
333
334 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
335
336 indexer.reindex(userIds);
337
338 PermissionCacheUtil.clearCache();
339 }
340
341
349 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
350 throws SystemException {
351
352 passwordPolicyRelLocalService.addPasswordPolicyRels(
353 passwordPolicyId, User.class.getName(), userIds);
354 }
355
356
365 public void addRoleUsers(long roleId, long[] userIds)
366 throws PortalException, SystemException {
367
368 rolePersistence.addUsers(roleId, userIds);
369
370 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
371
372 indexer.reindex(userIds);
373
374 PermissionCacheUtil.clearCache();
375 }
376
377
386 public void addTeamUsers(long teamId, long[] userIds)
387 throws PortalException, SystemException {
388
389 teamPersistence.addUsers(teamId, userIds);
390
391 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
392
393 indexer.reindex(userIds);
394
395 PermissionCacheUtil.clearCache();
396 }
397
398
446 public User addUser(
447 long creatorUserId, long companyId, boolean autoPassword,
448 String password1, String password2, boolean autoScreenName,
449 String screenName, String emailAddress, long facebookId,
450 String openId, Locale locale, String firstName, String middleName,
451 String lastName, int prefixId, int suffixId, boolean male,
452 int birthdayMonth, int birthdayDay, int birthdayYear,
453 String jobTitle, long[] groupIds, long[] organizationIds,
454 long[] roleIds, long[] userGroupIds, boolean sendEmail,
455 ServiceContext serviceContext)
456 throws PortalException, SystemException {
457
458 boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
459
460 try {
461 WorkflowThreadLocal.setEnabled(false);
462
463 return addUserWithWorkflow(
464 creatorUserId, companyId, autoPassword, password1, password2,
465 autoScreenName, screenName, emailAddress, facebookId, openId,
466 locale, firstName, middleName, lastName, prefixId, suffixId,
467 male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
468 groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
469 serviceContext);
470 }
471 finally {
472 WorkflowThreadLocal.setEnabled(workflowEnabled);
473 }
474 }
475
476
485 @SuppressWarnings("deprecation")
486 public void addUserGroupUsers(long userGroupId, long[] userIds)
487 throws PortalException, SystemException {
488
489 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
490 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
491 }
492
493 userGroupPersistence.addUsers(userGroupId, userIds);
494
495 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
496
497 indexer.reindex(userIds);
498
499 PermissionCacheUtil.clearCache();
500 }
501
502
550 @SuppressWarnings("deprecation")
551 public User addUserWithWorkflow(
552 long creatorUserId, long companyId, boolean autoPassword,
553 String password1, String password2, boolean autoScreenName,
554 String screenName, String emailAddress, long facebookId,
555 String openId, Locale locale, String firstName, String middleName,
556 String lastName, int prefixId, int suffixId, boolean male,
557 int birthdayMonth, int birthdayDay, int birthdayYear,
558 String jobTitle, long[] groupIds, long[] organizationIds,
559 long[] roleIds, long[] userGroupIds, boolean sendEmail,
560 ServiceContext serviceContext)
561 throws PortalException, SystemException {
562
563
564
565 Company company = companyPersistence.findByPrimaryKey(companyId);
566 screenName = getScreenName(screenName);
567 emailAddress = emailAddress.trim().toLowerCase();
568 openId = openId.trim();
569 Date now = new Date();
570
571 if (PrefsPropsUtil.getBoolean(
572 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
573
574 autoScreenName = true;
575 }
576
577 long userId = counterLocalService.increment();
578
579 EmailAddressGenerator emailAddressGenerator =
580 EmailAddressGeneratorFactory.getInstance();
581
582 if (emailAddressGenerator.isGenerated(emailAddress)) {
583 emailAddress = StringPool.BLANK;
584 }
585
586 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
587 Validator.isNull(emailAddress)) {
588
589 emailAddress = emailAddressGenerator.generate(companyId, userId);
590 }
591
592 validate(
593 companyId, userId, autoPassword, password1, password2,
594 autoScreenName, screenName, emailAddress, firstName, middleName,
595 lastName, organizationIds);
596
597 if (!autoPassword) {
598 if (Validator.isNull(password1) || Validator.isNull(password2)) {
599 throw new UserPasswordException(
600 UserPasswordException.PASSWORD_INVALID);
601 }
602 }
603
604 if (autoScreenName) {
605 ScreenNameGenerator screenNameGenerator =
606 ScreenNameGeneratorFactory.getInstance();
607
608 try {
609 screenName = screenNameGenerator.generate(
610 companyId, userId, emailAddress);
611 }
612 catch (Exception e) {
613 throw new SystemException(e);
614 }
615 }
616
617 User defaultUser = getDefaultUser(companyId);
618
619 FullNameGenerator fullNameGenerator =
620 FullNameGeneratorFactory.getInstance();
621
622 String fullName = fullNameGenerator.getFullName(
623 firstName, middleName, lastName);
624
625 String greeting = LanguageUtil.format(
626 locale, "welcome-x", " " + fullName, false);
627
628 User user = userPersistence.create(userId);
629
630 if (serviceContext != null) {
631 String uuid = serviceContext.getUuid();
632
633 if (Validator.isNotNull(uuid)) {
634 user.setUuid(uuid);
635 }
636 }
637
638 user.setCompanyId(companyId);
639 user.setCreateDate(now);
640 user.setModifiedDate(now);
641 user.setDefaultUser(false);
642 user.setContactId(counterLocalService.increment());
643
644 if (Validator.isNotNull(password1)) {
645 user.setPassword(PwdEncryptor.encrypt(password1));
646 user.setPasswordUnencrypted(password1);
647 }
648
649 user.setPasswordEncrypted(true);
650
651 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
652
653 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
654 passwordPolicy.isChangeRequired()) {
655
656 user.setPasswordReset(true);
657 }
658 else {
659 user.setPasswordReset(false);
660 }
661
662 user.setDigest(StringPool.BLANK);
663 user.setScreenName(screenName);
664 user.setEmailAddress(emailAddress);
665 user.setFacebookId(facebookId);
666 user.setOpenId(openId);
667 user.setLanguageId(locale.toString());
668 user.setTimeZoneId(defaultUser.getTimeZoneId());
669 user.setGreeting(greeting);
670 user.setFirstName(firstName);
671 user.setMiddleName(middleName);
672 user.setLastName(lastName);
673 user.setJobTitle(jobTitle);
674 user.setStatus(WorkflowConstants.STATUS_DRAFT);
675
676 userPersistence.update(user, false, serviceContext);
677
678
679
680 String creatorUserName = StringPool.BLANK;
681
682 if (creatorUserId <= 0) {
683 creatorUserId = user.getUserId();
684
685
686
687
688
689 }
690 else {
691 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
692
693 creatorUserName = creatorUser.getFullName();
694 }
695
696 resourceLocalService.addResources(
697 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
698 false, false, false);
699
700
701
702 Date birthday = PortalUtil.getDate(
703 birthdayMonth, birthdayDay, birthdayYear,
704 new ContactBirthdayException());
705
706 Contact contact = contactPersistence.create(user.getContactId());
707
708 contact.setCompanyId(user.getCompanyId());
709 contact.setUserId(creatorUserId);
710 contact.setUserName(creatorUserName);
711 contact.setCreateDate(now);
712 contact.setModifiedDate(now);
713 contact.setAccountId(company.getAccountId());
714 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
715 contact.setFirstName(firstName);
716 contact.setMiddleName(middleName);
717 contact.setLastName(lastName);
718 contact.setPrefixId(prefixId);
719 contact.setSuffixId(suffixId);
720 contact.setMale(male);
721 contact.setBirthday(birthday);
722 contact.setJobTitle(jobTitle);
723
724 contactPersistence.update(contact, false, serviceContext);
725
726
727
728 groupLocalService.addGroup(
729 user.getUserId(), User.class.getName(), user.getUserId(), null,
730 null, 0, StringPool.SLASH + screenName, false, true, null);
731
732
733
734 if (groupIds != null) {
735 groupLocalService.addUserGroups(userId, groupIds);
736 }
737
738 addDefaultGroups(userId);
739
740
741
742 boolean indexingEnabled = serviceContext.isIndexingEnabled();
743
744 serviceContext.setIndexingEnabled(false);
745
746 try {
747 updateOrganizations(userId, organizationIds, serviceContext);
748 }
749 finally {
750 serviceContext.setIndexingEnabled(indexingEnabled);
751 }
752
753
754
755 if (roleIds != null) {
756 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
757
758 userPersistence.setRoles(userId, roleIds);
759 }
760
761 addDefaultRoles(userId);
762
763
764
765 if (userGroupIds != null) {
766 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
767 for (long userGroupId : userGroupIds) {
768 userGroupLocalService.copyUserGroupLayouts(
769 userGroupId, new long[] {userId});
770 }
771 }
772
773 userPersistence.setUserGroups(userId, userGroupIds);
774 }
775
776 addDefaultUserGroups(userId);
777
778
779
780 if (serviceContext != null) {
781 updateAsset(
782 creatorUserId, user, serviceContext.getAssetCategoryIds(),
783 serviceContext.getAssetTagNames());
784 }
785
786
787
788 user.setExpandoBridgeAttributes(serviceContext);
789
790
791
792 if (serviceContext.isIndexingEnabled()) {
793 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
1783 public User fetchUserById(long userId) throws SystemException {
1784 return userPersistence.fetchByPrimaryKey(userId);
1785 }
1786
1787
1796 public User fetchUserByScreenName(long companyId, String screenName)
1797 throws SystemException {
1798
1799 screenName = getScreenName(screenName);
1800
1801 return userPersistence.fetchByC_SN(companyId, screenName);
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
2856 public List<User> search(
2857 long companyId, String keywords, int status,
2858 LinkedHashMap<String, Object> params, int start, int end,
2859 OrderByComparator obc)
2860 throws SystemException {
2861
2862 return userFinder.findByKeywords(
2863 companyId, keywords, status, params, start, end, obc);
2864 }
2865
2866
2897 public Hits search(
2898 long companyId, String keywords, int status,
2899 LinkedHashMap<String, Object> params, int start, int end, Sort sort)
2900 throws SystemException {
2901
2902 String firstName = null;
2903 String middleName = null;
2904 String lastName = null;
2905 String fullName = null;
2906 String screenName = null;
2907 String emailAddress = null;
2908 String street = null;
2909 String city = null;
2910 String zip = null;
2911 String region = null;
2912 String country = null;
2913 boolean andOperator = false;
2914
2915 if (Validator.isNotNull(keywords)) {
2916 firstName = keywords;
2917 middleName = keywords;
2918 lastName = keywords;
2919 fullName = keywords;
2920 screenName = keywords;
2921 emailAddress = keywords;
2922 street = keywords;
2923 city = keywords;
2924 zip = keywords;
2925 region = keywords;
2926 country = keywords;
2927 }
2928 else {
2929 andOperator = true;
2930 }
2931
2932 params.put("keywords", keywords);
2933
2934 return search(
2935 companyId, firstName, middleName, lastName, fullName, screenName,
2936 emailAddress, street, city, zip, region, country, status, params,
2937 andOperator, start, end, sort);
2938 }
2939
2940
2980 public List<User> search(
2981 long companyId, String firstName, String middleName,
2982 String lastName, String screenName, String emailAddress,
2983 int status, LinkedHashMap<String, Object> params,
2984 boolean andSearch, int start, int end, OrderByComparator obc)
2985 throws SystemException {
2986
2987 return userFinder.findByC_FN_MN_LN_SN_EA_S(
2988 companyId, firstName, middleName, lastName, screenName,
2989 emailAddress, status, params, andSearch, start, end, obc);
2990 }
2991
2992
3031 public Hits search(
3032 long companyId, String firstName, String middleName,
3033 String lastName, String screenName, String emailAddress,
3034 int status, LinkedHashMap<String, Object> params,
3035 boolean andSearch, int start, int end, Sort sort)
3036 throws SystemException {
3037
3038 return search(
3039 companyId, firstName, middleName, lastName, null, screenName,
3040 emailAddress, null, null, null, null, null, status, params,
3041 andSearch, start, end, sort);
3042 }
3043
3044
3058 public int searchCount(
3059 long companyId, String keywords, int status,
3060 LinkedHashMap<String, Object> params)
3061 throws SystemException {
3062
3063 return userFinder.countByKeywords(companyId, keywords, status, params);
3064 }
3065
3066
3088 public int searchCount(
3089 long companyId, String firstName, String middleName,
3090 String lastName, String screenName, String emailAddress,
3091 int status, LinkedHashMap<String, Object> params,
3092 boolean andSearch)
3093 throws SystemException {
3094
3095 return userFinder.countByC_FN_MN_LN_SN_EA_S(
3096 companyId, firstName, middleName, lastName, screenName,
3097 emailAddress, status, params, andSearch);
3098 }
3099
3100
3111 public void sendEmailAddressVerification(
3112 User user, String emailAddress, ServiceContext serviceContext)
3113 throws PortalException, SystemException {
3114
3115 if (user.isEmailAddressVerified() &&
3116 emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
3117
3118 return;
3119 }
3120
3121 Ticket ticket = ticketLocalService.addTicket(
3122 user.getCompanyId(), User.class.getName(), user.getUserId(),
3123 TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3124 serviceContext);
3125
3126 String verifyEmailAddressURL =
3127 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3128 "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3129
3130 Layout layout = layoutLocalService.getLayout(serviceContext.getPlid());
3131
3132 Group group = layout.getGroup();
3133
3134 if (!layout.isPrivateLayout() && !group.isUser()) {
3135 verifyEmailAddressURL += "&p_l_id=" + serviceContext.getPlid();
3136 }
3137
3138 String fromName = PrefsPropsUtil.getString(
3139 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3140 String fromAddress = PrefsPropsUtil.getString(
3141 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3142
3143 String toName = user.getFullName();
3144 String toAddress = emailAddress;
3145
3146 String subject = PrefsPropsUtil.getContent(
3147 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3148
3149 String body = PrefsPropsUtil.getContent(
3150 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3151
3152 SubscriptionSender subscriptionSender = new SubscriptionSender();
3153
3154 subscriptionSender.setBody(body);
3155 subscriptionSender.setCompanyId(user.getCompanyId());
3156 subscriptionSender.setContextAttributes(
3157 "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3158 "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3159 "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3160 "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_AGENT$]",
3161 serviceContext.getUserAgent(), "[$USER_ID$]", user.getUserId(),
3162 "[$USER_SCREENNAME$]", user.getScreenName());
3163 subscriptionSender.setFrom(fromAddress, fromName);
3164 subscriptionSender.setHtmlFormat(true);
3165 subscriptionSender.setMailId("user", user.getUserId());
3166 subscriptionSender.setServiceContext(serviceContext);
3167 subscriptionSender.setSubject(subject);
3168 subscriptionSender.setUserId(user.getUserId());
3169
3170 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3171
3172 subscriptionSender.flushNotificationsAsync();
3173 }
3174
3175
3194 public void sendPassword(
3195 long companyId, String emailAddress, String fromName,
3196 String fromAddress, String subject, String body,
3197 ServiceContext serviceContext)
3198 throws PortalException, SystemException {
3199
3200 Company company = companyPersistence.findByPrimaryKey(companyId);
3201
3202 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3203 return;
3204 }
3205
3206 emailAddress = emailAddress.trim().toLowerCase();
3207
3208 if (Validator.isNull(emailAddress)) {
3209 throw new UserEmailAddressException();
3210 }
3211
3212 User user = userPersistence.findByC_EA(companyId, emailAddress);
3213
3214 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3215
3216 String newPassword = StringPool.BLANK;
3217 String passwordResetURL = StringPool.BLANK;
3218
3219 if (company.isSendPasswordResetLink()) {
3220 Date expirationDate = new Date(
3221 System.currentTimeMillis() +
3222 (passwordPolicy.getResetTicketMaxAge() * 1000));
3223
3224 Ticket ticket = ticketLocalService.addTicket(
3225 companyId, User.class.getName(), user.getUserId(),
3226 TicketConstants.TYPE_PASSWORD, null, expirationDate,
3227 serviceContext);
3228
3229 passwordResetURL =
3230 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3231 "/portal/update_password?p_l_id="+
3232 serviceContext.getPlid() +
3233 "&ticketKey=" + ticket.getKey();
3234 }
3235 else {
3236 if (!PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
3237 PwdEncryptor.TYPE_NONE)) {
3238
3239 newPassword = PwdToolkitUtil.generate(passwordPolicy);
3240
3241 boolean passwordReset = false;
3242
3243 if (passwordPolicy.getChangeable() &&
3244 passwordPolicy.getChangeRequired()) {
3245
3246 passwordReset = true;
3247 }
3248
3249 user.setPassword(PwdEncryptor.encrypt(newPassword));
3250 user.setPasswordUnencrypted(newPassword);
3251 user.setPasswordEncrypted(true);
3252 user.setPasswordReset(passwordReset);
3253 user.setPasswordModified(true);
3254 user.setPasswordModifiedDate(new Date());
3255
3256 userPersistence.update(user, false);
3257
3258 user.setPasswordModified(false);
3259 }
3260 else {
3261 newPassword = user.getPassword();
3262 }
3263 }
3264
3265 if (Validator.isNull(fromName)) {
3266 fromName = PrefsPropsUtil.getString(
3267 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3268 }
3269
3270 if (Validator.isNull(fromAddress)) {
3271 fromAddress = PrefsPropsUtil.getString(
3272 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3273 }
3274
3275 String toName = user.getFullName();
3276 String toAddress = user.getEmailAddress();
3277
3278 if (Validator.isNull(subject)) {
3279 if (company.isSendPasswordResetLink()) {
3280 subject = PrefsPropsUtil.getContent(
3281 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
3282 }
3283 else {
3284 subject = PrefsPropsUtil.getContent(
3285 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
3286 }
3287 }
3288
3289 if (Validator.isNull(body)) {
3290 if (company.isSendPasswordResetLink()) {
3291 body = PrefsPropsUtil.getContent(
3292 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
3293 }
3294 else {
3295 body = PrefsPropsUtil.getContent(
3296 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
3297 }
3298 }
3299
3300 SubscriptionSender subscriptionSender = new SubscriptionSender();
3301
3302 subscriptionSender.setBody(body);
3303 subscriptionSender.setCompanyId(companyId);
3304 subscriptionSender.setContextAttributes(
3305 "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
3306 serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
3307 serviceContext.getRemoteHost(), "[$USER_AGENT$]",
3308 serviceContext.getUserAgent(), "[$USER_ID$]", user.getUserId(),
3309 "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
3310 user.getScreenName());
3311 subscriptionSender.setFrom(fromAddress, fromName);
3312 subscriptionSender.setHtmlFormat(true);
3313 subscriptionSender.setMailId("user", user.getUserId());
3314 subscriptionSender.setServiceContext(serviceContext);
3315 subscriptionSender.setSubject(subject);
3316 subscriptionSender.setUserId(user.getUserId());
3317
3318 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3319
3320 subscriptionSender.flushNotificationsAsync();
3321 }
3322
3323
3332 public void setRoleUsers(long roleId, long[] userIds)
3333 throws PortalException, SystemException {
3334
3335 rolePersistence.setUsers(roleId, userIds);
3336
3337 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3338
3339 indexer.reindex(userIds);
3340
3341 PermissionCacheUtil.clearCache();
3342 }
3343
3344
3353 @SuppressWarnings("deprecation")
3354 public void setUserGroupUsers(long userGroupId, long[] userIds)
3355 throws PortalException, SystemException {
3356
3357 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3358 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3359 }
3360
3361 userGroupPersistence.setUsers(userGroupId, userIds);
3362
3363 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3364
3365 indexer.reindex(userIds);
3366
3367 PermissionCacheUtil.clearCache();
3368 }
3369
3370
3378 public void unsetGroupUsers(
3379 long groupId, long[] userIds, ServiceContext serviceContext)
3380 throws PortalException, SystemException {
3381
3382 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
3383
3384 groupPersistence.removeUsers(groupId, userIds);
3385
3386 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3387
3388 indexer.reindex(userIds);
3389
3390 PermissionCacheUtil.clearCache();
3391 }
3392
3393
3401 public void unsetOrganizationUsers(long organizationId, long[] userIds)
3402 throws PortalException, SystemException {
3403
3404 Organization organization = organizationPersistence.findByPrimaryKey(
3405 organizationId);
3406
3407 Group group = organization.getGroup();
3408
3409 long groupId = group.getGroupId();
3410
3411 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
3412
3413 organizationPersistence.removeUsers(organizationId, userIds);
3414
3415 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3416
3417 indexer.reindex(userIds);
3418
3419 PermissionCacheUtil.clearCache();
3420 }
3421
3422
3429 public void unsetPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
3430 throws SystemException {
3431
3432 passwordPolicyRelLocalService.deletePasswordPolicyRels(
3433 passwordPolicyId, User.class.getName(), userIds);
3434 }
3435
3436
3444 public void unsetRoleUsers(long roleId, List<User> users)
3445 throws PortalException, SystemException {
3446
3447 Role role = rolePersistence.findByPrimaryKey(roleId);
3448
3449 if (role.getName().equals(RoleConstants.USER)) {
3450 return;
3451 }
3452
3453 rolePersistence.removeUsers(roleId, users);
3454
3455 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3456
3457 indexer.reindex(users);
3458
3459 PermissionCacheUtil.clearCache();
3460 }
3461
3462
3470 public void unsetRoleUsers(long roleId, long[] userIds)
3471 throws PortalException, SystemException {
3472
3473 Role role = rolePersistence.findByPrimaryKey(roleId);
3474
3475 if (role.getName().equals(RoleConstants.USER)) {
3476 return;
3477 }
3478
3479 rolePersistence.removeUsers(roleId, userIds);
3480
3481 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3482
3483 indexer.reindex(userIds);
3484
3485 PermissionCacheUtil.clearCache();
3486 }
3487
3488
3496 public void unsetTeamUsers(long teamId, long[] userIds)
3497 throws PortalException, SystemException {
3498
3499 teamPersistence.removeUsers(teamId, userIds);
3500
3501 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3502
3503 indexer.reindex(userIds);
3504
3505 PermissionCacheUtil.clearCache();
3506 }
3507
3508
3516 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
3517 throws PortalException, SystemException {
3518
3519 userGroupPersistence.removeUsers(userGroupId, userIds);
3520
3521 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3522
3523 indexer.reindex(userIds);
3524
3525 PermissionCacheUtil.clearCache();
3526 }
3527
3528
3538 public User updateAgreedToTermsOfUse(
3539 long userId, boolean agreedToTermsOfUse)
3540 throws PortalException, SystemException {
3541
3542 User user = userPersistence.findByPrimaryKey(userId);
3543
3544 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
3545
3546 userPersistence.update(user, false);
3547
3548 return user;
3549 }
3550
3551
3562 public void updateAsset(
3563 long userId, User user, long[] assetCategoryIds,
3564 String[] assetTagNames)
3565 throws PortalException, SystemException {
3566
3567 User owner = userPersistence.findByPrimaryKey(userId);
3568
3569 Company company = companyPersistence.findByPrimaryKey(
3570 owner.getCompanyId());
3571
3572 Group companyGroup = company.getGroup();
3573
3574 assetEntryLocalService.updateEntry(
3575 userId, companyGroup.getGroupId(), User.class.getName(),
3576 user.getUserId(), user.getUuid(), 0, assetCategoryIds,
3577 assetTagNames, false, null, null, null, null, null,
3578 user.getFullName(), null, null, null, null, 0, 0, null, false);
3579 }
3580
3581
3590 public User updateCreateDate(long userId, Date createDate)
3591 throws PortalException, SystemException {
3592
3593 User user = userPersistence.findByPrimaryKey(userId);
3594
3595 user.setCreateDate(createDate);
3596
3597 userPersistence.update(user, false);
3598
3599 return user;
3600 }
3601
3602
3613 public User updateEmailAddress(
3614 long userId, String password, String emailAddress1,
3615 String emailAddress2)
3616 throws PortalException, SystemException {
3617
3618 emailAddress1 = emailAddress1.trim().toLowerCase();
3619 emailAddress2 = emailAddress2.trim().toLowerCase();
3620
3621 User user = userPersistence.findByPrimaryKey(userId);
3622
3623 validateEmailAddress(user, emailAddress1, emailAddress2);
3624
3625 setEmailAddress(
3626 user, password, user.getFirstName(), user.getMiddleName(),
3627 user.getLastName(), emailAddress1);
3628
3629 userPersistence.update(user, false);
3630
3631 return user;
3632 }
3633
3634
3645 public User updateEmailAddress(
3646 long userId, String password, String emailAddress1,
3647 String emailAddress2, ServiceContext serviceContext)
3648 throws PortalException, SystemException {
3649
3650 emailAddress1 = emailAddress1.trim().toLowerCase();
3651 emailAddress2 = emailAddress2.trim().toLowerCase();
3652
3653 User user = userPersistence.findByPrimaryKey(userId);
3654
3655 validateEmailAddress(user, emailAddress1, emailAddress2);
3656
3657 Company company = companyPersistence.findByPrimaryKey(
3658 user.getCompanyId());
3659
3660 if (!company.isStrangersVerify()) {
3661 setEmailAddress(
3662 user, password, user.getFirstName(), user.getMiddleName(),
3663 user.getLastName(), emailAddress1);
3664
3665 userPersistence.update(user, false);
3666 }
3667 else {
3668 sendEmailAddressVerification(user, emailAddress1, serviceContext);
3669 }
3670
3671 return user;
3672 }
3673
3674
3683 public User updateEmailAddressVerified(
3684 long userId, boolean emailAddressVerified)
3685 throws PortalException, SystemException {
3686
3687 User user = userPersistence.findByPrimaryKey(userId);
3688
3689 user.setEmailAddressVerified(emailAddressVerified);
3690
3691 userPersistence.update(user, false);
3692
3693 return user;
3694 }
3695
3696
3705 public User updateFacebookId(long userId, long facebookId)
3706 throws PortalException, SystemException {
3707
3708 User user = userPersistence.findByPrimaryKey(userId);
3709
3710 user.setFacebookId(facebookId);
3711
3712 userPersistence.update(user, false);
3713
3714 return user;
3715 }
3716
3717
3725 public void updateGroups(
3726 long userId, long[] newGroupIds, ServiceContext serviceContext)
3727 throws PortalException, SystemException {
3728
3729 if (newGroupIds == null) {
3730 return;
3731 }
3732
3733 List<Group> oldGroups = userPersistence.getGroups(userId);
3734
3735 List<Long> oldGroupIds = new ArrayList<Long>(oldGroups.size());
3736
3737 for (Group oldGroup : oldGroups) {
3738 long oldGroupId = oldGroup.getGroupId();
3739
3740 oldGroupIds.add(oldGroupId);
3741
3742 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
3743 unsetGroupUsers(
3744 oldGroupId, new long[] {userId}, serviceContext);
3745 }
3746 }
3747
3748 for (long newGroupId : newGroupIds) {
3749 if (!oldGroupIds.contains(newGroupId)) {
3750 addGroupUsers(newGroupId, new long[] {userId});
3751 }
3752 }
3753
3754 if (serviceContext.isIndexingEnabled()) {
3755 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3756
3757 indexer.reindex(new long[] {userId});
3758 }
3759
3760 PermissionCacheUtil.clearCache();
3761 }
3762
3763
3802 public User updateIncompleteUser(
3803 long creatorUserId, long companyId, boolean autoPassword,
3804 String password1, String password2, boolean autoScreenName,
3805 String screenName, String emailAddress, long facebookId,
3806 String openId, Locale locale, String firstName, String middleName,
3807 String lastName, int prefixId, int suffixId, boolean male,
3808 int birthdayMonth, int birthdayDay, int birthdayYear,
3809 String jobTitle, boolean updateUserInformation, boolean sendEmail,
3810 ServiceContext serviceContext)
3811 throws PortalException, SystemException {
3812
3813 User user = getUserByEmailAddress(companyId, emailAddress);
3814
3815 if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
3816 throw new PortalException("Invalid user status");
3817 }
3818
3819 User defaultUser = getDefaultUser(companyId);
3820
3821 if (updateUserInformation) {
3822 autoScreenName = false;
3823
3824 if (PrefsPropsUtil.getBoolean(
3825 companyId,
3826 PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
3827
3828 autoScreenName = true;
3829 }
3830
3831 validate(
3832 companyId, user.getUserId(), autoPassword, password1, password2,
3833 autoScreenName, screenName, emailAddress, firstName, middleName,
3834 lastName, null);
3835
3836 if (!autoPassword) {
3837 if (Validator.isNull(password1) ||
3838 Validator.isNull(password2)) {
3839 throw new UserPasswordException(
3840 UserPasswordException.PASSWORD_INVALID);
3841 }
3842 }
3843
3844 if (autoScreenName) {
3845 ScreenNameGenerator screenNameGenerator =
3846 ScreenNameGeneratorFactory.getInstance();
3847
3848 try {
3849 screenName = screenNameGenerator.generate(
3850 companyId, user.getUserId(), emailAddress);
3851 }
3852 catch (Exception e) {
3853 throw new SystemException(e);
3854 }
3855 }
3856
3857 FullNameGenerator fullNameGenerator =
3858 FullNameGeneratorFactory.getInstance();
3859
3860 String fullName = fullNameGenerator.getFullName(
3861 firstName, middleName, lastName);
3862
3863 String greeting = LanguageUtil.format(
3864 locale, "welcome-x", " " + fullName, false);
3865
3866 if (Validator.isNotNull(password1)) {
3867 user.setPassword(PwdEncryptor.encrypt(password1));
3868 user.setPasswordUnencrypted(password1);
3869 }
3870
3871 user.setPasswordEncrypted(true);
3872
3873 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
3874
3875 if (passwordPolicy.isChangeable() &&
3876 passwordPolicy.isChangeRequired()) {
3877
3878 user.setPasswordReset(true);
3879 }
3880 else {
3881 user.setPasswordReset(false);
3882 }
3883
3884 user.setScreenName(screenName);
3885 user.setFacebookId(facebookId);
3886 user.setOpenId(openId);
3887 user.setLanguageId(locale.toString());
3888 user.setTimeZoneId(defaultUser.getTimeZoneId());
3889 user.setGreeting(greeting);
3890 user.setFirstName(firstName);
3891 user.setMiddleName(middleName);
3892 user.setLastName(lastName);
3893 user.setJobTitle(jobTitle);
3894
3895 Date birthday = PortalUtil.getDate(
3896 birthdayMonth, birthdayDay, birthdayYear,
3897 new ContactBirthdayException());
3898
3899 Contact contact = user.getContact();
3900
3901 contact.setFirstName(firstName);
3902 contact.setMiddleName(middleName);
3903 contact.setLastName(lastName);
3904 contact.setPrefixId(prefixId);
3905 contact.setSuffixId(suffixId);
3906 contact.setMale(male);
3907 contact.setBirthday(birthday);
3908 contact.setJobTitle(jobTitle);
3909
3910 contactPersistence.update(contact, false, serviceContext);
3911
3912
3913
3914 user.setExpandoBridgeAttributes(serviceContext);
3915
3916
3917
3918 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3919
3920 indexer.reindex(user);
3921 }
3922
3923 user.setStatus(WorkflowConstants.STATUS_DRAFT);
3924
3925 userPersistence.update(user, false, serviceContext);
3926
3927
3928
3929 long workflowUserId = creatorUserId;
3930
3931 if (workflowUserId == user.getUserId()) {
3932 workflowUserId = defaultUser.getUserId();
3933 }
3934
3935 serviceContext.setAttribute("autoPassword", autoPassword);
3936 serviceContext.setAttribute("sendEmail", sendEmail);
3937
3938 WorkflowHandlerRegistryUtil.startWorkflowInstance(
3939 companyId, workflowUserId, User.class.getName(), user.getUserId(),
3940 user, serviceContext);
3941
3942 return getUserByEmailAddress(companyId, emailAddress);
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 = ImageToolUtil.read(bytes);
4383
4384 RenderedImage renderedImage = imageBag.getRenderedImage();
4385
4386 if (renderedImage == null) {
4387 throw new UserPortraitTypeException();
4388 }
4389
4390 renderedImage = ImageToolUtil.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 ImageToolUtil.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 reindex(user);
4495
4496 return user;
4497 }
4498
4499
4555 @SuppressWarnings("deprecation")
4556 public User updateUser(
4557 long userId, String oldPassword, String newPassword1,
4558 String newPassword2, boolean passwordReset,
4559 String reminderQueryQuestion, String reminderQueryAnswer,
4560 String screenName, String emailAddress, long facebookId,
4561 String openId, String languageId, String timeZoneId,
4562 String greeting, String comments, String firstName,
4563 String middleName, String lastName, int prefixId, int suffixId,
4564 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
4565 String smsSn, String aimSn, String facebookSn, String icqSn,
4566 String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
4567 String twitterSn, String ymSn, String jobTitle, long[] groupIds,
4568 long[] organizationIds, long[] roleIds,
4569 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
4570 ServiceContext serviceContext)
4571 throws PortalException, SystemException {
4572
4573
4574
4575 User user = userPersistence.findByPrimaryKey(userId);
4576 Company company = companyPersistence.findByPrimaryKey(
4577 user.getCompanyId());
4578 String password = oldPassword;
4579 screenName = getScreenName(screenName);
4580 emailAddress = emailAddress.trim().toLowerCase();
4581 openId = openId.trim();
4582 String oldFullName = user.getFullName();
4583 aimSn = aimSn.trim().toLowerCase();
4584 facebookSn = facebookSn.trim().toLowerCase();
4585 icqSn = icqSn.trim().toLowerCase();
4586 jabberSn = jabberSn.trim().toLowerCase();
4587 msnSn = msnSn.trim().toLowerCase();
4588 mySpaceSn = mySpaceSn.trim().toLowerCase();
4589 skypeSn = skypeSn.trim().toLowerCase();
4590 twitterSn = twitterSn.trim().toLowerCase();
4591 ymSn = ymSn.trim().toLowerCase();
4592 Date now = new Date();
4593
4594 EmailAddressGenerator emailAddressGenerator =
4595 EmailAddressGeneratorFactory.getInstance();
4596
4597 if (emailAddressGenerator.isGenerated(emailAddress)) {
4598 emailAddress = StringPool.BLANK;
4599 }
4600
4601 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
4602 Validator.isNull(emailAddress)) {
4603
4604 emailAddress = emailAddressGenerator.generate(
4605 user.getCompanyId(), userId);
4606 }
4607
4608 validate(
4609 userId, screenName, emailAddress, firstName, middleName, lastName,
4610 smsSn);
4611
4612 if (Validator.isNotNull(newPassword1) ||
4613 Validator.isNotNull(newPassword2)) {
4614
4615 user = updatePassword(
4616 userId, newPassword1, newPassword2, passwordReset);
4617
4618 password = newPassword1;
4619
4620 user.setDigest(StringPool.BLANK);
4621 }
4622
4623 user.setModifiedDate(now);
4624
4625 if (user.getContactId() <= 0) {
4626 user.setContactId(counterLocalService.increment());
4627 }
4628
4629 user.setPasswordReset(passwordReset);
4630
4631 if (Validator.isNotNull(reminderQueryQuestion) &&
4632 Validator.isNotNull(reminderQueryAnswer)) {
4633
4634 user.setReminderQueryQuestion(reminderQueryQuestion);
4635 user.setReminderQueryAnswer(reminderQueryAnswer);
4636 }
4637
4638 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
4639 user.setScreenName(screenName);
4640
4641 user.setDigest(StringPool.BLANK);
4642 }
4643
4644 boolean sendEmailAddressVerification = false;
4645
4646 if (!company.isStrangersVerify()) {
4647 setEmailAddress(
4648 user, password, firstName, middleName, lastName, emailAddress);
4649 }
4650 else {
4651 sendEmailAddressVerification = true;
4652 }
4653
4654 if (serviceContext != null) {
4655 String uuid = serviceContext.getUuid();
4656
4657 if (Validator.isNotNull(uuid)) {
4658 user.setUuid(uuid);
4659 }
4660 }
4661
4662 user.setFacebookId(facebookId);
4663 user.setOpenId(openId);
4664 user.setLanguageId(languageId);
4665 user.setTimeZoneId(timeZoneId);
4666 user.setGreeting(greeting);
4667 user.setComments(comments);
4668 user.setFirstName(firstName);
4669 user.setMiddleName(middleName);
4670 user.setLastName(lastName);
4671 user.setJobTitle(jobTitle);
4672
4673 userPersistence.update(user, false, serviceContext);
4674
4675
4676
4677 Date birthday = PortalUtil.getDate(
4678 birthdayMonth, birthdayDay, birthdayYear,
4679 new ContactBirthdayException());
4680
4681 long contactId = user.getContactId();
4682
4683 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
4684
4685 if (contact == null) {
4686 contact = contactPersistence.create(contactId);
4687
4688 contact.setCompanyId(user.getCompanyId());
4689 contact.setUserName(StringPool.BLANK);
4690 contact.setCreateDate(now);
4691 contact.setAccountId(company.getAccountId());
4692 contact.setParentContactId(
4693 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
4694 }
4695
4696 contact.setModifiedDate(now);
4697 contact.setFirstName(firstName);
4698 contact.setMiddleName(middleName);
4699 contact.setLastName(lastName);
4700 contact.setPrefixId(prefixId);
4701 contact.setSuffixId(suffixId);
4702 contact.setMale(male);
4703 contact.setBirthday(birthday);
4704 contact.setSmsSn(smsSn);
4705 contact.setAimSn(aimSn);
4706 contact.setFacebookSn(facebookSn);
4707 contact.setIcqSn(icqSn);
4708 contact.setJabberSn(jabberSn);
4709 contact.setMsnSn(msnSn);
4710 contact.setMySpaceSn(mySpaceSn);
4711 contact.setSkypeSn(skypeSn);
4712 contact.setTwitterSn(twitterSn);
4713 contact.setYmSn(ymSn);
4714 contact.setJobTitle(jobTitle);
4715
4716 contactPersistence.update(contact, false, serviceContext);
4717
4718
4719
4720 Group group = groupLocalService.getUserGroup(
4721 user.getCompanyId(), userId);
4722
4723 group.setFriendlyURL(StringPool.SLASH + screenName);
4724
4725 groupPersistence.update(group, false);
4726
4727
4728
4729 boolean indexingEnabled = serviceContext.isIndexingEnabled();
4730
4731 serviceContext.setIndexingEnabled(false);
4732
4733 try {
4734 updateGroups(userId, groupIds, serviceContext);
4735 updateOrganizations(userId, organizationIds, serviceContext);
4736 }
4737 finally {
4738 serviceContext.setIndexingEnabled(indexingEnabled);
4739 }
4740
4741
4742
4743 if (roleIds != null) {
4744 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
4745
4746 userPersistence.setRoles(userId, roleIds);
4747 }
4748
4749
4750
4751 updateUserGroupRoles(user, groupIds, organizationIds, userGroupRoles);
4752
4753
4754
4755 if (userGroupIds != null) {
4756 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
4757 userGroupLocalService.copyUserGroupLayouts(
4758 userGroupIds, userId);
4759 }
4760
4761 userPersistence.setUserGroups(userId, userGroupIds);
4762 }
4763
4764
4765
4766 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
4767
4768
4769
4770 if (serviceContext != null) {
4771 updateAsset(
4772 userId, user, serviceContext.getAssetCategoryIds(),
4773 serviceContext.getAssetTagNames());
4774 }
4775
4776
4777
4778 user.setExpandoBridgeAttributes(serviceContext);
4779
4780
4781
4782 if (GetterUtil.getBoolean(
4783 PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
4784 !oldFullName.equals(user.getFullName())) {
4785
4786 mbMessageLocalService.updateUserName(userId, user.getFullName());
4787 }
4788
4789
4790
4791 if (serviceContext.isIndexingEnabled()) {
4792 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
4793
4794 indexer.reindex(user);
4795 }
4796
4797
4798
4799 if (sendEmailAddressVerification) {
4800 sendEmailAddressVerification(user, emailAddress, serviceContext);
4801 }
4802
4803
4804
4805 PermissionCacheUtil.clearCache();
4806
4807 return user;
4808 }
4809
4810
4819 public void verifyEmailAddress(String ticketKey)
4820 throws PortalException, SystemException {
4821
4822 Ticket ticket = ticketLocalService.getTicket(ticketKey);
4823
4824 if (ticket.isExpired() ||
4825 (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
4826
4827 throw new NoSuchTicketException();
4828 }
4829
4830 User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
4831
4832 String emailAddress = ticket.getExtraInfo();
4833
4834 emailAddress = emailAddress.toLowerCase().trim();
4835
4836 if (!emailAddress.equals(user.getEmailAddress())) {
4837 if (userPersistence.fetchByC_EA(
4838 user.getCompanyId(), emailAddress) != null) {
4839
4840 throw new DuplicateUserEmailAddressException();
4841 }
4842
4843 setEmailAddress(
4844 user, StringPool.BLANK, user.getFirstName(),
4845 user.getMiddleName(), user.getLastName(), emailAddress);
4846 }
4847
4848 user.setEmailAddressVerified(true);
4849
4850 userPersistence.update(user, false);
4851
4852 ticketLocalService.deleteTicket(ticket);
4853 }
4854
4855
4901 protected int authenticate(
4902 long companyId, String login, String password, String authType,
4903 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
4904 Map<String, Object> resultsMap)
4905 throws PortalException, SystemException {
4906
4907 if (PropsValues.AUTH_LOGIN_DISABLED) {
4908 return Authenticator.FAILURE;
4909 }
4910
4911 login = login.trim().toLowerCase();
4912
4913 long userId = GetterUtil.getLong(login);
4914
4915
4916
4917 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
4918 if (Validator.isNull(login)) {
4919 throw new UserEmailAddressException();
4920 }
4921 }
4922 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
4923 if (Validator.isNull(login)) {
4924 throw new UserScreenNameException();
4925 }
4926 }
4927 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
4928 if (Validator.isNull(login)) {
4929 throw new UserIdException();
4930 }
4931 }
4932
4933 if (Validator.isNull(password)) {
4934 throw new UserPasswordException(
4935 UserPasswordException.PASSWORD_INVALID);
4936 }
4937
4938 int authResult = Authenticator.FAILURE;
4939
4940
4941
4942 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
4943 authResult = AuthPipeline.authenticateByEmailAddress(
4944 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
4945 headerMap, parameterMap);
4946 }
4947 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
4948 authResult = AuthPipeline.authenticateByScreenName(
4949 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
4950 headerMap, parameterMap);
4951 }
4952 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
4953 authResult = AuthPipeline.authenticateByUserId(
4954 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
4955 headerMap, parameterMap);
4956 }
4957
4958
4959
4960 User user = null;
4961
4962 try {
4963 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
4964 user = userPersistence.findByC_EA(companyId, login);
4965 }
4966 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
4967 user = userPersistence.findByC_SN(companyId, login);
4968 }
4969 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
4970 user = userPersistence.findByC_U(
4971 companyId, GetterUtil.getLong(login));
4972 }
4973 }
4974 catch (NoSuchUserException nsue) {
4975 return Authenticator.DNE;
4976 }
4977
4978 if (user.isDefaultUser()) {
4979 if (_log.isInfoEnabled()) {
4980 _log.info("Authentication is disabled for the default user");
4981 }
4982
4983 return Authenticator.DNE;
4984 }
4985 else if (!user.isActive()) {
4986 if (_log.isInfoEnabled()) {
4987 _log.info(
4988 "Authentication is disabled for inactive user " +
4989 user.getUserId());
4990 }
4991
4992 return Authenticator.FAILURE;
4993 }
4994
4995 if (!user.isPasswordEncrypted()) {
4996 user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
4997 user.setPasswordEncrypted(true);
4998
4999 userPersistence.update(user, false);
5000 }
5001
5002
5003
5004
5005 checkLockout(user);
5006
5007 checkPasswordExpired(user);
5008
5009
5010
5011 if (authResult == Authenticator.SUCCESS) {
5012 if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5013 boolean authenticated = PwdAuthenticator.authenticate(
5014 login, password, user.getPassword());
5015
5016 if (authenticated) {
5017 authResult = Authenticator.SUCCESS;
5018 }
5019 else {
5020 authResult = Authenticator.FAILURE;
5021 }
5022 }
5023 }
5024
5025
5026
5027 if (authResult == Authenticator.SUCCESS) {
5028 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5029 authResult = AuthPipeline.authenticateByEmailAddress(
5030 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5031 headerMap, parameterMap);
5032 }
5033 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5034 authResult = AuthPipeline.authenticateByScreenName(
5035 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5036 headerMap, parameterMap);
5037 }
5038 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5039 authResult = AuthPipeline.authenticateByUserId(
5040 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5041 headerMap, parameterMap);
5042 }
5043 }
5044
5045 if (authResult == Authenticator.SUCCESS) {
5046 if (resultsMap != null) {
5047 resultsMap.put("userId", user.getUserId());
5048 }
5049
5050
5051
5052 boolean updateDigest = true;
5053
5054 if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5055 if (Validator.isNotNull(user.getDigest())) {
5056 updateDigest = false;
5057 }
5058 }
5059
5060 if (updateDigest) {
5061 String digest = user.getDigest(password);
5062
5063 user.setDigest(digest);
5064
5065 userPersistence.update(user, false);
5066 }
5067 }
5068
5069
5070
5071 if (authResult == Authenticator.FAILURE) {
5072 try {
5073 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5074 AuthPipeline.onFailureByEmailAddress(
5075 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5076 parameterMap);
5077 }
5078 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5079 AuthPipeline.onFailureByScreenName(
5080 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5081 parameterMap);
5082 }
5083 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5084 AuthPipeline.onFailureByUserId(
5085 PropsKeys.AUTH_FAILURE, companyId, userId, headerMap,
5086 parameterMap);
5087 }
5088
5089
5090
5091 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5092 user.getCompanyId())) {
5093
5094 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5095
5096 int failedLoginAttempts = user.getFailedLoginAttempts();
5097 int maxFailures = passwordPolicy.getMaxFailure();
5098
5099 if ((failedLoginAttempts >= maxFailures) &&
5100 (maxFailures != 0)) {
5101
5102 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5103 AuthPipeline.onMaxFailuresByEmailAddress(
5104 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5105 headerMap, parameterMap);
5106 }
5107 else if (authType.equals(
5108 CompanyConstants.AUTH_TYPE_SN)) {
5109
5110 AuthPipeline.onMaxFailuresByScreenName(
5111 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5112 headerMap, parameterMap);
5113 }
5114 else if (authType.equals(
5115 CompanyConstants.AUTH_TYPE_ID)) {
5116
5117 AuthPipeline.onMaxFailuresByUserId(
5118 PropsKeys.AUTH_MAX_FAILURES, companyId, userId,
5119 headerMap, parameterMap);
5120 }
5121 }
5122 }
5123 }
5124 catch (Exception e) {
5125 _log.error(e, e);
5126 }
5127 }
5128
5129 return authResult;
5130 }
5131
5132 protected String getScreenName(String screenName) {
5133 return StringUtil.lowerCase(StringUtil.trim(screenName));
5134 }
5135
5136 protected long[] getUserIds(List<User> users) {
5137 long[] userIds = new long[users.size()];
5138
5139 for (int i = 0; i < users.size(); i++) {
5140 User user = users.get(i);
5141
5142 userIds[i] = user.getUserId();
5143 }
5144
5145 return userIds;
5146 }
5147
5148 protected void reindex(final User user) {
5149 final Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
5150
5151 Callable<Void> callable = new Callable<Void>() {
5152
5153 public Void call() throws Exception {
5154 indexer.reindex(user);
5155
5156 return null;
5157 }
5158
5159 };
5160
5161 TransactionCommitCallbackUtil.registerCallback(callable);
5162 }
5163
5164 protected Hits search(
5165 long companyId, String firstName, String middleName,
5166 String lastName, String fullName, String screenName,
5167 String emailAddress, String street, String city, String zip,
5168 String region, String country, int status,
5169 LinkedHashMap<String, Object> params, boolean andSearch, int start,
5170 int end, Sort sort)
5171 throws SystemException {
5172
5173 try {
5174 Map<String, Serializable> attributes =
5175 new HashMap<String, Serializable>();
5176
5177 attributes.put("city", city);
5178 attributes.put("country", country);
5179 attributes.put("emailAddress", emailAddress);
5180 attributes.put("firstName", firstName);
5181 attributes.put("fullName", fullName);
5182 attributes.put("lastName", lastName);
5183 attributes.put("middleName", middleName);
5184 attributes.put("params", params);
5185 attributes.put("region", region);
5186 attributes.put("screenName", screenName);
5187 attributes.put("street", street);
5188 attributes.put("status", status);
5189 attributes.put("zip", zip);
5190
5191 SearchContext searchContext = new SearchContext();
5192
5193 searchContext.setAndSearch(andSearch);
5194 searchContext.setAttributes(attributes);
5195 searchContext.setCompanyId(companyId);
5196 searchContext.setEnd(end);
5197
5198 String keywords = (String)params.remove("keywords");
5199
5200 if (Validator.isNotNull(keywords)) {
5201 searchContext.setKeywords(keywords);
5202 }
5203
5204 searchContext.setSorts(new Sort[] {sort});
5205
5206 QueryConfig queryConfig = new QueryConfig();
5207
5208 queryConfig.setHighlightEnabled(false);
5209 queryConfig.setScoreEnabled(false);
5210
5211 searchContext.setQueryConfig(queryConfig);
5212
5213 searchContext.setStart(start);
5214
5215 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
5216
5217 return indexer.search(searchContext);
5218 }
5219 catch (Exception e) {
5220 throw new SystemException(e);
5221 }
5222 }
5223
5224 protected void sendEmail(
5225 User user, String password, ServiceContext serviceContext)
5226 throws SystemException {
5227
5228 if (!PrefsPropsUtil.getBoolean(
5229 user.getCompanyId(),
5230 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
5231
5232 return;
5233 }
5234
5235 String fromName = PrefsPropsUtil.getString(
5236 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
5237 String fromAddress = PrefsPropsUtil.getString(
5238 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
5239
5240 String toName = user.getFullName();
5241 String toAddress = user.getEmailAddress();
5242
5243 String subject = PrefsPropsUtil.getContent(
5244 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
5245
5246 String body = null;
5247
5248 if (Validator.isNotNull(password)) {
5249 body = PrefsPropsUtil.getContent(
5250 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
5251 }
5252 else {
5253 body = PrefsPropsUtil.getContent(
5254 user.getCompanyId(),
5255 PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
5256 }
5257
5258 SubscriptionSender subscriptionSender = new SubscriptionSender();
5259
5260 subscriptionSender.setBody(body);
5261 subscriptionSender.setCompanyId(user.getCompanyId());
5262 subscriptionSender.setContextAttributes(
5263 "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
5264 "[$USER_SCREENNAME$]", user.getScreenName());
5265 subscriptionSender.setFrom(fromAddress, fromName);
5266 subscriptionSender.setHtmlFormat(true);
5267 subscriptionSender.setMailId("user", user.getUserId());
5268 subscriptionSender.setServiceContext(serviceContext);
5269 subscriptionSender.setSubject(subject);
5270 subscriptionSender.setUserId(user.getUserId());
5271
5272 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
5273
5274 subscriptionSender.flushNotificationsAsync();
5275 }
5276
5277 protected void setEmailAddress(
5278 User user, String password, String firstName, String middleName,
5279 String lastName, String emailAddress)
5280 throws PortalException, SystemException {
5281
5282 if (emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
5283 return;
5284 }
5285
5286 long userId = user.getUserId();
5287
5288
5289
5290 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
5291 Validator.isNotNull(password)) {
5292
5293 mailService.addUser(
5294 user.getCompanyId(), userId, password, firstName, middleName,
5295 lastName, emailAddress);
5296 }
5297
5298
5299
5300 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
5301 mailService.updateEmailAddress(
5302 user.getCompanyId(), userId, emailAddress);
5303 }
5304
5305
5306
5307 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
5308 mailService.deleteEmailAddress(user.getCompanyId(), userId);
5309 }
5310
5311 user.setEmailAddress(emailAddress);
5312 user.setDigest(StringPool.BLANK);
5313 }
5314
5315 protected void updateUserGroupRoles(
5316 User user, long[] groupIds, long[] organizationIds,
5317 List<UserGroupRole> userGroupRoles)
5318 throws PortalException, SystemException {
5319
5320 if (userGroupRoles == null) {
5321 return;
5322 }
5323
5324 List<UserGroupRole> previousUserGroupRoles =
5325 userGroupRolePersistence.findByUserId(user.getUserId());
5326
5327 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
5328 if (userGroupRoles.contains(userGroupRole)) {
5329 userGroupRoles.remove(userGroupRole);
5330 }
5331 else {
5332 userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
5333 }
5334 }
5335
5336 long[] validGroupIds = null;
5337
5338 if (groupIds != null) {
5339 validGroupIds = ArrayUtil.clone(groupIds);
5340 }
5341 else {
5342 validGroupIds = user.getGroupIds();
5343 }
5344
5345 if (organizationIds == null) {
5346 organizationIds = user.getOrganizationIds();
5347 }
5348
5349 long[] organizationGroupIds = new long[organizationIds.length];
5350
5351 for (int i = 0; i < organizationIds.length; i++) {
5352 long organizationId = organizationIds[i];
5353
5354 Organization organization =
5355 organizationPersistence.findByPrimaryKey(organizationId);
5356
5357 Group organizationGroup = organization.getGroup();
5358
5359 organizationGroupIds[i] = organizationGroup.getGroupId();
5360 }
5361
5362 validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
5363
5364 Arrays.sort(validGroupIds);
5365
5366 for (UserGroupRole userGroupRole : userGroupRoles) {
5367 if (Arrays.binarySearch(
5368 validGroupIds, userGroupRole.getGroupId()) >= 0) {
5369
5370 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
5371 }
5372 }
5373 }
5374
5375 protected void validate(
5376 long companyId, long userId, boolean autoPassword, String password1,
5377 String password2, boolean autoScreenName, String screenName,
5378 String emailAddress, String firstName, String middleName,
5379 String lastName, long[] organizationIds)
5380 throws PortalException, SystemException {
5381
5382 Company company = companyPersistence.findByPrimaryKey(companyId);
5383
5384 if (company.isSystem()) {
5385 return;
5386 }
5387
5388 if ((company.getMaxUsers() > 0) &&
5389 (company.getMaxUsers() <=
5390 searchCount(
5391 companyId, null, WorkflowConstants.STATUS_APPROVED,
5392 null))) {
5393
5394 throw new CompanyMaxUsersException();
5395 }
5396
5397 if (!autoScreenName) {
5398 validateScreenName(companyId, userId, screenName);
5399 }
5400
5401 if (!autoPassword) {
5402 PasswordPolicy passwordPolicy =
5403 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
5404
5405 PwdToolkitUtil.validate(
5406 companyId, 0, password1, password2, passwordPolicy);
5407 }
5408
5409 validateEmailAddress(companyId, emailAddress);
5410
5411 if (Validator.isNotNull(emailAddress)) {
5412 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
5413
5414 if ((user != null) && (user.getUserId() != userId)) {
5415 throw new DuplicateUserEmailAddressException();
5416 }
5417 }
5418
5419 validateFullName(companyId, firstName, middleName, lastName);
5420 }
5421
5422 protected void validate(
5423 long userId, String screenName, String emailAddress,
5424 String firstName, String middleName, String lastName, String smsSn)
5425 throws PortalException, SystemException {
5426
5427 User user = userPersistence.findByPrimaryKey(userId);
5428
5429 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
5430 validateScreenName(user.getCompanyId(), userId, screenName);
5431 }
5432
5433 validateEmailAddress(user.getCompanyId(), emailAddress);
5434
5435 if (!user.isDefaultUser()) {
5436 if (Validator.isNotNull(emailAddress) &&
5437 !user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
5438
5439 if (userPersistence.fetchByC_EA(
5440 user.getCompanyId(), emailAddress) != null) {
5441
5442 throw new DuplicateUserEmailAddressException();
5443 }
5444 }
5445
5446 validateFullName(
5447 user.getCompanyId(), firstName, middleName, lastName);
5448 }
5449
5450 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
5451 throw new UserSmsException();
5452 }
5453 }
5454
5455 protected void validateEmailAddress(long companyId, String emailAddress)
5456 throws PortalException, SystemException {
5457
5458 if (Validator.isNull(emailAddress) &&
5459 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
5460
5461 return;
5462 }
5463
5464 if (!Validator.isEmailAddress(emailAddress) ||
5465 emailAddress.startsWith("root@") ||
5466 emailAddress.startsWith("postmaster@")) {
5467
5468 throw new UserEmailAddressException();
5469 }
5470
5471 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
5472 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
5473 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
5474
5475 for (String reservedEmailAddress : reservedEmailAddresses) {
5476 if (emailAddress.equalsIgnoreCase(reservedEmailAddress)) {
5477 throw new ReservedUserEmailAddressException();
5478 }
5479 }
5480 }
5481
5482 protected void validateEmailAddress(
5483 User user, String emailAddress1, String emailAddress2)
5484 throws PortalException, SystemException {
5485
5486 if (!emailAddress1.equals(emailAddress2)) {
5487 throw new UserEmailAddressException();
5488 }
5489
5490 validateEmailAddress(user.getCompanyId(), emailAddress1);
5491 validateEmailAddress(user.getCompanyId(), emailAddress2);
5492
5493 if (!emailAddress1.equalsIgnoreCase(user.getEmailAddress())) {
5494 if (userPersistence.fetchByC_EA(
5495 user.getCompanyId(), emailAddress1) != null) {
5496
5497 throw new DuplicateUserEmailAddressException();
5498 }
5499 }
5500 }
5501
5502 protected void validateFullName(
5503 long companyId, String firstName, String middleName,
5504 String lastName)
5505 throws PortalException, SystemException {
5506
5507 if (Validator.isNull(firstName)) {
5508 throw new ContactFirstNameException();
5509 }
5510 else if (Validator.isNull(lastName) &&
5511 PrefsPropsUtil.getBoolean(
5512 companyId, PropsKeys.USERS_LAST_NAME_REQUIRED,
5513 PropsValues.USERS_LAST_NAME_REQUIRED)) {
5514
5515 throw new ContactLastNameException();
5516 }
5517
5518 FullNameValidator fullNameValidator =
5519 FullNameValidatorFactory.getInstance();
5520
5521 if (!fullNameValidator.validate(
5522 companyId, firstName, middleName, lastName)) {
5523
5524 throw new ContactFullNameException();
5525 }
5526 }
5527
5528 protected void validatePassword(
5529 long companyId, long userId, String password1, String password2)
5530 throws PortalException, SystemException {
5531
5532 if (Validator.isNull(password1) || Validator.isNull(password2)) {
5533 throw new UserPasswordException(
5534 UserPasswordException.PASSWORD_INVALID);
5535 }
5536
5537 if (!password1.equals(password2)) {
5538 throw new UserPasswordException(
5539 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
5540 }
5541
5542 PasswordPolicy passwordPolicy =
5543 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
5544
5545 PwdToolkitUtil.validate(
5546 companyId, userId, password1, password2, passwordPolicy);
5547 }
5548
5549 protected void validateReminderQuery(String question, String answer)
5550 throws PortalException {
5551
5552 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
5553 return;
5554 }
5555
5556 if (Validator.isNull(question)) {
5557 throw new UserReminderQueryException("Question cannot be null");
5558 }
5559
5560 if (Validator.isNull(answer)) {
5561 throw new UserReminderQueryException("Answer cannot be null");
5562 }
5563 }
5564
5565 protected void validateScreenName(
5566 long companyId, long userId, String screenName)
5567 throws PortalException, SystemException {
5568
5569 if (Validator.isNull(screenName)) {
5570 throw new UserScreenNameException();
5571 }
5572
5573 ScreenNameValidator screenNameValidator =
5574 ScreenNameValidatorFactory.getInstance();
5575
5576 if (!screenNameValidator.validate(companyId, screenName)) {
5577 throw new UserScreenNameException();
5578 }
5579
5580 if (Validator.isNumber(screenName)) {
5581 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
5582 throw new UserScreenNameException();
5583 }
5584
5585 if (!screenName.equals(String.valueOf(userId))) {
5586 Group group = groupPersistence.fetchByPrimaryKey(
5587 GetterUtil.getLong(screenName));
5588
5589 if (group != null) {
5590 throw new UserScreenNameException();
5591 }
5592 }
5593 }
5594
5595 for (char c : screenName.toCharArray()) {
5596 if ((!Validator.isChar(c)) && (!Validator.isDigit(c)) &&
5597 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
5598 (c != CharPool.UNDERLINE)) {
5599
5600 throw new UserScreenNameException();
5601 }
5602 }
5603
5604 String[] anonymousNames = PrincipalBean.ANONYMOUS_NAMES;
5605
5606 for (String anonymousName : anonymousNames) {
5607 if (screenName.equalsIgnoreCase(anonymousName)) {
5608 throw new UserScreenNameException();
5609 }
5610 }
5611
5612 User user = userPersistence.fetchByC_SN(companyId, screenName);
5613
5614 if ((user != null) && (user.getUserId() != userId)) {
5615 throw new DuplicateUserScreenNameException();
5616 }
5617
5618 String friendlyURL = StringPool.SLASH + screenName;
5619
5620 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
5621
5622 if ((group != null) && (group.getClassPK() != userId)) {
5623 throw new GroupFriendlyURLException(
5624 GroupFriendlyURLException.DUPLICATE);
5625 }
5626
5627 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
5628
5629 if (exceptionType != -1) {
5630 throw new UserScreenNameException(
5631 new GroupFriendlyURLException(exceptionType));
5632 }
5633
5634 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
5635 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
5636 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
5637
5638 for (String reservedScreenName : reservedScreenNames) {
5639 if (screenName.equalsIgnoreCase(reservedScreenName)) {
5640 throw new ReservedUserScreenNameException();
5641 }
5642 }
5643 }
5644
5645 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
5646
5647 private static Map<Long, User> _defaultUsers =
5648 new ConcurrentHashMap<Long, User>();
5649
5650 }