001
014
015 package com.liferay.portal.service.impl;
016
017 import com.liferay.portal.CompanyMaxUsersException;
018 import com.liferay.portal.ContactBirthdayException;
019 import com.liferay.portal.ContactFirstNameException;
020 import com.liferay.portal.ContactFullNameException;
021 import com.liferay.portal.ContactLastNameException;
022 import com.liferay.portal.DuplicateUserEmailAddressException;
023 import com.liferay.portal.DuplicateUserScreenNameException;
024 import com.liferay.portal.GroupFriendlyURLException;
025 import com.liferay.portal.ModelListenerException;
026 import com.liferay.portal.NoSuchContactException;
027 import com.liferay.portal.NoSuchGroupException;
028 import com.liferay.portal.NoSuchRoleException;
029 import com.liferay.portal.NoSuchTicketException;
030 import com.liferay.portal.NoSuchUserException;
031 import com.liferay.portal.NoSuchUserGroupException;
032 import com.liferay.portal.PasswordExpiredException;
033 import com.liferay.portal.RequiredUserException;
034 import com.liferay.portal.ReservedUserEmailAddressException;
035 import com.liferay.portal.ReservedUserScreenNameException;
036 import com.liferay.portal.UserEmailAddressException;
037 import com.liferay.portal.UserIdException;
038 import com.liferay.portal.UserLockoutException;
039 import com.liferay.portal.UserPasswordException;
040 import com.liferay.portal.UserPortraitSizeException;
041 import com.liferay.portal.UserPortraitTypeException;
042 import com.liferay.portal.UserReminderQueryException;
043 import com.liferay.portal.UserScreenNameException;
044 import com.liferay.portal.UserSmsException;
045 import com.liferay.portal.kernel.exception.PortalException;
046 import com.liferay.portal.kernel.exception.SystemException;
047 import com.liferay.portal.kernel.image.ImageBag;
048 import com.liferay.portal.kernel.image.ImageProcessorUtil;
049 import com.liferay.portal.kernel.language.LanguageUtil;
050 import com.liferay.portal.kernel.log.Log;
051 import com.liferay.portal.kernel.log.LogFactoryUtil;
052 import com.liferay.portal.kernel.search.Hits;
053 import com.liferay.portal.kernel.search.Indexer;
054 import com.liferay.portal.kernel.search.IndexerRegistryUtil;
055 import com.liferay.portal.kernel.search.QueryConfig;
056 import com.liferay.portal.kernel.search.SearchContext;
057 import com.liferay.portal.kernel.search.Sort;
058 import com.liferay.portal.kernel.spring.aop.Skip;
059 import com.liferay.portal.kernel.transaction.Propagation;
060 import com.liferay.portal.kernel.transaction.Transactional;
061 import com.liferay.portal.kernel.util.ArrayUtil;
062 import com.liferay.portal.kernel.util.CharPool;
063 import com.liferay.portal.kernel.util.Digester;
064 import com.liferay.portal.kernel.util.DigesterUtil;
065 import com.liferay.portal.kernel.util.GetterUtil;
066 import com.liferay.portal.kernel.util.KeyValuePair;
067 import com.liferay.portal.kernel.util.OrderByComparator;
068 import com.liferay.portal.kernel.util.PropsKeys;
069 import com.liferay.portal.kernel.util.StringPool;
070 import com.liferay.portal.kernel.util.StringUtil;
071 import com.liferay.portal.kernel.util.Validator;
072 import com.liferay.portal.kernel.workflow.WorkflowConstants;
073 import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil;
074 import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
075 import com.liferay.portal.model.Account;
076 import com.liferay.portal.model.Company;
077 import com.liferay.portal.model.CompanyConstants;
078 import com.liferay.portal.model.Contact;
079 import com.liferay.portal.model.ContactConstants;
080 import com.liferay.portal.model.Group;
081 import com.liferay.portal.model.GroupConstants;
082 import com.liferay.portal.model.Layout;
083 import com.liferay.portal.model.Organization;
084 import com.liferay.portal.model.PasswordPolicy;
085 import com.liferay.portal.model.ResourceConstants;
086 import com.liferay.portal.model.Role;
087 import com.liferay.portal.model.RoleConstants;
088 import com.liferay.portal.model.Ticket;
089 import com.liferay.portal.model.TicketConstants;
090 import com.liferay.portal.model.User;
091 import com.liferay.portal.model.UserGroup;
092 import com.liferay.portal.model.UserGroupRole;
093 import com.liferay.portal.model.impl.LayoutImpl;
094 import com.liferay.portal.security.auth.AuthPipeline;
095 import com.liferay.portal.security.auth.Authenticator;
096 import com.liferay.portal.security.auth.EmailAddressGenerator;
097 import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
098 import com.liferay.portal.security.auth.FullNameGenerator;
099 import com.liferay.portal.security.auth.FullNameGeneratorFactory;
100 import com.liferay.portal.security.auth.FullNameValidator;
101 import com.liferay.portal.security.auth.FullNameValidatorFactory;
102 import com.liferay.portal.security.auth.PrincipalException;
103 import com.liferay.portal.security.auth.ScreenNameGenerator;
104 import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
105 import com.liferay.portal.security.auth.ScreenNameValidator;
106 import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
107 import com.liferay.portal.security.ldap.LDAPSettingsUtil;
108 import com.liferay.portal.security.permission.PermissionCacheUtil;
109 import com.liferay.portal.security.pwd.PwdAuthenticator;
110 import com.liferay.portal.security.pwd.PwdEncryptor;
111 import com.liferay.portal.security.pwd.PwdToolkitUtil;
112 import com.liferay.portal.service.ServiceContext;
113 import com.liferay.portal.service.base.PrincipalBean;
114 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
115 import com.liferay.portal.util.PortalUtil;
116 import com.liferay.portal.util.PrefsPropsUtil;
117 import com.liferay.portal.util.PropsValues;
118 import com.liferay.portal.util.SubscriptionSender;
119 import com.liferay.portlet.documentlibrary.ImageSizeException;
120 import com.liferay.portlet.messageboards.model.MBMessage;
121 import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
122 import com.liferay.util.Encryptor;
123 import com.liferay.util.EncryptorException;
124
125 import java.awt.image.RenderedImage;
126
127 import java.io.IOException;
128 import java.io.Serializable;
129
130 import java.util.ArrayList;
131 import java.util.Arrays;
132 import java.util.Date;
133 import java.util.HashMap;
134 import java.util.HashSet;
135 import java.util.LinkedHashMap;
136 import java.util.List;
137 import java.util.Locale;
138 import java.util.Map;
139 import java.util.Set;
140 import java.util.concurrent.ConcurrentHashMap;
141
142
153 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
154
155
166 public void addDefaultGroups(long userId)
167 throws PortalException, SystemException {
168
169 User user = userPersistence.findByPrimaryKey(userId);
170
171 Set<Long> groupIdsSet = new HashSet<Long>();
172
173 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
174 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
175 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
176
177 for (String defaultGroupName : defaultGroupNames) {
178 Company company = companyPersistence.findByPrimaryKey(
179 user.getCompanyId());
180
181 Account account = company.getAccount();
182
183 if (defaultGroupName.equalsIgnoreCase(account.getName())) {
184 defaultGroupName = GroupConstants.GUEST;
185 }
186
187 try {
188 Group group = groupPersistence.findByC_N(
189 user.getCompanyId(), defaultGroupName);
190
191 if (!userPersistence.containsGroup(
192 userId, group.getGroupId())) {
193
194 groupIdsSet.add(group.getGroupId());
195 }
196 }
197 catch (NoSuchGroupException nsge) {
198 }
199 }
200
201 long[] groupIds = ArrayUtil.toArray(
202 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
203
204 groupLocalService.addUserGroups(userId, groupIds);
205 }
206
207
218 public void addDefaultRoles(long userId)
219 throws PortalException, SystemException {
220
221 User user = userPersistence.findByPrimaryKey(userId);
222
223 Set<Long> roleIdSet = new HashSet<Long>();
224
225 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
226 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
227 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
228
229 for (String defaultRoleName : defaultRoleNames) {
230 try {
231 Role role = rolePersistence.findByC_N(
232 user.getCompanyId(), defaultRoleName);
233
234 if (!userPersistence.containsRole(
235 userId, role.getRoleId())) {
236
237 roleIdSet.add(role.getRoleId());
238 }
239 }
240 catch (NoSuchRoleException nsre) {
241 }
242 }
243
244 long[] roleIds = ArrayUtil.toArray(
245 roleIdSet.toArray(new Long[roleIdSet.size()]));
246
247 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
248
249 userPersistence.addRoles(userId, roleIds);
250 }
251
252
263 public void addDefaultUserGroups(long userId)
264 throws PortalException, SystemException {
265
266 User user = userPersistence.findByPrimaryKey(userId);
267
268 Set<Long> userGroupIdSet = new HashSet<Long>();
269
270 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
271 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
272 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
273
274 for (String defaultUserGroupName : defaultUserGroupNames) {
275 try {
276 UserGroup userGroup = userGroupPersistence.findByC_N(
277 user.getCompanyId(), defaultUserGroupName);
278
279 if (!userPersistence.containsUserGroup(
280 userId, userGroup.getUserGroupId())) {
281
282 userGroupIdSet.add(userGroup.getUserGroupId());
283 }
284 }
285 catch (NoSuchUserGroupException nsuge) {
286 }
287 }
288
289 long[] userGroupIds = ArrayUtil.toArray(
290 userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
291
292 for (long userGroupId : userGroupIds) {
293 userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
294 }
295
296 userPersistence.addUserGroups(userId, userGroupIds);
297 }
298
299
308 public void addGroupUsers(long groupId, long[] userIds)
309 throws PortalException, SystemException {
310
311 groupPersistence.addUsers(groupId, userIds);
312
313 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
314
315 indexer.reindex(userIds);
316
317 PermissionCacheUtil.clearCache();
318 }
319
320
329 public void addOrganizationUsers(long organizationId, long[] userIds)
330 throws PortalException, SystemException {
331
332 organizationPersistence.addUsers(organizationId, userIds);
333
334 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
335
336 indexer.reindex(userIds);
337
338 PermissionCacheUtil.clearCache();
339 }
340
341
349 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
350 throws SystemException {
351
352 passwordPolicyRelLocalService.addPasswordPolicyRels(
353 passwordPolicyId, User.class.getName(), userIds);
354 }
355
356
365 public void addRoleUsers(long roleId, long[] userIds)
366 throws PortalException, SystemException {
367
368 rolePersistence.addUsers(roleId, userIds);
369
370 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
371
372 indexer.reindex(userIds);
373
374 PermissionCacheUtil.clearCache();
375 }
376
377
386 public void addTeamUsers(long teamId, long[] userIds)
387 throws PortalException, SystemException {
388
389 teamPersistence.addUsers(teamId, userIds);
390
391 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
392
393 indexer.reindex(userIds);
394
395 PermissionCacheUtil.clearCache();
396 }
397
398
446 public User addUser(
447 long creatorUserId, long companyId, boolean autoPassword,
448 String password1, String password2, boolean autoScreenName,
449 String screenName, String emailAddress, long facebookId,
450 String openId, Locale locale, String firstName, String middleName,
451 String lastName, int prefixId, int suffixId, boolean male,
452 int birthdayMonth, int birthdayDay, int birthdayYear,
453 String jobTitle, long[] groupIds, long[] organizationIds,
454 long[] roleIds, long[] userGroupIds, boolean sendEmail,
455 ServiceContext serviceContext)
456 throws PortalException, SystemException {
457
458 boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
459
460 try {
461 WorkflowThreadLocal.setEnabled(false);
462
463 return addUserWithWorkflow(
464 creatorUserId, companyId, autoPassword, password1, password2,
465 autoScreenName, screenName, emailAddress, facebookId, openId,
466 locale, firstName, middleName, lastName, prefixId, suffixId,
467 male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
468 groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
469 serviceContext);
470 }
471 finally {
472 WorkflowThreadLocal.setEnabled(workflowEnabled);
473 }
474 }
475
476
485 public void addUserGroupUsers(long userGroupId, long[] userIds)
486 throws PortalException, SystemException {
487
488 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
489
490 userGroupPersistence.addUsers(userGroupId, userIds);
491
492 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
493
494 indexer.reindex(userIds);
495
496 PermissionCacheUtil.clearCache();
497 }
498
499
547 public User addUserWithWorkflow(
548 long creatorUserId, long companyId, boolean autoPassword,
549 String password1, String password2, boolean autoScreenName,
550 String screenName, String emailAddress, long facebookId,
551 String openId, Locale locale, String firstName, String middleName,
552 String lastName, int prefixId, int suffixId, boolean male,
553 int birthdayMonth, int birthdayDay, int birthdayYear,
554 String jobTitle, long[] groupIds, long[] organizationIds,
555 long[] roleIds, long[] userGroupIds, boolean sendEmail,
556 ServiceContext serviceContext)
557 throws PortalException, SystemException {
558
559
560
561 Company company = companyPersistence.findByPrimaryKey(companyId);
562 screenName = getScreenName(screenName);
563 emailAddress = emailAddress.trim().toLowerCase();
564 openId = openId.trim();
565 Date now = new Date();
566
567 if (PrefsPropsUtil.getBoolean(
568 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
569
570 autoScreenName = true;
571 }
572
573 long userId = counterLocalService.increment();
574
575 EmailAddressGenerator emailAddressGenerator =
576 EmailAddressGeneratorFactory.getInstance();
577
578 if (emailAddressGenerator.isGenerated(emailAddress)) {
579 emailAddress = StringPool.BLANK;
580 }
581
582 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
583 Validator.isNull(emailAddress)) {
584
585 emailAddress = emailAddressGenerator.generate(companyId, userId);
586 }
587
588 validate(
589 companyId, userId, autoPassword, password1, password2,
590 autoScreenName, screenName, emailAddress, firstName, middleName,
591 lastName, organizationIds);
592
593 if (!autoPassword) {
594 if (Validator.isNull(password1) || Validator.isNull(password2)) {
595 throw new UserPasswordException(
596 UserPasswordException.PASSWORD_INVALID);
597 }
598 }
599
600 if (autoScreenName) {
601 ScreenNameGenerator screenNameGenerator =
602 ScreenNameGeneratorFactory.getInstance();
603
604 try {
605 screenName = screenNameGenerator.generate(
606 companyId, userId, emailAddress);
607 }
608 catch (Exception e) {
609 throw new SystemException(e);
610 }
611 }
612
613 User defaultUser = getDefaultUser(companyId);
614
615 FullNameGenerator fullNameGenerator =
616 FullNameGeneratorFactory.getInstance();
617
618 String fullName = fullNameGenerator.getFullName(
619 firstName, middleName, lastName);
620
621 String greeting = LanguageUtil.format(
622 locale, "welcome-x", " " + fullName, false);
623
624 User user = userPersistence.create(userId);
625
626 if (serviceContext != null) {
627 String uuid = serviceContext.getUuid();
628
629 if (Validator.isNotNull(uuid)) {
630 user.setUuid(uuid);
631 }
632 }
633
634 user.setCompanyId(companyId);
635 user.setCreateDate(now);
636 user.setModifiedDate(now);
637 user.setDefaultUser(false);
638 user.setContactId(counterLocalService.increment());
639
640 if (Validator.isNotNull(password1)) {
641 user.setPassword(PwdEncryptor.encrypt(password1));
642 user.setPasswordUnencrypted(password1);
643 }
644
645 user.setPasswordEncrypted(true);
646
647 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
648
649 if (passwordPolicy.isChangeable() &&
650 passwordPolicy.isChangeRequired()) {
651
652 user.setPasswordReset(true);
653 }
654 else {
655 user.setPasswordReset(false);
656 }
657
658 user.setDigest(StringPool.BLANK);
659 user.setScreenName(screenName);
660 user.setEmailAddress(emailAddress);
661 user.setFacebookId(facebookId);
662 user.setOpenId(openId);
663 user.setLanguageId(locale.toString());
664 user.setTimeZoneId(defaultUser.getTimeZoneId());
665 user.setGreeting(greeting);
666 user.setFirstName(firstName);
667 user.setMiddleName(middleName);
668 user.setLastName(lastName);
669 user.setJobTitle(jobTitle);
670 user.setStatus(WorkflowConstants.STATUS_DRAFT);
671
672 userPersistence.update(user, false, serviceContext);
673
674
675
676 String creatorUserName = StringPool.BLANK;
677
678 if (creatorUserId <= 0) {
679 creatorUserId = user.getUserId();
680
681
682
683
684
685 }
686 else {
687 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
688
689 creatorUserName = creatorUser.getFullName();
690 }
691
692 resourceLocalService.addResources(
693 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
694 false, false, false);
695
696
697
698 Date birthday = PortalUtil.getDate(
699 birthdayMonth, birthdayDay, birthdayYear,
700 new ContactBirthdayException());
701
702 Contact contact = contactPersistence.create(user.getContactId());
703
704 contact.setCompanyId(user.getCompanyId());
705 contact.setUserId(creatorUserId);
706 contact.setUserName(creatorUserName);
707 contact.setCreateDate(now);
708 contact.setModifiedDate(now);
709 contact.setAccountId(company.getAccountId());
710 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
711 contact.setFirstName(firstName);
712 contact.setMiddleName(middleName);
713 contact.setLastName(lastName);
714 contact.setPrefixId(prefixId);
715 contact.setSuffixId(suffixId);
716 contact.setMale(male);
717 contact.setBirthday(birthday);
718 contact.setJobTitle(jobTitle);
719
720 contactPersistence.update(contact, false, serviceContext);
721
722
723
724 groupLocalService.addGroup(
725 user.getUserId(), User.class.getName(), user.getUserId(), null,
726 null, 0, StringPool.SLASH + screenName, false, true, null);
727
728
729
730 if (groupIds != null) {
731 groupLocalService.addUserGroups(userId, groupIds);
732 }
733
734 addDefaultGroups(userId);
735
736
737
738 boolean indexingEnabled = serviceContext.isIndexingEnabled();
739
740 serviceContext.setIndexingEnabled(false);
741
742 try {
743 updateOrganizations(userId, organizationIds, serviceContext);
744 }
745 finally {
746 serviceContext.setIndexingEnabled(indexingEnabled);
747 }
748
749
750
751 if (roleIds != null) {
752 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
753
754 userPersistence.setRoles(userId, roleIds);
755 }
756
757 addDefaultRoles(userId);
758
759
760
761 if (userGroupIds != null) {
762 for (long userGroupId : userGroupIds) {
763 userGroupLocalService.copyUserGroupLayouts(
764 userGroupId, new long[] {userId});
765 }
766
767 userPersistence.setUserGroups(userId, userGroupIds);
768 }
769
770 addDefaultUserGroups(userId);
771
772
773
774 if (serviceContext != null) {
775 updateAsset(
776 creatorUserId, user, serviceContext.getAssetCategoryIds(),
777 serviceContext.getAssetTagNames());
778 }
779
780
781
782 user.setExpandoBridgeAttributes(serviceContext);
783
784
785
786 if (serviceContext.isIndexingEnabled()) {
787 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
788
789 indexer.reindex(user);
790 }
791
792
793
794 long workflowUserId = creatorUserId;
795
796 if (workflowUserId == userId) {
797 workflowUserId = defaultUser.getUserId();
798 }
799
800 serviceContext.setAttribute("autoPassword", autoPassword);
801 serviceContext.setAttribute("sendEmail", sendEmail);
802
803 WorkflowHandlerRegistryUtil.startWorkflowInstance(
804 companyId, workflowUserId, User.class.getName(), userId, user,
805 serviceContext);
806
807 String passwordUnencrypted =
808 (String) serviceContext.getAttribute("passwordUnencrypted");
809
810 if (Validator.isNotNull(passwordUnencrypted)) {
811 user.setPasswordUnencrypted(passwordUnencrypted);
812 }
813
814 return user;
815 }
816
817
841 public int authenticateByEmailAddress(
842 long companyId, String emailAddress, String password,
843 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
844 Map<String, Object> resultsMap)
845 throws PortalException, SystemException {
846
847 return authenticate(
848 companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
849 headerMap, parameterMap, resultsMap);
850 }
851
852
876 public int authenticateByScreenName(
877 long companyId, String screenName, String password,
878 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
879 Map<String, Object> resultsMap)
880 throws PortalException, SystemException {
881
882 return authenticate(
883 companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
884 headerMap, parameterMap, resultsMap);
885 }
886
887
911 public int authenticateByUserId(
912 long companyId, long userId, String password,
913 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
914 Map<String, Object> resultsMap)
915 throws PortalException, SystemException {
916
917 return authenticate(
918 companyId, String.valueOf(userId), password,
919 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap, resultsMap);
920 }
921
922
962 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
963 public long authenticateForBasic(
964 long companyId, String authType, String login, String password)
965 throws PortalException, SystemException {
966
967 if (PropsValues.AUTH_LOGIN_DISABLED) {
968 return 0;
969 }
970
971 try {
972 User user = null;
973
974 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
975 user = getUserByEmailAddress(companyId, login);
976 }
977 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
978 user = getUserByScreenName(companyId, login);
979 }
980 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
981 user = getUserById(companyId, GetterUtil.getLong(login));
982 }
983
984 if (user.isDefaultUser()) {
985 if (_log.isInfoEnabled()) {
986 _log.info(
987 "Basic authentication is disabled for the default " +
988 "user");
989 }
990
991 return 0;
992 }
993 else if (!user.isActive()) {
994 if (_log.isInfoEnabled()) {
995 _log.info(
996 "Basic authentication is disabled for inactive user " +
997 user.getUserId());
998 }
999
1000 return 0;
1001 }
1002
1003 if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
1004 return user.getUserId();
1005 }
1006
1007 String userPassword = user.getPassword();
1008
1009 if (!user.isPasswordEncrypted()) {
1010 userPassword = PwdEncryptor.encrypt(userPassword);
1011 }
1012
1013 String encPassword = PwdEncryptor.encrypt(password);
1014
1015 if (userPassword.equals(password) ||
1016 userPassword.equals(encPassword)) {
1017
1018 return user.getUserId();
1019 }
1020 }
1021 catch (NoSuchUserException nsue) {
1022 }
1023
1024 return 0;
1025 }
1026
1027
1045 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1046 public long authenticateForDigest(
1047 long companyId, String username, String realm, String nonce,
1048 String method, String uri, String response)
1049 throws PortalException, SystemException {
1050
1051 if (PropsValues.AUTH_LOGIN_DISABLED) {
1052 return 0;
1053 }
1054
1055
1056
1057 User user = null;
1058
1059 try {
1060 user = getUserByEmailAddress(companyId, username);
1061 }
1062 catch (NoSuchUserException nsue) {
1063 try {
1064 user = getUserByScreenName(companyId, username);
1065 }
1066 catch (NoSuchUserException nsue2) {
1067 try {
1068 user = getUserById(GetterUtil.getLong(username));
1069 }
1070 catch (NoSuchUserException nsue3) {
1071 return 0;
1072 }
1073 }
1074 }
1075
1076 if (user.isDefaultUser()) {
1077 if (_log.isInfoEnabled()) {
1078 _log.info(
1079 "Digest authentication is disabled for the default user");
1080 }
1081
1082 return 0;
1083 }
1084 else if (!user.isActive()) {
1085 if (_log.isInfoEnabled()) {
1086 _log.info(
1087 "Digest authentication is disabled for inactive user " +
1088 user.getUserId());
1089 }
1090
1091 return 0;
1092 }
1093
1094
1095
1096 String digest = user.getDigest();
1097
1098 if (Validator.isNull(digest)) {
1099 _log.error(
1100 "User must first login through the portal " + user.getUserId());
1101
1102 return 0;
1103 }
1104
1105 String[] digestArray = StringUtil.split(user.getDigest());
1106
1107 for (String ha1 : digestArray) {
1108 String ha2 = DigesterUtil.digestHex(Digester.MD5, method, uri);
1109
1110 String curResponse = DigesterUtil.digestHex(
1111 Digester.MD5, ha1, nonce, ha2);
1112
1113 if (response.equals(curResponse)) {
1114 return user.getUserId();
1115 }
1116 }
1117
1118 return 0;
1119 }
1120
1121
1130 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1131 public boolean authenticateForJAAS(long userId, String encPassword) {
1132 if (PropsValues.AUTH_LOGIN_DISABLED) {
1133 return false;
1134 }
1135
1136 try {
1137 User user = userPersistence.findByPrimaryKey(userId);
1138
1139 if (user.isDefaultUser()) {
1140 if (_log.isInfoEnabled()) {
1141 _log.info(
1142 "JAAS authentication is disabled for the default user");
1143 }
1144
1145 return false;
1146 }
1147 else if (!user.isActive()) {
1148 if (_log.isInfoEnabled()) {
1149 _log.info(
1150 "JAAS authentication is disabled for inactive user " +
1151 userId);
1152 }
1153
1154 return false;
1155 }
1156
1157 String password = user.getPassword();
1158
1159 if (user.isPasswordEncrypted()) {
1160 if (password.equals(encPassword)) {
1161 return true;
1162 }
1163
1164 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1165 encPassword = PwdEncryptor.encrypt(encPassword, password);
1166
1167 if (password.equals(encPassword)) {
1168 return true;
1169 }
1170 }
1171 }
1172 else {
1173 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1174 if (password.equals(encPassword)) {
1175 return true;
1176 }
1177 }
1178
1179 password = PwdEncryptor.encrypt(password);
1180
1181 if (password.equals(encPassword)) {
1182 return true;
1183 }
1184 }
1185 }
1186 catch (Exception e) {
1187 _log.error(e);
1188 }
1189
1190 return false;
1191 }
1192
1193
1202 public void checkLockout(User user)
1203 throws PortalException, SystemException {
1204
1205 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1206 return;
1207 }
1208
1209 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1210
1211 if (passwordPolicy.isLockout()) {
1212
1213
1214
1215 Date now = new Date();
1216 int failedLoginAttempts = user.getFailedLoginAttempts();
1217
1218 if (failedLoginAttempts > 0) {
1219 long failedLoginTime = user.getLastFailedLoginDate().getTime();
1220 long elapsedTime = now.getTime() - failedLoginTime;
1221 long requiredElapsedTime =
1222 passwordPolicy.getResetFailureCount() * 1000;
1223
1224 if ((requiredElapsedTime != 0) &&
1225 (elapsedTime > requiredElapsedTime)) {
1226
1227 user.setLastFailedLoginDate(null);
1228 user.setFailedLoginAttempts(0);
1229
1230 userPersistence.update(user, false);
1231 }
1232 }
1233
1234
1235
1236 if (user.isLockout()) {
1237 long lockoutTime = user.getLockoutDate().getTime();
1238 long elapsedTime = now.getTime() - lockoutTime;
1239 long requiredElapsedTime =
1240 passwordPolicy.getLockoutDuration() * 1000;
1241
1242 if ((requiredElapsedTime != 0) &&
1243 (elapsedTime > requiredElapsedTime)) {
1244
1245 user.setLockout(false);
1246 user.setLockoutDate(null);
1247
1248 userPersistence.update(user, false);
1249 }
1250 }
1251
1252 if (user.isLockout()) {
1253 throw new UserLockoutException();
1254 }
1255 }
1256 }
1257
1258
1265 public void checkLoginFailure(User user) throws SystemException {
1266 Date now = new Date();
1267
1268 int failedLoginAttempts = user.getFailedLoginAttempts();
1269
1270 user.setLastFailedLoginDate(now);
1271 user.setFailedLoginAttempts(++failedLoginAttempts);
1272
1273 userPersistence.update(user, false);
1274 }
1275
1276
1286 public void checkLoginFailureByEmailAddress(
1287 long companyId, String emailAddress)
1288 throws PortalException, SystemException {
1289
1290 User user = getUserByEmailAddress(companyId, emailAddress);
1291
1292 checkLoginFailure(user);
1293 }
1294
1295
1304 public void checkLoginFailureById(long userId)
1305 throws PortalException, SystemException {
1306
1307 User user = userPersistence.findByPrimaryKey(userId);
1308
1309 checkLoginFailure(user);
1310 }
1311
1312
1322 public void checkLoginFailureByScreenName(long companyId, String screenName)
1323 throws PortalException, SystemException {
1324
1325 User user = getUserByScreenName(companyId, screenName);
1326
1327 checkLoginFailure(user);
1328 }
1329
1330
1340 public void checkPasswordExpired(User user)
1341 throws PortalException, SystemException {
1342
1343 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1344 return;
1345 }
1346
1347 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1348
1349
1350
1351 if (isPasswordExpired(user)) {
1352 int graceLoginCount = user.getGraceLoginCount();
1353
1354 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
1355 user.setGraceLoginCount(++graceLoginCount);
1356
1357 userPersistence.update(user, false);
1358 }
1359 else {
1360 user.setDigest(StringPool.BLANK);
1361
1362 userPersistence.update(user, false);
1363
1364 throw new PasswordExpiredException();
1365 }
1366 }
1367
1368
1369
1370 if (isPasswordExpiringSoon(user)) {
1371 user.setPasswordReset(true);
1372
1373 userPersistence.update(user, false);
1374 }
1375
1376
1377
1378 if (passwordPolicy.isChangeable() &&
1379 passwordPolicy.isChangeRequired()) {
1380
1381 if ((user.getLastLoginDate() == null)) {
1382 user.setPasswordReset(true);
1383
1384 userPersistence.update(user, false);
1385 }
1386 }
1387 }
1388
1389
1395 public void clearOrganizationUsers(long organizationId)
1396 throws SystemException {
1397
1398 organizationPersistence.clearUsers(organizationId);
1399
1400 PermissionCacheUtil.clearCache();
1401 }
1402
1403
1409 public void clearUserGroupUsers(long userGroupId) throws SystemException {
1410 userGroupPersistence.clearUsers(userGroupId);
1411
1412 PermissionCacheUtil.clearCache();
1413 }
1414
1415
1427 public void completeUserRegistration(
1428 User user, ServiceContext serviceContext)
1429 throws PortalException, SystemException {
1430
1431 boolean autoPassword = GetterUtil.getBoolean(
1432 serviceContext.getAttribute("autoPassword"));
1433
1434 String password = null;
1435
1436 if (autoPassword) {
1437 PasswordPolicy passwordPolicy =
1438 passwordPolicyLocalService.getPasswordPolicy(
1439 user.getCompanyId(), user.getOrganizationIds());
1440
1441 password = PwdToolkitUtil.generate(passwordPolicy);
1442
1443 user.setPassword(PwdEncryptor.encrypt(password));
1444 user.setPasswordEncrypted(true);
1445 user.setPasswordUnencrypted(password);
1446
1447 userPersistence.update(user, false);
1448
1449 }
1450
1451 if (user.hasCompanyMx()) {
1452 String mailPassword = password;
1453
1454 if (Validator.isNull(mailPassword)) {
1455 mailPassword = user.getPasswordUnencrypted();
1456 }
1457
1458 mailService.addUser(
1459 user.getCompanyId(), user.getUserId(), mailPassword,
1460 user.getFirstName(), user.getMiddleName(),
1461 user.getLastName(), user.getEmailAddress());
1462 }
1463
1464 boolean sendEmail = GetterUtil.getBoolean(
1465 serviceContext.getAttribute("sendEmail"));
1466
1467 if (sendEmail) {
1468 sendEmail(user, password, serviceContext);
1469 }
1470
1471 Company company = companyPersistence.findByPrimaryKey(
1472 user.getCompanyId());
1473
1474 if (company.isStrangersVerify() && (serviceContext.getPlid() > 0)) {
1475 sendEmailAddressVerification(
1476 user, user.getEmailAddress(), serviceContext);
1477 }
1478 }
1479
1480
1493 public KeyValuePair decryptUserId(
1494 long companyId, String name, String password)
1495 throws PortalException, SystemException {
1496
1497 Company company = companyPersistence.findByPrimaryKey(companyId);
1498
1499 try {
1500 name = Encryptor.decrypt(company.getKeyObj(), name);
1501 }
1502 catch (EncryptorException ee) {
1503 throw new SystemException(ee);
1504 }
1505
1506 long userId = GetterUtil.getLong(name);
1507
1508 User user = userPersistence.findByPrimaryKey(userId);
1509
1510 try {
1511 password = Encryptor.decrypt(company.getKeyObj(), password);
1512 }
1513 catch (EncryptorException ee) {
1514 throw new SystemException(ee);
1515 }
1516
1517 String encPassword = PwdEncryptor.encrypt(password);
1518
1519 if (user.getPassword().equals(encPassword)) {
1520 if (isPasswordExpired(user)) {
1521 user.setPasswordReset(true);
1522
1523 userPersistence.update(user, false);
1524 }
1525
1526 return new KeyValuePair(name, password);
1527 }
1528 else {
1529 throw new PrincipalException();
1530 }
1531 }
1532
1533
1541 public void deletePortrait(long userId)
1542 throws PortalException, SystemException {
1543
1544 User user = userPersistence.findByPrimaryKey(userId);
1545
1546 long portraitId = user.getPortraitId();
1547
1548 if (portraitId > 0) {
1549 user.setPortraitId(0);
1550
1551 userPersistence.update(user, false);
1552
1553 imageLocalService.deleteImage(portraitId);
1554 }
1555 }
1556
1557
1566 public void deleteRoleUser(long roleId, long userId)
1567 throws PortalException, SystemException {
1568
1569 rolePersistence.removeUser(roleId, userId);
1570
1571 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1572
1573 indexer.reindex(userId);
1574
1575 PermissionCacheUtil.clearCache();
1576 }
1577
1578
1586 @Override
1587 public void deleteUser(long userId)
1588 throws PortalException, SystemException {
1589
1590 User user = userPersistence.findByPrimaryKey(userId);
1591
1592 deleteUser(user);
1593 }
1594
1595
1602 @Override
1603 public void deleteUser(User user) throws PortalException, SystemException {
1604 if (!PropsValues.USERS_DELETE) {
1605 throw new RequiredUserException();
1606 }
1607
1608
1609
1610 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1611
1612 indexer.delete(user);
1613
1614
1615
1616 browserTrackerLocalService.deleteUserBrowserTracker(user.getUserId());
1617
1618
1619
1620 Group group = user.getGroup();
1621
1622 if (group != null) {
1623 groupLocalService.deleteGroup(group);
1624 }
1625
1626
1627
1628 imageLocalService.deleteImage(user.getPortraitId());
1629
1630
1631
1632 passwordPolicyRelLocalService.deletePasswordPolicyRel(
1633 User.class.getName(), user.getUserId());
1634
1635
1636
1637 passwordTrackerLocalService.deletePasswordTrackers(user.getUserId());
1638
1639
1640
1641 subscriptionLocalService.deleteSubscriptions(user.getUserId());
1642
1643
1644
1645 userIdMapperLocalService.deleteUserIdMappers(user.getUserId());
1646
1647
1648
1649 announcementsDeliveryLocalService.deleteDeliveries(user.getUserId());
1650
1651
1652
1653 assetEntryLocalService.deleteEntry(
1654 User.class.getName(), user.getUserId());
1655
1656
1657
1658 blogsStatsUserLocalService.deleteStatsUserByUserId(user.getUserId());
1659
1660
1661
1662 dlFileRankLocalService.deleteFileRanksByUserId(user.getUserId());
1663
1664
1665
1666 expandoValueLocalService.deleteValues(
1667 User.class.getName(), user.getUserId());
1668
1669
1670
1671 mbBanLocalService.deleteBansByBanUserId(user.getUserId());
1672 mbStatsUserLocalService.deleteStatsUsersByUserId(user.getUserId());
1673 mbThreadFlagLocalService.deleteThreadFlagsByUserId(user.getUserId());
1674
1675
1676
1677 membershipRequestLocalService.deleteMembershipRequestsByUserId(
1678 user.getUserId());
1679
1680
1681
1682 shoppingCartLocalService.deleteUserCarts(user.getUserId());
1683
1684
1685
1686 socialActivityLocalService.deleteUserActivities(user.getUserId());
1687 socialRequestLocalService.deleteReceiverUserRequests(user.getUserId());
1688 socialRequestLocalService.deleteUserRequests(user.getUserId());
1689
1690
1691
1692 mailService.deleteUser(user.getCompanyId(), user.getUserId());
1693
1694
1695
1696 try {
1697 contactLocalService.deleteContact(user.getContactId());
1698 }
1699 catch (NoSuchContactException nsce) {
1700 }
1701
1702
1703
1704 resourceLocalService.deleteResource(
1705 user.getCompanyId(), User.class.getName(),
1706 ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
1707
1708
1709
1710 userGroupRoleLocalService.deleteUserGroupRolesByUserId(
1711 user.getUserId());
1712
1713
1714
1715 userPersistence.remove(user);
1716
1717
1718
1719 PermissionCacheUtil.clearCache();
1720
1721
1722
1723 workflowInstanceLinkLocalService.deleteWorkflowInstanceLinks(
1724 user.getCompanyId(), 0, User.class.getName(), user.getUserId());
1725 }
1726
1727
1735 public void deleteUserGroupUser(long userGroupId, long userId)
1736 throws PortalException, SystemException {
1737
1738 userGroupPersistence.removeUser(userGroupId, userId);
1739
1740 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1741
1742 indexer.reindex(userId);
1743
1744 PermissionCacheUtil.clearCache();
1745 }
1746
1747
1757 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1758 public String encryptUserId(String name)
1759 throws PortalException, SystemException {
1760
1761 long userId = GetterUtil.getLong(name);
1762
1763 User user = userPersistence.findByPrimaryKey(userId);
1764
1765 Company company = companyPersistence.findByPrimaryKey(
1766 user.getCompanyId());
1767
1768 try {
1769 return Encryptor.encrypt(company.getKeyObj(), name);
1770 }
1771 catch (EncryptorException ee) {
1772 throw new SystemException(ee);
1773 }
1774 }
1775
1776
1785 public User fetchUserByScreenName(long companyId, String screenName)
1786 throws SystemException {
1787
1788 screenName = getScreenName(screenName);
1789
1790 return userPersistence.fetchByC_SN(companyId, screenName);
1791 }
1792
1793
1801 public User fetchUserById(long userId) throws SystemException {
1802 return userPersistence.fetchByPrimaryKey(userId);
1803 }
1804
1805
1824 public List<User> getCompanyUsers(long companyId, int start, int end)
1825 throws SystemException {
1826
1827 return userPersistence.findByCompanyId(companyId, start, end);
1828 }
1829
1830
1837 public int getCompanyUsersCount(long companyId) throws SystemException {
1838 return userPersistence.countByCompanyId(companyId);
1839 }
1840
1841
1850 @Skip
1851 public User getDefaultUser(long companyId)
1852 throws PortalException, SystemException {
1853
1854 User userModel = _defaultUsers.get(companyId);
1855
1856 if (userModel == null) {
1857 userModel = userLocalService.loadGetDefaultUser(companyId);
1858
1859 _defaultUsers.put(companyId, userModel);
1860 }
1861
1862 return userModel;
1863 }
1864
1865
1874 @Skip
1875 public long getDefaultUserId(long companyId)
1876 throws PortalException, SystemException {
1877
1878 User user = getDefaultUser(companyId);
1879
1880 return user.getUserId();
1881 }
1882
1883
1890 public long[] getGroupUserIds(long groupId) throws SystemException {
1891 return getUserIds(getGroupUsers(groupId));
1892 }
1893
1894
1901 public List<User> getGroupUsers(long groupId) throws SystemException {
1902 return groupPersistence.getUsers(groupId);
1903 }
1904
1905
1912 public int getGroupUsersCount(long groupId) throws SystemException {
1913 return groupPersistence.getUsersSize(groupId);
1914 }
1915
1916
1926 public int getGroupUsersCount(long groupId, int status)
1927 throws PortalException, SystemException {
1928
1929 Group group = groupPersistence.findByPrimaryKey(groupId);
1930
1931 LinkedHashMap<String, Object> params =
1932 new LinkedHashMap<String, Object>();
1933
1934 params.put("usersGroups", new Long(groupId));
1935
1936 return searchCount(group.getCompanyId(), null, status, params);
1937 }
1938
1939
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
2026 public int getOrganizationUsersCount(long organizationId, int status)
2027 throws PortalException, SystemException {
2028
2029 Organization organization = organizationPersistence.findByPrimaryKey(
2030 organizationId);
2031
2032 LinkedHashMap<String, Object> params =
2033 new LinkedHashMap<String, Object>();
2034
2035 params.put("usersOrgs", new Long(organizationId));
2036
2037 return searchCount(organization.getCompanyId(), null, status, params);
2038 }
2039
2040
2047 public long[] getRoleUserIds(long roleId) throws SystemException {
2048 return getUserIds(getRoleUsers(roleId));
2049 }
2050
2051
2058 public List<User> getRoleUsers(long roleId) throws SystemException {
2059 return rolePersistence.getUsers(roleId);
2060 }
2061
2062
2081 public List<User> getRoleUsers(long roleId, int start, int end)
2082 throws SystemException {
2083
2084 return rolePersistence.getUsers(roleId, start, end);
2085 }
2086
2087
2094 public int getRoleUsersCount(long roleId) throws SystemException {
2095 return rolePersistence.getUsersSize(roleId);
2096 }
2097
2098
2108 public int getRoleUsersCount(long roleId, int status)
2109 throws PortalException, SystemException {
2110
2111 Role role = rolePersistence.findByPrimaryKey(
2112 roleId);
2113
2114 LinkedHashMap<String, Object> params =
2115 new LinkedHashMap<String, Object>();
2116
2117 params.put("usersRoles", new Long(roleId));
2118
2119 return searchCount(role.getCompanyId(), null, status, params);
2120 }
2121
2122
2150 public List<User> getSocialUsers(
2151 long userId, int type, int start, int end, OrderByComparator obc)
2152 throws PortalException, SystemException {
2153
2154 User user = userPersistence.findByPrimaryKey(userId);
2155
2156 LinkedHashMap<String, Object> params =
2157 new LinkedHashMap<String, Object>();
2158
2159 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2160
2161 return search(
2162 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2163 params, start, end, obc);
2164 }
2165
2166
2190 public List<User> getSocialUsers(
2191 long userId, int start, int end, OrderByComparator obc)
2192 throws PortalException, SystemException {
2193
2194 User user = userPersistence.findByPrimaryKey(userId);
2195
2196 LinkedHashMap<String, Object> params =
2197 new LinkedHashMap<String, Object>();
2198
2199 params.put("socialRelation", new Long[] {userId});
2200
2201 return search(
2202 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2203 params, start, end, obc);
2204 }
2205
2206
2235 public List<User> getSocialUsers(
2236 long userId1, long userId2, int type, int start, int end,
2237 OrderByComparator obc)
2238 throws PortalException, SystemException {
2239
2240 User user1 = userPersistence.findByPrimaryKey(userId1);
2241
2242 LinkedHashMap<String, Object> params =
2243 new LinkedHashMap<String, Object>();
2244
2245 params.put(
2246 "socialMutualRelationType",
2247 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2248
2249 return search(
2250 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2251 params, start, end, obc);
2252 }
2253
2254
2280 public List<User> getSocialUsers(
2281 long userId1, long userId2, int start, int end,
2282 OrderByComparator obc)
2283 throws PortalException, SystemException {
2284
2285 User user1 = userPersistence.findByPrimaryKey(userId1);
2286
2287 LinkedHashMap<String, Object> params =
2288 new LinkedHashMap<String, Object>();
2289
2290 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2291
2292 return search(
2293 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2294 params, start, end, obc);
2295 }
2296
2297
2306 public int getSocialUsersCount(long userId)
2307 throws PortalException, SystemException {
2308
2309 User user = userPersistence.findByPrimaryKey(userId);
2310
2311 LinkedHashMap<String, Object> params =
2312 new LinkedHashMap<String, Object>();
2313
2314 params.put("socialRelation", new Long[] {userId});
2315
2316 return searchCount(user.getCompanyId(), null,
2317 WorkflowConstants.STATUS_APPROVED, params);
2318 }
2319
2320
2334 public int getSocialUsersCount(long userId, int type)
2335 throws PortalException, SystemException {
2336
2337 User user = userPersistence.findByPrimaryKey(userId);
2338
2339 LinkedHashMap<String, Object> params =
2340 new LinkedHashMap<String, Object>();
2341
2342 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2343
2344 return searchCount(user.getCompanyId(), null,
2345 WorkflowConstants.STATUS_APPROVED, params);
2346 }
2347
2348
2359 public int getSocialUsersCount(long userId1, long userId2)
2360 throws PortalException, SystemException {
2361
2362 User user1 = userPersistence.findByPrimaryKey(userId1);
2363
2364 LinkedHashMap<String, Object> params =
2365 new LinkedHashMap<String, Object>();
2366
2367 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2368
2369 return searchCount(user1.getCompanyId(), null,
2370 WorkflowConstants.STATUS_APPROVED, params);
2371 }
2372
2373
2388 public int getSocialUsersCount(long userId1, long userId2, int type)
2389 throws PortalException, SystemException {
2390
2391 User user1 = userPersistence.findByPrimaryKey(userId1);
2392
2393 LinkedHashMap<String, Object> params =
2394 new LinkedHashMap<String, Object>();
2395
2396 params.put(
2397 "socialMutualRelationType",
2398 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2399
2400 return searchCount(user1.getCompanyId(), null,
2401 WorkflowConstants.STATUS_APPROVED, params);
2402 }
2403
2404
2412 public User getUserByContactId(long contactId)
2413 throws PortalException, SystemException {
2414
2415 return userPersistence.findByContactId(contactId);
2416 }
2417
2418
2428 public User getUserByEmailAddress(long companyId, String emailAddress)
2429 throws PortalException, SystemException {
2430
2431 emailAddress = emailAddress.trim().toLowerCase();
2432
2433 return userPersistence.findByC_EA(companyId, emailAddress);
2434 }
2435
2436
2446 public User getUserByFacebookId(long companyId, long facebookId)
2447 throws PortalException, SystemException {
2448
2449 return userPersistence.findByC_FID(companyId, facebookId);
2450 }
2451
2452
2461 public User getUserById(long userId)
2462 throws PortalException, SystemException {
2463
2464 return userPersistence.findByPrimaryKey(userId);
2465 }
2466
2467
2477 public User getUserById(long companyId, long userId)
2478 throws PortalException, SystemException {
2479
2480 return userPersistence.findByC_U(companyId, userId);
2481 }
2482
2483
2492 public User getUserByOpenId(long companyId, String openId)
2493 throws PortalException, SystemException {
2494
2495 return userPersistence.findByC_O(companyId, openId);
2496 }
2497
2498
2507 public User getUserByPortraitId(long portraitId)
2508 throws PortalException, SystemException {
2509
2510 return userPersistence.findByPortraitId(portraitId);
2511 }
2512
2513
2523 public User getUserByScreenName(long companyId, String screenName)
2524 throws PortalException, SystemException {
2525
2526 screenName = getScreenName(screenName);
2527
2528 return userPersistence.findByC_SN(companyId, screenName);
2529 }
2530
2531
2540 public User getUserByUuid(String uuid)
2541 throws PortalException, SystemException {
2542
2543 List<User> users = userPersistence.findByUuid(uuid);
2544
2545 if (users.isEmpty()) {
2546 throw new NoSuchUserException();
2547 }
2548 else {
2549 return users.get(0);
2550 }
2551 }
2552
2553
2560 public List<User> getUserGroupUsers(long userGroupId)
2561 throws SystemException {
2562
2563 return userGroupPersistence.getUsers(userGroupId);
2564 }
2565
2566
2573 public int getUserGroupUsersCount(long userGroupId) throws SystemException {
2574 return userGroupPersistence.getUsersSize(userGroupId);
2575 }
2576
2577
2587 public int getUserGroupUsersCount(long userGroupId, int status)
2588 throws PortalException, SystemException {
2589
2590 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
2591 userGroupId);
2592
2593 LinkedHashMap<String, Object> params =
2594 new LinkedHashMap<String, Object>();
2595
2596 params.put("usersUserGroups", new Long(userGroupId));
2597
2598 return searchCount(userGroup.getCompanyId(), null, status, params);
2599 }
2600
2601
2611 public long getUserIdByEmailAddress(long companyId, String emailAddress)
2612 throws PortalException, SystemException {
2613
2614 emailAddress = emailAddress.trim().toLowerCase();
2615
2616 User user = userPersistence.findByC_EA(companyId, emailAddress);
2617
2618 return user.getUserId();
2619 }
2620
2621
2631 public long getUserIdByScreenName(long companyId, String screenName)
2632 throws PortalException, SystemException {
2633
2634 screenName = getScreenName(screenName);
2635
2636 User user = userPersistence.findByC_SN(companyId, screenName);
2637
2638 return user.getUserId();
2639 }
2640
2641
2650 public boolean hasGroupUser(long groupId, long userId)
2651 throws SystemException {
2652
2653 return groupPersistence.containsUser(groupId, userId);
2654 }
2655
2656
2665 public boolean hasOrganizationUser(long organizationId, long userId)
2666 throws SystemException {
2667
2668 return organizationPersistence.containsUser(organizationId, userId);
2669 }
2670
2671
2681 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
2682 throws SystemException {
2683
2684 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
2685 passwordPolicyId, User.class.getName(), userId);
2686 }
2687
2688
2697 public boolean hasRoleUser(long roleId, long userId)
2698 throws SystemException {
2699
2700 return rolePersistence.containsUser(roleId, userId);
2701 }
2702
2703
2718 public boolean hasRoleUser(
2719 long companyId, String name, long userId, boolean inherited)
2720 throws PortalException, SystemException {
2721
2722 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
2723 }
2724
2725
2734 public boolean hasTeamUser(long teamId, long userId)
2735 throws SystemException {
2736
2737 return teamPersistence.containsUser(teamId, userId);
2738 }
2739
2740
2749 public boolean hasUserGroupUser(long userGroupId, long userId)
2750 throws SystemException {
2751
2752 return userGroupPersistence.containsUser(userGroupId, userId);
2753 }
2754
2755
2765 public boolean isPasswordExpired(User user)
2766 throws PortalException, SystemException {
2767
2768 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2769
2770 if (passwordPolicy.getExpireable()) {
2771 Date now = new Date();
2772
2773 if (user.getPasswordModifiedDate() == null) {
2774 user.setPasswordModifiedDate(now);
2775
2776 userLocalService.updateUser(user, false);
2777 }
2778
2779 long passwordStartTime = user.getPasswordModifiedDate().getTime();
2780 long elapsedTime = now.getTime() - passwordStartTime;
2781
2782 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
2783 return true;
2784 }
2785 else {
2786 return false;
2787 }
2788 }
2789
2790 return false;
2791 }
2792
2793
2803 public boolean isPasswordExpiringSoon(User user)
2804 throws PortalException, SystemException {
2805
2806 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2807
2808 if (passwordPolicy.isExpireable()) {
2809 Date now = new Date();
2810
2811 if (user.getPasswordModifiedDate() == null) {
2812 user.setPasswordModifiedDate(now);
2813
2814 userLocalService.updateUser(user, false);
2815 }
2816
2817 long timeModified = user.getPasswordModifiedDate().getTime();
2818 long passwordExpiresOn =
2819 (passwordPolicy.getMaxAge() * 1000) + timeModified;
2820
2821 long timeStartWarning =
2822 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
2823
2824 if (now.getTime() > timeStartWarning) {
2825 return true;
2826 }
2827 else {
2828 return false;
2829 }
2830 }
2831
2832 return false;
2833 }
2834
2835 public User loadGetDefaultUser(long companyId)
2836 throws PortalException, SystemException {
2837
2838 return userPersistence.findByC_DU(companyId, true);
2839 }
2840
2841
2880 public User updateIncompleteUser(
2881 long creatorUserId, long companyId, boolean autoPassword,
2882 String password1, String password2, boolean autoScreenName,
2883 String screenName, String emailAddress, long facebookId,
2884 String openId, Locale locale, String firstName, String middleName,
2885 String lastName, int prefixId, int suffixId, boolean male,
2886 int birthdayMonth, int birthdayDay, int birthdayYear,
2887 String jobTitle, boolean updateUserInformation, boolean sendEmail,
2888 ServiceContext serviceContext)
2889 throws PortalException, SystemException {
2890
2891 User user = getUserByEmailAddress(companyId, emailAddress);
2892
2893 if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
2894 throw new PortalException("Invalid user status");
2895 }
2896
2897 User defaultUser = getDefaultUser(companyId);
2898
2899 if (updateUserInformation) {
2900 autoScreenName = false;
2901
2902 if (PrefsPropsUtil.getBoolean(
2903 companyId,
2904 PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
2905
2906 autoScreenName = true;
2907 }
2908
2909 validate(
2910 companyId, user.getUserId(), autoPassword, password1, password2,
2911 autoScreenName, screenName, emailAddress, firstName, middleName,
2912 lastName, null);
2913
2914 if (!autoPassword) {
2915 if (Validator.isNull(password1) ||
2916 Validator.isNull(password2)) {
2917 throw new UserPasswordException(
2918 UserPasswordException.PASSWORD_INVALID);
2919 }
2920 }
2921
2922 if (autoScreenName) {
2923 ScreenNameGenerator screenNameGenerator =
2924 ScreenNameGeneratorFactory.getInstance();
2925
2926 try {
2927 screenName = screenNameGenerator.generate(
2928 companyId, user.getUserId(), emailAddress);
2929 }
2930 catch (Exception e) {
2931 throw new SystemException(e);
2932 }
2933 }
2934
2935 FullNameGenerator fullNameGenerator =
2936 FullNameGeneratorFactory.getInstance();
2937
2938 String fullName = fullNameGenerator.getFullName(
2939 firstName, middleName, lastName);
2940
2941 String greeting = LanguageUtil.format(
2942 locale, "welcome-x", " " + fullName, false);
2943
2944 if (Validator.isNotNull(password1)) {
2945 user.setPassword(PwdEncryptor.encrypt(password1));
2946 user.setPasswordUnencrypted(password1);
2947 }
2948
2949 user.setPasswordEncrypted(true);
2950
2951 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
2952
2953 if (passwordPolicy.isChangeable() &&
2954 passwordPolicy.isChangeRequired()) {
2955
2956 user.setPasswordReset(true);
2957 }
2958 else {
2959 user.setPasswordReset(false);
2960 }
2961
2962 user.setScreenName(screenName);
2963 user.setFacebookId(facebookId);
2964 user.setOpenId(openId);
2965 user.setLanguageId(locale.toString());
2966 user.setTimeZoneId(defaultUser.getTimeZoneId());
2967 user.setGreeting(greeting);
2968 user.setFirstName(firstName);
2969 user.setMiddleName(middleName);
2970 user.setLastName(lastName);
2971 user.setJobTitle(jobTitle);
2972
2973 Date birthday = PortalUtil.getDate(
2974 birthdayMonth, birthdayDay, birthdayYear,
2975 new ContactBirthdayException());
2976
2977 Contact contact = user.getContact();
2978
2979 contact.setFirstName(firstName);
2980 contact.setMiddleName(middleName);
2981 contact.setLastName(lastName);
2982 contact.setPrefixId(prefixId);
2983 contact.setSuffixId(suffixId);
2984 contact.setMale(male);
2985 contact.setBirthday(birthday);
2986 contact.setJobTitle(jobTitle);
2987
2988 contactPersistence.update(contact, false, serviceContext);
2989
2990
2991
2992 user.setExpandoBridgeAttributes(serviceContext);
2993
2994
2995
2996 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
2997
2998 indexer.reindex(user);
2999 }
3000
3001 user.setStatus(WorkflowConstants.STATUS_DRAFT);
3002
3003 userPersistence.update(user, false, serviceContext);
3004
3005
3006
3007 long workflowUserId = creatorUserId;
3008
3009 if (workflowUserId == user.getUserId()) {
3010 workflowUserId = defaultUser.getUserId();
3011 }
3012
3013 serviceContext.setAttribute("autoPassword", autoPassword);
3014 serviceContext.setAttribute("sendEmail", sendEmail);
3015
3016 WorkflowHandlerRegistryUtil.startWorkflowInstance(
3017 companyId, workflowUserId, User.class.getName(), user.getUserId(),
3018 user, serviceContext);
3019
3020 return getUserByEmailAddress(companyId, emailAddress);
3021 }
3022
3023
3055 public List<User> search(
3056 long companyId, String keywords, int status,
3057 LinkedHashMap<String, Object> params, int start, int end,
3058 OrderByComparator obc)
3059 throws SystemException {
3060
3061 return userFinder.findByKeywords(
3062 companyId, keywords, status, params, start, end, obc);
3063 }
3064
3065
3096 public Hits search(
3097 long companyId, String keywords, int status,
3098 LinkedHashMap<String, Object> params, int start, int end, Sort sort)
3099 throws SystemException {
3100
3101 String firstName = null;
3102 String middleName = null;
3103 String lastName = null;
3104 String fullName = null;
3105 String screenName = null;
3106 String emailAddress = null;
3107 String street = null;
3108 String city = null;
3109 String zip = null;
3110 String region = null;
3111 String country = null;
3112 boolean andOperator = false;
3113
3114 if (Validator.isNotNull(keywords)) {
3115 firstName = keywords;
3116 middleName = keywords;
3117 lastName = keywords;
3118 fullName = keywords;
3119 screenName = keywords;
3120 emailAddress = keywords;
3121 street = keywords;
3122 city = keywords;
3123 zip = keywords;
3124 region = keywords;
3125 country = keywords;
3126 }
3127 else {
3128 andOperator = true;
3129 }
3130
3131 return search(
3132 companyId, firstName, middleName, lastName, fullName, screenName,
3133 emailAddress, street, city, zip, region, country, status, params,
3134 andOperator, start, end, sort);
3135 }
3136
3137
3177 public List<User> search(
3178 long companyId, String firstName, String middleName,
3179 String lastName, String screenName, String emailAddress,
3180 int status, LinkedHashMap<String, Object> params,
3181 boolean andSearch, int start, int end, OrderByComparator obc)
3182 throws SystemException {
3183
3184 return userFinder.findByC_FN_MN_LN_SN_EA_S(
3185 companyId, firstName, middleName, lastName, screenName,
3186 emailAddress, status, params, andSearch, start, end, obc);
3187 }
3188
3189
3228 public Hits search(
3229 long companyId, String firstName, String middleName,
3230 String lastName, String screenName, String emailAddress,
3231 int status, LinkedHashMap<String, Object> params,
3232 boolean andSearch, int start, int end, Sort sort)
3233 throws SystemException {
3234
3235 return search(
3236 companyId, firstName, middleName, lastName, null, screenName,
3237 emailAddress, null, null, null, null, null, status, params,
3238 andSearch, start, end, sort);
3239 }
3240
3241
3255 public int searchCount(
3256 long companyId, String keywords, int status,
3257 LinkedHashMap<String, Object> params)
3258 throws SystemException {
3259
3260 return userFinder.countByKeywords(companyId, keywords, status, params);
3261 }
3262
3263
3285 public int searchCount(
3286 long companyId, String firstName, String middleName,
3287 String lastName, String screenName, String emailAddress,
3288 int status, LinkedHashMap<String, Object> params,
3289 boolean andSearch)
3290 throws SystemException {
3291
3292 return userFinder.countByC_FN_MN_LN_SN_EA_S(
3293 companyId, firstName, middleName, lastName, screenName,
3294 emailAddress, status, params, andSearch);
3295 }
3296
3297
3308 public void sendEmailAddressVerification(
3309 User user, String emailAddress, ServiceContext serviceContext)
3310 throws PortalException, SystemException {
3311
3312 if (user.isEmailAddressVerified() &&
3313 emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
3314
3315 return;
3316 }
3317
3318 Ticket ticket = ticketLocalService.addTicket(
3319 user.getCompanyId(), User.class.getName(), user.getUserId(),
3320 TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3321 serviceContext);
3322
3323 String verifyEmailAddressURL =
3324 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3325 "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3326
3327 Layout layout = layoutLocalService.getLayout(serviceContext.getPlid());
3328
3329 Group group = layout.getGroup();
3330
3331 if (!layout.isPrivateLayout() && !group.isUser()) {
3332 verifyEmailAddressURL += "&p_l_id=" + serviceContext.getPlid();
3333 }
3334
3335 String fromName = PrefsPropsUtil.getString(
3336 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3337 String fromAddress = PrefsPropsUtil.getString(
3338 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3339
3340 String toName = user.getFullName();
3341 String toAddress = emailAddress;
3342
3343 String subject = PrefsPropsUtil.getContent(
3344 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3345
3346 String body = PrefsPropsUtil.getContent(
3347 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3348
3349 SubscriptionSender subscriptionSender = new SubscriptionSender();
3350
3351 subscriptionSender.setBody(body);
3352 subscriptionSender.setCompanyId(user.getCompanyId());
3353 subscriptionSender.setContextAttributes(
3354 "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3355 "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3356 "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3357 "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_AGENT$]",
3358 serviceContext.getUserAgent(), "[$USER_ID$]", user.getUserId(),
3359 "[$USER_SCREENNAME$]", user.getScreenName());
3360 subscriptionSender.setFrom(fromAddress, fromName);
3361 subscriptionSender.setHtmlFormat(true);
3362 subscriptionSender.setMailId("user", user.getUserId());
3363 subscriptionSender.setSubject(subject);
3364 subscriptionSender.setUserId(user.getUserId());
3365
3366 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3367
3368 subscriptionSender.flushNotificationsAsync();
3369 }
3370
3371
3391 public void sendPassword(
3392 long companyId, String emailAddress, String fromName,
3393 String fromAddress, String subject, String body,
3394 ServiceContext serviceContext)
3395 throws PortalException, SystemException {
3396
3397 Company company = companyPersistence.findByPrimaryKey(companyId);
3398
3399 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3400 return;
3401 }
3402
3403 emailAddress = emailAddress.trim().toLowerCase();
3404
3405 if (Validator.isNull(emailAddress)) {
3406 throw new UserEmailAddressException();
3407 }
3408
3409 User user = userPersistence.findByC_EA(companyId, emailAddress);
3410
3411 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3412
3413 String newPassword = StringPool.BLANK;
3414 String passwordResetURL = StringPool.BLANK;
3415
3416 if (company.isSendPasswordResetLink()) {
3417 Date expirationDate = new Date(
3418 System.currentTimeMillis() +
3419 (passwordPolicy.getResetTicketMaxAge() * 1000));
3420
3421 Ticket ticket = ticketLocalService.addTicket(
3422 companyId, User.class.getName(), user.getUserId(),
3423 TicketConstants.TYPE_PASSWORD, null, expirationDate,
3424 serviceContext);
3425
3426 passwordResetURL =
3427 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3428 "/portal/update_password?p_l_id="+
3429 serviceContext.getPlid() +
3430 "&ticketKey=" + ticket.getKey();
3431 }
3432 else {
3433 if (!PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
3434 PwdEncryptor.TYPE_NONE)) {
3435
3436 newPassword = PwdToolkitUtil.generate(passwordPolicy);
3437
3438 boolean passwordReset = false;
3439
3440 if (passwordPolicy.getChangeable() &&
3441 passwordPolicy.getChangeRequired()) {
3442
3443 passwordReset = true;
3444 }
3445
3446 user.setPassword(PwdEncryptor.encrypt(newPassword));
3447 user.setPasswordUnencrypted(newPassword);
3448 user.setPasswordEncrypted(true);
3449 user.setPasswordReset(passwordReset);
3450 user.setPasswordModified(true);
3451 user.setPasswordModifiedDate(new Date());
3452
3453 userPersistence.update(user, false);
3454
3455 user.setPasswordModified(false);
3456 }
3457 else {
3458 newPassword = user.getPassword();
3459 }
3460 }
3461
3462 if (Validator.isNull(fromName)) {
3463 fromName = PrefsPropsUtil.getString(
3464 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3465 }
3466
3467 if (Validator.isNull(fromAddress)) {
3468 fromAddress = PrefsPropsUtil.getString(
3469 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3470 }
3471
3472 String toName = user.getFullName();
3473 String toAddress = user.getEmailAddress();
3474
3475 if (Validator.isNull(subject)) {
3476 if (company.isSendPasswordResetLink()) {
3477 subject = PrefsPropsUtil.getContent(
3478 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
3479 }
3480 else {
3481 subject = PrefsPropsUtil.getContent(
3482 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
3483 }
3484 }
3485
3486 if (Validator.isNull(body)) {
3487 if (company.isSendPasswordResetLink()) {
3488 body = PrefsPropsUtil.getContent(
3489 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
3490 }
3491 else {
3492 body = PrefsPropsUtil.getContent(
3493 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
3494 }
3495 }
3496
3497 SubscriptionSender subscriptionSender = new SubscriptionSender();
3498
3499 subscriptionSender.setBody(body);
3500 subscriptionSender.setCompanyId(companyId);
3501 subscriptionSender.setContextAttributes(
3502 "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
3503 serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
3504 serviceContext.getRemoteHost(), "[$USER_AGENT$]",
3505 serviceContext.getUserAgent(), "[$USER_ID$]", user.getUserId(),
3506 "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
3507 user.getScreenName());
3508 subscriptionSender.setFrom(fromAddress, fromName);
3509 subscriptionSender.setHtmlFormat(true);
3510 subscriptionSender.setMailId("user", user.getUserId());
3511 subscriptionSender.setSubject(subject);
3512 subscriptionSender.setUserId(user.getUserId());
3513
3514 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3515
3516 subscriptionSender.flushNotificationsAsync();
3517 }
3518
3519
3528 public void setRoleUsers(long roleId, long[] userIds)
3529 throws PortalException, SystemException {
3530
3531 rolePersistence.setUsers(roleId, userIds);
3532
3533 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3534
3535 indexer.reindex(userIds);
3536
3537 PermissionCacheUtil.clearCache();
3538 }
3539
3540
3549 public void setUserGroupUsers(long userGroupId, long[] userIds)
3550 throws PortalException, SystemException {
3551
3552 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3553
3554 userGroupPersistence.setUsers(userGroupId, userIds);
3555
3556 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3557
3558 indexer.reindex(userIds);
3559
3560 PermissionCacheUtil.clearCache();
3561 }
3562
3563
3571 public void unsetGroupUsers(long groupId, long[] userIds)
3572 throws PortalException, SystemException {
3573
3574 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
3575
3576 groupPersistence.removeUsers(groupId, userIds);
3577
3578 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3579
3580 indexer.reindex(userIds);
3581
3582 PermissionCacheUtil.clearCache();
3583 }
3584
3585
3593 public void unsetOrganizationUsers(long organizationId, long[] userIds)
3594 throws PortalException, SystemException {
3595
3596 Organization organization = organizationPersistence.findByPrimaryKey(
3597 organizationId);
3598
3599 Group group = organization.getGroup();
3600
3601 long groupId = group.getGroupId();
3602
3603 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
3604
3605 organizationPersistence.removeUsers(organizationId, userIds);
3606
3607 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3608
3609 indexer.reindex(userIds);
3610
3611 PermissionCacheUtil.clearCache();
3612 }
3613
3614
3621 public void unsetPasswordPolicyUsers(
3622 long passwordPolicyId, long[] userIds)
3623 throws SystemException {
3624
3625 passwordPolicyRelLocalService.deletePasswordPolicyRels(
3626 passwordPolicyId, User.class.getName(), userIds);
3627 }
3628
3629
3637 public void unsetRoleUsers(long roleId, List<User> users)
3638 throws PortalException, SystemException {
3639
3640 Role role = rolePersistence.findByPrimaryKey(roleId);
3641
3642 if (role.getName().equals(RoleConstants.USER)) {
3643 return;
3644 }
3645
3646 rolePersistence.removeUsers(roleId, users);
3647
3648 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3649
3650 indexer.reindex(users);
3651
3652 PermissionCacheUtil.clearCache();
3653 }
3654
3655
3663 public void unsetRoleUsers(long roleId, long[] userIds)
3664 throws PortalException, SystemException {
3665
3666 Role role = rolePersistence.findByPrimaryKey(roleId);
3667
3668 if (role.getName().equals(RoleConstants.USER)) {
3669 return;
3670 }
3671
3672 rolePersistence.removeUsers(roleId, userIds);
3673
3674 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3675
3676 indexer.reindex(userIds);
3677
3678 PermissionCacheUtil.clearCache();
3679 }
3680
3681
3689 public void unsetTeamUsers(long teamId, long[] userIds)
3690 throws PortalException, SystemException {
3691
3692 teamPersistence.removeUsers(teamId, userIds);
3693
3694 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3695
3696 indexer.reindex(userIds);
3697
3698 PermissionCacheUtil.clearCache();
3699 }
3700
3701
3709 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
3710 throws PortalException, SystemException {
3711
3712 userGroupPersistence.removeUsers(userGroupId, userIds);
3713
3714 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3715
3716 indexer.reindex(userIds);
3717
3718 PermissionCacheUtil.clearCache();
3719 }
3720
3721
3732 public User updateAgreedToTermsOfUse(
3733 long userId, boolean agreedToTermsOfUse)
3734 throws PortalException, SystemException {
3735
3736 User user = userPersistence.findByPrimaryKey(userId);
3737
3738 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
3739
3740 userPersistence.update(user, false);
3741
3742 return user;
3743 }
3744
3745
3757 public void updateAsset(
3758 long userId, User user, long[] assetCategoryIds,
3759 String[] assetTagNames)
3760 throws PortalException, SystemException {
3761
3762 User owner = userPersistence.findByPrimaryKey(userId);
3763
3764 Company company = companyPersistence.findByPrimaryKey(
3765 owner.getCompanyId());
3766
3767 Group companyGroup = company.getGroup();
3768
3769 assetEntryLocalService.updateEntry(
3770 userId, companyGroup.getGroupId(), User.class.getName(),
3771 user.getUserId(), user.getUuid(), 0, assetCategoryIds,
3772 assetTagNames, false, null, null, null, null, null,
3773 user.getFullName(), null, null, null, null, 0, 0, null, false);
3774 }
3775
3776
3786 public User updateCreateDate(long userId, Date createDate)
3787 throws PortalException, SystemException {
3788
3789 User user = userPersistence.findByPrimaryKey(userId);
3790
3791 user.setCreateDate(createDate);
3792
3793 userPersistence.update(user, false);
3794
3795 return user;
3796 }
3797
3798
3810 public User updateEmailAddress(
3811 long userId, String password, String emailAddress1,
3812 String emailAddress2)
3813 throws PortalException, SystemException {
3814
3815 emailAddress1 = emailAddress1.trim().toLowerCase();
3816 emailAddress2 = emailAddress2.trim().toLowerCase();
3817
3818 if (!emailAddress1.equals(emailAddress2)) {
3819 throw new UserEmailAddressException();
3820 }
3821
3822 User user = userPersistence.findByPrimaryKey(userId);
3823
3824 validateEmailAddress(user.getCompanyId(), emailAddress1);
3825 validateEmailAddress(user.getCompanyId(), emailAddress2);
3826
3827 if (!user.getEmailAddress().equalsIgnoreCase(emailAddress1)) {
3828 if (userPersistence.fetchByC_EA(
3829 user.getCompanyId(), emailAddress1) != null) {
3830
3831 throw new DuplicateUserEmailAddressException();
3832 }
3833 }
3834
3835 setEmailAddress(
3836 user, password, user.getFirstName(), user.getMiddleName(),
3837 user.getLastName(), emailAddress1);
3838
3839 userPersistence.update(user, false);
3840
3841 return user;
3842 }
3843
3844
3854 public User updateEmailAddressVerified(
3855 long userId, boolean emailAddressVerified)
3856 throws PortalException, SystemException {
3857
3858 User user = userPersistence.findByPrimaryKey(userId);
3859
3860 user.setEmailAddressVerified(emailAddressVerified);
3861
3862 userPersistence.update(user, false);
3863
3864 return user;
3865 }
3866
3867
3877 public User updateFacebookId(long userId, long facebookId)
3878 throws PortalException, SystemException {
3879
3880 User user = userPersistence.findByPrimaryKey(userId);
3881
3882 user.setFacebookId(facebookId);
3883
3884 userPersistence.update(user, false);
3885
3886 return user;
3887 }
3888
3889
3897 public void updateGroups(
3898 long userId, long[] newGroupIds, ServiceContext serviceContext)
3899 throws PortalException, SystemException {
3900
3901 if (newGroupIds == null) {
3902 return;
3903 }
3904
3905 List<Group> oldGroups = userPersistence.getGroups(userId);
3906
3907 List<Long> oldGroupIds = new ArrayList<Long>(oldGroups.size());
3908
3909 for (Group oldGroup : oldGroups) {
3910 long oldGroupId = oldGroup.getGroupId();
3911
3912 oldGroupIds.add(oldGroupId);
3913
3914 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
3915 unsetGroupUsers(oldGroupId, new long[] {userId});
3916 }
3917 }
3918
3919 for (long newGroupId : newGroupIds) {
3920 if (!oldGroupIds.contains(newGroupId)) {
3921 addGroupUsers(newGroupId, new long[] {userId});
3922 }
3923 }
3924
3925 if (serviceContext.isIndexingEnabled()) {
3926 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3927
3928 indexer.reindex(new long[] {userId});
3929 }
3930
3931 PermissionCacheUtil.clearCache();
3932 }
3933
3934
3945 public User updateJobTitle(long userId, String jobTitle)
3946 throws PortalException, SystemException {
3947
3948 User user = userPersistence.findByPrimaryKey(userId);
3949
3950 user.setJobTitle(jobTitle);
3951
3952 userPersistence.update(user, false);
3953
3954 Contact contact = contactPersistence.findByPrimaryKey(
3955 user.getContactId());
3956
3957 contact.setJobTitle(jobTitle);
3958
3959 contactPersistence.update(contact, false);
3960
3961 return user;
3962 }
3963
3964
3974 public User updateLastLogin(long userId, String loginIP)
3975 throws PortalException, SystemException {
3976
3977 User user = userPersistence.findByPrimaryKey(userId);
3978
3979 Date lastLoginDate = user.getLoginDate();
3980
3981 if (lastLoginDate == null) {
3982 lastLoginDate = new Date();
3983 }
3984
3985 user.setLoginDate(new Date());
3986 user.setLoginIP(loginIP);
3987 user.setLastLoginDate(lastLoginDate);
3988 user.setLastLoginIP(user.getLoginIP());
3989 user.setLastFailedLoginDate(null);
3990 user.setFailedLoginAttempts(0);
3991
3992 userPersistence.update(user, false);
3993
3994 return user;
3995 }
3996
3997
4006 public User updateLockout(User user, boolean lockout)
4007 throws PortalException, SystemException {
4008
4009 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
4010
4011 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
4012 return user;
4013 }
4014
4015 Date lockoutDate = null;
4016
4017 if (lockout) {
4018 lockoutDate = new Date();
4019 }
4020
4021 user.setLockout(lockout);
4022 user.setLockoutDate(lockoutDate);
4023
4024 if (!lockout) {
4025 user.setLastFailedLoginDate(lockoutDate);
4026 user.setFailedLoginAttempts(0);
4027 }
4028
4029 userPersistence.update(user, false);
4030
4031 return user;
4032 }
4033
4034
4045 public User updateLockoutByEmailAddress(
4046 long companyId, String emailAddress, boolean lockout)
4047 throws PortalException, SystemException {
4048
4049 User user = getUserByEmailAddress(companyId, emailAddress);
4050
4051 return updateLockout(user, lockout);
4052 }
4053
4054
4064 public User updateLockoutById(long userId, boolean lockout)
4065 throws PortalException, SystemException {
4066
4067 User user = userPersistence.findByPrimaryKey(userId);
4068
4069 return updateLockout(user, lockout);
4070 }
4071
4072
4083 public User updateLockoutByScreenName(
4084 long companyId, String screenName, boolean lockout)
4085 throws PortalException, SystemException {
4086
4087 User user = getUserByScreenName(companyId, screenName);
4088
4089 return updateLockout(user, lockout);
4090 }
4091
4092
4102 public User updateModifiedDate(long userId, Date modifiedDate)
4103 throws PortalException, SystemException {
4104
4105 User user = userPersistence.findByPrimaryKey(userId);
4106
4107 user.setModifiedDate(modifiedDate);
4108
4109 userPersistence.update(user, false);
4110
4111 return user;
4112 }
4113
4114
4124 public User updateOpenId(long userId, String openId)
4125 throws PortalException, SystemException {
4126
4127 openId = openId.trim();
4128
4129 User user = userPersistence.findByPrimaryKey(userId);
4130
4131 user.setOpenId(openId);
4132
4133 userPersistence.update(user, false);
4134
4135 return user;
4136 }
4137
4138
4148 public void updateOrganizations(
4149 long userId, long[] newOrganizationIds,
4150 ServiceContext serviceContext)
4151 throws PortalException, SystemException {
4152
4153 if (newOrganizationIds == null) {
4154 return;
4155 }
4156
4157 List<Organization> oldOrganizations = userPersistence.getOrganizations(
4158 userId);
4159
4160 List<Long> oldOrganizationIds = new ArrayList<Long>(
4161 oldOrganizations.size());
4162
4163 for (Organization oldOrganization : oldOrganizations) {
4164 long oldOrganizationId = oldOrganization.getOrganizationId();
4165
4166 oldOrganizationIds.add(oldOrganizationId);
4167
4168 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
4169 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
4170 }
4171 }
4172
4173 for (long newOrganizationId : newOrganizationIds) {
4174 if (!oldOrganizationIds.contains(newOrganizationId)) {
4175 addOrganizationUsers(newOrganizationId, new long[] {userId});
4176 }
4177 }
4178
4179 if (serviceContext.isIndexingEnabled()) {
4180 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
4181
4182 indexer.reindex(new long[] {userId});
4183 }
4184
4185 PermissionCacheUtil.clearCache();
4186 }
4187
4188
4202 public User updatePassword(
4203 long userId, String password1, String password2,
4204 boolean passwordReset)
4205 throws PortalException, SystemException {
4206
4207 return updatePassword(
4208 userId, password1, password2, passwordReset, false);
4209 }
4210
4211
4228 public User updatePassword(
4229 long userId, String password1, String password2,
4230 boolean passwordReset, boolean silentUpdate)
4231 throws PortalException, SystemException {
4232
4233 User user = userPersistence.findByPrimaryKey(userId);
4234
4235 if (!silentUpdate) {
4236 validatePassword(user.getCompanyId(), userId, password1, password2);
4237 }
4238
4239 String oldEncPwd = user.getPassword();
4240
4241 if (!user.isPasswordEncrypted()) {
4242 oldEncPwd = PwdEncryptor.encrypt(user.getPassword());
4243 }
4244
4245 String newEncPwd = PwdEncryptor.encrypt(password1);
4246
4247 if (user.hasCompanyMx()) {
4248 mailService.updatePassword(user.getCompanyId(), userId, password1);
4249 }
4250
4251 user.setPassword(newEncPwd);
4252 user.setPasswordUnencrypted(password1);
4253 user.setPasswordEncrypted(true);
4254 user.setPasswordReset(passwordReset);
4255 user.setPasswordModifiedDate(new Date());
4256 user.setDigest(StringPool.BLANK);
4257 user.setGraceLoginCount(0);
4258
4259 if (!silentUpdate) {
4260 user.setPasswordModified(true);
4261 }
4262
4263 try {
4264 userPersistence.update(user, false);
4265 }
4266 catch (ModelListenerException mle) {
4267 String msg = GetterUtil.getString(mle.getCause().getMessage());
4268
4269 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
4270 String passwordHistory = PrefsPropsUtil.getString(
4271 user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
4272
4273 if (msg.indexOf(passwordHistory) != -1) {
4274 throw new UserPasswordException(
4275 UserPasswordException.PASSWORD_ALREADY_USED);
4276 }
4277 }
4278
4279 throw new UserPasswordException(
4280 UserPasswordException.PASSWORD_INVALID);
4281 }
4282
4283 if (!silentUpdate) {
4284 user.setPasswordModified(false);
4285
4286 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
4287 }
4288
4289 return user;
4290 }
4291
4292
4307 public User updatePasswordManually(
4308 long userId, String password, boolean passwordEncrypted,
4309 boolean passwordReset, Date passwordModifiedDate)
4310 throws PortalException, SystemException {
4311
4312
4313
4314 User user = userPersistence.findByPrimaryKey(userId);
4315
4316 user.setPassword(password);
4317 user.setPasswordEncrypted(passwordEncrypted);
4318 user.setPasswordReset(passwordReset);
4319 user.setPasswordModifiedDate(passwordModifiedDate);
4320 user.setDigest(StringPool.BLANK);
4321
4322 userPersistence.update(user, false);
4323
4324 return user;
4325 }
4326
4327
4339 public User updatePasswordReset(long userId, boolean passwordReset)
4340 throws PortalException, SystemException {
4341
4342 User user = userPersistence.findByPrimaryKey(userId);
4343
4344 user.setPasswordReset(passwordReset);
4345
4346 userPersistence.update(user, false);
4347
4348 return user;
4349 }
4350
4351
4361 public User updatePortrait(long userId, byte[] bytes)
4362 throws PortalException, SystemException {
4363
4364 User user = userPersistence.findByPrimaryKey(userId);
4365
4366 long imageMaxSize = PrefsPropsUtil.getLong(
4367 PropsKeys.USERS_IMAGE_MAX_SIZE);
4368
4369 if ((imageMaxSize > 0) &&
4370 ((bytes == null) || (bytes.length > imageMaxSize))) {
4371
4372 throw new UserPortraitSizeException();
4373 }
4374
4375 long portraitId = user.getPortraitId();
4376
4377 if (portraitId <= 0) {
4378 portraitId = counterLocalService.increment();
4379
4380 user.setPortraitId(portraitId);
4381 }
4382
4383 try {
4384 ImageBag imageBag = ImageProcessorUtil.read(bytes);
4385
4386 RenderedImage renderedImage = imageBag.getRenderedImage();
4387
4388 if (renderedImage == null) {
4389 throw new UserPortraitTypeException();
4390 }
4391
4392 renderedImage = ImageProcessorUtil.scale(
4393 renderedImage, PropsValues.USERS_IMAGE_MAX_HEIGHT,
4394 PropsValues.USERS_IMAGE_MAX_WIDTH);
4395
4396 String contentType = imageBag.getType();
4397
4398 imageLocalService.updateImage(
4399 portraitId,
4400 ImageProcessorUtil.getBytes(renderedImage, contentType));
4401 }
4402 catch (IOException ioe) {
4403 throw new ImageSizeException(ioe);
4404 }
4405
4406 userPersistence.update(user, false);
4407
4408 return user;
4409 }
4410
4411
4422 public User updateReminderQuery(long userId, String question, String answer)
4423 throws PortalException, SystemException {
4424
4425 validateReminderQuery(question, answer) ;
4426
4427 User user = userPersistence.findByPrimaryKey(userId);
4428
4429 user.setReminderQueryQuestion(question);
4430 user.setReminderQueryAnswer(answer);
4431
4432 userPersistence.update(user, false);
4433
4434 return user;
4435 }
4436
4437
4447 public User updateScreenName(long userId, String screenName)
4448 throws PortalException, SystemException {
4449
4450
4451
4452 User user = userPersistence.findByPrimaryKey(userId);
4453
4454 screenName = getScreenName(screenName);
4455
4456 validateScreenName(user.getCompanyId(), userId, screenName);
4457
4458 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
4459 user.setDigest(StringPool.BLANK);
4460 }
4461
4462 user.setScreenName(screenName);
4463
4464 userPersistence.update(user, false);
4465
4466
4467
4468 Group group = groupLocalService.getUserGroup(
4469 user.getCompanyId(), userId);
4470
4471 group.setFriendlyURL(StringPool.SLASH + screenName);
4472
4473 groupPersistence.update(group, false);
4474
4475 return user;
4476 }
4477
4478
4488 public User updateStatus(long userId, int status)
4489 throws PortalException, SystemException {
4490
4491 User user = userPersistence.findByPrimaryKey(userId);
4492
4493 user.setStatus(status);
4494
4495 userPersistence.update(user, false);
4496
4497 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
4498
4499 indexer.reindex(user);
4500
4501 return user;
4502 }
4503
4504
4561 public User updateUser(
4562 long userId, String oldPassword, String newPassword1,
4563 String newPassword2, boolean passwordReset,
4564 String reminderQueryQuestion, String reminderQueryAnswer,
4565 String screenName, String emailAddress, long facebookId,
4566 String openId, String languageId, String timeZoneId,
4567 String greeting, String comments, String firstName,
4568 String middleName, String lastName, int prefixId, int suffixId,
4569 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
4570 String smsSn, String aimSn, String facebookSn, String icqSn,
4571 String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
4572 String twitterSn, String ymSn, String jobTitle, long[] groupIds,
4573 long[] organizationIds, long[] roleIds,
4574 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
4575 ServiceContext serviceContext)
4576 throws PortalException, SystemException {
4577
4578
4579
4580 User user = userPersistence.findByPrimaryKey(userId);
4581 Company company = companyPersistence.findByPrimaryKey(
4582 user.getCompanyId());
4583 String password = oldPassword;
4584 screenName = getScreenName(screenName);
4585 emailAddress = emailAddress.trim().toLowerCase();
4586 openId = openId.trim();
4587 String oldFullName = user.getFullName();
4588 aimSn = aimSn.trim().toLowerCase();
4589 facebookSn = facebookSn.trim().toLowerCase();
4590 icqSn = icqSn.trim().toLowerCase();
4591 jabberSn = jabberSn.trim().toLowerCase();
4592 msnSn = msnSn.trim().toLowerCase();
4593 mySpaceSn = mySpaceSn.trim().toLowerCase();
4594 skypeSn = skypeSn.trim().toLowerCase();
4595 twitterSn = twitterSn.trim().toLowerCase();
4596 ymSn = ymSn.trim().toLowerCase();
4597 Date now = new Date();
4598
4599 EmailAddressGenerator emailAddressGenerator =
4600 EmailAddressGeneratorFactory.getInstance();
4601
4602 if (emailAddressGenerator.isGenerated(emailAddress)) {
4603 emailAddress = StringPool.BLANK;
4604 }
4605
4606 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
4607 Validator.isNull(emailAddress)) {
4608
4609 emailAddress = emailAddressGenerator.generate(
4610 user.getCompanyId(), userId);
4611 }
4612
4613 validate(
4614 userId, screenName, emailAddress, firstName, middleName, lastName,
4615 smsSn);
4616
4617 if (Validator.isNotNull(newPassword1) ||
4618 Validator.isNotNull(newPassword2)) {
4619
4620 user = updatePassword(
4621 userId, newPassword1, newPassword2, passwordReset);
4622
4623 password = newPassword1;
4624
4625 user.setDigest(StringPool.BLANK);
4626 }
4627
4628 user.setModifiedDate(now);
4629
4630 if (user.getContactId() <= 0) {
4631 user.setContactId(counterLocalService.increment());
4632 }
4633
4634 user.setPasswordReset(passwordReset);
4635
4636 if (Validator.isNotNull(reminderQueryQuestion) &&
4637 Validator.isNotNull(reminderQueryAnswer)) {
4638
4639 user.setReminderQueryQuestion(reminderQueryQuestion);
4640 user.setReminderQueryAnswer(reminderQueryAnswer);
4641 }
4642
4643 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
4644 user.setScreenName(screenName);
4645
4646 user.setDigest(StringPool.BLANK);
4647 }
4648
4649 boolean sendEmailAddressVerification = false;
4650
4651 if (!company.isStrangersVerify()) {
4652 setEmailAddress(
4653 user, password, firstName, middleName, lastName, emailAddress);
4654 }
4655 else {
4656 sendEmailAddressVerification = true;
4657 }
4658
4659 if (serviceContext != null) {
4660 String uuid = serviceContext.getUuid();
4661
4662 if (Validator.isNotNull(uuid)) {
4663 user.setUuid(uuid);
4664 }
4665 }
4666
4667 user.setFacebookId(facebookId);
4668 user.setOpenId(openId);
4669 user.setLanguageId(languageId);
4670 user.setTimeZoneId(timeZoneId);
4671 user.setGreeting(greeting);
4672 user.setComments(comments);
4673 user.setFirstName(firstName);
4674 user.setMiddleName(middleName);
4675 user.setLastName(lastName);
4676 user.setJobTitle(jobTitle);
4677
4678 userPersistence.update(user, false, serviceContext);
4679
4680
4681
4682 Date birthday = PortalUtil.getDate(
4683 birthdayMonth, birthdayDay, birthdayYear,
4684 new ContactBirthdayException());
4685
4686 long contactId = user.getContactId();
4687
4688 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
4689
4690 if (contact == null) {
4691 contact = contactPersistence.create(contactId);
4692
4693 contact.setCompanyId(user.getCompanyId());
4694 contact.setUserName(StringPool.BLANK);
4695 contact.setCreateDate(now);
4696 contact.setAccountId(company.getAccountId());
4697 contact.setParentContactId(
4698 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
4699 }
4700
4701 contact.setModifiedDate(now);
4702 contact.setFirstName(firstName);
4703 contact.setMiddleName(middleName);
4704 contact.setLastName(lastName);
4705 contact.setPrefixId(prefixId);
4706 contact.setSuffixId(suffixId);
4707 contact.setMale(male);
4708 contact.setBirthday(birthday);
4709 contact.setSmsSn(smsSn);
4710 contact.setAimSn(aimSn);
4711 contact.setFacebookSn(facebookSn);
4712 contact.setIcqSn(icqSn);
4713 contact.setJabberSn(jabberSn);
4714 contact.setMsnSn(msnSn);
4715 contact.setMySpaceSn(mySpaceSn);
4716 contact.setSkypeSn(skypeSn);
4717 contact.setTwitterSn(twitterSn);
4718 contact.setYmSn(ymSn);
4719 contact.setJobTitle(jobTitle);
4720
4721 contactPersistence.update(contact, false, serviceContext);
4722
4723
4724
4725 Group group = groupLocalService.getUserGroup(
4726 user.getCompanyId(), userId);
4727
4728 group.setFriendlyURL(StringPool.SLASH + screenName);
4729
4730 groupPersistence.update(group, false);
4731
4732
4733
4734 boolean indexingEnabled = serviceContext.isIndexingEnabled();
4735
4736 serviceContext.setIndexingEnabled(false);
4737
4738 try {
4739 updateGroups(userId, groupIds, serviceContext);
4740 updateOrganizations(userId, organizationIds, serviceContext);
4741 }
4742 finally {
4743 serviceContext.setIndexingEnabled(indexingEnabled);
4744 }
4745
4746
4747
4748 if (roleIds != null) {
4749 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
4750
4751 userPersistence.setRoles(userId, roleIds);
4752 }
4753
4754
4755
4756 updateUserGroupRoles(user, groupIds, organizationIds, userGroupRoles);
4757
4758
4759
4760 if (userGroupIds != null) {
4761 userGroupLocalService.copyUserGroupLayouts(userGroupIds, userId);
4762
4763 userPersistence.setUserGroups(userId, userGroupIds);
4764 }
4765
4766
4767
4768 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
4769
4770
4771
4772 if (serviceContext != null) {
4773 updateAsset(
4774 userId, user, serviceContext.getAssetCategoryIds(),
4775 serviceContext.getAssetTagNames());
4776 }
4777
4778
4779
4780 user.setExpandoBridgeAttributes(serviceContext);
4781
4782
4783
4784 if (GetterUtil.getBoolean(
4785 PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
4786 !oldFullName.equals(user.getFullName())) {
4787
4788 mbMessageLocalService.updateUserName(userId, user.getFullName());
4789 }
4790
4791
4792
4793 if (serviceContext.isIndexingEnabled()) {
4794 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
4795
4796 indexer.reindex(user);
4797 }
4798
4799
4800
4801 if (sendEmailAddressVerification) {
4802 sendEmailAddressVerification(user, emailAddress, serviceContext);
4803 }
4804
4805
4806
4807 PermissionCacheUtil.clearCache();
4808
4809 return user;
4810 }
4811
4812
4821 public void verifyEmailAddress(String ticketKey)
4822 throws PortalException, SystemException {
4823
4824 Ticket ticket = ticketLocalService.getTicket(ticketKey);
4825
4826 if (ticket.isExpired() ||
4827 (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
4828
4829 throw new NoSuchTicketException();
4830 }
4831
4832 User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
4833
4834 String emailAddress = ticket.getExtraInfo();
4835
4836 emailAddress = emailAddress.toLowerCase().trim();
4837
4838 if (!emailAddress.equals(user.getEmailAddress())) {
4839 if (userPersistence.fetchByC_EA(
4840 user.getCompanyId(), emailAddress) != null) {
4841
4842 throw new DuplicateUserEmailAddressException();
4843 }
4844
4845 setEmailAddress(
4846 user, StringPool.BLANK, user.getFirstName(),
4847 user.getMiddleName(), user.getLastName(), emailAddress);
4848 }
4849
4850 user.setEmailAddressVerified(true);
4851
4852 userPersistence.update(user, false);
4853
4854 ticketLocalService.deleteTicket(ticket);
4855 }
4856
4857
4903 protected int authenticate(
4904 long companyId, String login, String password, String authType,
4905 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
4906 Map<String, Object> resultsMap)
4907 throws PortalException, SystemException {
4908
4909 if (PropsValues.AUTH_LOGIN_DISABLED) {
4910 return Authenticator.FAILURE;
4911 }
4912
4913 login = login.trim().toLowerCase();
4914
4915 long userId = GetterUtil.getLong(login);
4916
4917
4918
4919 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
4920 if (Validator.isNull(login)) {
4921 throw new UserEmailAddressException();
4922 }
4923 }
4924 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
4925 if (Validator.isNull(login)) {
4926 throw new UserScreenNameException();
4927 }
4928 }
4929 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
4930 if (Validator.isNull(login)) {
4931 throw new UserIdException();
4932 }
4933 }
4934
4935 if (Validator.isNull(password)) {
4936 throw new UserPasswordException(
4937 UserPasswordException.PASSWORD_INVALID);
4938 }
4939
4940 int authResult = Authenticator.FAILURE;
4941
4942
4943
4944 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
4945 authResult = AuthPipeline.authenticateByEmailAddress(
4946 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
4947 headerMap, parameterMap);
4948 }
4949 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
4950 authResult = AuthPipeline.authenticateByScreenName(
4951 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
4952 headerMap, parameterMap);
4953 }
4954 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
4955 authResult = AuthPipeline.authenticateByUserId(
4956 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
4957 headerMap, parameterMap);
4958 }
4959
4960
4961
4962 User user = null;
4963
4964 try {
4965 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
4966 user = userPersistence.findByC_EA(companyId, login);
4967 }
4968 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
4969 user = userPersistence.findByC_SN(companyId, login);
4970 }
4971 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
4972 user = userPersistence.findByC_U(
4973 companyId, GetterUtil.getLong(login));
4974 }
4975 }
4976 catch (NoSuchUserException nsue) {
4977 return Authenticator.DNE;
4978 }
4979
4980 if (user.isDefaultUser()) {
4981 if (_log.isInfoEnabled()) {
4982 _log.info("Authentication is disabled for the default user");
4983 }
4984
4985 return Authenticator.DNE;
4986 }
4987 else if (!user.isActive()) {
4988 if (_log.isInfoEnabled()) {
4989 _log.info(
4990 "Authentication is disabled for inactive user " +
4991 user.getUserId());
4992 }
4993
4994 return Authenticator.FAILURE;
4995 }
4996
4997 if (!user.isPasswordEncrypted()) {
4998 user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
4999 user.setPasswordEncrypted(true);
5000
5001 userPersistence.update(user, false);
5002 }
5003
5004
5005
5006
5007 checkLockout(user);
5008
5009 checkPasswordExpired(user);
5010
5011
5012
5013 if (authResult == Authenticator.SUCCESS) {
5014 if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5015 boolean authenticated = PwdAuthenticator.authenticate(
5016 login, password, user.getPassword());
5017
5018 if (authenticated) {
5019 authResult = Authenticator.SUCCESS;
5020 }
5021 else {
5022 authResult = Authenticator.FAILURE;
5023 }
5024 }
5025 }
5026
5027
5028
5029 if (authResult == Authenticator.SUCCESS) {
5030 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5031 authResult = AuthPipeline.authenticateByEmailAddress(
5032 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5033 headerMap, parameterMap);
5034 }
5035 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5036 authResult = AuthPipeline.authenticateByScreenName(
5037 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5038 headerMap, parameterMap);
5039 }
5040 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5041 authResult = AuthPipeline.authenticateByUserId(
5042 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5043 headerMap, parameterMap);
5044 }
5045 }
5046
5047 if (authResult == Authenticator.SUCCESS) {
5048 if (resultsMap != null) {
5049 resultsMap.put("userId", user.getUserId());
5050 }
5051
5052
5053
5054 boolean updateDigest = true;
5055
5056 if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5057 if (Validator.isNotNull(user.getDigest())) {
5058 updateDigest = false;
5059 }
5060 }
5061
5062 if (updateDigest) {
5063 String digest = user.getDigest(password);
5064
5065 user.setDigest(digest);
5066
5067 userPersistence.update(user, false);
5068 }
5069 }
5070
5071
5072
5073 if (authResult == Authenticator.FAILURE) {
5074 try {
5075 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5076 AuthPipeline.onFailureByEmailAddress(
5077 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5078 parameterMap);
5079 }
5080 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5081 AuthPipeline.onFailureByScreenName(
5082 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5083 parameterMap);
5084 }
5085 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5086 AuthPipeline.onFailureByUserId(
5087 PropsKeys.AUTH_FAILURE, companyId, userId, headerMap,
5088 parameterMap);
5089 }
5090
5091
5092
5093 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5094 user.getCompanyId())) {
5095
5096 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5097
5098 int failedLoginAttempts = user.getFailedLoginAttempts();
5099 int maxFailures = passwordPolicy.getMaxFailure();
5100
5101 if ((failedLoginAttempts >= maxFailures) &&
5102 (maxFailures != 0)) {
5103
5104 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5105 AuthPipeline.onMaxFailuresByEmailAddress(
5106 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5107 headerMap, parameterMap);
5108 }
5109 else if (authType.equals(
5110 CompanyConstants.AUTH_TYPE_SN)) {
5111
5112 AuthPipeline.onMaxFailuresByScreenName(
5113 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5114 headerMap, parameterMap);
5115 }
5116 else if (authType.equals(
5117 CompanyConstants.AUTH_TYPE_ID)) {
5118
5119 AuthPipeline.onMaxFailuresByUserId(
5120 PropsKeys.AUTH_MAX_FAILURES, companyId, userId,
5121 headerMap, parameterMap);
5122 }
5123 }
5124 }
5125 }
5126 catch (Exception e) {
5127 _log.error(e, e);
5128 }
5129 }
5130
5131 return authResult;
5132 }
5133
5134 protected String getScreenName(String screenName) {
5135 return StringUtil.lowerCase(StringUtil.trim(screenName));
5136 }
5137
5138 protected long[] getUserIds(List<User> users) {
5139 long[] userIds = new long[users.size()];
5140
5141 for (int i = 0; i < users.size(); i++) {
5142 User user = users.get(i);
5143
5144 userIds[i] = user.getUserId();
5145 }
5146
5147 return userIds;
5148 }
5149
5150 protected void sendEmail(
5151 User user, String password, ServiceContext serviceContext)
5152 throws SystemException {
5153
5154 if (!PrefsPropsUtil.getBoolean(
5155 user.getCompanyId(),
5156 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
5157
5158 return;
5159 }
5160
5161 String fromName = PrefsPropsUtil.getString(
5162 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
5163 String fromAddress = PrefsPropsUtil.getString(
5164 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
5165
5166 String toName = user.getFullName();
5167 String toAddress = user.getEmailAddress();
5168
5169 String subject = PrefsPropsUtil.getContent(
5170 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
5171
5172 String body = null;
5173
5174 if (Validator.isNotNull(password)) {
5175 body = PrefsPropsUtil.getContent(
5176 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
5177 }
5178 else {
5179 body = PrefsPropsUtil.getContent(
5180 user.getCompanyId(),
5181 PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
5182 }
5183
5184 SubscriptionSender subscriptionSender = new SubscriptionSender();
5185
5186 subscriptionSender.setBody(body);
5187 subscriptionSender.setCompanyId(user.getCompanyId());
5188 subscriptionSender.setContextAttributes(
5189 "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
5190 "[$USER_SCREENNAME$]", user.getScreenName());
5191 subscriptionSender.setFrom(fromAddress, fromName);
5192 subscriptionSender.setHtmlFormat(true);
5193 subscriptionSender.setMailId("user", user.getUserId());
5194 subscriptionSender.setSubject(subject);
5195 subscriptionSender.setUserId(user.getUserId());
5196
5197 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
5198
5199 subscriptionSender.flushNotificationsAsync();
5200 }
5201
5202 protected Hits search(
5203 long companyId, String firstName, String middleName,
5204 String lastName, String fullName, String screenName,
5205 String emailAddress, String street, String city, String zip,
5206 String region, String country, int status,
5207 LinkedHashMap<String, Object> params, boolean andSearch, int start,
5208 int end, Sort sort)
5209 throws SystemException {
5210
5211 try {
5212 Map<String, Serializable> attributes =
5213 new HashMap<String, Serializable>();
5214
5215 attributes.put("city", city);
5216 attributes.put("country", country);
5217 attributes.put("emailAddress", emailAddress);
5218 attributes.put("firstName", firstName);
5219 attributes.put("fullName", fullName);
5220 attributes.put("lastName", lastName);
5221 attributes.put("middleName", middleName);
5222 attributes.put("params", params);
5223 attributes.put("region", region);
5224 attributes.put("screenName", screenName);
5225 attributes.put("street", street);
5226 attributes.put("status", status);
5227 attributes.put("zip", zip);
5228
5229 SearchContext searchContext = new SearchContext();
5230
5231 searchContext.setAndSearch(andSearch);
5232 searchContext.setAttributes(attributes);
5233 searchContext.setCompanyId(companyId);
5234 searchContext.setEnd(end);
5235 searchContext.setSorts(new Sort[] {sort});
5236
5237 QueryConfig queryConfig = new QueryConfig();
5238
5239 queryConfig.setHighlightEnabled(false);
5240 queryConfig.setScoreEnabled(false);
5241
5242 searchContext.setQueryConfig(queryConfig);
5243
5244 searchContext.setStart(start);
5245
5246 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
5247
5248 return indexer.search(searchContext);
5249 }
5250 catch (Exception e) {
5251 throw new SystemException(e);
5252 }
5253 }
5254
5255 protected void setEmailAddress(
5256 User user, String password, String firstName, String middleName,
5257 String lastName, String emailAddress)
5258 throws PortalException, SystemException {
5259
5260 if (emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
5261 return;
5262 }
5263
5264 long userId = user.getUserId();
5265
5266
5267
5268 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
5269 Validator.isNotNull(password)) {
5270
5271 mailService.addUser(
5272 user.getCompanyId(), userId, password, firstName, middleName,
5273 lastName, emailAddress);
5274 }
5275
5276
5277
5278 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
5279 mailService.updateEmailAddress(
5280 user.getCompanyId(), userId, emailAddress);
5281 }
5282
5283
5284
5285 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
5286 mailService.deleteEmailAddress(user.getCompanyId(), userId);
5287 }
5288
5289 user.setEmailAddress(emailAddress);
5290 user.setDigest(StringPool.BLANK);
5291 }
5292
5293 protected void updateUserGroupRoles(
5294 User user, long[] groupIds, long[] organizationIds,
5295 List<UserGroupRole> userGroupRoles)
5296 throws PortalException, SystemException {
5297
5298 if (userGroupRoles == null) {
5299 return;
5300 }
5301
5302 List<UserGroupRole> previousUserGroupRoles =
5303 userGroupRolePersistence.findByUserId(user.getUserId());
5304
5305 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
5306 if (userGroupRoles.contains(userGroupRole)) {
5307 userGroupRoles.remove(userGroupRole);
5308 }
5309 else {
5310 userGroupRoleLocalService.deleteUserGroupRole(
5311 userGroupRole);
5312 }
5313 }
5314
5315 long[] validGroupIds = null;
5316
5317 if (groupIds != null) {
5318 validGroupIds = ArrayUtil.clone(groupIds);
5319 }
5320 else {
5321 validGroupIds = user.getGroupIds();
5322 }
5323
5324 if (organizationIds == null) {
5325 organizationIds = user.getOrganizationIds();
5326 }
5327
5328 long[] organizationGroupIds = new long[organizationIds.length];
5329
5330 for (int i = 0; i < organizationIds.length; i++) {
5331 long organizationId = organizationIds[i];
5332
5333 Organization organization =
5334 organizationPersistence.findByPrimaryKey(
5335 organizationId);
5336
5337 Group organizationGroup = organization.getGroup();
5338
5339 organizationGroupIds[i] = organizationGroup.getGroupId();
5340 }
5341
5342 validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
5343
5344 Arrays.sort(validGroupIds);
5345
5346 for (UserGroupRole userGroupRole : userGroupRoles) {
5347 if (Arrays.binarySearch(
5348 validGroupIds, userGroupRole.getGroupId()) >= 0) {
5349
5350 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
5351 }
5352 }
5353 }
5354
5355 protected void validate(
5356 long companyId, long userId, boolean autoPassword, String password1,
5357 String password2, boolean autoScreenName, String screenName,
5358 String emailAddress, String firstName, String middleName,
5359 String lastName, long[] organizationIds)
5360 throws PortalException, SystemException {
5361
5362 Company company = companyPersistence.findByPrimaryKey(companyId);
5363
5364 if (company.isSystem()) {
5365 return;
5366 }
5367
5368 if ((company.getMaxUsers() > 0) &&
5369 (company.getMaxUsers() <=
5370 searchCount(
5371 companyId, null, WorkflowConstants.STATUS_APPROVED,
5372 null))) {
5373
5374 throw new CompanyMaxUsersException();
5375 }
5376
5377 if (!autoScreenName) {
5378 validateScreenName(companyId, userId, screenName);
5379 }
5380
5381 if (!autoPassword) {
5382 PasswordPolicy passwordPolicy =
5383 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
5384
5385 PwdToolkitUtil.validate(
5386 companyId, 0, password1, password2, passwordPolicy);
5387 }
5388
5389 validateEmailAddress(companyId, emailAddress);
5390
5391 if (Validator.isNotNull(emailAddress)) {
5392 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
5393
5394 if ((user != null) && (user.getUserId() != userId)) {
5395 throw new DuplicateUserEmailAddressException();
5396 }
5397 }
5398
5399 validateFullName(companyId, firstName, middleName, lastName);
5400 }
5401
5402 protected void validate(
5403 long userId, String screenName, String emailAddress,
5404 String firstName, String middleName, String lastName, String smsSn)
5405 throws PortalException, SystemException {
5406
5407 User user = userPersistence.findByPrimaryKey(userId);
5408
5409 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
5410 validateScreenName(user.getCompanyId(), userId, screenName);
5411 }
5412
5413 validateEmailAddress(user.getCompanyId(), emailAddress);
5414
5415 if (!user.isDefaultUser()) {
5416 if (Validator.isNotNull(emailAddress) &&
5417 !user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
5418
5419 if (userPersistence.fetchByC_EA(
5420 user.getCompanyId(), emailAddress) != null) {
5421
5422 throw new DuplicateUserEmailAddressException();
5423 }
5424 }
5425
5426 validateFullName(
5427 user.getCompanyId(), firstName, middleName, lastName);
5428 }
5429
5430 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
5431 throw new UserSmsException();
5432 }
5433 }
5434
5435 protected void validateEmailAddress(long companyId, String emailAddress)
5436 throws PortalException, SystemException {
5437
5438 if (Validator.isNull(emailAddress) &&
5439 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
5440
5441 return;
5442 }
5443
5444 if (!Validator.isEmailAddress(emailAddress) ||
5445 emailAddress.startsWith("root@") ||
5446 emailAddress.startsWith("postmaster@")) {
5447
5448 throw new UserEmailAddressException();
5449 }
5450
5451 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
5452 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
5453 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
5454
5455 for (String reservedEmailAddress : reservedEmailAddresses) {
5456 if (emailAddress.equalsIgnoreCase(reservedEmailAddress)) {
5457 throw new ReservedUserEmailAddressException();
5458 }
5459 }
5460 }
5461
5462 protected void validateFullName(
5463 long companyId, String firstName, String middleName,
5464 String lastName)
5465 throws PortalException, SystemException {
5466
5467 if (Validator.isNull(firstName)) {
5468 throw new ContactFirstNameException();
5469 }
5470 else if (Validator.isNull(lastName) &&
5471 PrefsPropsUtil.getBoolean(
5472 companyId, PropsKeys.USERS_LAST_NAME_REQUIRED,
5473 PropsValues.USERS_LAST_NAME_REQUIRED)) {
5474
5475 throw new ContactLastNameException();
5476 }
5477
5478 FullNameValidator fullNameValidator =
5479 FullNameValidatorFactory.getInstance();
5480
5481 if (!fullNameValidator.validate(
5482 companyId, firstName, middleName, lastName)) {
5483
5484 throw new ContactFullNameException();
5485 }
5486 }
5487
5488 protected void validatePassword(
5489 long companyId, long userId, String password1, String password2)
5490 throws PortalException, SystemException {
5491
5492 if (Validator.isNull(password1) || Validator.isNull(password2)) {
5493 throw new UserPasswordException(
5494 UserPasswordException.PASSWORD_INVALID);
5495 }
5496
5497 if (!password1.equals(password2)) {
5498 throw new UserPasswordException(
5499 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
5500 }
5501
5502 PasswordPolicy passwordPolicy =
5503 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
5504
5505 PwdToolkitUtil.validate(
5506 companyId, userId, password1, password2, passwordPolicy);
5507 }
5508
5509 protected void validateReminderQuery(String question, String answer)
5510 throws PortalException {
5511
5512 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
5513 return;
5514 }
5515
5516 if (Validator.isNull(question)) {
5517 throw new UserReminderQueryException("Question cannot be null");
5518 }
5519
5520 if (Validator.isNull(answer)) {
5521 throw new UserReminderQueryException("Answer cannot be null");
5522 }
5523 }
5524
5525 protected void validateScreenName(
5526 long companyId, long userId, String screenName)
5527 throws PortalException, SystemException {
5528
5529 if (Validator.isNull(screenName)) {
5530 throw new UserScreenNameException();
5531 }
5532
5533 ScreenNameValidator screenNameValidator =
5534 ScreenNameValidatorFactory.getInstance();
5535
5536 if (!screenNameValidator.validate(companyId, screenName)) {
5537 throw new UserScreenNameException();
5538 }
5539
5540 if (Validator.isNumber(screenName)) {
5541 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
5542 throw new UserScreenNameException();
5543 }
5544
5545 if (!screenName.equals(String.valueOf(userId))) {
5546 Group group = groupPersistence.fetchByPrimaryKey(
5547 GetterUtil.getLong(screenName));
5548
5549 if (group != null) {
5550 throw new UserScreenNameException();
5551 }
5552 }
5553 }
5554
5555 for (char c : screenName.toCharArray()) {
5556 if ((!Validator.isChar(c)) && (!Validator.isDigit(c)) &&
5557 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
5558 (c != CharPool.UNDERLINE)) {
5559
5560 throw new UserScreenNameException();
5561 }
5562 }
5563
5564 String[] anonymousNames = PrincipalBean.ANONYMOUS_NAMES;
5565
5566 for (String anonymousName : anonymousNames) {
5567 if (screenName.equalsIgnoreCase(anonymousName)) {
5568 throw new UserScreenNameException();
5569 }
5570 }
5571
5572 User user = userPersistence.fetchByC_SN(companyId, screenName);
5573
5574 if ((user != null) && (user.getUserId() != userId)) {
5575 throw new DuplicateUserScreenNameException();
5576 }
5577
5578 String friendlyURL = StringPool.SLASH + screenName;
5579
5580 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
5581
5582 if ((group != null) && (group.getClassPK() != userId)) {
5583 throw new GroupFriendlyURLException(
5584 GroupFriendlyURLException.DUPLICATE);
5585 }
5586
5587 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
5588
5589 if (exceptionType != -1) {
5590 throw new UserScreenNameException(
5591 new GroupFriendlyURLException(exceptionType));
5592 }
5593
5594 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
5595 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
5596 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
5597
5598 for (String reservedScreenName : reservedScreenNames) {
5599 if (screenName.equalsIgnoreCase(reservedScreenName)) {
5600 throw new ReservedUserScreenNameException();
5601 }
5602 }
5603 }
5604
5605 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
5606
5607 private static Map<Long, User> _defaultUsers =
5608 new ConcurrentHashMap<Long, User>();
5609
5610 }