001
014
015 package com.liferay.portal.service.impl;
016
017 import com.liferay.portal.CompanyMaxUsersException;
018 import com.liferay.portal.ContactBirthdayException;
019 import com.liferay.portal.ContactFirstNameException;
020 import com.liferay.portal.ContactFullNameException;
021 import com.liferay.portal.ContactLastNameException;
022 import com.liferay.portal.DuplicateUserEmailAddressException;
023 import com.liferay.portal.DuplicateUserScreenNameException;
024 import com.liferay.portal.GroupFriendlyURLException;
025 import com.liferay.portal.ModelListenerException;
026 import com.liferay.portal.NoSuchContactException;
027 import com.liferay.portal.NoSuchGroupException;
028 import com.liferay.portal.NoSuchOrganizationException;
029 import com.liferay.portal.NoSuchRoleException;
030 import com.liferay.portal.NoSuchTicketException;
031 import com.liferay.portal.NoSuchUserException;
032 import com.liferay.portal.NoSuchUserGroupException;
033 import com.liferay.portal.PasswordExpiredException;
034 import com.liferay.portal.RequiredUserException;
035 import com.liferay.portal.ReservedUserEmailAddressException;
036 import com.liferay.portal.ReservedUserScreenNameException;
037 import com.liferay.portal.UserEmailAddressException;
038 import com.liferay.portal.UserIdException;
039 import com.liferay.portal.UserLockoutException;
040 import com.liferay.portal.UserPasswordException;
041 import com.liferay.portal.UserPortraitSizeException;
042 import com.liferay.portal.UserPortraitTypeException;
043 import com.liferay.portal.UserReminderQueryException;
044 import com.liferay.portal.UserScreenNameException;
045 import com.liferay.portal.UserSmsException;
046 import com.liferay.portal.kernel.exception.PortalException;
047 import com.liferay.portal.kernel.exception.SystemException;
048 import com.liferay.portal.kernel.image.ImageBag;
049 import com.liferay.portal.kernel.image.ImageToolUtil;
050 import com.liferay.portal.kernel.language.LanguageUtil;
051 import com.liferay.portal.kernel.log.Log;
052 import com.liferay.portal.kernel.log.LogFactoryUtil;
053 import com.liferay.portal.kernel.search.Hits;
054 import com.liferay.portal.kernel.search.Indexer;
055 import com.liferay.portal.kernel.search.IndexerRegistryUtil;
056 import com.liferay.portal.kernel.search.QueryConfig;
057 import com.liferay.portal.kernel.search.SearchContext;
058 import com.liferay.portal.kernel.search.Sort;
059 import com.liferay.portal.kernel.spring.aop.Skip;
060 import com.liferay.portal.kernel.transaction.Propagation;
061 import com.liferay.portal.kernel.transaction.Transactional;
062 import com.liferay.portal.kernel.util.ArrayUtil;
063 import com.liferay.portal.kernel.util.CharPool;
064 import com.liferay.portal.kernel.util.Digester;
065 import com.liferay.portal.kernel.util.DigesterUtil;
066 import com.liferay.portal.kernel.util.GetterUtil;
067 import com.liferay.portal.kernel.util.KeyValuePair;
068 import com.liferay.portal.kernel.util.OrderByComparator;
069 import com.liferay.portal.kernel.util.PropsKeys;
070 import com.liferay.portal.kernel.util.StringPool;
071 import com.liferay.portal.kernel.util.StringUtil;
072 import com.liferay.portal.kernel.util.Validator;
073 import com.liferay.portal.kernel.workflow.WorkflowConstants;
074 import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil;
075 import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
076 import com.liferay.portal.model.Account;
077 import com.liferay.portal.model.Company;
078 import com.liferay.portal.model.CompanyConstants;
079 import com.liferay.portal.model.Contact;
080 import com.liferay.portal.model.ContactConstants;
081 import com.liferay.portal.model.Group;
082 import com.liferay.portal.model.GroupConstants;
083 import com.liferay.portal.model.Layout;
084 import com.liferay.portal.model.Organization;
085 import com.liferay.portal.model.PasswordPolicy;
086 import com.liferay.portal.model.ResourceConstants;
087 import com.liferay.portal.model.Role;
088 import com.liferay.portal.model.RoleConstants;
089 import com.liferay.portal.model.Ticket;
090 import com.liferay.portal.model.TicketConstants;
091 import com.liferay.portal.model.User;
092 import com.liferay.portal.model.UserGroup;
093 import com.liferay.portal.model.UserGroupRole;
094 import com.liferay.portal.model.impl.LayoutImpl;
095 import com.liferay.portal.security.auth.AuthPipeline;
096 import com.liferay.portal.security.auth.Authenticator;
097 import com.liferay.portal.security.auth.EmailAddressGenerator;
098 import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
099 import com.liferay.portal.security.auth.FullNameGenerator;
100 import com.liferay.portal.security.auth.FullNameGeneratorFactory;
101 import com.liferay.portal.security.auth.FullNameValidator;
102 import com.liferay.portal.security.auth.FullNameValidatorFactory;
103 import com.liferay.portal.security.auth.PrincipalException;
104 import com.liferay.portal.security.auth.ScreenNameGenerator;
105 import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
106 import com.liferay.portal.security.auth.ScreenNameValidator;
107 import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
108 import com.liferay.portal.security.ldap.LDAPSettingsUtil;
109 import com.liferay.portal.security.permission.PermissionCacheUtil;
110 import com.liferay.portal.security.pwd.PwdAuthenticator;
111 import com.liferay.portal.security.pwd.PwdEncryptor;
112 import com.liferay.portal.security.pwd.PwdToolkitUtil;
113 import com.liferay.portal.service.ServiceContext;
114 import com.liferay.portal.service.base.PrincipalBean;
115 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
116 import com.liferay.portal.spring.transaction.TransactionCommitCallbackUtil;
117 import com.liferay.portal.util.PortalUtil;
118 import com.liferay.portal.util.PrefsPropsUtil;
119 import com.liferay.portal.util.PropsValues;
120 import com.liferay.portal.util.SubscriptionSender;
121 import com.liferay.portlet.documentlibrary.ImageSizeException;
122 import com.liferay.portlet.messageboards.model.MBMessage;
123 import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
124 import com.liferay.util.Encryptor;
125 import com.liferay.util.EncryptorException;
126
127 import java.awt.image.RenderedImage;
128
129 import java.io.IOException;
130 import java.io.Serializable;
131
132 import java.util.ArrayList;
133 import java.util.Arrays;
134 import java.util.Date;
135 import java.util.HashMap;
136 import java.util.HashSet;
137 import java.util.LinkedHashMap;
138 import java.util.List;
139 import java.util.Locale;
140 import java.util.Map;
141 import java.util.Set;
142 import java.util.concurrent.Callable;
143 import java.util.concurrent.ConcurrentHashMap;
144
145
156 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
157
158
168 public void addDefaultGroups(long userId)
169 throws PortalException, SystemException {
170
171 User user = userPersistence.findByPrimaryKey(userId);
172
173 Set<Long> groupIdsSet = new HashSet<Long>();
174
175 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
176 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
177 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
178
179 for (String defaultGroupName : defaultGroupNames) {
180 Company company = companyPersistence.findByPrimaryKey(
181 user.getCompanyId());
182
183 Account account = company.getAccount();
184
185 if (defaultGroupName.equalsIgnoreCase(account.getName())) {
186 defaultGroupName = GroupConstants.GUEST;
187 }
188
189 try {
190 Group group = groupPersistence.findByC_N(
191 user.getCompanyId(), defaultGroupName);
192
193 if (!userPersistence.containsGroup(
194 userId, group.getGroupId())) {
195
196 groupIdsSet.add(group.getGroupId());
197 }
198 }
199 catch (NoSuchGroupException nsge) {
200 }
201 }
202
203 long[] groupIds = ArrayUtil.toArray(
204 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
205
206 groupLocalService.addUserGroups(userId, groupIds);
207 }
208
209
219 public void addDefaultRoles(long userId)
220 throws PortalException, SystemException {
221
222 User user = userPersistence.findByPrimaryKey(userId);
223
224 Set<Long> roleIdSet = new HashSet<Long>();
225
226 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
227 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
228 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
229
230 for (String defaultRoleName : defaultRoleNames) {
231 try {
232 Role role = rolePersistence.findByC_N(
233 user.getCompanyId(), defaultRoleName);
234
235 if (!userPersistence.containsRole(userId, role.getRoleId())) {
236 roleIdSet.add(role.getRoleId());
237 }
238 }
239 catch (NoSuchRoleException nsre) {
240 }
241 }
242
243 long[] roleIds = ArrayUtil.toArray(
244 roleIdSet.toArray(new Long[roleIdSet.size()]));
245
246 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
247
248 userPersistence.addRoles(userId, roleIds);
249 }
250
251
261 @SuppressWarnings("deprecation")
262 public void addDefaultUserGroups(long userId)
263 throws PortalException, SystemException {
264
265 User user = userPersistence.findByPrimaryKey(userId);
266
267 Set<Long> userGroupIdSet = new HashSet<Long>();
268
269 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
270 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
271 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
272
273 for (String defaultUserGroupName : defaultUserGroupNames) {
274 try {
275 UserGroup userGroup = userGroupPersistence.findByC_N(
276 user.getCompanyId(), defaultUserGroupName);
277
278 if (!userPersistence.containsUserGroup(
279 userId, userGroup.getUserGroupId())) {
280
281 userGroupIdSet.add(userGroup.getUserGroupId());
282 }
283 }
284 catch (NoSuchUserGroupException nsuge) {
285 }
286 }
287
288 long[] userGroupIds = ArrayUtil.toArray(
289 userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
290
291 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
292 for (long userGroupId : userGroupIds) {
293 userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
294 }
295 }
296
297 userPersistence.addUserGroups(userId, userGroupIds);
298 }
299
300
309 public void addGroupUsers(long groupId, long[] userIds)
310 throws PortalException, SystemException {
311
312 groupPersistence.addUsers(groupId, userIds);
313
314 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
315
316 indexer.reindex(userIds);
317
318 PermissionCacheUtil.clearCache();
319 }
320
321
330 public void addOrganizationUsers(long organizationId, long[] userIds)
331 throws PortalException, SystemException {
332
333 organizationPersistence.addUsers(organizationId, userIds);
334
335 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
336
337 indexer.reindex(userIds);
338
339 PermissionCacheUtil.clearCache();
340 }
341
342
350 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
351 throws SystemException {
352
353 passwordPolicyRelLocalService.addPasswordPolicyRels(
354 passwordPolicyId, User.class.getName(), userIds);
355 }
356
357
366 public void addRoleUsers(long roleId, long[] userIds)
367 throws PortalException, SystemException {
368
369 rolePersistence.addUsers(roleId, userIds);
370
371 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
372
373 indexer.reindex(userIds);
374
375 PermissionCacheUtil.clearCache();
376 }
377
378
387 public void addTeamUsers(long teamId, long[] userIds)
388 throws PortalException, SystemException {
389
390 teamPersistence.addUsers(teamId, userIds);
391
392 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
393
394 indexer.reindex(userIds);
395
396 PermissionCacheUtil.clearCache();
397 }
398
399
447 public User addUser(
448 long creatorUserId, long companyId, boolean autoPassword,
449 String password1, String password2, boolean autoScreenName,
450 String screenName, String emailAddress, long facebookId,
451 String openId, Locale locale, String firstName, String middleName,
452 String lastName, int prefixId, int suffixId, boolean male,
453 int birthdayMonth, int birthdayDay, int birthdayYear,
454 String jobTitle, long[] groupIds, long[] organizationIds,
455 long[] roleIds, long[] userGroupIds, boolean sendEmail,
456 ServiceContext serviceContext)
457 throws PortalException, SystemException {
458
459 boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
460
461 try {
462 WorkflowThreadLocal.setEnabled(false);
463
464 return addUserWithWorkflow(
465 creatorUserId, companyId, autoPassword, password1, password2,
466 autoScreenName, screenName, emailAddress, facebookId, openId,
467 locale, firstName, middleName, lastName, prefixId, suffixId,
468 male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
469 groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
470 serviceContext);
471 }
472 finally {
473 WorkflowThreadLocal.setEnabled(workflowEnabled);
474 }
475 }
476
477
486 @SuppressWarnings("deprecation")
487 public void addUserGroupUsers(long userGroupId, long[] userIds)
488 throws PortalException, SystemException {
489
490 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
491 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
492 }
493
494 userGroupPersistence.addUsers(userGroupId, userIds);
495
496 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
497
498 indexer.reindex(userIds);
499
500 PermissionCacheUtil.clearCache();
501 }
502
503
551 @SuppressWarnings("deprecation")
552 public User addUserWithWorkflow(
553 long creatorUserId, long companyId, boolean autoPassword,
554 String password1, String password2, boolean autoScreenName,
555 String screenName, String emailAddress, long facebookId,
556 String openId, Locale locale, String firstName, String middleName,
557 String lastName, int prefixId, int suffixId, boolean male,
558 int birthdayMonth, int birthdayDay, int birthdayYear,
559 String jobTitle, long[] groupIds, long[] organizationIds,
560 long[] roleIds, long[] userGroupIds, boolean sendEmail,
561 ServiceContext serviceContext)
562 throws PortalException, SystemException {
563
564
565
566 Company company = companyPersistence.findByPrimaryKey(companyId);
567 screenName = getScreenName(screenName);
568 emailAddress = emailAddress.trim().toLowerCase();
569 openId = openId.trim();
570 Date now = new Date();
571
572 if (PrefsPropsUtil.getBoolean(
573 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
574
575 autoScreenName = true;
576 }
577
578 long userId = counterLocalService.increment();
579
580 EmailAddressGenerator emailAddressGenerator =
581 EmailAddressGeneratorFactory.getInstance();
582
583 if (emailAddressGenerator.isGenerated(emailAddress)) {
584 emailAddress = StringPool.BLANK;
585 }
586
587 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
588 Validator.isNull(emailAddress)) {
589
590 emailAddress = emailAddressGenerator.generate(companyId, userId);
591 }
592
593 validate(
594 companyId, userId, autoPassword, password1, password2,
595 autoScreenName, screenName, emailAddress, firstName, middleName,
596 lastName, organizationIds);
597
598 if (!autoPassword) {
599 if (Validator.isNull(password1) || Validator.isNull(password2)) {
600 throw new UserPasswordException(
601 UserPasswordException.PASSWORD_INVALID);
602 }
603 }
604
605 if (autoScreenName) {
606 ScreenNameGenerator screenNameGenerator =
607 ScreenNameGeneratorFactory.getInstance();
608
609 try {
610 screenName = screenNameGenerator.generate(
611 companyId, userId, emailAddress);
612 }
613 catch (Exception e) {
614 throw new SystemException(e);
615 }
616 }
617
618 User defaultUser = getDefaultUser(companyId);
619
620 FullNameGenerator fullNameGenerator =
621 FullNameGeneratorFactory.getInstance();
622
623 String fullName = fullNameGenerator.getFullName(
624 firstName, middleName, lastName);
625
626 String greeting = LanguageUtil.format(
627 locale, "welcome-x", " " + fullName, false);
628
629 User user = userPersistence.create(userId);
630
631 if (serviceContext != null) {
632 String uuid = serviceContext.getUuid();
633
634 if (Validator.isNotNull(uuid)) {
635 user.setUuid(uuid);
636 }
637 }
638
639 user.setCompanyId(companyId);
640 user.setCreateDate(now);
641 user.setModifiedDate(now);
642 user.setDefaultUser(false);
643 user.setContactId(counterLocalService.increment());
644
645 if (Validator.isNotNull(password1)) {
646 user.setPassword(PwdEncryptor.encrypt(password1));
647 user.setPasswordUnencrypted(password1);
648 }
649
650 user.setPasswordEncrypted(true);
651
652 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
653
654 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
655 passwordPolicy.isChangeRequired()) {
656
657 user.setPasswordReset(true);
658 }
659 else {
660 user.setPasswordReset(false);
661 }
662
663 user.setDigest(StringPool.BLANK);
664 user.setScreenName(screenName);
665 user.setEmailAddress(emailAddress);
666 user.setFacebookId(facebookId);
667 user.setOpenId(openId);
668 user.setLanguageId(locale.toString());
669 user.setTimeZoneId(defaultUser.getTimeZoneId());
670 user.setGreeting(greeting);
671 user.setFirstName(firstName);
672 user.setMiddleName(middleName);
673 user.setLastName(lastName);
674 user.setJobTitle(jobTitle);
675 user.setStatus(WorkflowConstants.STATUS_DRAFT);
676
677 userPersistence.update(user, false, serviceContext);
678
679
680
681 String creatorUserName = StringPool.BLANK;
682
683 if (creatorUserId <= 0) {
684 creatorUserId = user.getUserId();
685
686
687
688
689
690 }
691 else {
692 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
693
694 creatorUserName = creatorUser.getFullName();
695 }
696
697 resourceLocalService.addResources(
698 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
699 false, false, false);
700
701
702
703 Date birthday = PortalUtil.getDate(
704 birthdayMonth, birthdayDay, birthdayYear,
705 new ContactBirthdayException());
706
707 Contact contact = contactPersistence.create(user.getContactId());
708
709 contact.setCompanyId(user.getCompanyId());
710 contact.setUserId(creatorUserId);
711 contact.setUserName(creatorUserName);
712 contact.setCreateDate(now);
713 contact.setModifiedDate(now);
714 contact.setAccountId(company.getAccountId());
715 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
716 contact.setFirstName(firstName);
717 contact.setMiddleName(middleName);
718 contact.setLastName(lastName);
719 contact.setPrefixId(prefixId);
720 contact.setSuffixId(suffixId);
721 contact.setMale(male);
722 contact.setBirthday(birthday);
723 contact.setJobTitle(jobTitle);
724
725 contactPersistence.update(contact, false, serviceContext);
726
727
728
729 groupLocalService.addGroup(
730 user.getUserId(), User.class.getName(), user.getUserId(), null,
731 null, 0, StringPool.SLASH + screenName, false, true, null);
732
733
734
735 if (groupIds != null) {
736 groupLocalService.addUserGroups(userId, groupIds);
737 }
738
739 addDefaultGroups(userId);
740
741
742
743 updateOrganizations(userId, organizationIds, false);
744
745
746
747 if (roleIds != null) {
748 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
749
750 userPersistence.setRoles(userId, roleIds);
751 }
752
753 addDefaultRoles(userId);
754
755
756
757 if (userGroupIds != null) {
758 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
759 for (long userGroupId : userGroupIds) {
760 userGroupLocalService.copyUserGroupLayouts(
761 userGroupId, new long[] {userId});
762 }
763 }
764
765 userPersistence.setUserGroups(userId, userGroupIds);
766 }
767
768 addDefaultUserGroups(userId);
769
770
771
772 if (serviceContext != null) {
773 updateAsset(
774 creatorUserId, user, serviceContext.getAssetCategoryIds(),
775 serviceContext.getAssetTagNames());
776 }
777
778
779
780 if (serviceContext != null) {
781 user.setExpandoBridgeAttributes(serviceContext);
782 }
783
784
785
786 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
787 reindex(user);
788 }
789
790
791
792 long workflowUserId = creatorUserId;
793
794 if (workflowUserId == userId) {
795 workflowUserId = defaultUser.getUserId();
796 }
797
798 ServiceContext workflowServiceContext = serviceContext;
799
800 if (workflowServiceContext == null) {
801 workflowServiceContext = new ServiceContext();
802 }
803
804 workflowServiceContext.setAttribute("autoPassword", autoPassword);
805 workflowServiceContext.setAttribute("sendEmail", sendEmail);
806
807 WorkflowHandlerRegistryUtil.startWorkflowInstance(
808 companyId, workflowUserId, User.class.getName(), userId, user,
809 workflowServiceContext);
810
811 if (serviceContext != null) {
812 String passwordUnencrypted =
813 (String)serviceContext.getAttribute("passwordUnencrypted");
814
815 if (Validator.isNotNull(passwordUnencrypted)) {
816 user.setPasswordUnencrypted(passwordUnencrypted);
817 }
818 }
819
820 return user;
821 }
822
823
847 public int authenticateByEmailAddress(
848 long companyId, String emailAddress, String password,
849 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
850 Map<String, Object> resultsMap)
851 throws PortalException, SystemException {
852
853 return authenticate(
854 companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
855 headerMap, parameterMap, resultsMap);
856 }
857
858
882 public int authenticateByScreenName(
883 long companyId, String screenName, String password,
884 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
885 Map<String, Object> resultsMap)
886 throws PortalException, SystemException {
887
888 return authenticate(
889 companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
890 headerMap, parameterMap, resultsMap);
891 }
892
893
917 public int authenticateByUserId(
918 long companyId, long userId, String password,
919 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
920 Map<String, Object> resultsMap)
921 throws PortalException, SystemException {
922
923 return authenticate(
924 companyId, String.valueOf(userId), password,
925 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap, resultsMap);
926 }
927
928
968 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
969 public long authenticateForBasic(
970 long companyId, String authType, String login, String password)
971 throws PortalException, SystemException {
972
973 if (PropsValues.AUTH_LOGIN_DISABLED) {
974 return 0;
975 }
976
977 try {
978 User user = null;
979
980 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
981 user = getUserByEmailAddress(companyId, login);
982 }
983 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
984 user = getUserByScreenName(companyId, login);
985 }
986 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
987 user = getUserById(companyId, GetterUtil.getLong(login));
988 }
989
990 if (user.isDefaultUser()) {
991 if (_log.isInfoEnabled()) {
992 _log.info(
993 "Basic authentication is disabled for the default " +
994 "user");
995 }
996
997 return 0;
998 }
999 else if (!user.isActive()) {
1000 if (_log.isInfoEnabled()) {
1001 _log.info(
1002 "Basic authentication is disabled for inactive user " +
1003 user.getUserId());
1004 }
1005
1006 return 0;
1007 }
1008
1009 if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
1010 return user.getUserId();
1011 }
1012
1013 String userPassword = user.getPassword();
1014
1015 if (!user.isPasswordEncrypted()) {
1016 userPassword = PwdEncryptor.encrypt(userPassword);
1017 }
1018
1019 String encPassword = PwdEncryptor.encrypt(password);
1020
1021 if (userPassword.equals(password) ||
1022 userPassword.equals(encPassword)) {
1023
1024 return user.getUserId();
1025 }
1026 }
1027 catch (NoSuchUserException nsue) {
1028 }
1029
1030 return 0;
1031 }
1032
1033
1051 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1052 public long authenticateForDigest(
1053 long companyId, String username, String realm, String nonce,
1054 String method, String uri, String response)
1055 throws PortalException, SystemException {
1056
1057 if (PropsValues.AUTH_LOGIN_DISABLED) {
1058 return 0;
1059 }
1060
1061
1062
1063 User user = null;
1064
1065 try {
1066 user = getUserByEmailAddress(companyId, username);
1067 }
1068 catch (NoSuchUserException nsue) {
1069 try {
1070 user = getUserByScreenName(companyId, username);
1071 }
1072 catch (NoSuchUserException nsue2) {
1073 try {
1074 user = getUserById(GetterUtil.getLong(username));
1075 }
1076 catch (NoSuchUserException nsue3) {
1077 return 0;
1078 }
1079 }
1080 }
1081
1082 if (user.isDefaultUser()) {
1083 if (_log.isInfoEnabled()) {
1084 _log.info(
1085 "Digest authentication is disabled for the default user");
1086 }
1087
1088 return 0;
1089 }
1090 else if (!user.isActive()) {
1091 if (_log.isInfoEnabled()) {
1092 _log.info(
1093 "Digest authentication is disabled for inactive user " +
1094 user.getUserId());
1095 }
1096
1097 return 0;
1098 }
1099
1100
1101
1102 String digest = user.getDigest();
1103
1104 if (Validator.isNull(digest)) {
1105 _log.error(
1106 "User must first login through the portal " + user.getUserId());
1107
1108 return 0;
1109 }
1110
1111 String[] digestArray = StringUtil.split(user.getDigest());
1112
1113 for (String ha1 : digestArray) {
1114 String ha2 = DigesterUtil.digestHex(Digester.MD5, method, uri);
1115
1116 String curResponse = DigesterUtil.digestHex(
1117 Digester.MD5, ha1, nonce, ha2);
1118
1119 if (response.equals(curResponse)) {
1120 return user.getUserId();
1121 }
1122 }
1123
1124 return 0;
1125 }
1126
1127
1136 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1137 public boolean authenticateForJAAS(long userId, String encPassword) {
1138 if (PropsValues.AUTH_LOGIN_DISABLED) {
1139 return false;
1140 }
1141
1142 try {
1143 User user = userPersistence.findByPrimaryKey(userId);
1144
1145 if (user.isDefaultUser()) {
1146 if (_log.isInfoEnabled()) {
1147 _log.info(
1148 "JAAS authentication is disabled for the default user");
1149 }
1150
1151 return false;
1152 }
1153 else if (!user.isActive()) {
1154 if (_log.isInfoEnabled()) {
1155 _log.info(
1156 "JAAS authentication is disabled for inactive user " +
1157 userId);
1158 }
1159
1160 return false;
1161 }
1162
1163 String password = user.getPassword();
1164
1165 if (user.isPasswordEncrypted()) {
1166 if (password.equals(encPassword)) {
1167 return true;
1168 }
1169
1170 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1171 encPassword = PwdEncryptor.encrypt(encPassword, password);
1172
1173 if (password.equals(encPassword)) {
1174 return true;
1175 }
1176 }
1177 }
1178 else {
1179 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1180 if (password.equals(encPassword)) {
1181 return true;
1182 }
1183 }
1184
1185 password = PwdEncryptor.encrypt(password);
1186
1187 if (password.equals(encPassword)) {
1188 return true;
1189 }
1190 }
1191 }
1192 catch (Exception e) {
1193 _log.error(e);
1194 }
1195
1196 return false;
1197 }
1198
1199
1207 public void checkLockout(User user)
1208 throws PortalException, SystemException {
1209
1210 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1211 return;
1212 }
1213
1214 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1215
1216 if (passwordPolicy.isLockout()) {
1217
1218
1219
1220 Date now = new Date();
1221 int failedLoginAttempts = user.getFailedLoginAttempts();
1222
1223 if (failedLoginAttempts > 0) {
1224 long failedLoginTime = user.getLastFailedLoginDate().getTime();
1225 long elapsedTime = now.getTime() - failedLoginTime;
1226 long requiredElapsedTime =
1227 passwordPolicy.getResetFailureCount() * 1000;
1228
1229 if ((requiredElapsedTime != 0) &&
1230 (elapsedTime > requiredElapsedTime)) {
1231
1232 user.setLastFailedLoginDate(null);
1233 user.setFailedLoginAttempts(0);
1234
1235 userPersistence.update(user, false);
1236 }
1237 }
1238
1239
1240
1241 if (user.isLockout()) {
1242 long lockoutTime = user.getLockoutDate().getTime();
1243 long elapsedTime = now.getTime() - lockoutTime;
1244 long requiredElapsedTime =
1245 passwordPolicy.getLockoutDuration() * 1000;
1246
1247 if ((requiredElapsedTime != 0) &&
1248 (elapsedTime > requiredElapsedTime)) {
1249
1250 user.setLockout(false);
1251 user.setLockoutDate(null);
1252
1253 userPersistence.update(user, false);
1254 }
1255 }
1256
1257 if (user.isLockout()) {
1258 throw new UserLockoutException();
1259 }
1260 }
1261 }
1262
1263
1270 public void checkLoginFailure(User user) throws SystemException {
1271 Date now = new Date();
1272
1273 int failedLoginAttempts = user.getFailedLoginAttempts();
1274
1275 user.setLastFailedLoginDate(now);
1276 user.setFailedLoginAttempts(++failedLoginAttempts);
1277
1278 userPersistence.update(user, false);
1279 }
1280
1281
1291 public void checkLoginFailureByEmailAddress(
1292 long companyId, String emailAddress)
1293 throws PortalException, SystemException {
1294
1295 User user = getUserByEmailAddress(companyId, emailAddress);
1296
1297 checkLoginFailure(user);
1298 }
1299
1300
1308 public void checkLoginFailureById(long userId)
1309 throws PortalException, SystemException {
1310
1311 User user = userPersistence.findByPrimaryKey(userId);
1312
1313 checkLoginFailure(user);
1314 }
1315
1316
1325 public void checkLoginFailureByScreenName(long companyId, String screenName)
1326 throws PortalException, SystemException {
1327
1328 User user = getUserByScreenName(companyId, screenName);
1329
1330 checkLoginFailure(user);
1331 }
1332
1333
1343 public void checkPasswordExpired(User user)
1344 throws PortalException, SystemException {
1345
1346 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1347 return;
1348 }
1349
1350 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1351
1352
1353
1354 if (isPasswordExpired(user)) {
1355 int graceLoginCount = user.getGraceLoginCount();
1356
1357 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
1358 user.setGraceLoginCount(++graceLoginCount);
1359
1360 userPersistence.update(user, false);
1361 }
1362 else {
1363 user.setDigest(StringPool.BLANK);
1364
1365 userPersistence.update(user, false);
1366
1367 throw new PasswordExpiredException();
1368 }
1369 }
1370
1371
1372
1373 if (isPasswordExpiringSoon(user)) {
1374 user.setPasswordReset(true);
1375
1376 userPersistence.update(user, false);
1377 }
1378
1379
1380
1381 if (passwordPolicy.isChangeable() &&
1382 passwordPolicy.isChangeRequired()) {
1383
1384 if ((user.getLastLoginDate() == null)) {
1385 user.setPasswordReset(true);
1386
1387 userPersistence.update(user, false);
1388 }
1389 }
1390 }
1391
1392
1398 public void clearOrganizationUsers(long organizationId)
1399 throws SystemException {
1400
1401 organizationPersistence.clearUsers(organizationId);
1402
1403 PermissionCacheUtil.clearCache();
1404 }
1405
1406
1412 public void clearUserGroupUsers(long userGroupId) throws SystemException {
1413 userGroupPersistence.clearUsers(userGroupId);
1414
1415 PermissionCacheUtil.clearCache();
1416 }
1417
1418
1430 public void completeUserRegistration(
1431 User user, ServiceContext serviceContext)
1432 throws PortalException, SystemException {
1433
1434 boolean autoPassword = GetterUtil.getBoolean(
1435 serviceContext.getAttribute("autoPassword"));
1436
1437 String password = null;
1438
1439 if (autoPassword) {
1440 PasswordPolicy passwordPolicy =
1441 passwordPolicyLocalService.getPasswordPolicy(
1442 user.getCompanyId(), user.getOrganizationIds());
1443
1444 password = PwdToolkitUtil.generate(passwordPolicy);
1445
1446 user.setPassword(PwdEncryptor.encrypt(password));
1447 user.setPasswordEncrypted(true);
1448 user.setPasswordUnencrypted(password);
1449
1450 userPersistence.update(user, false);
1451
1452 }
1453
1454 if (user.hasCompanyMx()) {
1455 String mailPassword = password;
1456
1457 if (Validator.isNull(mailPassword)) {
1458 mailPassword = user.getPasswordUnencrypted();
1459 }
1460
1461 mailService.addUser(
1462 user.getCompanyId(), user.getUserId(), mailPassword,
1463 user.getFirstName(), user.getMiddleName(), user.getLastName(),
1464 user.getEmailAddress());
1465 }
1466
1467 boolean sendEmail = GetterUtil.getBoolean(
1468 serviceContext.getAttribute("sendEmail"));
1469
1470 if (sendEmail) {
1471 sendEmail(user, password, serviceContext);
1472 }
1473
1474 Company company = companyPersistence.findByPrimaryKey(
1475 user.getCompanyId());
1476
1477 if (company.isStrangersVerify() && (serviceContext.getPlid() > 0)) {
1478 sendEmailAddressVerification(
1479 user, user.getEmailAddress(), serviceContext);
1480 }
1481 }
1482
1483
1496 public KeyValuePair decryptUserId(
1497 long companyId, String name, String password)
1498 throws PortalException, SystemException {
1499
1500 Company company = companyPersistence.findByPrimaryKey(companyId);
1501
1502 try {
1503 name = Encryptor.decrypt(company.getKeyObj(), name);
1504 }
1505 catch (EncryptorException ee) {
1506 throw new SystemException(ee);
1507 }
1508
1509 long userId = GetterUtil.getLong(name);
1510
1511 User user = userPersistence.findByPrimaryKey(userId);
1512
1513 try {
1514 password = Encryptor.decrypt(company.getKeyObj(), password);
1515 }
1516 catch (EncryptorException ee) {
1517 throw new SystemException(ee);
1518 }
1519
1520 String encPassword = PwdEncryptor.encrypt(password);
1521
1522 if (user.getPassword().equals(encPassword)) {
1523 if (isPasswordExpired(user)) {
1524 user.setPasswordReset(true);
1525
1526 userPersistence.update(user, false);
1527 }
1528
1529 return new KeyValuePair(name, password);
1530 }
1531 else {
1532 throw new PrincipalException();
1533 }
1534 }
1535
1536
1544 public void deletePortrait(long userId)
1545 throws PortalException, SystemException {
1546
1547 User user = userPersistence.findByPrimaryKey(userId);
1548
1549 long portraitId = user.getPortraitId();
1550
1551 if (portraitId > 0) {
1552 user.setPortraitId(0);
1553
1554 userPersistence.update(user, false);
1555
1556 imageLocalService.deleteImage(portraitId);
1557 }
1558 }
1559
1560
1569 public void deleteRoleUser(long roleId, long userId)
1570 throws PortalException, SystemException {
1571
1572 rolePersistence.removeUser(roleId, userId);
1573
1574 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1575
1576 indexer.reindex(userId);
1577
1578 PermissionCacheUtil.clearCache();
1579 }
1580
1581
1588 @Override
1589 public void deleteUser(long userId)
1590 throws PortalException, SystemException {
1591
1592 User user = userPersistence.findByPrimaryKey(userId);
1593
1594 deleteUser(user);
1595 }
1596
1597
1604 @Override
1605 public void deleteUser(User user) throws PortalException, SystemException {
1606 if (!PropsValues.USERS_DELETE) {
1607 throw new RequiredUserException();
1608 }
1609
1610
1611
1612 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1613
1614 indexer.delete(user);
1615
1616
1617
1618 browserTrackerLocalService.deleteUserBrowserTracker(user.getUserId());
1619
1620
1621
1622 Group group = user.getGroup();
1623
1624 if (group != null) {
1625 groupLocalService.deleteGroup(group);
1626 }
1627
1628
1629
1630 imageLocalService.deleteImage(user.getPortraitId());
1631
1632
1633
1634 passwordPolicyRelLocalService.deletePasswordPolicyRel(
1635 User.class.getName(), user.getUserId());
1636
1637
1638
1639 passwordTrackerLocalService.deletePasswordTrackers(user.getUserId());
1640
1641
1642
1643 subscriptionLocalService.deleteSubscriptions(user.getUserId());
1644
1645
1646
1647 userIdMapperLocalService.deleteUserIdMappers(user.getUserId());
1648
1649
1650
1651 announcementsDeliveryLocalService.deleteDeliveries(user.getUserId());
1652
1653
1654
1655 assetEntryLocalService.deleteEntry(
1656 User.class.getName(), user.getUserId());
1657
1658
1659
1660 blogsStatsUserLocalService.deleteStatsUserByUserId(user.getUserId());
1661
1662
1663
1664 dlFileRankLocalService.deleteFileRanksByUserId(user.getUserId());
1665
1666
1667
1668 expandoValueLocalService.deleteValues(
1669 User.class.getName(), user.getUserId());
1670
1671
1672
1673 mbBanLocalService.deleteBansByBanUserId(user.getUserId());
1674 mbStatsUserLocalService.deleteStatsUsersByUserId(user.getUserId());
1675 mbThreadFlagLocalService.deleteThreadFlagsByUserId(user.getUserId());
1676
1677
1678
1679 membershipRequestLocalService.deleteMembershipRequestsByUserId(
1680 user.getUserId());
1681
1682
1683
1684 shoppingCartLocalService.deleteUserCarts(user.getUserId());
1685
1686
1687
1688 socialActivityLocalService.deleteUserActivities(user.getUserId());
1689 socialRequestLocalService.deleteReceiverUserRequests(user.getUserId());
1690 socialRequestLocalService.deleteUserRequests(user.getUserId());
1691
1692
1693
1694 mailService.deleteUser(user.getCompanyId(), user.getUserId());
1695
1696
1697
1698 try {
1699 contactLocalService.deleteContact(user.getContactId());
1700 }
1701 catch (NoSuchContactException nsce) {
1702 }
1703
1704
1705
1706 resourceLocalService.deleteResource(
1707 user.getCompanyId(), User.class.getName(),
1708 ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
1709
1710
1711
1712 userGroupRoleLocalService.deleteUserGroupRolesByUserId(
1713 user.getUserId());
1714
1715
1716
1717 userPersistence.remove(user);
1718
1719
1720
1721 PermissionCacheUtil.clearCache();
1722
1723
1724
1725 workflowInstanceLinkLocalService.deleteWorkflowInstanceLinks(
1726 user.getCompanyId(), 0, User.class.getName(), user.getUserId());
1727 }
1728
1729
1737 public void deleteUserGroupUser(long userGroupId, long userId)
1738 throws PortalException, SystemException {
1739
1740 userGroupPersistence.removeUser(userGroupId, userId);
1741
1742 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1743
1744 indexer.reindex(userId);
1745
1746 PermissionCacheUtil.clearCache();
1747 }
1748
1749
1758 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1759 public String encryptUserId(String name)
1760 throws PortalException, SystemException {
1761
1762 long userId = GetterUtil.getLong(name);
1763
1764 User user = userPersistence.findByPrimaryKey(userId);
1765
1766 Company company = companyPersistence.findByPrimaryKey(
1767 user.getCompanyId());
1768
1769 try {
1770 return Encryptor.encrypt(company.getKeyObj(), name);
1771 }
1772 catch (EncryptorException ee) {
1773 throw new SystemException(ee);
1774 }
1775 }
1776
1777
1785 public User fetchUserById(long userId) throws SystemException {
1786 return userPersistence.fetchByPrimaryKey(userId);
1787 }
1788
1789
1798 public User fetchUserByScreenName(long companyId, String screenName)
1799 throws SystemException {
1800
1801 screenName = getScreenName(screenName);
1802
1803 return userPersistence.fetchByC_SN(companyId, screenName);
1804 }
1805
1806
1825 public List<User> getCompanyUsers(long companyId, int start, int end)
1826 throws SystemException {
1827
1828 return userPersistence.findByCompanyId(companyId, start, end);
1829 }
1830
1831
1838 public int getCompanyUsersCount(long companyId) throws SystemException {
1839 return userPersistence.countByCompanyId(companyId);
1840 }
1841
1842
1851 @Skip
1852 public User getDefaultUser(long companyId)
1853 throws PortalException, SystemException {
1854
1855 User userModel = _defaultUsers.get(companyId);
1856
1857 if (userModel == null) {
1858 userModel = userLocalService.loadGetDefaultUser(companyId);
1859
1860 _defaultUsers.put(companyId, userModel);
1861 }
1862
1863 return userModel;
1864 }
1865
1866
1875 @Skip
1876 public long getDefaultUserId(long companyId)
1877 throws PortalException, SystemException {
1878
1879 User user = getDefaultUser(companyId);
1880
1881 return user.getUserId();
1882 }
1883
1884
1891 public long[] getGroupUserIds(long groupId) throws SystemException {
1892 return getUserIds(getGroupUsers(groupId));
1893 }
1894
1895
1902 public List<User> getGroupUsers(long groupId) throws SystemException {
1903 return groupPersistence.getUsers(groupId);
1904 }
1905
1906
1913 public int getGroupUsersCount(long groupId) throws SystemException {
1914 return groupPersistence.getUsersSize(groupId);
1915 }
1916
1917
1927 public int getGroupUsersCount(long groupId, int status)
1928 throws PortalException, SystemException {
1929
1930 Group group = groupPersistence.findByPrimaryKey(groupId);
1931
1932 LinkedHashMap<String, Object> params =
1933 new LinkedHashMap<String, Object>();
1934
1935 params.put("usersGroups", new Long(groupId));
1936
1937 return searchCount(group.getCompanyId(), null, status, params);
1938 }
1939
1940
1948 public List<User> getNoAnnouncementsDeliveries(String type)
1949 throws SystemException {
1950
1951 return userFinder.findByNoAnnouncementsDeliveries(type);
1952 }
1953
1954
1960 public List<User> getNoContacts() throws SystemException {
1961 return userFinder.findByNoContacts();
1962 }
1963
1964
1971 public List<User> getNoGroups() throws SystemException {
1972 return userFinder.findByNoGroups();
1973 }
1974
1975
1982 public long[] getOrganizationUserIds(long organizationId)
1983 throws SystemException {
1984
1985 return getUserIds(getOrganizationUsers(organizationId));
1986 }
1987
1988
1995 public List<User> getOrganizationUsers(long organizationId)
1996 throws SystemException {
1997
1998 return organizationPersistence.getUsers(organizationId);
1999 }
2000
2001
2008 public int getOrganizationUsersCount(long organizationId)
2009 throws SystemException {
2010
2011 return organizationPersistence.getUsersSize(organizationId);
2012 }
2013
2014
2025 public int getOrganizationUsersCount(long organizationId, int status)
2026 throws PortalException, SystemException {
2027
2028 Organization organization = organizationPersistence.findByPrimaryKey(
2029 organizationId);
2030
2031 LinkedHashMap<String, Object> params =
2032 new LinkedHashMap<String, Object>();
2033
2034 params.put("usersOrgs", new Long(organizationId));
2035
2036 return searchCount(organization.getCompanyId(), null, status, params);
2037 }
2038
2039
2046 public long[] getRoleUserIds(long roleId) throws SystemException {
2047 return getUserIds(getRoleUsers(roleId));
2048 }
2049
2050
2057 public List<User> getRoleUsers(long roleId) throws SystemException {
2058 return rolePersistence.getUsers(roleId);
2059 }
2060
2061
2080 public List<User> getRoleUsers(long roleId, int start, int end)
2081 throws SystemException {
2082
2083 return rolePersistence.getUsers(roleId, start, end);
2084 }
2085
2086
2093 public int getRoleUsersCount(long roleId) throws SystemException {
2094 return rolePersistence.getUsersSize(roleId);
2095 }
2096
2097
2107 public int getRoleUsersCount(long roleId, int status)
2108 throws PortalException, SystemException {
2109
2110 Role role = rolePersistence.findByPrimaryKey(roleId);
2111
2112 LinkedHashMap<String, Object> params =
2113 new LinkedHashMap<String, Object>();
2114
2115 params.put("usersRoles", new Long(roleId));
2116
2117 return searchCount(role.getCompanyId(), null, status, params);
2118 }
2119
2120
2147 public List<User> getSocialUsers(
2148 long userId, int type, int start, int end, OrderByComparator obc)
2149 throws PortalException, SystemException {
2150
2151 User user = userPersistence.findByPrimaryKey(userId);
2152
2153 LinkedHashMap<String, Object> params =
2154 new LinkedHashMap<String, Object>();
2155
2156 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2157
2158 return search(
2159 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2160 params, start, end, obc);
2161 }
2162
2163
2186 public List<User> getSocialUsers(
2187 long userId, int start, int end, OrderByComparator obc)
2188 throws PortalException, SystemException {
2189
2190 User user = userPersistence.findByPrimaryKey(userId);
2191
2192 LinkedHashMap<String, Object> params =
2193 new LinkedHashMap<String, Object>();
2194
2195 params.put("socialRelation", new Long[] {userId});
2196
2197 return search(
2198 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2199 params, start, end, obc);
2200 }
2201
2202
2230 public List<User> getSocialUsers(
2231 long userId1, long userId2, int type, int start, int end,
2232 OrderByComparator obc)
2233 throws PortalException, SystemException {
2234
2235 User user1 = userPersistence.findByPrimaryKey(userId1);
2236
2237 LinkedHashMap<String, Object> params =
2238 new LinkedHashMap<String, Object>();
2239
2240 params.put(
2241 "socialMutualRelationType",
2242 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2243
2244 return search(
2245 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2246 params, start, end, obc);
2247 }
2248
2249
2274 public List<User> getSocialUsers(
2275 long userId1, long userId2, int start, int end,
2276 OrderByComparator obc)
2277 throws PortalException, SystemException {
2278
2279 User user1 = userPersistence.findByPrimaryKey(userId1);
2280
2281 LinkedHashMap<String, Object> params =
2282 new LinkedHashMap<String, Object>();
2283
2284 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2285
2286 return search(
2287 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2288 params, start, end, obc);
2289 }
2290
2291
2299 public int getSocialUsersCount(long userId)
2300 throws PortalException, SystemException {
2301
2302 User user = userPersistence.findByPrimaryKey(userId);
2303
2304 LinkedHashMap<String, Object> params =
2305 new LinkedHashMap<String, Object>();
2306
2307 params.put("socialRelation", new Long[] {userId});
2308
2309 return searchCount(user.getCompanyId(), null,
2310 WorkflowConstants.STATUS_APPROVED, params);
2311 }
2312
2313
2326 public int getSocialUsersCount(long userId, int type)
2327 throws PortalException, SystemException {
2328
2329 User user = userPersistence.findByPrimaryKey(userId);
2330
2331 LinkedHashMap<String, Object> params =
2332 new LinkedHashMap<String, Object>();
2333
2334 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2335
2336 return searchCount(user.getCompanyId(), null,
2337 WorkflowConstants.STATUS_APPROVED, params);
2338 }
2339
2340
2350 public int getSocialUsersCount(long userId1, long userId2)
2351 throws PortalException, SystemException {
2352
2353 User user1 = userPersistence.findByPrimaryKey(userId1);
2354
2355 LinkedHashMap<String, Object> params =
2356 new LinkedHashMap<String, Object>();
2357
2358 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2359
2360 return searchCount(user1.getCompanyId(), null,
2361 WorkflowConstants.STATUS_APPROVED, params);
2362 }
2363
2364
2378 public int getSocialUsersCount(long userId1, long userId2, int type)
2379 throws PortalException, SystemException {
2380
2381 User user1 = userPersistence.findByPrimaryKey(userId1);
2382
2383 LinkedHashMap<String, Object> params =
2384 new LinkedHashMap<String, Object>();
2385
2386 params.put(
2387 "socialMutualRelationType",
2388 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2389
2390 return searchCount(user1.getCompanyId(), null,
2391 WorkflowConstants.STATUS_APPROVED, params);
2392 }
2393
2394
2402 public User getUserByContactId(long contactId)
2403 throws PortalException, SystemException {
2404
2405 return userPersistence.findByContactId(contactId);
2406 }
2407
2408
2418 public User getUserByEmailAddress(long companyId, String emailAddress)
2419 throws PortalException, SystemException {
2420
2421 emailAddress = emailAddress.trim().toLowerCase();
2422
2423 return userPersistence.findByC_EA(companyId, emailAddress);
2424 }
2425
2426
2435 public User getUserByFacebookId(long companyId, long facebookId)
2436 throws PortalException, SystemException {
2437
2438 return userPersistence.findByC_FID(companyId, facebookId);
2439 }
2440
2441
2449 public User getUserById(long userId)
2450 throws PortalException, SystemException {
2451
2452 return userPersistence.findByPrimaryKey(userId);
2453 }
2454
2455
2465 public User getUserById(long companyId, long userId)
2466 throws PortalException, SystemException {
2467
2468 return userPersistence.findByC_U(companyId, userId);
2469 }
2470
2471
2480 public User getUserByOpenId(long companyId, String openId)
2481 throws PortalException, SystemException {
2482
2483 return userPersistence.findByC_O(companyId, openId);
2484 }
2485
2486
2494 public User getUserByPortraitId(long portraitId)
2495 throws PortalException, SystemException {
2496
2497 return userPersistence.findByPortraitId(portraitId);
2498 }
2499
2500
2509 public User getUserByScreenName(long companyId, String screenName)
2510 throws PortalException, SystemException {
2511
2512 screenName = getScreenName(screenName);
2513
2514 return userPersistence.findByC_SN(companyId, screenName);
2515 }
2516
2517
2526 public User getUserByUuid(String uuid)
2527 throws PortalException, SystemException {
2528
2529 List<User> users = userPersistence.findByUuid(uuid);
2530
2531 if (users.isEmpty()) {
2532 throw new NoSuchUserException();
2533 }
2534 else {
2535 return users.get(0);
2536 }
2537 }
2538
2539
2546 public List<User> getUserGroupUsers(long userGroupId)
2547 throws SystemException {
2548
2549 return userGroupPersistence.getUsers(userGroupId);
2550 }
2551
2552
2559 public int getUserGroupUsersCount(long userGroupId) throws SystemException {
2560 return userGroupPersistence.getUsersSize(userGroupId);
2561 }
2562
2563
2573 public int getUserGroupUsersCount(long userGroupId, int status)
2574 throws PortalException, SystemException {
2575
2576 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
2577 userGroupId);
2578
2579 LinkedHashMap<String, Object> params =
2580 new LinkedHashMap<String, Object>();
2581
2582 params.put("usersUserGroups", new Long(userGroupId));
2583
2584 return searchCount(userGroup.getCompanyId(), null, status, params);
2585 }
2586
2587
2597 public long getUserIdByEmailAddress(long companyId, String emailAddress)
2598 throws PortalException, SystemException {
2599
2600 emailAddress = emailAddress.trim().toLowerCase();
2601
2602 User user = userPersistence.findByC_EA(companyId, emailAddress);
2603
2604 return user.getUserId();
2605 }
2606
2607
2616 public long getUserIdByScreenName(long companyId, String screenName)
2617 throws PortalException, SystemException {
2618
2619 screenName = getScreenName(screenName);
2620
2621 User user = userPersistence.findByC_SN(companyId, screenName);
2622
2623 return user.getUserId();
2624 }
2625
2626
2635 public boolean hasGroupUser(long groupId, long userId)
2636 throws SystemException {
2637
2638 return groupPersistence.containsUser(groupId, userId);
2639 }
2640
2641
2650 public boolean hasOrganizationUser(long organizationId, long userId)
2651 throws SystemException {
2652
2653 return organizationPersistence.containsUser(organizationId, userId);
2654 }
2655
2656
2666 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
2667 throws SystemException {
2668
2669 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
2670 passwordPolicyId, User.class.getName(), userId);
2671 }
2672
2673
2682 public boolean hasRoleUser(long roleId, long userId)
2683 throws SystemException {
2684
2685 return rolePersistence.containsUser(roleId, userId);
2686 }
2687
2688
2703 public boolean hasRoleUser(
2704 long companyId, String name, long userId, boolean inherited)
2705 throws PortalException, SystemException {
2706
2707 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
2708 }
2709
2710
2719 public boolean hasTeamUser(long teamId, long userId)
2720 throws SystemException {
2721
2722 return teamPersistence.containsUser(teamId, userId);
2723 }
2724
2725
2734 public boolean hasUserGroupUser(long userGroupId, long userId)
2735 throws SystemException {
2736
2737 return userGroupPersistence.containsUser(userGroupId, userId);
2738 }
2739
2740
2750 public boolean isPasswordExpired(User user)
2751 throws PortalException, SystemException {
2752
2753 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2754
2755 if (passwordPolicy.getExpireable()) {
2756 Date now = new Date();
2757
2758 if (user.getPasswordModifiedDate() == null) {
2759 user.setPasswordModifiedDate(now);
2760
2761 userLocalService.updateUser(user, false);
2762 }
2763
2764 long passwordStartTime = user.getPasswordModifiedDate().getTime();
2765 long elapsedTime = now.getTime() - passwordStartTime;
2766
2767 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
2768 return true;
2769 }
2770 else {
2771 return false;
2772 }
2773 }
2774
2775 return false;
2776 }
2777
2778
2788 public boolean isPasswordExpiringSoon(User user)
2789 throws PortalException, SystemException {
2790
2791 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2792
2793 if (passwordPolicy.isExpireable()) {
2794 Date now = new Date();
2795
2796 if (user.getPasswordModifiedDate() == null) {
2797 user.setPasswordModifiedDate(now);
2798
2799 userLocalService.updateUser(user, false);
2800 }
2801
2802 long timeModified = user.getPasswordModifiedDate().getTime();
2803 long passwordExpiresOn =
2804 (passwordPolicy.getMaxAge() * 1000) + timeModified;
2805
2806 long timeStartWarning =
2807 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
2808
2809 if (now.getTime() > timeStartWarning) {
2810 return true;
2811 }
2812 else {
2813 return false;
2814 }
2815 }
2816
2817 return false;
2818 }
2819
2820 public User loadGetDefaultUser(long companyId)
2821 throws PortalException, SystemException {
2822
2823 return userPersistence.findByC_DU(companyId, true);
2824 }
2825
2826
2858 public List<User> search(
2859 long companyId, String keywords, int status,
2860 LinkedHashMap<String, Object> params, int start, int end,
2861 OrderByComparator obc)
2862 throws SystemException {
2863
2864 return userFinder.findByKeywords(
2865 companyId, keywords, status, params, start, end, obc);
2866 }
2867
2868
2899 public Hits search(
2900 long companyId, String keywords, int status,
2901 LinkedHashMap<String, Object> params, int start, int end, Sort sort)
2902 throws SystemException {
2903
2904 String firstName = null;
2905 String middleName = null;
2906 String lastName = null;
2907 String fullName = null;
2908 String screenName = null;
2909 String emailAddress = null;
2910 String street = null;
2911 String city = null;
2912 String zip = null;
2913 String region = null;
2914 String country = null;
2915 boolean andOperator = false;
2916
2917 if (Validator.isNotNull(keywords)) {
2918 firstName = keywords;
2919 middleName = keywords;
2920 lastName = keywords;
2921 fullName = keywords;
2922 screenName = keywords;
2923 emailAddress = keywords;
2924 street = keywords;
2925 city = keywords;
2926 zip = keywords;
2927 region = keywords;
2928 country = keywords;
2929 }
2930 else {
2931 andOperator = true;
2932 }
2933
2934 if (params != null) {
2935 params.put("keywords", keywords);
2936 }
2937
2938 return search(
2939 companyId, firstName, middleName, lastName, fullName, screenName,
2940 emailAddress, street, city, zip, region, country, status, params,
2941 andOperator, start, end, sort);
2942 }
2943
2944
2984 public List<User> search(
2985 long companyId, String firstName, String middleName,
2986 String lastName, String screenName, String emailAddress, int status,
2987 LinkedHashMap<String, Object> params, boolean andSearch, int start,
2988 int end, OrderByComparator obc)
2989 throws SystemException {
2990
2991 return userFinder.findByC_FN_MN_LN_SN_EA_S(
2992 companyId, firstName, middleName, lastName, screenName,
2993 emailAddress, status, params, andSearch, start, end, obc);
2994 }
2995
2996
3035 public Hits search(
3036 long companyId, String firstName, String middleName,
3037 String lastName, String screenName, String emailAddress, int status,
3038 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3039 int end, Sort sort)
3040 throws SystemException {
3041
3042 return search(
3043 companyId, firstName, middleName, lastName, null, screenName,
3044 emailAddress, null, null, null, null, null, status, params,
3045 andSearch, start, end, sort);
3046 }
3047
3048
3062 public int searchCount(
3063 long companyId, String keywords, int status,
3064 LinkedHashMap<String, Object> params)
3065 throws SystemException {
3066
3067 return userFinder.countByKeywords(companyId, keywords, status, params);
3068 }
3069
3070
3092 public int searchCount(
3093 long companyId, String firstName, String middleName,
3094 String lastName, String screenName, String emailAddress, int status,
3095 LinkedHashMap<String, Object> params, boolean andSearch)
3096 throws SystemException {
3097
3098 return userFinder.countByC_FN_MN_LN_SN_EA_S(
3099 companyId, firstName, middleName, lastName, screenName,
3100 emailAddress, status, params, andSearch);
3101 }
3102
3103
3114 public void sendEmailAddressVerification(
3115 User user, String emailAddress, ServiceContext serviceContext)
3116 throws PortalException, SystemException {
3117
3118 if (user.isEmailAddressVerified() &&
3119 emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
3120
3121 return;
3122 }
3123
3124 Ticket ticket = ticketLocalService.addTicket(
3125 user.getCompanyId(), User.class.getName(), user.getUserId(),
3126 TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3127 serviceContext);
3128
3129 String verifyEmailAddressURL =
3130 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3131 "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3132
3133 Layout layout = layoutLocalService.getLayout(serviceContext.getPlid());
3134
3135 Group group = layout.getGroup();
3136
3137 if (!layout.isPrivateLayout() && !group.isUser()) {
3138 verifyEmailAddressURL += "&p_l_id=" + serviceContext.getPlid();
3139 }
3140
3141 String fromName = PrefsPropsUtil.getString(
3142 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3143 String fromAddress = PrefsPropsUtil.getString(
3144 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3145
3146 String toName = user.getFullName();
3147 String toAddress = emailAddress;
3148
3149 String subject = PrefsPropsUtil.getContent(
3150 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3151
3152 String body = PrefsPropsUtil.getContent(
3153 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3154
3155 SubscriptionSender subscriptionSender = new SubscriptionSender();
3156
3157 subscriptionSender.setBody(body);
3158 subscriptionSender.setCompanyId(user.getCompanyId());
3159 subscriptionSender.setContextAttributes(
3160 "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3161 "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3162 "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3163 "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_AGENT$]",
3164 serviceContext.getUserAgent(), "[$USER_ID$]", user.getUserId(),
3165 "[$USER_SCREENNAME$]", user.getScreenName());
3166 subscriptionSender.setFrom(fromAddress, fromName);
3167 subscriptionSender.setHtmlFormat(true);
3168 subscriptionSender.setMailId("user", user.getUserId());
3169 subscriptionSender.setServiceContext(serviceContext);
3170 subscriptionSender.setSubject(subject);
3171 subscriptionSender.setUserId(user.getUserId());
3172
3173 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3174
3175 subscriptionSender.flushNotificationsAsync();
3176 }
3177
3178
3197 public void sendPassword(
3198 long companyId, String emailAddress, String fromName,
3199 String fromAddress, String subject, String body,
3200 ServiceContext serviceContext)
3201 throws PortalException, SystemException {
3202
3203 Company company = companyPersistence.findByPrimaryKey(companyId);
3204
3205 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3206 return;
3207 }
3208
3209 emailAddress = emailAddress.trim().toLowerCase();
3210
3211 if (Validator.isNull(emailAddress)) {
3212 throw new UserEmailAddressException();
3213 }
3214
3215 User user = userPersistence.findByC_EA(companyId, emailAddress);
3216
3217 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3218
3219 String newPassword = StringPool.BLANK;
3220 String passwordResetURL = StringPool.BLANK;
3221
3222 if (company.isSendPasswordResetLink()) {
3223 Date expirationDate = new Date(
3224 System.currentTimeMillis() +
3225 (passwordPolicy.getResetTicketMaxAge() * 1000));
3226
3227 Ticket ticket = ticketLocalService.addTicket(
3228 companyId, User.class.getName(), user.getUserId(),
3229 TicketConstants.TYPE_PASSWORD, null, expirationDate,
3230 serviceContext);
3231
3232 passwordResetURL =
3233 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3234 "/portal/update_password?p_l_id="+
3235 serviceContext.getPlid() +
3236 "&ticketKey=" + ticket.getKey();
3237 }
3238 else {
3239 if (!PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
3240 PwdEncryptor.TYPE_NONE)) {
3241
3242 newPassword = PwdToolkitUtil.generate(passwordPolicy);
3243
3244 boolean passwordReset = false;
3245
3246 if (passwordPolicy.getChangeable() &&
3247 passwordPolicy.getChangeRequired()) {
3248
3249 passwordReset = true;
3250 }
3251
3252 user.setPassword(PwdEncryptor.encrypt(newPassword));
3253 user.setPasswordUnencrypted(newPassword);
3254 user.setPasswordEncrypted(true);
3255 user.setPasswordReset(passwordReset);
3256 user.setPasswordModified(true);
3257 user.setPasswordModifiedDate(new Date());
3258
3259 userPersistence.update(user, false);
3260
3261 user.setPasswordModified(false);
3262 }
3263 else {
3264 newPassword = user.getPassword();
3265 }
3266 }
3267
3268 if (Validator.isNull(fromName)) {
3269 fromName = PrefsPropsUtil.getString(
3270 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3271 }
3272
3273 if (Validator.isNull(fromAddress)) {
3274 fromAddress = PrefsPropsUtil.getString(
3275 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3276 }
3277
3278 String toName = user.getFullName();
3279 String toAddress = user.getEmailAddress();
3280
3281 if (Validator.isNull(subject)) {
3282 if (company.isSendPasswordResetLink()) {
3283 subject = PrefsPropsUtil.getContent(
3284 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
3285 }
3286 else {
3287 subject = PrefsPropsUtil.getContent(
3288 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
3289 }
3290 }
3291
3292 if (Validator.isNull(body)) {
3293 if (company.isSendPasswordResetLink()) {
3294 body = PrefsPropsUtil.getContent(
3295 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
3296 }
3297 else {
3298 body = PrefsPropsUtil.getContent(
3299 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
3300 }
3301 }
3302
3303 SubscriptionSender subscriptionSender = new SubscriptionSender();
3304
3305 subscriptionSender.setBody(body);
3306 subscriptionSender.setCompanyId(companyId);
3307 subscriptionSender.setContextAttributes(
3308 "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
3309 serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
3310 serviceContext.getRemoteHost(), "[$USER_AGENT$]",
3311 serviceContext.getUserAgent(), "[$USER_ID$]", user.getUserId(),
3312 "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
3313 user.getScreenName());
3314 subscriptionSender.setFrom(fromAddress, fromName);
3315 subscriptionSender.setHtmlFormat(true);
3316 subscriptionSender.setMailId("user", user.getUserId());
3317 subscriptionSender.setServiceContext(serviceContext);
3318 subscriptionSender.setSubject(subject);
3319 subscriptionSender.setUserId(user.getUserId());
3320
3321 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3322
3323 subscriptionSender.flushNotificationsAsync();
3324 }
3325
3326
3335 public void setRoleUsers(long roleId, long[] userIds)
3336 throws PortalException, SystemException {
3337
3338 rolePersistence.setUsers(roleId, userIds);
3339
3340 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3341
3342 indexer.reindex(userIds);
3343
3344 PermissionCacheUtil.clearCache();
3345 }
3346
3347
3356 @SuppressWarnings("deprecation")
3357 public void setUserGroupUsers(long userGroupId, long[] userIds)
3358 throws PortalException, SystemException {
3359
3360 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3361 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3362 }
3363
3364 userGroupPersistence.setUsers(userGroupId, userIds);
3365
3366 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3367
3368 indexer.reindex(userIds);
3369
3370 PermissionCacheUtil.clearCache();
3371 }
3372
3373
3381 public void unsetGroupUsers(
3382 long groupId, long[] userIds, ServiceContext serviceContext)
3383 throws PortalException, SystemException {
3384
3385 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
3386
3387 groupPersistence.removeUsers(groupId, userIds);
3388
3389 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3390
3391 indexer.reindex(userIds);
3392
3393 PermissionCacheUtil.clearCache();
3394 }
3395
3396
3404 public void unsetOrganizationUsers(long organizationId, long[] userIds)
3405 throws PortalException, SystemException {
3406
3407 Organization organization = organizationPersistence.findByPrimaryKey(
3408 organizationId);
3409
3410 Group group = organization.getGroup();
3411
3412 long groupId = group.getGroupId();
3413
3414 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
3415
3416 organizationPersistence.removeUsers(organizationId, userIds);
3417
3418 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3419
3420 indexer.reindex(userIds);
3421
3422 PermissionCacheUtil.clearCache();
3423 }
3424
3425
3432 public void unsetPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
3433 throws SystemException {
3434
3435 passwordPolicyRelLocalService.deletePasswordPolicyRels(
3436 passwordPolicyId, User.class.getName(), userIds);
3437 }
3438
3439
3447 public void unsetRoleUsers(long roleId, List<User> users)
3448 throws PortalException, SystemException {
3449
3450 Role role = rolePersistence.findByPrimaryKey(roleId);
3451
3452 if (role.getName().equals(RoleConstants.USER)) {
3453 return;
3454 }
3455
3456 rolePersistence.removeUsers(roleId, users);
3457
3458 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3459
3460 indexer.reindex(users);
3461
3462 PermissionCacheUtil.clearCache();
3463 }
3464
3465
3473 public void unsetRoleUsers(long roleId, long[] userIds)
3474 throws PortalException, SystemException {
3475
3476 Role role = rolePersistence.findByPrimaryKey(roleId);
3477
3478 if (role.getName().equals(RoleConstants.USER)) {
3479 return;
3480 }
3481
3482 rolePersistence.removeUsers(roleId, userIds);
3483
3484 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3485
3486 indexer.reindex(userIds);
3487
3488 PermissionCacheUtil.clearCache();
3489 }
3490
3491
3499 public void unsetTeamUsers(long teamId, long[] userIds)
3500 throws PortalException, SystemException {
3501
3502 teamPersistence.removeUsers(teamId, userIds);
3503
3504 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3505
3506 indexer.reindex(userIds);
3507
3508 PermissionCacheUtil.clearCache();
3509 }
3510
3511
3519 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
3520 throws PortalException, SystemException {
3521
3522 userGroupPersistence.removeUsers(userGroupId, userIds);
3523
3524 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3525
3526 indexer.reindex(userIds);
3527
3528 PermissionCacheUtil.clearCache();
3529 }
3530
3531
3541 public User updateAgreedToTermsOfUse(
3542 long userId, boolean agreedToTermsOfUse)
3543 throws PortalException, SystemException {
3544
3545 User user = userPersistence.findByPrimaryKey(userId);
3546
3547 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
3548
3549 userPersistence.update(user, false);
3550
3551 return user;
3552 }
3553
3554
3565 public void updateAsset(
3566 long userId, User user, long[] assetCategoryIds,
3567 String[] assetTagNames)
3568 throws PortalException, SystemException {
3569
3570 User owner = userPersistence.findByPrimaryKey(userId);
3571
3572 Company company = companyPersistence.findByPrimaryKey(
3573 owner.getCompanyId());
3574
3575 Group companyGroup = company.getGroup();
3576
3577 assetEntryLocalService.updateEntry(
3578 userId, companyGroup.getGroupId(), User.class.getName(),
3579 user.getUserId(), user.getUuid(), 0, assetCategoryIds,
3580 assetTagNames, false, null, null, null, null, null,
3581 user.getFullName(), null, null, null, null, 0, 0, null, false);
3582 }
3583
3584
3593 public User updateCreateDate(long userId, Date createDate)
3594 throws PortalException, SystemException {
3595
3596 User user = userPersistence.findByPrimaryKey(userId);
3597
3598 user.setCreateDate(createDate);
3599
3600 userPersistence.update(user, false);
3601
3602 return user;
3603 }
3604
3605
3616 public User updateEmailAddress(
3617 long userId, String password, String emailAddress1,
3618 String emailAddress2)
3619 throws PortalException, SystemException {
3620
3621 emailAddress1 = emailAddress1.trim().toLowerCase();
3622 emailAddress2 = emailAddress2.trim().toLowerCase();
3623
3624 User user = userPersistence.findByPrimaryKey(userId);
3625
3626 validateEmailAddress(user, emailAddress1, emailAddress2);
3627
3628 setEmailAddress(
3629 user, password, user.getFirstName(), user.getMiddleName(),
3630 user.getLastName(), emailAddress1);
3631
3632 userPersistence.update(user, false);
3633
3634 return user;
3635 }
3636
3637
3648 public User updateEmailAddress(
3649 long userId, String password, String emailAddress1,
3650 String emailAddress2, ServiceContext serviceContext)
3651 throws PortalException, SystemException {
3652
3653 emailAddress1 = emailAddress1.trim().toLowerCase();
3654 emailAddress2 = emailAddress2.trim().toLowerCase();
3655
3656 User user = userPersistence.findByPrimaryKey(userId);
3657
3658 validateEmailAddress(user, emailAddress1, emailAddress2);
3659
3660 Company company = companyPersistence.findByPrimaryKey(
3661 user.getCompanyId());
3662
3663 if (!company.isStrangersVerify()) {
3664 setEmailAddress(
3665 user, password, user.getFirstName(), user.getMiddleName(),
3666 user.getLastName(), emailAddress1);
3667
3668 userPersistence.update(user, false);
3669 }
3670 else {
3671 sendEmailAddressVerification(user, emailAddress1, serviceContext);
3672 }
3673
3674 return user;
3675 }
3676
3677
3686 public User updateEmailAddressVerified(
3687 long userId, boolean emailAddressVerified)
3688 throws PortalException, SystemException {
3689
3690 User user = userPersistence.findByPrimaryKey(userId);
3691
3692 user.setEmailAddressVerified(emailAddressVerified);
3693
3694 userPersistence.update(user, false);
3695
3696 return user;
3697 }
3698
3699
3708 public User updateFacebookId(long userId, long facebookId)
3709 throws PortalException, SystemException {
3710
3711 User user = userPersistence.findByPrimaryKey(userId);
3712
3713 user.setFacebookId(facebookId);
3714
3715 userPersistence.update(user, false);
3716
3717 return user;
3718 }
3719
3720
3728 public void updateGroups(
3729 long userId, long[] newGroupIds, ServiceContext serviceContext)
3730 throws PortalException, SystemException {
3731
3732 updateGroups(
3733 userId, newGroupIds, serviceContext,
3734 serviceContext.isIndexingEnabled());
3735 }
3736
3737
3776 public User updateIncompleteUser(
3777 long creatorUserId, long companyId, boolean autoPassword,
3778 String password1, String password2, boolean autoScreenName,
3779 String screenName, String emailAddress, long facebookId,
3780 String openId, Locale locale, String firstName, String middleName,
3781 String lastName, int prefixId, int suffixId, boolean male,
3782 int birthdayMonth, int birthdayDay, int birthdayYear,
3783 String jobTitle, boolean updateUserInformation, boolean sendEmail,
3784 ServiceContext serviceContext)
3785 throws PortalException, SystemException {
3786
3787 User user = getUserByEmailAddress(companyId, emailAddress);
3788
3789 if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
3790 throw new PortalException("Invalid user status");
3791 }
3792
3793 User defaultUser = getDefaultUser(companyId);
3794
3795 if (updateUserInformation) {
3796 autoScreenName = false;
3797
3798 if (PrefsPropsUtil.getBoolean(
3799 companyId,
3800 PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
3801
3802 autoScreenName = true;
3803 }
3804
3805 validate(
3806 companyId, user.getUserId(), autoPassword, password1, password2,
3807 autoScreenName, screenName, emailAddress, firstName, middleName,
3808 lastName, null);
3809
3810 if (!autoPassword) {
3811 if (Validator.isNull(password1) ||
3812 Validator.isNull(password2)) {
3813 throw new UserPasswordException(
3814 UserPasswordException.PASSWORD_INVALID);
3815 }
3816 }
3817
3818 if (autoScreenName) {
3819 ScreenNameGenerator screenNameGenerator =
3820 ScreenNameGeneratorFactory.getInstance();
3821
3822 try {
3823 screenName = screenNameGenerator.generate(
3824 companyId, user.getUserId(), emailAddress);
3825 }
3826 catch (Exception e) {
3827 throw new SystemException(e);
3828 }
3829 }
3830
3831 FullNameGenerator fullNameGenerator =
3832 FullNameGeneratorFactory.getInstance();
3833
3834 String fullName = fullNameGenerator.getFullName(
3835 firstName, middleName, lastName);
3836
3837 String greeting = LanguageUtil.format(
3838 locale, "welcome-x", " " + fullName, false);
3839
3840 if (Validator.isNotNull(password1)) {
3841 user.setPassword(PwdEncryptor.encrypt(password1));
3842 user.setPasswordUnencrypted(password1);
3843 }
3844
3845 user.setPasswordEncrypted(true);
3846
3847 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
3848
3849 if (passwordPolicy.isChangeable() &&
3850 passwordPolicy.isChangeRequired()) {
3851
3852 user.setPasswordReset(true);
3853 }
3854 else {
3855 user.setPasswordReset(false);
3856 }
3857
3858 user.setScreenName(screenName);
3859 user.setFacebookId(facebookId);
3860 user.setOpenId(openId);
3861 user.setLanguageId(locale.toString());
3862 user.setTimeZoneId(defaultUser.getTimeZoneId());
3863 user.setGreeting(greeting);
3864 user.setFirstName(firstName);
3865 user.setMiddleName(middleName);
3866 user.setLastName(lastName);
3867 user.setJobTitle(jobTitle);
3868
3869 Date birthday = PortalUtil.getDate(
3870 birthdayMonth, birthdayDay, birthdayYear,
3871 new ContactBirthdayException());
3872
3873 Contact contact = user.getContact();
3874
3875 contact.setFirstName(firstName);
3876 contact.setMiddleName(middleName);
3877 contact.setLastName(lastName);
3878 contact.setPrefixId(prefixId);
3879 contact.setSuffixId(suffixId);
3880 contact.setMale(male);
3881 contact.setBirthday(birthday);
3882 contact.setJobTitle(jobTitle);
3883
3884 contactPersistence.update(contact, false, serviceContext);
3885
3886
3887
3888 user.setExpandoBridgeAttributes(serviceContext);
3889
3890
3891
3892 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3893
3894 indexer.reindex(user);
3895 }
3896
3897 user.setStatus(WorkflowConstants.STATUS_DRAFT);
3898
3899 userPersistence.update(user, false, serviceContext);
3900
3901
3902
3903 long workflowUserId = creatorUserId;
3904
3905 if (workflowUserId == user.getUserId()) {
3906 workflowUserId = defaultUser.getUserId();
3907 }
3908
3909 ServiceContext workflowServiceContext = serviceContext;
3910
3911 if (workflowServiceContext == null) {
3912 workflowServiceContext = new ServiceContext();
3913 }
3914
3915 workflowServiceContext.setAttribute("autoPassword", autoPassword);
3916 workflowServiceContext.setAttribute("sendEmail", sendEmail);
3917
3918 WorkflowHandlerRegistryUtil.startWorkflowInstance(
3919 companyId, workflowUserId, User.class.getName(), user.getUserId(),
3920 user, workflowServiceContext);
3921
3922 return getUserByEmailAddress(companyId, emailAddress);
3923 }
3924
3925
3935 public User updateJobTitle(long userId, String jobTitle)
3936 throws PortalException, SystemException {
3937
3938 User user = userPersistence.findByPrimaryKey(userId);
3939
3940 user.setJobTitle(jobTitle);
3941
3942 userPersistence.update(user, false);
3943
3944 Contact contact = contactPersistence.findByPrimaryKey(
3945 user.getContactId());
3946
3947 contact.setJobTitle(jobTitle);
3948
3949 contactPersistence.update(contact, false);
3950
3951 return user;
3952 }
3953
3954
3963 public User updateLastLogin(long userId, String loginIP)
3964 throws PortalException, SystemException {
3965
3966 User user = userPersistence.findByPrimaryKey(userId);
3967
3968 Date lastLoginDate = user.getLoginDate();
3969
3970 if (lastLoginDate == null) {
3971 lastLoginDate = new Date();
3972 }
3973
3974 user.setLoginDate(new Date());
3975 user.setLoginIP(loginIP);
3976 user.setLastLoginDate(lastLoginDate);
3977 user.setLastLoginIP(user.getLoginIP());
3978 user.setLastFailedLoginDate(null);
3979 user.setFailedLoginAttempts(0);
3980
3981 userPersistence.update(user, false);
3982
3983 return user;
3984 }
3985
3986
3995 public User updateLockout(User user, boolean lockout)
3996 throws PortalException, SystemException {
3997
3998 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3999
4000 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
4001 return user;
4002 }
4003
4004 Date lockoutDate = null;
4005
4006 if (lockout) {
4007 lockoutDate = new Date();
4008 }
4009
4010 user.setLockout(lockout);
4011 user.setLockoutDate(lockoutDate);
4012
4013 if (!lockout) {
4014 user.setLastFailedLoginDate(lockoutDate);
4015 user.setFailedLoginAttempts(0);
4016 }
4017
4018 userPersistence.update(user, false);
4019
4020 return user;
4021 }
4022
4023
4034 public User updateLockoutByEmailAddress(
4035 long companyId, String emailAddress, boolean lockout)
4036 throws PortalException, SystemException {
4037
4038 User user = getUserByEmailAddress(companyId, emailAddress);
4039
4040 return updateLockout(user, lockout);
4041 }
4042
4043
4052 public User updateLockoutById(long userId, boolean lockout)
4053 throws PortalException, SystemException {
4054
4055 User user = userPersistence.findByPrimaryKey(userId);
4056
4057 return updateLockout(user, lockout);
4058 }
4059
4060
4070 public User updateLockoutByScreenName(
4071 long companyId, String screenName, boolean lockout)
4072 throws PortalException, SystemException {
4073
4074 User user = getUserByScreenName(companyId, screenName);
4075
4076 return updateLockout(user, lockout);
4077 }
4078
4079
4088 public User updateModifiedDate(long userId, Date modifiedDate)
4089 throws PortalException, SystemException {
4090
4091 User user = userPersistence.findByPrimaryKey(userId);
4092
4093 user.setModifiedDate(modifiedDate);
4094
4095 userPersistence.update(user, false);
4096
4097 return user;
4098 }
4099
4100
4109 public User updateOpenId(long userId, String openId)
4110 throws PortalException, SystemException {
4111
4112 openId = openId.trim();
4113
4114 User user = userPersistence.findByPrimaryKey(userId);
4115
4116 user.setOpenId(openId);
4117
4118 userPersistence.update(user, false);
4119
4120 return user;
4121 }
4122
4123
4132 public void updateOrganizations(
4133 long userId, long[] newOrganizationIds,
4134 ServiceContext serviceContext)
4135 throws PortalException, SystemException {
4136
4137 updateOrganizations(
4138 userId, newOrganizationIds, serviceContext.isIndexingEnabled());
4139 }
4140
4141
4153 public User updatePassword(
4154 long userId, String password1, String password2,
4155 boolean passwordReset)
4156 throws PortalException, SystemException {
4157
4158 return updatePassword(
4159 userId, password1, password2, passwordReset, false);
4160 }
4161
4162
4177 public User updatePassword(
4178 long userId, String password1, String password2,
4179 boolean passwordReset, boolean silentUpdate)
4180 throws PortalException, SystemException {
4181
4182 User user = userPersistence.findByPrimaryKey(userId);
4183
4184 if (!silentUpdate) {
4185 validatePassword(user.getCompanyId(), userId, password1, password2);
4186 }
4187
4188 String oldEncPwd = user.getPassword();
4189
4190 if (!user.isPasswordEncrypted()) {
4191 oldEncPwd = PwdEncryptor.encrypt(user.getPassword());
4192 }
4193
4194 String newEncPwd = PwdEncryptor.encrypt(password1);
4195
4196 if (user.hasCompanyMx()) {
4197 mailService.updatePassword(user.getCompanyId(), userId, password1);
4198 }
4199
4200 user.setPassword(newEncPwd);
4201 user.setPasswordUnencrypted(password1);
4202 user.setPasswordEncrypted(true);
4203 user.setPasswordReset(passwordReset);
4204 user.setPasswordModifiedDate(new Date());
4205 user.setDigest(StringPool.BLANK);
4206 user.setGraceLoginCount(0);
4207
4208 if (!silentUpdate) {
4209 user.setPasswordModified(true);
4210 }
4211
4212 try {
4213 userPersistence.update(user, false);
4214 }
4215 catch (ModelListenerException mle) {
4216 String msg = GetterUtil.getString(mle.getCause().getMessage());
4217
4218 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
4219 String passwordHistory = PrefsPropsUtil.getString(
4220 user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
4221
4222 if (msg.indexOf(passwordHistory) != -1) {
4223 throw new UserPasswordException(
4224 UserPasswordException.PASSWORD_ALREADY_USED);
4225 }
4226 }
4227
4228 throw new UserPasswordException(
4229 UserPasswordException.PASSWORD_INVALID);
4230 }
4231
4232 if (!silentUpdate) {
4233 user.setPasswordModified(false);
4234
4235 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
4236 }
4237
4238 return user;
4239 }
4240
4241
4255 public User updatePasswordManually(
4256 long userId, String password, boolean passwordEncrypted,
4257 boolean passwordReset, Date passwordModifiedDate)
4258 throws PortalException, SystemException {
4259
4260
4261
4262 User user = userPersistence.findByPrimaryKey(userId);
4263
4264 user.setPassword(password);
4265 user.setPasswordEncrypted(passwordEncrypted);
4266 user.setPasswordReset(passwordReset);
4267 user.setPasswordModifiedDate(passwordModifiedDate);
4268 user.setDigest(StringPool.BLANK);
4269
4270 userPersistence.update(user, false);
4271
4272 return user;
4273 }
4274
4275
4286 public User updatePasswordReset(long userId, boolean passwordReset)
4287 throws PortalException, SystemException {
4288
4289 User user = userPersistence.findByPrimaryKey(userId);
4290
4291 user.setPasswordReset(passwordReset);
4292
4293 userPersistence.update(user, false);
4294
4295 return user;
4296 }
4297
4298
4308 public User updatePortrait(long userId, byte[] bytes)
4309 throws PortalException, SystemException {
4310
4311 User user = userPersistence.findByPrimaryKey(userId);
4312
4313 long imageMaxSize = PrefsPropsUtil.getLong(
4314 PropsKeys.USERS_IMAGE_MAX_SIZE);
4315
4316 if ((imageMaxSize > 0) &&
4317 ((bytes == null) || (bytes.length > imageMaxSize))) {
4318
4319 throw new UserPortraitSizeException();
4320 }
4321
4322 long portraitId = user.getPortraitId();
4323
4324 if (portraitId <= 0) {
4325 portraitId = counterLocalService.increment();
4326
4327 user.setPortraitId(portraitId);
4328 }
4329
4330 try {
4331 ImageBag imageBag = ImageToolUtil.read(bytes);
4332
4333 RenderedImage renderedImage = imageBag.getRenderedImage();
4334
4335 if (renderedImage == null) {
4336 throw new UserPortraitTypeException();
4337 }
4338
4339 renderedImage = ImageToolUtil.scale(
4340 renderedImage, PropsValues.USERS_IMAGE_MAX_HEIGHT,
4341 PropsValues.USERS_IMAGE_MAX_WIDTH);
4342
4343 String contentType = imageBag.getType();
4344
4345 imageLocalService.updateImage(
4346 portraitId,
4347 ImageToolUtil.getBytes(renderedImage, contentType));
4348 }
4349 catch (IOException ioe) {
4350 throw new ImageSizeException(ioe);
4351 }
4352
4353 userPersistence.update(user, false);
4354
4355 return user;
4356 }
4357
4358
4369 public User updateReminderQuery(long userId, String question, String answer)
4370 throws PortalException, SystemException {
4371
4372 validateReminderQuery(question, answer) ;
4373
4374 User user = userPersistence.findByPrimaryKey(userId);
4375
4376 user.setReminderQueryQuestion(question);
4377 user.setReminderQueryAnswer(answer);
4378
4379 userPersistence.update(user, false);
4380
4381 return user;
4382 }
4383
4384
4394 public User updateScreenName(long userId, String screenName)
4395 throws PortalException, SystemException {
4396
4397
4398
4399 User user = userPersistence.findByPrimaryKey(userId);
4400
4401 screenName = getScreenName(screenName);
4402
4403 validateScreenName(user.getCompanyId(), userId, screenName);
4404
4405 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
4406 user.setDigest(StringPool.BLANK);
4407 }
4408
4409 user.setScreenName(screenName);
4410
4411 userPersistence.update(user, false);
4412
4413
4414
4415 Group group = groupLocalService.getUserGroup(
4416 user.getCompanyId(), userId);
4417
4418 group.setFriendlyURL(StringPool.SLASH + screenName);
4419
4420 groupPersistence.update(group, false);
4421
4422 return user;
4423 }
4424
4425
4434 public User updateStatus(long userId, int status)
4435 throws PortalException, SystemException {
4436
4437 User user = userPersistence.findByPrimaryKey(userId);
4438
4439 user.setStatus(status);
4440
4441 userPersistence.update(user, false);
4442
4443 reindex(user);
4444
4445 return user;
4446 }
4447
4448
4504 @SuppressWarnings("deprecation")
4505 public User updateUser(
4506 long userId, String oldPassword, String newPassword1,
4507 String newPassword2, boolean passwordReset,
4508 String reminderQueryQuestion, String reminderQueryAnswer,
4509 String screenName, String emailAddress, long facebookId,
4510 String openId, String languageId, String timeZoneId,
4511 String greeting, String comments, String firstName,
4512 String middleName, String lastName, int prefixId, int suffixId,
4513 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
4514 String smsSn, String aimSn, String facebookSn, String icqSn,
4515 String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
4516 String twitterSn, String ymSn, String jobTitle, long[] groupIds,
4517 long[] organizationIds, long[] roleIds,
4518 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
4519 ServiceContext serviceContext)
4520 throws PortalException, SystemException {
4521
4522
4523
4524 User user = userPersistence.findByPrimaryKey(userId);
4525 Company company = companyPersistence.findByPrimaryKey(
4526 user.getCompanyId());
4527 String password = oldPassword;
4528 screenName = getScreenName(screenName);
4529 emailAddress = emailAddress.trim().toLowerCase();
4530 openId = openId.trim();
4531 String oldFullName = user.getFullName();
4532 aimSn = aimSn.trim().toLowerCase();
4533 facebookSn = facebookSn.trim().toLowerCase();
4534 icqSn = icqSn.trim().toLowerCase();
4535 jabberSn = jabberSn.trim().toLowerCase();
4536 msnSn = msnSn.trim().toLowerCase();
4537 mySpaceSn = mySpaceSn.trim().toLowerCase();
4538 skypeSn = skypeSn.trim().toLowerCase();
4539 twitterSn = twitterSn.trim().toLowerCase();
4540 ymSn = ymSn.trim().toLowerCase();
4541 Date now = new Date();
4542
4543 EmailAddressGenerator emailAddressGenerator =
4544 EmailAddressGeneratorFactory.getInstance();
4545
4546 if (emailAddressGenerator.isGenerated(emailAddress)) {
4547 emailAddress = StringPool.BLANK;
4548 }
4549
4550 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
4551 Validator.isNull(emailAddress)) {
4552
4553 emailAddress = emailAddressGenerator.generate(
4554 user.getCompanyId(), userId);
4555 }
4556
4557 validate(
4558 userId, screenName, emailAddress, firstName, middleName, lastName,
4559 smsSn);
4560
4561 if (Validator.isNotNull(newPassword1) ||
4562 Validator.isNotNull(newPassword2)) {
4563
4564 user = updatePassword(
4565 userId, newPassword1, newPassword2, passwordReset);
4566
4567 password = newPassword1;
4568
4569 user.setDigest(StringPool.BLANK);
4570 }
4571
4572 user.setModifiedDate(now);
4573
4574 if (user.getContactId() <= 0) {
4575 user.setContactId(counterLocalService.increment());
4576 }
4577
4578 user.setPasswordReset(passwordReset);
4579
4580 if (Validator.isNotNull(reminderQueryQuestion) &&
4581 Validator.isNotNull(reminderQueryAnswer)) {
4582
4583 user.setReminderQueryQuestion(reminderQueryQuestion);
4584 user.setReminderQueryAnswer(reminderQueryAnswer);
4585 }
4586
4587 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
4588 user.setScreenName(screenName);
4589
4590 user.setDigest(StringPool.BLANK);
4591 }
4592
4593 boolean sendEmailAddressVerification = false;
4594
4595 if (!company.isStrangersVerify()) {
4596 setEmailAddress(
4597 user, password, firstName, middleName, lastName, emailAddress);
4598 }
4599 else {
4600 sendEmailAddressVerification = true;
4601 }
4602
4603 if (serviceContext != null) {
4604 String uuid = serviceContext.getUuid();
4605
4606 if (Validator.isNotNull(uuid)) {
4607 user.setUuid(uuid);
4608 }
4609 }
4610
4611 user.setFacebookId(facebookId);
4612 user.setOpenId(openId);
4613 user.setLanguageId(languageId);
4614 user.setTimeZoneId(timeZoneId);
4615 user.setGreeting(greeting);
4616 user.setComments(comments);
4617 user.setFirstName(firstName);
4618 user.setMiddleName(middleName);
4619 user.setLastName(lastName);
4620 user.setJobTitle(jobTitle);
4621
4622 userPersistence.update(user, false, serviceContext);
4623
4624
4625
4626 Date birthday = PortalUtil.getDate(
4627 birthdayMonth, birthdayDay, birthdayYear,
4628 new ContactBirthdayException());
4629
4630 long contactId = user.getContactId();
4631
4632 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
4633
4634 if (contact == null) {
4635 contact = contactPersistence.create(contactId);
4636
4637 contact.setCompanyId(user.getCompanyId());
4638 contact.setUserName(StringPool.BLANK);
4639 contact.setCreateDate(now);
4640 contact.setAccountId(company.getAccountId());
4641 contact.setParentContactId(
4642 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
4643 }
4644
4645 contact.setModifiedDate(now);
4646 contact.setFirstName(firstName);
4647 contact.setMiddleName(middleName);
4648 contact.setLastName(lastName);
4649 contact.setPrefixId(prefixId);
4650 contact.setSuffixId(suffixId);
4651 contact.setMale(male);
4652 contact.setBirthday(birthday);
4653 contact.setSmsSn(smsSn);
4654 contact.setAimSn(aimSn);
4655 contact.setFacebookSn(facebookSn);
4656 contact.setIcqSn(icqSn);
4657 contact.setJabberSn(jabberSn);
4658 contact.setMsnSn(msnSn);
4659 contact.setMySpaceSn(mySpaceSn);
4660 contact.setSkypeSn(skypeSn);
4661 contact.setTwitterSn(twitterSn);
4662 contact.setYmSn(ymSn);
4663 contact.setJobTitle(jobTitle);
4664
4665 contactPersistence.update(contact, false, serviceContext);
4666
4667
4668
4669 Group group = groupLocalService.getUserGroup(
4670 user.getCompanyId(), userId);
4671
4672 group.setFriendlyURL(StringPool.SLASH + screenName);
4673
4674 groupPersistence.update(group, false);
4675
4676
4677
4678 updateGroups(userId, groupIds, serviceContext, false);
4679 updateOrganizations(userId, organizationIds, false);
4680
4681
4682
4683 if (roleIds != null) {
4684 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
4685
4686 userPersistence.setRoles(userId, roleIds);
4687 }
4688
4689
4690
4691 updateUserGroupRoles(user, groupIds, organizationIds, userGroupRoles);
4692
4693
4694
4695 if (userGroupIds != null) {
4696 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
4697 userGroupLocalService.copyUserGroupLayouts(
4698 userGroupIds, userId);
4699 }
4700
4701 userPersistence.setUserGroups(userId, userGroupIds);
4702 }
4703
4704
4705
4706 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
4707
4708
4709
4710 if (serviceContext != null) {
4711 updateAsset(
4712 userId, user, serviceContext.getAssetCategoryIds(),
4713 serviceContext.getAssetTagNames());
4714 }
4715
4716
4717
4718 if (serviceContext != null) {
4719 user.setExpandoBridgeAttributes(serviceContext);
4720 }
4721
4722
4723
4724 if (GetterUtil.getBoolean(
4725 PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
4726 !oldFullName.equals(user.getFullName())) {
4727
4728 mbMessageLocalService.updateUserName(userId, user.getFullName());
4729 }
4730
4731
4732
4733 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
4734 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
4735
4736 indexer.reindex(user);
4737 }
4738
4739
4740
4741 if ((serviceContext != null) && sendEmailAddressVerification) {
4742 sendEmailAddressVerification(user, emailAddress, serviceContext);
4743 }
4744
4745
4746
4747 PermissionCacheUtil.clearCache();
4748
4749 return user;
4750 }
4751
4752
4761 public void verifyEmailAddress(String ticketKey)
4762 throws PortalException, SystemException {
4763
4764 Ticket ticket = ticketLocalService.getTicket(ticketKey);
4765
4766 if (ticket.isExpired() ||
4767 (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
4768
4769 throw new NoSuchTicketException();
4770 }
4771
4772 User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
4773
4774 String emailAddress = ticket.getExtraInfo();
4775
4776 emailAddress = emailAddress.toLowerCase().trim();
4777
4778 if (!emailAddress.equals(user.getEmailAddress())) {
4779 if (userPersistence.fetchByC_EA(
4780 user.getCompanyId(), emailAddress) != null) {
4781
4782 throw new DuplicateUserEmailAddressException();
4783 }
4784
4785 setEmailAddress(
4786 user, StringPool.BLANK, user.getFirstName(),
4787 user.getMiddleName(), user.getLastName(), emailAddress);
4788 }
4789
4790 user.setEmailAddressVerified(true);
4791
4792 userPersistence.update(user, false);
4793
4794 ticketLocalService.deleteTicket(ticket);
4795 }
4796
4797
4843 protected int authenticate(
4844 long companyId, String login, String password, String authType,
4845 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
4846 Map<String, Object> resultsMap)
4847 throws PortalException, SystemException {
4848
4849 if (PropsValues.AUTH_LOGIN_DISABLED) {
4850 return Authenticator.FAILURE;
4851 }
4852
4853 login = login.trim().toLowerCase();
4854
4855 long userId = GetterUtil.getLong(login);
4856
4857
4858
4859 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
4860 if (Validator.isNull(login)) {
4861 throw new UserEmailAddressException();
4862 }
4863 }
4864 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
4865 if (Validator.isNull(login)) {
4866 throw new UserScreenNameException();
4867 }
4868 }
4869 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
4870 if (Validator.isNull(login)) {
4871 throw new UserIdException();
4872 }
4873 }
4874
4875 if (Validator.isNull(password)) {
4876 throw new UserPasswordException(
4877 UserPasswordException.PASSWORD_INVALID);
4878 }
4879
4880 int authResult = Authenticator.FAILURE;
4881
4882
4883
4884 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
4885 authResult = AuthPipeline.authenticateByEmailAddress(
4886 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
4887 headerMap, parameterMap);
4888 }
4889 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
4890 authResult = AuthPipeline.authenticateByScreenName(
4891 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
4892 headerMap, parameterMap);
4893 }
4894 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
4895 authResult = AuthPipeline.authenticateByUserId(
4896 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
4897 headerMap, parameterMap);
4898 }
4899
4900
4901
4902 User user = null;
4903
4904 try {
4905 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
4906 user = userPersistence.findByC_EA(companyId, login);
4907 }
4908 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
4909 user = userPersistence.findByC_SN(companyId, login);
4910 }
4911 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
4912 user = userPersistence.findByC_U(
4913 companyId, GetterUtil.getLong(login));
4914 }
4915 }
4916 catch (NoSuchUserException nsue) {
4917 return Authenticator.DNE;
4918 }
4919
4920 if (user.isDefaultUser()) {
4921 if (_log.isInfoEnabled()) {
4922 _log.info("Authentication is disabled for the default user");
4923 }
4924
4925 return Authenticator.DNE;
4926 }
4927 else if (!user.isActive()) {
4928 if (_log.isInfoEnabled()) {
4929 _log.info(
4930 "Authentication is disabled for inactive user " +
4931 user.getUserId());
4932 }
4933
4934 return Authenticator.FAILURE;
4935 }
4936
4937 if (!user.isPasswordEncrypted()) {
4938 user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
4939 user.setPasswordEncrypted(true);
4940
4941 userPersistence.update(user, false);
4942 }
4943
4944
4945
4946
4947 checkLockout(user);
4948
4949 checkPasswordExpired(user);
4950
4951
4952
4953 if ((authResult == Authenticator.SUCCESS) &&
4954 PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK &&
4955 (!PrefsPropsUtil.getBoolean(
4956 companyId, PropsKeys.LDAP_AUTH_ENABLED) ||
4957 PropsValues.LDAP_IMPORT_USER_PASSWORD_ENABLED)) {
4958
4959 boolean authenticated = PwdAuthenticator.authenticate(
4960 login, password, user.getPassword());
4961
4962 if (authenticated) {
4963 authResult = Authenticator.SUCCESS;
4964 }
4965 else {
4966 authResult = Authenticator.FAILURE;
4967 }
4968 }
4969
4970
4971
4972 if (authResult == Authenticator.SUCCESS) {
4973 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
4974 authResult = AuthPipeline.authenticateByEmailAddress(
4975 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
4976 headerMap, parameterMap);
4977 }
4978 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
4979 authResult = AuthPipeline.authenticateByScreenName(
4980 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
4981 headerMap, parameterMap);
4982 }
4983 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
4984 authResult = AuthPipeline.authenticateByUserId(
4985 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
4986 headerMap, parameterMap);
4987 }
4988 }
4989
4990 if (authResult == Authenticator.SUCCESS) {
4991 if (resultsMap != null) {
4992 resultsMap.put("userId", user.getUserId());
4993 }
4994
4995
4996
4997 boolean updateDigest = true;
4998
4999 if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5000 if (Validator.isNotNull(user.getDigest())) {
5001 updateDigest = false;
5002 }
5003 }
5004
5005 if (updateDigest) {
5006 String digest = user.getDigest(password);
5007
5008 user.setDigest(digest);
5009
5010 userPersistence.update(user, false);
5011 }
5012 }
5013
5014
5015
5016 if (authResult == Authenticator.FAILURE) {
5017 try {
5018 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5019 AuthPipeline.onFailureByEmailAddress(
5020 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5021 parameterMap);
5022 }
5023 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5024 AuthPipeline.onFailureByScreenName(
5025 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5026 parameterMap);
5027 }
5028 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5029 AuthPipeline.onFailureByUserId(
5030 PropsKeys.AUTH_FAILURE, companyId, userId, headerMap,
5031 parameterMap);
5032 }
5033
5034
5035
5036 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5037 user.getCompanyId())) {
5038
5039 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5040
5041 int failedLoginAttempts = user.getFailedLoginAttempts();
5042 int maxFailures = passwordPolicy.getMaxFailure();
5043
5044 if ((failedLoginAttempts >= maxFailures) &&
5045 (maxFailures != 0)) {
5046
5047 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5048 AuthPipeline.onMaxFailuresByEmailAddress(
5049 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5050 headerMap, parameterMap);
5051 }
5052 else if (authType.equals(
5053 CompanyConstants.AUTH_TYPE_SN)) {
5054
5055 AuthPipeline.onMaxFailuresByScreenName(
5056 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5057 headerMap, parameterMap);
5058 }
5059 else if (authType.equals(
5060 CompanyConstants.AUTH_TYPE_ID)) {
5061
5062 AuthPipeline.onMaxFailuresByUserId(
5063 PropsKeys.AUTH_MAX_FAILURES, companyId, userId,
5064 headerMap, parameterMap);
5065 }
5066 }
5067 }
5068 }
5069 catch (Exception e) {
5070 _log.error(e, e);
5071 }
5072 }
5073
5074 return authResult;
5075 }
5076
5077 protected String getScreenName(String screenName) {
5078 return StringUtil.lowerCase(StringUtil.trim(screenName));
5079 }
5080
5081 protected long[] getUserIds(List<User> users) {
5082 long[] userIds = new long[users.size()];
5083
5084 for (int i = 0; i < users.size(); i++) {
5085 User user = users.get(i);
5086
5087 userIds[i] = user.getUserId();
5088 }
5089
5090 return userIds;
5091 }
5092
5093 protected void reindex(final User user) {
5094 final Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
5095
5096 Callable<Void> callable = new Callable<Void>() {
5097
5098 public Void call() throws Exception {
5099 indexer.reindex(user);
5100
5101 return null;
5102 }
5103
5104 };
5105
5106 TransactionCommitCallbackUtil.registerCallback(callable);
5107 }
5108
5109 protected Hits search(
5110 long companyId, String firstName, String middleName,
5111 String lastName, String fullName, String screenName,
5112 String emailAddress, String street, String city, String zip,
5113 String region, String country, int status,
5114 LinkedHashMap<String, Object> params, boolean andSearch, int start,
5115 int end, Sort sort)
5116 throws SystemException {
5117
5118 try {
5119 SearchContext searchContext = new SearchContext();
5120
5121 searchContext.setAndSearch(andSearch);
5122
5123 Map<String, Serializable> attributes =
5124 new HashMap<String, Serializable>();
5125
5126 attributes.put("city", city);
5127 attributes.put("country", country);
5128 attributes.put("emailAddress", emailAddress);
5129 attributes.put("firstName", firstName);
5130 attributes.put("fullName", fullName);
5131 attributes.put("lastName", lastName);
5132 attributes.put("middleName", middleName);
5133 attributes.put("params", params);
5134 attributes.put("region", region);
5135 attributes.put("screenName", screenName);
5136 attributes.put("street", street);
5137 attributes.put("status", status);
5138 attributes.put("zip", zip);
5139
5140 searchContext.setAttributes(attributes);
5141
5142 searchContext.setCompanyId(companyId);
5143 searchContext.setEnd(end);
5144
5145 if (params != null) {
5146 String keywords = (String)params.remove("keywords");
5147
5148 if (Validator.isNotNull(keywords)) {
5149 searchContext.setKeywords(keywords);
5150 }
5151 }
5152
5153 QueryConfig queryConfig = new QueryConfig();
5154
5155 queryConfig.setHighlightEnabled(false);
5156 queryConfig.setScoreEnabled(false);
5157
5158 searchContext.setQueryConfig(queryConfig);
5159
5160 searchContext.setSorts(new Sort[] {sort});
5161 searchContext.setStart(start);
5162
5163 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
5164
5165 return indexer.search(searchContext);
5166 }
5167 catch (Exception e) {
5168 throw new SystemException(e);
5169 }
5170 }
5171
5172 protected void sendEmail(
5173 User user, String password, ServiceContext serviceContext)
5174 throws SystemException {
5175
5176 if (!PrefsPropsUtil.getBoolean(
5177 user.getCompanyId(),
5178 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
5179
5180 return;
5181 }
5182
5183 String fromName = PrefsPropsUtil.getString(
5184 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
5185 String fromAddress = PrefsPropsUtil.getString(
5186 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
5187
5188 String toName = user.getFullName();
5189 String toAddress = user.getEmailAddress();
5190
5191 String subject = PrefsPropsUtil.getContent(
5192 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
5193
5194 String body = null;
5195
5196 if (Validator.isNotNull(password)) {
5197 body = PrefsPropsUtil.getContent(
5198 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
5199 }
5200 else {
5201 body = PrefsPropsUtil.getContent(
5202 user.getCompanyId(),
5203 PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
5204 }
5205
5206 SubscriptionSender subscriptionSender = new SubscriptionSender();
5207
5208 subscriptionSender.setBody(body);
5209 subscriptionSender.setCompanyId(user.getCompanyId());
5210 subscriptionSender.setContextAttributes(
5211 "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
5212 "[$USER_SCREENNAME$]", user.getScreenName());
5213 subscriptionSender.setFrom(fromAddress, fromName);
5214 subscriptionSender.setHtmlFormat(true);
5215 subscriptionSender.setMailId("user", user.getUserId());
5216 subscriptionSender.setServiceContext(serviceContext);
5217 subscriptionSender.setSubject(subject);
5218 subscriptionSender.setUserId(user.getUserId());
5219
5220 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
5221
5222 subscriptionSender.flushNotificationsAsync();
5223 }
5224
5225 protected void setEmailAddress(
5226 User user, String password, String firstName, String middleName,
5227 String lastName, String emailAddress)
5228 throws PortalException, SystemException {
5229
5230 if (emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
5231 return;
5232 }
5233
5234 long userId = user.getUserId();
5235
5236
5237
5238 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
5239 Validator.isNotNull(password)) {
5240
5241 mailService.addUser(
5242 user.getCompanyId(), userId, password, firstName, middleName,
5243 lastName, emailAddress);
5244 }
5245
5246
5247
5248 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
5249 mailService.updateEmailAddress(
5250 user.getCompanyId(), userId, emailAddress);
5251 }
5252
5253
5254
5255 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
5256 mailService.deleteEmailAddress(user.getCompanyId(), userId);
5257 }
5258
5259 user.setEmailAddress(emailAddress);
5260 user.setDigest(StringPool.BLANK);
5261 }
5262
5263 protected void updateGroups(
5264 long userId, long[] newGroupIds, ServiceContext serviceContext,
5265 boolean indexingEnabled)
5266 throws PortalException, SystemException {
5267
5268 if (newGroupIds == null) {
5269 return;
5270 }
5271
5272 List<Group> oldGroups = userPersistence.getGroups(userId);
5273
5274 List<Long> oldGroupIds = new ArrayList<Long>(oldGroups.size());
5275
5276 for (Group oldGroup : oldGroups) {
5277 long oldGroupId = oldGroup.getGroupId();
5278
5279 oldGroupIds.add(oldGroupId);
5280
5281 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
5282 unsetGroupUsers(
5283 oldGroupId, new long[] {userId}, serviceContext);
5284 }
5285 }
5286
5287 for (long newGroupId : newGroupIds) {
5288 if (!oldGroupIds.contains(newGroupId)) {
5289 addGroupUsers(newGroupId, new long[] {userId});
5290 }
5291 }
5292
5293 if (indexingEnabled) {
5294 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
5295
5296 indexer.reindex(new long[] {userId});
5297 }
5298
5299 PermissionCacheUtil.clearCache();
5300 }
5301
5302 protected void updateOrganizations(
5303 long userId, long[] newOrganizationIds, boolean indexingEnabled)
5304 throws PortalException, SystemException {
5305
5306 if (newOrganizationIds == null) {
5307 return;
5308 }
5309
5310 List<Organization> oldOrganizations = userPersistence.getOrganizations(
5311 userId);
5312
5313 List<Long> oldOrganizationIds = new ArrayList<Long>(
5314 oldOrganizations.size());
5315
5316 for (Organization oldOrganization : oldOrganizations) {
5317 long oldOrganizationId = oldOrganization.getOrganizationId();
5318
5319 oldOrganizationIds.add(oldOrganizationId);
5320
5321 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
5322 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
5323 }
5324 }
5325
5326 for (long newOrganizationId : newOrganizationIds) {
5327 if (!oldOrganizationIds.contains(newOrganizationId)) {
5328 addOrganizationUsers(newOrganizationId, new long[] {userId});
5329 }
5330 }
5331
5332 if (indexingEnabled) {
5333 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
5334
5335 indexer.reindex(new long[] {userId});
5336 }
5337
5338 PermissionCacheUtil.clearCache();
5339 }
5340
5341 protected void updateUserGroupRoles(
5342 User user, long[] groupIds, long[] organizationIds,
5343 List<UserGroupRole> userGroupRoles)
5344 throws PortalException, SystemException {
5345
5346 if (userGroupRoles == null) {
5347 return;
5348 }
5349
5350 List<UserGroupRole> previousUserGroupRoles =
5351 userGroupRolePersistence.findByUserId(user.getUserId());
5352
5353 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
5354 if (userGroupRoles.contains(userGroupRole)) {
5355 userGroupRoles.remove(userGroupRole);
5356 }
5357 else {
5358 userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
5359 }
5360 }
5361
5362 long[] validGroupIds = null;
5363
5364 if (groupIds != null) {
5365 validGroupIds = ArrayUtil.clone(groupIds);
5366 }
5367 else {
5368 validGroupIds = user.getGroupIds();
5369 }
5370
5371 if (organizationIds == null) {
5372 organizationIds = user.getOrganizationIds();
5373 }
5374
5375 long[] organizationGroupIds = new long[organizationIds.length];
5376
5377 for (int i = 0; i < organizationIds.length; i++) {
5378 long organizationId = organizationIds[i];
5379
5380 Organization organization =
5381 organizationPersistence.findByPrimaryKey(organizationId);
5382
5383 Group organizationGroup = organization.getGroup();
5384
5385 organizationGroupIds[i] = organizationGroup.getGroupId();
5386 }
5387
5388 validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
5389
5390 Arrays.sort(validGroupIds);
5391
5392 for (UserGroupRole userGroupRole : userGroupRoles) {
5393 if (Arrays.binarySearch(
5394 validGroupIds, userGroupRole.getGroupId()) >= 0) {
5395
5396 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
5397 }
5398 }
5399 }
5400
5401 protected void validate(
5402 long companyId, long userId, boolean autoPassword, String password1,
5403 String password2, boolean autoScreenName, String screenName,
5404 String emailAddress, String firstName, String middleName,
5405 String lastName, long[] organizationIds)
5406 throws PortalException, SystemException {
5407
5408 Company company = companyPersistence.findByPrimaryKey(companyId);
5409
5410 if (company.isSystem()) {
5411 return;
5412 }
5413
5414 if ((company.getMaxUsers() > 0) &&
5415 (company.getMaxUsers() <=
5416 searchCount(
5417 companyId, null, WorkflowConstants.STATUS_APPROVED,
5418 null))) {
5419
5420 throw new CompanyMaxUsersException();
5421 }
5422
5423 if (!autoScreenName) {
5424 validateScreenName(companyId, userId, screenName);
5425 }
5426
5427 if (!autoPassword) {
5428 PasswordPolicy passwordPolicy =
5429 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
5430
5431 PwdToolkitUtil.validate(
5432 companyId, 0, password1, password2, passwordPolicy);
5433 }
5434
5435 validateEmailAddress(companyId, emailAddress);
5436
5437 if (Validator.isNotNull(emailAddress)) {
5438 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
5439
5440 if ((user != null) && (user.getUserId() != userId)) {
5441 throw new DuplicateUserEmailAddressException();
5442 }
5443 }
5444
5445 validateFullName(companyId, firstName, middleName, lastName);
5446
5447 if (organizationIds != null) {
5448 for (long organizationId : organizationIds) {
5449 Organization organization =
5450 organizationPersistence.fetchByPrimaryKey(organizationId);
5451
5452 if (organization == null) {
5453 throw new NoSuchOrganizationException();
5454 }
5455 }
5456 }
5457 }
5458
5459 protected void validate(
5460 long userId, String screenName, String emailAddress,
5461 String firstName, String middleName, String lastName, String smsSn)
5462 throws PortalException, SystemException {
5463
5464 User user = userPersistence.findByPrimaryKey(userId);
5465
5466 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
5467 validateScreenName(user.getCompanyId(), userId, screenName);
5468 }
5469
5470 validateEmailAddress(user.getCompanyId(), emailAddress);
5471
5472 if (!user.isDefaultUser()) {
5473 if (Validator.isNotNull(emailAddress) &&
5474 !user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
5475
5476 if (userPersistence.fetchByC_EA(
5477 user.getCompanyId(), emailAddress) != null) {
5478
5479 throw new DuplicateUserEmailAddressException();
5480 }
5481 }
5482
5483 validateFullName(
5484 user.getCompanyId(), firstName, middleName, lastName);
5485 }
5486
5487 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
5488 throw new UserSmsException();
5489 }
5490 }
5491
5492 protected void validateEmailAddress(long companyId, String emailAddress)
5493 throws PortalException, SystemException {
5494
5495 if (Validator.isNull(emailAddress) &&
5496 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
5497
5498 return;
5499 }
5500
5501 if (!Validator.isEmailAddress(emailAddress) ||
5502 emailAddress.startsWith("root@") ||
5503 emailAddress.startsWith("postmaster@")) {
5504
5505 throw new UserEmailAddressException();
5506 }
5507
5508 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
5509 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
5510 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
5511
5512 for (String reservedEmailAddress : reservedEmailAddresses) {
5513 if (emailAddress.equalsIgnoreCase(reservedEmailAddress)) {
5514 throw new ReservedUserEmailAddressException();
5515 }
5516 }
5517 }
5518
5519 protected void validateEmailAddress(
5520 User user, String emailAddress1, String emailAddress2)
5521 throws PortalException, SystemException {
5522
5523 if (!emailAddress1.equals(emailAddress2)) {
5524 throw new UserEmailAddressException();
5525 }
5526
5527 validateEmailAddress(user.getCompanyId(), emailAddress1);
5528 validateEmailAddress(user.getCompanyId(), emailAddress2);
5529
5530 if (!emailAddress1.equalsIgnoreCase(user.getEmailAddress())) {
5531 if (userPersistence.fetchByC_EA(
5532 user.getCompanyId(), emailAddress1) != null) {
5533
5534 throw new DuplicateUserEmailAddressException();
5535 }
5536 }
5537 }
5538
5539 protected void validateFullName(
5540 long companyId, String firstName, String middleName,
5541 String lastName)
5542 throws PortalException, SystemException {
5543
5544 if (Validator.isNull(firstName)) {
5545 throw new ContactFirstNameException();
5546 }
5547 else if (Validator.isNull(lastName) &&
5548 PrefsPropsUtil.getBoolean(
5549 companyId, PropsKeys.USERS_LAST_NAME_REQUIRED,
5550 PropsValues.USERS_LAST_NAME_REQUIRED)) {
5551
5552 throw new ContactLastNameException();
5553 }
5554
5555 FullNameValidator fullNameValidator =
5556 FullNameValidatorFactory.getInstance();
5557
5558 if (!fullNameValidator.validate(
5559 companyId, firstName, middleName, lastName)) {
5560
5561 throw new ContactFullNameException();
5562 }
5563 }
5564
5565 protected void validatePassword(
5566 long companyId, long userId, String password1, String password2)
5567 throws PortalException, SystemException {
5568
5569 if (Validator.isNull(password1) || Validator.isNull(password2)) {
5570 throw new UserPasswordException(
5571 UserPasswordException.PASSWORD_INVALID);
5572 }
5573
5574 if (!password1.equals(password2)) {
5575 throw new UserPasswordException(
5576 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
5577 }
5578
5579 PasswordPolicy passwordPolicy =
5580 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
5581
5582 PwdToolkitUtil.validate(
5583 companyId, userId, password1, password2, passwordPolicy);
5584 }
5585
5586 protected void validateReminderQuery(String question, String answer)
5587 throws PortalException {
5588
5589 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
5590 return;
5591 }
5592
5593 if (Validator.isNull(question)) {
5594 throw new UserReminderQueryException("Question cannot be null");
5595 }
5596
5597 if (Validator.isNull(answer)) {
5598 throw new UserReminderQueryException("Answer cannot be null");
5599 }
5600 }
5601
5602 protected void validateScreenName(
5603 long companyId, long userId, String screenName)
5604 throws PortalException, SystemException {
5605
5606 if (Validator.isNull(screenName)) {
5607 throw new UserScreenNameException();
5608 }
5609
5610 ScreenNameValidator screenNameValidator =
5611 ScreenNameValidatorFactory.getInstance();
5612
5613 if (!screenNameValidator.validate(companyId, screenName)) {
5614 throw new UserScreenNameException();
5615 }
5616
5617 if (Validator.isNumber(screenName)) {
5618 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
5619 throw new UserScreenNameException();
5620 }
5621
5622 if (!screenName.equals(String.valueOf(userId))) {
5623 Group group = groupPersistence.fetchByPrimaryKey(
5624 GetterUtil.getLong(screenName));
5625
5626 if (group != null) {
5627 throw new UserScreenNameException();
5628 }
5629 }
5630 }
5631
5632 for (char c : screenName.toCharArray()) {
5633 if ((!Validator.isChar(c)) && (!Validator.isDigit(c)) &&
5634 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
5635 (c != CharPool.UNDERLINE)) {
5636
5637 throw new UserScreenNameException();
5638 }
5639 }
5640
5641 String[] anonymousNames = PrincipalBean.ANONYMOUS_NAMES;
5642
5643 for (String anonymousName : anonymousNames) {
5644 if (screenName.equalsIgnoreCase(anonymousName)) {
5645 throw new UserScreenNameException();
5646 }
5647 }
5648
5649 User user = userPersistence.fetchByC_SN(companyId, screenName);
5650
5651 if ((user != null) && (user.getUserId() != userId)) {
5652 throw new DuplicateUserScreenNameException();
5653 }
5654
5655 String friendlyURL = StringPool.SLASH + screenName;
5656
5657 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
5658
5659 if ((group != null) && (group.getClassPK() != userId)) {
5660 throw new GroupFriendlyURLException(
5661 GroupFriendlyURLException.DUPLICATE);
5662 }
5663
5664 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
5665
5666 if (exceptionType != -1) {
5667 throw new UserScreenNameException(
5668 new GroupFriendlyURLException(exceptionType));
5669 }
5670
5671 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
5672 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
5673 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
5674
5675 for (String reservedScreenName : reservedScreenNames) {
5676 if (screenName.equalsIgnoreCase(reservedScreenName)) {
5677 throw new ReservedUserScreenNameException();
5678 }
5679 }
5680 }
5681
5682 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
5683
5684 private static Map<Long, User> _defaultUsers =
5685 new ConcurrentHashMap<Long, User>();
5686
5687 }