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.DuplicateOpenIdException;
023 import com.liferay.portal.DuplicateUserEmailAddressException;
024 import com.liferay.portal.DuplicateUserScreenNameException;
025 import com.liferay.portal.GroupFriendlyURLException;
026 import com.liferay.portal.ModelListenerException;
027 import com.liferay.portal.NoSuchContactException;
028 import com.liferay.portal.NoSuchGroupException;
029 import com.liferay.portal.NoSuchOrganizationException;
030 import com.liferay.portal.NoSuchRoleException;
031 import com.liferay.portal.NoSuchTicketException;
032 import com.liferay.portal.NoSuchUserException;
033 import com.liferay.portal.NoSuchUserGroupException;
034 import com.liferay.portal.PasswordExpiredException;
035 import com.liferay.portal.RequiredUserException;
036 import com.liferay.portal.ReservedUserEmailAddressException;
037 import com.liferay.portal.ReservedUserScreenNameException;
038 import com.liferay.portal.UserEmailAddressException;
039 import com.liferay.portal.UserIdException;
040 import com.liferay.portal.UserLockoutException;
041 import com.liferay.portal.UserPasswordException;
042 import com.liferay.portal.UserPortraitSizeException;
043 import com.liferay.portal.UserPortraitTypeException;
044 import com.liferay.portal.UserReminderQueryException;
045 import com.liferay.portal.UserScreenNameException;
046 import com.liferay.portal.UserSmsException;
047 import com.liferay.portal.kernel.concurrent.PortalCallable;
048 import com.liferay.portal.kernel.exception.PortalException;
049 import com.liferay.portal.kernel.exception.SystemException;
050 import com.liferay.portal.kernel.image.ImageBag;
051 import com.liferay.portal.kernel.image.ImageToolUtil;
052 import com.liferay.portal.kernel.language.LanguageUtil;
053 import com.liferay.portal.kernel.log.Log;
054 import com.liferay.portal.kernel.log.LogFactoryUtil;
055 import com.liferay.portal.kernel.search.Hits;
056 import com.liferay.portal.kernel.search.Indexer;
057 import com.liferay.portal.kernel.search.IndexerRegistryUtil;
058 import com.liferay.portal.kernel.search.QueryConfig;
059 import com.liferay.portal.kernel.search.SearchContext;
060 import com.liferay.portal.kernel.search.Sort;
061 import com.liferay.portal.kernel.spring.aop.Skip;
062 import com.liferay.portal.kernel.transaction.Propagation;
063 import com.liferay.portal.kernel.transaction.TransactionCommitCallbackRegistryUtil;
064 import com.liferay.portal.kernel.transaction.Transactional;
065 import com.liferay.portal.kernel.util.ArrayUtil;
066 import com.liferay.portal.kernel.util.CharPool;
067 import com.liferay.portal.kernel.util.Digester;
068 import com.liferay.portal.kernel.util.DigesterUtil;
069 import com.liferay.portal.kernel.util.GetterUtil;
070 import com.liferay.portal.kernel.util.KeyValuePair;
071 import com.liferay.portal.kernel.util.OrderByComparator;
072 import com.liferay.portal.kernel.util.ParamUtil;
073 import com.liferay.portal.kernel.util.PropsKeys;
074 import com.liferay.portal.kernel.util.StringBundler;
075 import com.liferay.portal.kernel.util.StringPool;
076 import com.liferay.portal.kernel.util.StringUtil;
077 import com.liferay.portal.kernel.util.UnicodeProperties;
078 import com.liferay.portal.kernel.util.Validator;
079 import com.liferay.portal.kernel.workflow.WorkflowConstants;
080 import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil;
081 import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
082 import com.liferay.portal.model.Account;
083 import com.liferay.portal.model.Company;
084 import com.liferay.portal.model.CompanyConstants;
085 import com.liferay.portal.model.Contact;
086 import com.liferay.portal.model.ContactConstants;
087 import com.liferay.portal.model.Group;
088 import com.liferay.portal.model.GroupConstants;
089 import com.liferay.portal.model.Layout;
090 import com.liferay.portal.model.Organization;
091 import com.liferay.portal.model.PasswordPolicy;
092 import com.liferay.portal.model.ResourceConstants;
093 import com.liferay.portal.model.Role;
094 import com.liferay.portal.model.RoleConstants;
095 import com.liferay.portal.model.Team;
096 import com.liferay.portal.model.Ticket;
097 import com.liferay.portal.model.TicketConstants;
098 import com.liferay.portal.model.User;
099 import com.liferay.portal.model.UserGroup;
100 import com.liferay.portal.model.UserGroupRole;
101 import com.liferay.portal.model.impl.LayoutImpl;
102 import com.liferay.portal.security.auth.AuthPipeline;
103 import com.liferay.portal.security.auth.Authenticator;
104 import com.liferay.portal.security.auth.EmailAddressGenerator;
105 import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
106 import com.liferay.portal.security.auth.EmailAddressValidator;
107 import com.liferay.portal.security.auth.EmailAddressValidatorFactory;
108 import com.liferay.portal.security.auth.FullNameGenerator;
109 import com.liferay.portal.security.auth.FullNameGeneratorFactory;
110 import com.liferay.portal.security.auth.FullNameValidator;
111 import com.liferay.portal.security.auth.FullNameValidatorFactory;
112 import com.liferay.portal.security.auth.PrincipalException;
113 import com.liferay.portal.security.auth.ScreenNameGenerator;
114 import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
115 import com.liferay.portal.security.auth.ScreenNameValidator;
116 import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
117 import com.liferay.portal.security.ldap.LDAPSettingsUtil;
118 import com.liferay.portal.security.permission.PermissionCacheUtil;
119 import com.liferay.portal.security.pwd.PwdAuthenticator;
120 import com.liferay.portal.security.pwd.PwdEncryptor;
121 import com.liferay.portal.security.pwd.PwdToolkitUtil;
122 import com.liferay.portal.security.pwd.RegExpToolkit;
123 import com.liferay.portal.service.BaseServiceImpl;
124 import com.liferay.portal.service.ServiceContext;
125 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
126 import com.liferay.portal.util.PortalUtil;
127 import com.liferay.portal.util.PrefsPropsUtil;
128 import com.liferay.portal.util.PropsValues;
129 import com.liferay.portal.util.SubscriptionSender;
130 import com.liferay.portlet.documentlibrary.ImageSizeException;
131 import com.liferay.portlet.messageboards.model.MBMessage;
132 import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
133 import com.liferay.util.Encryptor;
134 import com.liferay.util.EncryptorException;
135
136 import java.awt.image.RenderedImage;
137
138 import java.io.IOException;
139 import java.io.Serializable;
140
141 import java.util.ArrayList;
142 import java.util.Arrays;
143 import java.util.Calendar;
144 import java.util.Date;
145 import java.util.HashMap;
146 import java.util.HashSet;
147 import java.util.LinkedHashMap;
148 import java.util.List;
149 import java.util.Locale;
150 import java.util.Map;
151 import java.util.Set;
152 import java.util.concurrent.Callable;
153 import java.util.concurrent.ConcurrentHashMap;
154
155
166 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
167
168
182 public User addDefaultAdminUser(
183 long companyId, String screenName, String emailAddress,
184 Locale locale, String firstName, String middleName, String lastName)
185 throws PortalException, SystemException {
186
187 long creatorUserId = 0;
188 boolean autoPassword = false;
189 String password1 = PropsValues.DEFAULT_ADMIN_PASSWORD;
190 String password2 = password1;
191 boolean autoScreenName = false;
192
193 screenName = getScreenName(screenName);
194
195 for (int i = 1;; i++) {
196 User screenNameUser = userPersistence.fetchByC_SN(
197 companyId, screenName);
198
199 if (screenNameUser == null) {
200 break;
201 }
202
203 screenName = screenName + i;
204 }
205
206 long facebookId = 0;
207 String openId = StringPool.BLANK;
208 int prefixId = 0;
209 int suffixId = 0;
210 boolean male = true;
211 int birthdayMonth = Calendar.JANUARY;
212 int birthdayDay = 1;
213 int birthdayYear = 1970;
214 String jobTitle = StringPool.BLANK;
215
216 Group guestGroup = groupLocalService.getGroup(
217 companyId, GroupConstants.GUEST);
218
219 long[] groupIds = {guestGroup.getGroupId()};
220
221 long[] organizationIds = null;
222
223 Role adminRole = roleLocalService.getRole(
224 companyId, RoleConstants.ADMINISTRATOR);
225
226 Role powerUserRole = roleLocalService.getRole(
227 companyId, RoleConstants.POWER_USER);
228
229 long[] roleIds = {adminRole.getRoleId(), powerUserRole.getRoleId()};
230
231 long[] userGroupIds = null;
232 boolean sendEmail = false;
233 ServiceContext serviceContext = new ServiceContext();
234
235 User defaultAdminUser = addUser(
236 creatorUserId, companyId, autoPassword, password1, password2,
237 autoScreenName, screenName, emailAddress, facebookId, openId,
238 locale, firstName, middleName, lastName, prefixId, suffixId, male,
239 birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
240 organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
241
242 updateEmailAddressVerified(defaultAdminUser.getUserId(), true);
243
244 updateLastLogin(
245 defaultAdminUser.getUserId(), defaultAdminUser.getLoginIP());
246
247 updatePasswordReset(defaultAdminUser.getUserId(), false);
248
249 return defaultAdminUser;
250 }
251
252
262 public void addDefaultGroups(long userId)
263 throws PortalException, SystemException {
264
265 User user = userPersistence.findByPrimaryKey(userId);
266
267 Set<Long> groupIdsSet = new HashSet<Long>();
268
269 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
270 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
271 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
272
273 for (String defaultGroupName : defaultGroupNames) {
274 Company company = companyPersistence.findByPrimaryKey(
275 user.getCompanyId());
276
277 Account account = company.getAccount();
278
279 if (defaultGroupName.equalsIgnoreCase(account.getName())) {
280 defaultGroupName = GroupConstants.GUEST;
281 }
282
283 try {
284 Group group = groupPersistence.findByC_N(
285 user.getCompanyId(), defaultGroupName);
286
287 if (!userPersistence.containsGroup(
288 userId, group.getGroupId())) {
289
290 groupIdsSet.add(group.getGroupId());
291 }
292 }
293 catch (NoSuchGroupException nsge) {
294 }
295 }
296
297 String[] defaultOrganizationGroupNames = PrefsPropsUtil.getStringArray(
298 user.getCompanyId(),
299 PropsKeys.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES,
300 StringPool.NEW_LINE,
301 PropsValues.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES);
302
303 for (String defaultOrganizationGroupName :
304 defaultOrganizationGroupNames) {
305
306 defaultOrganizationGroupName +=
307 GroupLocalServiceImpl.ORGANIZATION_NAME_SUFFIX;
308
309 try {
310 Group group = groupPersistence.findByC_N(
311 user.getCompanyId(), defaultOrganizationGroupName);
312
313 if (!userPersistence.containsGroup(
314 userId, group.getGroupId())) {
315
316 groupIdsSet.add(group.getGroupId());
317 }
318 }
319 catch (NoSuchGroupException nsge) {
320 }
321 }
322
323 long[] groupIds = ArrayUtil.toArray(
324 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
325
326 groupLocalService.addUserGroups(userId, groupIds);
327 }
328
329
339 public void addDefaultRoles(long userId)
340 throws PortalException, SystemException {
341
342 User user = userPersistence.findByPrimaryKey(userId);
343
344 Set<Long> roleIdSet = new HashSet<Long>();
345
346 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
347 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
348 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
349
350 for (String defaultRoleName : defaultRoleNames) {
351 try {
352 Role role = rolePersistence.findByC_N(
353 user.getCompanyId(), defaultRoleName);
354
355 if (!userPersistence.containsRole(userId, role.getRoleId())) {
356 roleIdSet.add(role.getRoleId());
357 }
358 }
359 catch (NoSuchRoleException nsre) {
360 }
361 }
362
363 long[] roleIds = ArrayUtil.toArray(
364 roleIdSet.toArray(new Long[roleIdSet.size()]));
365
366 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
367
368 userPersistence.addRoles(userId, roleIds);
369 }
370
371
381 @SuppressWarnings("deprecation")
382 public void addDefaultUserGroups(long userId)
383 throws PortalException, SystemException {
384
385 User user = userPersistence.findByPrimaryKey(userId);
386
387 Set<Long> userGroupIdSet = new HashSet<Long>();
388
389 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
390 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
391 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
392
393 for (String defaultUserGroupName : defaultUserGroupNames) {
394 try {
395 UserGroup userGroup = userGroupPersistence.findByC_N(
396 user.getCompanyId(), defaultUserGroupName);
397
398 if (!userPersistence.containsUserGroup(
399 userId, userGroup.getUserGroupId())) {
400
401 userGroupIdSet.add(userGroup.getUserGroupId());
402 }
403 }
404 catch (NoSuchUserGroupException nsuge) {
405 }
406 }
407
408 long[] userGroupIds = ArrayUtil.toArray(
409 userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
410
411 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
412 for (long userGroupId : userGroupIds) {
413 userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
414 }
415 }
416
417 userPersistence.addUserGroups(userId, userGroupIds);
418 }
419
420
429 public void addGroupUsers(long groupId, long[] userIds)
430 throws PortalException, SystemException {
431
432 groupPersistence.addUsers(groupId, userIds);
433
434 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
435
436 indexer.reindex(userIds);
437
438 PermissionCacheUtil.clearCache();
439
440 addDefaultRolesAndTeams(groupId, userIds);
441 }
442
443
452 public void addOrganizationUsers(long organizationId, long[] userIds)
453 throws PortalException, SystemException {
454
455 organizationPersistence.addUsers(organizationId, userIds);
456
457 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
458
459 indexer.reindex(userIds);
460
461 PermissionCacheUtil.clearCache();
462 }
463
464
472 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
473 throws SystemException {
474
475 passwordPolicyRelLocalService.addPasswordPolicyRels(
476 passwordPolicyId, User.class.getName(), userIds);
477 }
478
479
488 public void addRoleUsers(long roleId, long[] userIds)
489 throws PortalException, SystemException {
490
491 rolePersistence.addUsers(roleId, userIds);
492
493 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
494
495 indexer.reindex(userIds);
496
497 PermissionCacheUtil.clearCache();
498 }
499
500
509 public void addTeamUsers(long teamId, long[] userIds)
510 throws PortalException, SystemException {
511
512 teamPersistence.addUsers(teamId, userIds);
513
514 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
515
516 indexer.reindex(userIds);
517
518 PermissionCacheUtil.clearCache();
519 }
520
521
569 public User addUser(
570 long creatorUserId, long companyId, boolean autoPassword,
571 String password1, String password2, boolean autoScreenName,
572 String screenName, String emailAddress, long facebookId,
573 String openId, Locale locale, String firstName, String middleName,
574 String lastName, int prefixId, int suffixId, boolean male,
575 int birthdayMonth, int birthdayDay, int birthdayYear,
576 String jobTitle, long[] groupIds, long[] organizationIds,
577 long[] roleIds, long[] userGroupIds, boolean sendEmail,
578 ServiceContext serviceContext)
579 throws PortalException, SystemException {
580
581 boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
582
583 try {
584 WorkflowThreadLocal.setEnabled(false);
585
586 return addUserWithWorkflow(
587 creatorUserId, companyId, autoPassword, password1, password2,
588 autoScreenName, screenName, emailAddress, facebookId, openId,
589 locale, firstName, middleName, lastName, prefixId, suffixId,
590 male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
591 groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
592 serviceContext);
593 }
594 finally {
595 WorkflowThreadLocal.setEnabled(workflowEnabled);
596 }
597 }
598
599
608 @SuppressWarnings("deprecation")
609 public void addUserGroupUsers(long userGroupId, long[] userIds)
610 throws PortalException, SystemException {
611
612 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
613 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
614 }
615
616 userGroupPersistence.addUsers(userGroupId, userIds);
617
618 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
619
620 indexer.reindex(userIds);
621
622 PermissionCacheUtil.clearCache();
623 }
624
625
673 @SuppressWarnings("deprecation")
674 public User addUserWithWorkflow(
675 long creatorUserId, long companyId, boolean autoPassword,
676 String password1, String password2, boolean autoScreenName,
677 String screenName, String emailAddress, long facebookId,
678 String openId, Locale locale, String firstName, String middleName,
679 String lastName, int prefixId, int suffixId, boolean male,
680 int birthdayMonth, int birthdayDay, int birthdayYear,
681 String jobTitle, long[] groupIds, long[] organizationIds,
682 long[] roleIds, long[] userGroupIds, boolean sendEmail,
683 ServiceContext serviceContext)
684 throws PortalException, SystemException {
685
686
687
688 Company company = companyPersistence.findByPrimaryKey(companyId);
689 screenName = getScreenName(screenName);
690 openId = openId.trim();
691 Date now = new Date();
692
693 if (PrefsPropsUtil.getBoolean(
694 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
695
696 autoScreenName = true;
697 }
698
699
700
701 long userId = counterLocalService.increment();
702
703 EmailAddressGenerator emailAddressGenerator =
704 EmailAddressGeneratorFactory.getInstance();
705
706 if ((emailAddress == null) ||
707 emailAddressGenerator.isGenerated(emailAddress)) {
708
709 emailAddress = StringPool.BLANK;
710 }
711 else {
712 emailAddress = emailAddress.trim().toLowerCase();
713 }
714
715 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
716 Validator.isNull(emailAddress)) {
717
718 emailAddress = emailAddressGenerator.generate(companyId, userId);
719 }
720
721 validate(
722 companyId, userId, autoPassword, password1, password2,
723 autoScreenName, screenName, emailAddress, openId, firstName,
724 middleName, lastName, organizationIds);
725
726 if (!autoPassword) {
727 if (Validator.isNull(password1) || Validator.isNull(password2)) {
728 throw new UserPasswordException(
729 UserPasswordException.PASSWORD_INVALID);
730 }
731 }
732
733 if (autoScreenName) {
734 ScreenNameGenerator screenNameGenerator =
735 ScreenNameGeneratorFactory.getInstance();
736
737 try {
738 screenName = screenNameGenerator.generate(
739 companyId, userId, emailAddress);
740 }
741 catch (Exception e) {
742 throw new SystemException(e);
743 }
744 }
745
746 User defaultUser = getDefaultUser(companyId);
747
748 FullNameGenerator fullNameGenerator =
749 FullNameGeneratorFactory.getInstance();
750
751 String fullName = fullNameGenerator.getFullName(
752 firstName, middleName, lastName);
753
754 String greeting = LanguageUtil.format(
755 locale, "welcome-x", " " + fullName, false);
756
757 User user = userPersistence.create(userId);
758
759 if (serviceContext != null) {
760 String uuid = serviceContext.getUuid();
761
762 if (Validator.isNotNull(uuid)) {
763 user.setUuid(uuid);
764 }
765 }
766
767 user.setCompanyId(companyId);
768 user.setCreateDate(now);
769 user.setModifiedDate(now);
770 user.setDefaultUser(false);
771 user.setContactId(counterLocalService.increment());
772
773 if (Validator.isNotNull(password1)) {
774 user.setPassword(PwdEncryptor.encrypt(password1));
775 user.setPasswordUnencrypted(password1);
776 }
777
778 user.setPasswordEncrypted(true);
779
780 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
781
782 boolean passwordReset = false;
783
784 if (passwordPolicy != null) {
785 if (passwordPolicy.isChangeable() &&
786 passwordPolicy.isChangeRequired()) {
787
788 passwordReset = true;
789 }
790
791 addPasswordPolicyUsers(
792 passwordPolicy.getPasswordPolicyId(), new long[] {userId});
793 }
794
795 user.setPasswordReset(passwordReset);
796
797 user.setDigest(StringPool.BLANK);
798 user.setScreenName(screenName);
799 user.setEmailAddress(emailAddress);
800 user.setFacebookId(facebookId);
801
802 Long ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
803
804 if (ldapServerId != null) {
805 user.setLdapServerId(ldapServerId);
806 }
807 else {
808 user.setLdapServerId(-1);
809 }
810
811 user.setOpenId(openId);
812 user.setLanguageId(locale.toString());
813 user.setTimeZoneId(defaultUser.getTimeZoneId());
814 user.setGreeting(greeting);
815 user.setFirstName(firstName);
816 user.setMiddleName(middleName);
817 user.setLastName(lastName);
818 user.setJobTitle(jobTitle);
819 user.setStatus(WorkflowConstants.STATUS_DRAFT);
820 user.setExpandoBridgeAttributes(serviceContext);
821
822 userPersistence.update(user, serviceContext);
823
824
825
826 String creatorUserName = StringPool.BLANK;
827
828 if (creatorUserId <= 0) {
829 creatorUserId = user.getUserId();
830
831
832
833
834
835 }
836 else {
837 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
838
839 creatorUserName = creatorUser.getFullName();
840 }
841
842 resourceLocalService.addResources(
843 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
844 false, false, false);
845
846
847
848 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
849
850 Contact contact = contactPersistence.create(user.getContactId());
851
852 contact.setCompanyId(user.getCompanyId());
853 contact.setUserId(creatorUserId);
854 contact.setUserName(creatorUserName);
855 contact.setCreateDate(now);
856 contact.setModifiedDate(now);
857 contact.setClassName(User.class.getName());
858 contact.setClassPK(user.getUserId());
859 contact.setAccountId(company.getAccountId());
860 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
861 contact.setEmailAddress(user.getEmailAddress());
862 contact.setFirstName(firstName);
863 contact.setMiddleName(middleName);
864 contact.setLastName(lastName);
865 contact.setPrefixId(prefixId);
866 contact.setSuffixId(suffixId);
867 contact.setMale(male);
868 contact.setBirthday(birthday);
869 contact.setJobTitle(jobTitle);
870
871 contactPersistence.update(contact, serviceContext);
872
873
874
875 groupLocalService.addGroup(
876 user.getUserId(), GroupConstants.DEFAULT_PARENT_GROUP_ID,
877 User.class.getName(), user.getUserId(), null, null, 0,
878 StringPool.SLASH + screenName, false, true, null);
879
880
881
882 if (groupIds != null) {
883 groupLocalService.addUserGroups(userId, groupIds);
884 }
885
886 addDefaultGroups(userId);
887
888
889
890 updateOrganizations(userId, organizationIds, false);
891
892
893
894 if (roleIds != null) {
895 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
896
897 userPersistence.setRoles(userId, roleIds);
898 }
899
900 addDefaultRoles(userId);
901
902
903
904 if (userGroupIds != null) {
905 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
906 for (long userGroupId : userGroupIds) {
907 userGroupLocalService.copyUserGroupLayouts(
908 userGroupId, new long[] {userId});
909 }
910 }
911
912 userPersistence.setUserGroups(userId, userGroupIds);
913 }
914
915 addDefaultUserGroups(userId);
916
917
918
919 if (serviceContext != null) {
920 updateAsset(
921 creatorUserId, user, serviceContext.getAssetCategoryIds(),
922 serviceContext.getAssetTagNames());
923 }
924
925
926
927 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
928 reindex(user);
929 }
930
931
932
933 long workflowUserId = creatorUserId;
934
935 if (workflowUserId == userId) {
936 workflowUserId = defaultUser.getUserId();
937 }
938
939 ServiceContext workflowServiceContext = serviceContext;
940
941 if (workflowServiceContext == null) {
942 workflowServiceContext = new ServiceContext();
943 }
944
945 workflowServiceContext.setAttribute("autoPassword", autoPassword);
946 workflowServiceContext.setAttribute("sendEmail", sendEmail);
947
948 WorkflowHandlerRegistryUtil.startWorkflowInstance(
949 companyId, workflowUserId, User.class.getName(), userId, user,
950 workflowServiceContext);
951
952 if (serviceContext != null) {
953 String passwordUnencrypted = (String)serviceContext.getAttribute(
954 "passwordUnencrypted");
955
956 if (Validator.isNotNull(passwordUnencrypted)) {
957 user.setPasswordUnencrypted(passwordUnencrypted);
958 }
959 }
960
961 return user;
962 }
963
964
988 public int authenticateByEmailAddress(
989 long companyId, String emailAddress, String password,
990 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
991 Map<String, Object> resultsMap)
992 throws PortalException, SystemException {
993
994 return authenticate(
995 companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
996 headerMap, parameterMap, resultsMap);
997 }
998
999
1023 public int authenticateByScreenName(
1024 long companyId, String screenName, String password,
1025 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1026 Map<String, Object> resultsMap)
1027 throws PortalException, SystemException {
1028
1029 return authenticate(
1030 companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
1031 headerMap, parameterMap, resultsMap);
1032 }
1033
1034
1058 public int authenticateByUserId(
1059 long companyId, long userId, String password,
1060 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1061 Map<String, Object> resultsMap)
1062 throws PortalException, SystemException {
1063
1064 return authenticate(
1065 companyId, String.valueOf(userId), password,
1066 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap, resultsMap);
1067 }
1068
1069
1109 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1110 public long authenticateForBasic(
1111 long companyId, String authType, String login, String password)
1112 throws PortalException, SystemException {
1113
1114 if (PropsValues.AUTH_LOGIN_DISABLED) {
1115 return 0;
1116 }
1117
1118 try {
1119 User user = null;
1120
1121 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1122 user = getUserByEmailAddress(companyId, login);
1123 }
1124 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1125 user = getUserByScreenName(companyId, login);
1126 }
1127 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1128 user = getUserById(companyId, GetterUtil.getLong(login));
1129 }
1130
1131 if (user.isDefaultUser()) {
1132 if (_log.isInfoEnabled()) {
1133 _log.info(
1134 "Basic authentication is disabled for the default " +
1135 "user");
1136 }
1137
1138 return 0;
1139 }
1140 else if (!user.isActive()) {
1141 if (_log.isInfoEnabled()) {
1142 _log.info(
1143 "Basic authentication is disabled for inactive user " +
1144 user.getUserId());
1145 }
1146
1147 return 0;
1148 }
1149
1150 if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
1151 return user.getUserId();
1152 }
1153
1154 String userPassword = user.getPassword();
1155
1156 if (!user.isPasswordEncrypted()) {
1157 userPassword = PwdEncryptor.encrypt(userPassword);
1158 }
1159
1160 String encPassword = PwdEncryptor.encrypt(password);
1161
1162 if (userPassword.equals(password) ||
1163 userPassword.equals(encPassword)) {
1164
1165 return user.getUserId();
1166 }
1167 }
1168 catch (NoSuchUserException nsue) {
1169 }
1170
1171 return 0;
1172 }
1173
1174
1192 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1193 public long authenticateForDigest(
1194 long companyId, String username, String realm, String nonce,
1195 String method, String uri, String response)
1196 throws PortalException, SystemException {
1197
1198 if (PropsValues.AUTH_LOGIN_DISABLED) {
1199 return 0;
1200 }
1201
1202
1203
1204 User user = null;
1205
1206 try {
1207 user = getUserByEmailAddress(companyId, username);
1208 }
1209 catch (NoSuchUserException nsue) {
1210 try {
1211 user = getUserByScreenName(companyId, username);
1212 }
1213 catch (NoSuchUserException nsue2) {
1214 try {
1215 user = getUserById(GetterUtil.getLong(username));
1216 }
1217 catch (NoSuchUserException nsue3) {
1218 return 0;
1219 }
1220 }
1221 }
1222
1223 if (user.isDefaultUser()) {
1224 if (_log.isInfoEnabled()) {
1225 _log.info(
1226 "Digest authentication is disabled for the default user");
1227 }
1228
1229 return 0;
1230 }
1231 else if (!user.isActive()) {
1232 if (_log.isInfoEnabled()) {
1233 _log.info(
1234 "Digest authentication is disabled for inactive user " +
1235 user.getUserId());
1236 }
1237
1238 return 0;
1239 }
1240
1241
1242
1243 String digest = user.getDigest();
1244
1245 if (Validator.isNull(digest)) {
1246 _log.error(
1247 "User must first login through the portal " + user.getUserId());
1248
1249 return 0;
1250 }
1251
1252 String[] digestArray = StringUtil.split(user.getDigest());
1253
1254 for (String ha1 : digestArray) {
1255 String ha2 = DigesterUtil.digestHex(Digester.MD5, method, uri);
1256
1257 String curResponse = DigesterUtil.digestHex(
1258 Digester.MD5, ha1, nonce, ha2);
1259
1260 if (response.equals(curResponse)) {
1261 return user.getUserId();
1262 }
1263 }
1264
1265 return 0;
1266 }
1267
1268
1277 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1278 public boolean authenticateForJAAS(long userId, String encPassword) {
1279 if (PropsValues.AUTH_LOGIN_DISABLED) {
1280 return false;
1281 }
1282
1283 try {
1284 User user = userPersistence.findByPrimaryKey(userId);
1285
1286 if (user.isDefaultUser()) {
1287 if (_log.isInfoEnabled()) {
1288 _log.info(
1289 "JAAS authentication is disabled for the default user");
1290 }
1291
1292 return false;
1293 }
1294 else if (!user.isActive()) {
1295 if (_log.isInfoEnabled()) {
1296 _log.info(
1297 "JAAS authentication is disabled for inactive user " +
1298 userId);
1299 }
1300
1301 return false;
1302 }
1303
1304 String password = user.getPassword();
1305
1306 if (user.isPasswordEncrypted()) {
1307 if (password.equals(encPassword)) {
1308 return true;
1309 }
1310
1311 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1312 encPassword = PwdEncryptor.encrypt(encPassword, password);
1313
1314 if (password.equals(encPassword)) {
1315 return true;
1316 }
1317 }
1318 }
1319 else {
1320 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1321 if (password.equals(encPassword)) {
1322 return true;
1323 }
1324 }
1325
1326 password = PwdEncryptor.encrypt(password);
1327
1328 if (password.equals(encPassword)) {
1329 return true;
1330 }
1331 }
1332 }
1333 catch (Exception e) {
1334 _log.error(e);
1335 }
1336
1337 return false;
1338 }
1339
1340
1348 public void checkLockout(User user)
1349 throws PortalException, SystemException {
1350
1351 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1352 return;
1353 }
1354
1355 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1356
1357 if (passwordPolicy.isLockout()) {
1358
1359
1360
1361 Date now = new Date();
1362 int failedLoginAttempts = user.getFailedLoginAttempts();
1363
1364 if (failedLoginAttempts > 0) {
1365 long failedLoginTime = user.getLastFailedLoginDate().getTime();
1366 long elapsedTime = now.getTime() - failedLoginTime;
1367 long requiredElapsedTime =
1368 passwordPolicy.getResetFailureCount() * 1000;
1369
1370 if ((requiredElapsedTime != 0) &&
1371 (elapsedTime > requiredElapsedTime)) {
1372
1373 user.setLastFailedLoginDate(null);
1374 user.setFailedLoginAttempts(0);
1375
1376 userPersistence.update(user);
1377 }
1378 }
1379
1380
1381
1382 if (user.isLockout()) {
1383 long lockoutTime = user.getLockoutDate().getTime();
1384 long elapsedTime = now.getTime() - lockoutTime;
1385 long requiredElapsedTime =
1386 passwordPolicy.getLockoutDuration() * 1000;
1387
1388 if ((requiredElapsedTime != 0) &&
1389 (elapsedTime > requiredElapsedTime)) {
1390
1391 user.setLockout(false);
1392 user.setLockoutDate(null);
1393
1394 userPersistence.update(user);
1395 }
1396 }
1397
1398 if (user.isLockout()) {
1399 throw new UserLockoutException();
1400 }
1401 }
1402 }
1403
1404
1411 public void checkLoginFailure(User user) throws SystemException {
1412 Date now = new Date();
1413
1414 int failedLoginAttempts = user.getFailedLoginAttempts();
1415
1416 user.setLastFailedLoginDate(now);
1417 user.setFailedLoginAttempts(++failedLoginAttempts);
1418
1419 userPersistence.update(user);
1420 }
1421
1422
1432 public void checkLoginFailureByEmailAddress(
1433 long companyId, String emailAddress)
1434 throws PortalException, SystemException {
1435
1436 User user = getUserByEmailAddress(companyId, emailAddress);
1437
1438 checkLoginFailure(user);
1439 }
1440
1441
1449 public void checkLoginFailureById(long userId)
1450 throws PortalException, SystemException {
1451
1452 User user = userPersistence.findByPrimaryKey(userId);
1453
1454 checkLoginFailure(user);
1455 }
1456
1457
1466 public void checkLoginFailureByScreenName(long companyId, String screenName)
1467 throws PortalException, SystemException {
1468
1469 User user = getUserByScreenName(companyId, screenName);
1470
1471 checkLoginFailure(user);
1472 }
1473
1474
1484 public void checkPasswordExpired(User user)
1485 throws PortalException, SystemException {
1486
1487 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1488 return;
1489 }
1490
1491 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1492
1493
1494
1495 if (isPasswordExpired(user)) {
1496 int graceLoginCount = user.getGraceLoginCount();
1497
1498 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
1499 user.setGraceLoginCount(++graceLoginCount);
1500
1501 userPersistence.update(user);
1502 }
1503 else {
1504 user.setDigest(StringPool.BLANK);
1505
1506 userPersistence.update(user);
1507
1508 throw new PasswordExpiredException();
1509 }
1510 }
1511
1512
1513
1514 if (passwordPolicy.isChangeable() &&
1515 passwordPolicy.isChangeRequired()) {
1516
1517 if (user.getLastLoginDate() == null) {
1518 user.setPasswordReset(true);
1519
1520 userPersistence.update(user);
1521 }
1522 }
1523 }
1524
1525
1531 public void clearOrganizationUsers(long organizationId)
1532 throws SystemException {
1533
1534 organizationPersistence.clearUsers(organizationId);
1535
1536 PermissionCacheUtil.clearCache();
1537 }
1538
1539
1545 public void clearUserGroupUsers(long userGroupId) throws SystemException {
1546 userGroupPersistence.clearUsers(userGroupId);
1547
1548 PermissionCacheUtil.clearCache();
1549 }
1550
1551
1563 public void completeUserRegistration(
1564 User user, ServiceContext serviceContext)
1565 throws PortalException, SystemException {
1566
1567 boolean autoPassword = ParamUtil.getBoolean(
1568 serviceContext, "autoPassword");
1569
1570 String password = null;
1571
1572 if (autoPassword) {
1573 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1574 if (_log.isWarnEnabled()) {
1575 StringBundler sb = new StringBundler(4);
1576
1577 sb.append("When LDAP password policy is enabled, it is ");
1578 sb.append("possible that portal generated passwords will ");
1579 sb.append("not match the LDAP policy. Using ");
1580 sb.append("RegExpToolkit to generate new password.");
1581
1582 _log.warn(sb.toString());
1583 }
1584
1585 RegExpToolkit regExpToolkit = new RegExpToolkit();
1586
1587 password = regExpToolkit.generate(null);
1588 }
1589 else {
1590 PasswordPolicy passwordPolicy =
1591 passwordPolicyLocalService.getPasswordPolicy(
1592 user.getCompanyId(), user.getOrganizationIds());
1593
1594 password = PwdToolkitUtil.generate(passwordPolicy);
1595 }
1596
1597 user.setPassword(PwdEncryptor.encrypt(password));
1598 user.setPasswordEncrypted(true);
1599 user.setPasswordUnencrypted(password);
1600
1601 userPersistence.update(user);
1602 }
1603
1604 if (user.hasCompanyMx()) {
1605 String mailPassword = password;
1606
1607 if (Validator.isNull(mailPassword)) {
1608 mailPassword = user.getPasswordUnencrypted();
1609 }
1610
1611 mailService.addUser(
1612 user.getCompanyId(), user.getUserId(), mailPassword,
1613 user.getFirstName(), user.getMiddleName(), user.getLastName(),
1614 user.getEmailAddress());
1615 }
1616
1617 boolean sendEmail = ParamUtil.getBoolean(serviceContext, "sendEmail");
1618
1619 if (sendEmail) {
1620 sendEmail(user, password, serviceContext);
1621 }
1622
1623 Company company = companyPersistence.findByPrimaryKey(
1624 user.getCompanyId());
1625
1626 if (company.isStrangersVerify() && (serviceContext.getPlid() > 0)) {
1627 sendEmailAddressVerification(
1628 user, user.getEmailAddress(), serviceContext);
1629 }
1630 }
1631
1632
1645 public KeyValuePair decryptUserId(
1646 long companyId, String name, String password)
1647 throws PortalException, SystemException {
1648
1649 Company company = companyPersistence.findByPrimaryKey(companyId);
1650
1651 try {
1652 name = Encryptor.decrypt(company.getKeyObj(), name);
1653 }
1654 catch (EncryptorException ee) {
1655 throw new SystemException(ee);
1656 }
1657
1658 long userId = GetterUtil.getLong(name);
1659
1660 User user = userPersistence.findByPrimaryKey(userId);
1661
1662 try {
1663 password = Encryptor.decrypt(company.getKeyObj(), password);
1664 }
1665 catch (EncryptorException ee) {
1666 throw new SystemException(ee);
1667 }
1668
1669 String encPassword = PwdEncryptor.encrypt(password);
1670
1671 if (user.getPassword().equals(encPassword)) {
1672 if (isPasswordExpired(user)) {
1673 user.setPasswordReset(true);
1674
1675 userPersistence.update(user);
1676 }
1677
1678 return new KeyValuePair(name, password);
1679 }
1680 else {
1681 throw new PrincipalException();
1682 }
1683 }
1684
1685
1693 public void deletePortrait(long userId)
1694 throws PortalException, SystemException {
1695
1696 User user = userPersistence.findByPrimaryKey(userId);
1697
1698 long portraitId = user.getPortraitId();
1699
1700 if (portraitId > 0) {
1701 user.setPortraitId(0);
1702
1703 userPersistence.update(user);
1704
1705 imageLocalService.deleteImage(portraitId);
1706 }
1707 }
1708
1709
1718 public void deleteRoleUser(long roleId, long userId)
1719 throws PortalException, SystemException {
1720
1721 rolePersistence.removeUser(roleId, userId);
1722
1723 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1724
1725 indexer.reindex(userId);
1726
1727 PermissionCacheUtil.clearCache();
1728 }
1729
1730
1738 @Override
1739 public User deleteUser(long userId)
1740 throws PortalException, SystemException {
1741
1742 User user = userPersistence.findByPrimaryKey(userId);
1743
1744 return deleteUser(user);
1745 }
1746
1747
1755 @Override
1756 public User deleteUser(User user) throws PortalException, SystemException {
1757 if (!PropsValues.USERS_DELETE) {
1758 throw new RequiredUserException();
1759 }
1760
1761
1762
1763 browserTrackerLocalService.deleteUserBrowserTracker(user.getUserId());
1764
1765
1766
1767 Group group = user.getGroup();
1768
1769 if (group != null) {
1770 groupLocalService.deleteGroup(group);
1771 }
1772
1773
1774
1775 imageLocalService.deleteImage(user.getPortraitId());
1776
1777
1778
1779 passwordPolicyRelLocalService.deletePasswordPolicyRel(
1780 User.class.getName(), user.getUserId());
1781
1782
1783
1784 passwordTrackerLocalService.deletePasswordTrackers(user.getUserId());
1785
1786
1787
1788 subscriptionLocalService.deleteSubscriptions(user.getUserId());
1789
1790
1791
1792 userIdMapperLocalService.deleteUserIdMappers(user.getUserId());
1793
1794
1795
1796 announcementsDeliveryLocalService.deleteDeliveries(user.getUserId());
1797
1798
1799
1800 assetEntryLocalService.deleteEntry(
1801 User.class.getName(), user.getUserId());
1802
1803
1804
1805 blogsStatsUserLocalService.deleteStatsUserByUserId(user.getUserId());
1806
1807
1808
1809 dlFileRankLocalService.deleteFileRanksByUserId(user.getUserId());
1810
1811
1812
1813 expandoValueLocalService.deleteValues(
1814 User.class.getName(), user.getUserId());
1815
1816
1817
1818 mbBanLocalService.deleteBansByBanUserId(user.getUserId());
1819 mbStatsUserLocalService.deleteStatsUsersByUserId(user.getUserId());
1820 mbThreadFlagLocalService.deleteThreadFlagsByUserId(user.getUserId());
1821
1822
1823
1824 membershipRequestLocalService.deleteMembershipRequestsByUserId(
1825 user.getUserId());
1826
1827
1828
1829 shoppingCartLocalService.deleteUserCarts(user.getUserId());
1830
1831
1832
1833 socialActivityLocalService.deleteUserActivities(user.getUserId());
1834 socialRequestLocalService.deleteReceiverUserRequests(user.getUserId());
1835 socialRequestLocalService.deleteUserRequests(user.getUserId());
1836
1837
1838
1839 mailService.deleteUser(user.getCompanyId(), user.getUserId());
1840
1841
1842
1843 try {
1844 contactLocalService.deleteContact(user.getContactId());
1845 }
1846 catch (NoSuchContactException nsce) {
1847 }
1848
1849
1850
1851 resourceLocalService.deleteResource(
1852 user.getCompanyId(), User.class.getName(),
1853 ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
1854
1855
1856
1857 userGroupRoleLocalService.deleteUserGroupRolesByUserId(
1858 user.getUserId());
1859
1860
1861
1862 userPersistence.remove(user);
1863
1864
1865
1866 PermissionCacheUtil.clearCache();
1867
1868
1869
1870 workflowInstanceLinkLocalService.deleteWorkflowInstanceLinks(
1871 user.getCompanyId(), 0, User.class.getName(), user.getUserId());
1872
1873 return user;
1874 }
1875
1876
1884 public void deleteUserGroupUser(long userGroupId, long userId)
1885 throws PortalException, SystemException {
1886
1887 userGroupPersistence.removeUser(userGroupId, userId);
1888
1889 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1890
1891 indexer.reindex(userId);
1892
1893 PermissionCacheUtil.clearCache();
1894 }
1895
1896
1905 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1906 public String encryptUserId(String name)
1907 throws PortalException, SystemException {
1908
1909 long userId = GetterUtil.getLong(name);
1910
1911 User user = userPersistence.findByPrimaryKey(userId);
1912
1913 Company company = companyPersistence.findByPrimaryKey(
1914 user.getCompanyId());
1915
1916 try {
1917 return Encryptor.encrypt(company.getKeyObj(), name);
1918 }
1919 catch (EncryptorException ee) {
1920 throw new SystemException(ee);
1921 }
1922 }
1923
1924
1933 public User fetchUserByEmailAddress(long companyId, String emailAddress)
1934 throws SystemException {
1935
1936 return userPersistence.fetchByC_EA(companyId, emailAddress);
1937 }
1938
1939
1947 public User fetchUserById(long userId) throws SystemException {
1948 return userPersistence.fetchByPrimaryKey(userId);
1949 }
1950
1951
1960 public User fetchUserByScreenName(long companyId, String screenName)
1961 throws SystemException {
1962
1963 screenName = getScreenName(screenName);
1964
1965 return userPersistence.fetchByC_SN(companyId, screenName);
1966 }
1967
1968
1987 public List<User> getCompanyUsers(long companyId, int start, int end)
1988 throws SystemException {
1989
1990 return userPersistence.findByCompanyId(companyId, start, end);
1991 }
1992
1993
2000 public int getCompanyUsersCount(long companyId) throws SystemException {
2001 return userPersistence.countByCompanyId(companyId);
2002 }
2003
2004
2013 @Skip
2014 public User getDefaultUser(long companyId)
2015 throws PortalException, SystemException {
2016
2017 User userModel = _defaultUsers.get(companyId);
2018
2019 if (userModel == null) {
2020 userModel = userLocalService.loadGetDefaultUser(companyId);
2021
2022 _defaultUsers.put(companyId, userModel);
2023 }
2024
2025 return userModel;
2026 }
2027
2028
2037 @Skip
2038 public long getDefaultUserId(long companyId)
2039 throws PortalException, SystemException {
2040
2041 User user = getDefaultUser(companyId);
2042
2043 return user.getUserId();
2044 }
2045
2046
2053 public long[] getGroupUserIds(long groupId) throws SystemException {
2054 return getUserIds(getGroupUsers(groupId));
2055 }
2056
2057
2064 public List<User> getGroupUsers(long groupId) throws SystemException {
2065 return groupPersistence.getUsers(groupId);
2066 }
2067
2068
2075 public int getGroupUsersCount(long groupId) throws SystemException {
2076 return groupPersistence.getUsersSize(groupId);
2077 }
2078
2079
2089 public int getGroupUsersCount(long groupId, int status)
2090 throws PortalException, SystemException {
2091
2092 Group group = groupPersistence.findByPrimaryKey(groupId);
2093
2094 LinkedHashMap<String, Object> params =
2095 new LinkedHashMap<String, Object>();
2096
2097 params.put("usersGroups", new Long(groupId));
2098
2099 return searchCount(group.getCompanyId(), null, status, params);
2100 }
2101
2102
2110 public List<User> getNoAnnouncementsDeliveries(String type)
2111 throws SystemException {
2112
2113 return userFinder.findByNoAnnouncementsDeliveries(type);
2114 }
2115
2116
2122 public List<User> getNoContacts() throws SystemException {
2123 return userFinder.findByNoContacts();
2124 }
2125
2126
2133 public List<User> getNoGroups() throws SystemException {
2134 return userFinder.findByNoGroups();
2135 }
2136
2137
2144 public long[] getOrganizationUserIds(long organizationId)
2145 throws SystemException {
2146
2147 return getUserIds(getOrganizationUsers(organizationId));
2148 }
2149
2150
2157 public List<User> getOrganizationUsers(long organizationId)
2158 throws SystemException {
2159
2160 return organizationPersistence.getUsers(organizationId);
2161 }
2162
2163
2170 public int getOrganizationUsersCount(long organizationId)
2171 throws SystemException {
2172
2173 return organizationPersistence.getUsersSize(organizationId);
2174 }
2175
2176
2187 public int getOrganizationUsersCount(long organizationId, int status)
2188 throws PortalException, SystemException {
2189
2190 Organization organization = organizationPersistence.findByPrimaryKey(
2191 organizationId);
2192
2193 LinkedHashMap<String, Object> params =
2194 new LinkedHashMap<String, Object>();
2195
2196 params.put("usersOrgs", new Long(organizationId));
2197
2198 return searchCount(organization.getCompanyId(), null, status, params);
2199 }
2200
2201
2208 public long[] getRoleUserIds(long roleId) throws SystemException {
2209 return getUserIds(getRoleUsers(roleId));
2210 }
2211
2212
2219 public List<User> getRoleUsers(long roleId) throws SystemException {
2220 return rolePersistence.getUsers(roleId);
2221 }
2222
2223
2242 public List<User> getRoleUsers(long roleId, int start, int end)
2243 throws SystemException {
2244
2245 return rolePersistence.getUsers(roleId, start, end);
2246 }
2247
2248
2255 public int getRoleUsersCount(long roleId) throws SystemException {
2256 return rolePersistence.getUsersSize(roleId);
2257 }
2258
2259
2269 public int getRoleUsersCount(long roleId, int status)
2270 throws PortalException, SystemException {
2271
2272 Role role = rolePersistence.findByPrimaryKey(roleId);
2273
2274 LinkedHashMap<String, Object> params =
2275 new LinkedHashMap<String, Object>();
2276
2277 params.put("usersRoles", new Long(roleId));
2278
2279 return searchCount(role.getCompanyId(), null, status, params);
2280 }
2281
2282
2309 public List<User> getSocialUsers(
2310 long userId, int type, int start, int end, OrderByComparator obc)
2311 throws PortalException, SystemException {
2312
2313 User user = userPersistence.findByPrimaryKey(userId);
2314
2315 LinkedHashMap<String, Object> params =
2316 new LinkedHashMap<String, Object>();
2317
2318 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2319
2320 return search(
2321 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2322 params, start, end, obc);
2323 }
2324
2325
2348 public List<User> getSocialUsers(
2349 long userId, int start, int end, OrderByComparator obc)
2350 throws PortalException, SystemException {
2351
2352 User user = userPersistence.findByPrimaryKey(userId);
2353
2354 LinkedHashMap<String, Object> params =
2355 new LinkedHashMap<String, Object>();
2356
2357 params.put("socialRelation", new Long[] {userId});
2358
2359 return search(
2360 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2361 params, start, end, obc);
2362 }
2363
2364
2392 public List<User> getSocialUsers(
2393 long userId1, long userId2, int type, int start, int end,
2394 OrderByComparator obc)
2395 throws PortalException, SystemException {
2396
2397 User user1 = userPersistence.findByPrimaryKey(userId1);
2398
2399 LinkedHashMap<String, Object> params =
2400 new LinkedHashMap<String, Object>();
2401
2402 params.put(
2403 "socialMutualRelationType",
2404 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2405
2406 return search(
2407 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2408 params, start, end, obc);
2409 }
2410
2411
2436 public List<User> getSocialUsers(
2437 long userId1, long userId2, int start, int end,
2438 OrderByComparator obc)
2439 throws PortalException, SystemException {
2440
2441 User user1 = userPersistence.findByPrimaryKey(userId1);
2442
2443 LinkedHashMap<String, Object> params =
2444 new LinkedHashMap<String, Object>();
2445
2446 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2447
2448 return search(
2449 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2450 params, start, end, obc);
2451 }
2452
2453
2461 public int getSocialUsersCount(long userId)
2462 throws PortalException, SystemException {
2463
2464 User user = userPersistence.findByPrimaryKey(userId);
2465
2466 LinkedHashMap<String, Object> params =
2467 new LinkedHashMap<String, Object>();
2468
2469 params.put("socialRelation", new Long[] {userId});
2470
2471 return searchCount(
2472 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2473 params);
2474 }
2475
2476
2489 public int getSocialUsersCount(long userId, int type)
2490 throws PortalException, SystemException {
2491
2492 User user = userPersistence.findByPrimaryKey(userId);
2493
2494 LinkedHashMap<String, Object> params =
2495 new LinkedHashMap<String, Object>();
2496
2497 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2498
2499 return searchCount(
2500 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2501 params);
2502 }
2503
2504
2514 public int getSocialUsersCount(long userId1, long userId2)
2515 throws PortalException, SystemException {
2516
2517 User user1 = userPersistence.findByPrimaryKey(userId1);
2518
2519 LinkedHashMap<String, Object> params =
2520 new LinkedHashMap<String, Object>();
2521
2522 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2523
2524 return searchCount(
2525 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2526 params);
2527 }
2528
2529
2543 public int getSocialUsersCount(long userId1, long userId2, int type)
2544 throws PortalException, SystemException {
2545
2546 User user1 = userPersistence.findByPrimaryKey(userId1);
2547
2548 LinkedHashMap<String, Object> params =
2549 new LinkedHashMap<String, Object>();
2550
2551 params.put(
2552 "socialMutualRelationType",
2553 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2554
2555 return searchCount(
2556 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2557 params);
2558 }
2559
2560
2568 public User getUserByContactId(long contactId)
2569 throws PortalException, SystemException {
2570
2571 return userPersistence.findByContactId(contactId);
2572 }
2573
2574
2584 public User getUserByEmailAddress(long companyId, String emailAddress)
2585 throws PortalException, SystemException {
2586
2587 emailAddress = emailAddress.trim().toLowerCase();
2588
2589 return userPersistence.findByC_EA(companyId, emailAddress);
2590 }
2591
2592
2601 public User getUserByFacebookId(long companyId, long facebookId)
2602 throws PortalException, SystemException {
2603
2604 return userPersistence.findByC_FID(companyId, facebookId);
2605 }
2606
2607
2615 public User getUserById(long userId)
2616 throws PortalException, SystemException {
2617
2618 return userPersistence.findByPrimaryKey(userId);
2619 }
2620
2621
2631 public User getUserById(long companyId, long userId)
2632 throws PortalException, SystemException {
2633
2634 return userPersistence.findByC_U(companyId, userId);
2635 }
2636
2637
2646 public User getUserByOpenId(long companyId, String openId)
2647 throws PortalException, SystemException {
2648
2649 return userPersistence.findByC_O(companyId, openId);
2650 }
2651
2652
2660 public User getUserByPortraitId(long portraitId)
2661 throws PortalException, SystemException {
2662
2663 return userPersistence.findByPortraitId(portraitId);
2664 }
2665
2666
2675 public User getUserByScreenName(long companyId, String screenName)
2676 throws PortalException, SystemException {
2677
2678 screenName = getScreenName(screenName);
2679
2680 return userPersistence.findByC_SN(companyId, screenName);
2681 }
2682
2683
2693 public User getUserByUuid(String uuid)
2694 throws PortalException, SystemException {
2695
2696 List<User> users = userPersistence.findByUuid(uuid);
2697
2698 if (users.isEmpty()) {
2699 throw new NoSuchUserException();
2700 }
2701 else {
2702 return users.get(0);
2703 }
2704 }
2705
2706
2716 public User getUserByUuidAndCompanyId(String uuid, long companyId)
2717 throws PortalException, SystemException {
2718
2719 List<User> users = userPersistence.findByUuid_C(uuid, companyId);
2720
2721 if (users.isEmpty()) {
2722 throw new NoSuchUserException();
2723 }
2724 else {
2725 return users.get(0);
2726 }
2727 }
2728
2729
2736 public List<User> getUserGroupUsers(long userGroupId)
2737 throws SystemException {
2738
2739 return userGroupPersistence.getUsers(userGroupId);
2740 }
2741
2742
2749 public int getUserGroupUsersCount(long userGroupId) throws SystemException {
2750 return userGroupPersistence.getUsersSize(userGroupId);
2751 }
2752
2753
2763 public int getUserGroupUsersCount(long userGroupId, int status)
2764 throws PortalException, SystemException {
2765
2766 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
2767 userGroupId);
2768
2769 LinkedHashMap<String, Object> params =
2770 new LinkedHashMap<String, Object>();
2771
2772 params.put("usersUserGroups", new Long(userGroupId));
2773
2774 return searchCount(userGroup.getCompanyId(), null, status, params);
2775 }
2776
2777
2787 public long getUserIdByEmailAddress(long companyId, String emailAddress)
2788 throws PortalException, SystemException {
2789
2790 emailAddress = emailAddress.trim().toLowerCase();
2791
2792 User user = userPersistence.findByC_EA(companyId, emailAddress);
2793
2794 return user.getUserId();
2795 }
2796
2797
2806 public long getUserIdByScreenName(long companyId, String screenName)
2807 throws PortalException, SystemException {
2808
2809 screenName = getScreenName(screenName);
2810
2811 User user = userPersistence.findByC_SN(companyId, screenName);
2812
2813 return user.getUserId();
2814 }
2815
2816
2825 public boolean hasGroupUser(long groupId, long userId)
2826 throws SystemException {
2827
2828 return groupPersistence.containsUser(groupId, userId);
2829 }
2830
2831
2840 public boolean hasOrganizationUser(long organizationId, long userId)
2841 throws SystemException {
2842
2843 return organizationPersistence.containsUser(organizationId, userId);
2844 }
2845
2846
2856 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
2857 throws SystemException {
2858
2859 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
2860 passwordPolicyId, User.class.getName(), userId);
2861 }
2862
2863
2872 public boolean hasRoleUser(long roleId, long userId)
2873 throws SystemException {
2874
2875 return rolePersistence.containsUser(roleId, userId);
2876 }
2877
2878
2893 public boolean hasRoleUser(
2894 long companyId, String name, long userId, boolean inherited)
2895 throws PortalException, SystemException {
2896
2897 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
2898 }
2899
2900
2909 public boolean hasTeamUser(long teamId, long userId)
2910 throws SystemException {
2911
2912 return teamPersistence.containsUser(teamId, userId);
2913 }
2914
2915
2924 public boolean hasUserGroupUser(long userGroupId, long userId)
2925 throws SystemException {
2926
2927 return userGroupPersistence.containsUser(userGroupId, userId);
2928 }
2929
2930
2940 public boolean isPasswordExpired(User user)
2941 throws PortalException, SystemException {
2942
2943 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2944
2945 if ((passwordPolicy != null) && passwordPolicy.getExpireable()) {
2946 Date now = new Date();
2947
2948 if (user.getPasswordModifiedDate() == null) {
2949 user.setPasswordModifiedDate(now);
2950
2951 userLocalService.updateUser(user);
2952 }
2953
2954 long passwordStartTime = user.getPasswordModifiedDate().getTime();
2955 long elapsedTime = now.getTime() - passwordStartTime;
2956
2957 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
2958 return true;
2959 }
2960 else {
2961 return false;
2962 }
2963 }
2964
2965 return false;
2966 }
2967
2968
2980 public boolean isPasswordExpiringSoon(User user)
2981 throws PortalException, SystemException {
2982
2983 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2984
2985 if ((passwordPolicy != null) && passwordPolicy.isExpireable() &&
2986 (passwordPolicy.getWarningTime() > 0)) {
2987
2988 Date now = new Date();
2989
2990 if (user.getPasswordModifiedDate() == null) {
2991 user.setPasswordModifiedDate(now);
2992
2993 userLocalService.updateUser(user);
2994 }
2995
2996 long timeModified = user.getPasswordModifiedDate().getTime();
2997 long passwordExpiresOn =
2998 (passwordPolicy.getMaxAge() * 1000) + timeModified;
2999
3000 long timeStartWarning =
3001 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
3002
3003 if (now.getTime() > timeStartWarning) {
3004 return true;
3005 }
3006 else {
3007 return false;
3008 }
3009 }
3010
3011 return false;
3012 }
3013
3014
3022 public User loadGetDefaultUser(long companyId)
3023 throws PortalException, SystemException {
3024
3025 return userPersistence.findByC_DU(companyId, true);
3026 }
3027
3028
3060 public List<User> search(
3061 long companyId, String keywords, int status,
3062 LinkedHashMap<String, Object> params, int start, int end,
3063 OrderByComparator obc)
3064 throws SystemException {
3065
3066 return userFinder.findByKeywords(
3067 companyId, keywords, status, params, start, end, obc);
3068 }
3069
3070
3101 public Hits search(
3102 long companyId, String keywords, int status,
3103 LinkedHashMap<String, Object> params, int start, int end, Sort sort)
3104 throws SystemException {
3105
3106 String firstName = null;
3107 String middleName = null;
3108 String lastName = null;
3109 String fullName = null;
3110 String screenName = null;
3111 String emailAddress = null;
3112 String street = null;
3113 String city = null;
3114 String zip = null;
3115 String region = null;
3116 String country = null;
3117 boolean andOperator = false;
3118
3119 if (Validator.isNotNull(keywords)) {
3120 firstName = keywords;
3121 middleName = keywords;
3122 lastName = keywords;
3123 fullName = keywords;
3124 screenName = keywords;
3125 emailAddress = keywords;
3126 street = keywords;
3127 city = keywords;
3128 zip = keywords;
3129 region = keywords;
3130 country = keywords;
3131 }
3132 else {
3133 andOperator = true;
3134 }
3135
3136 if (params != null) {
3137 params.put("keywords", keywords);
3138 }
3139
3140 return search(
3141 companyId, firstName, middleName, lastName, fullName, screenName,
3142 emailAddress, street, city, zip, region, country, status, params,
3143 andOperator, start, end, sort);
3144 }
3145
3146
3186 public List<User> search(
3187 long companyId, String firstName, String middleName,
3188 String lastName, String screenName, String emailAddress, int status,
3189 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3190 int end, OrderByComparator obc)
3191 throws SystemException {
3192
3193 return userFinder.findByC_FN_MN_LN_SN_EA_S(
3194 companyId, firstName, middleName, lastName, screenName,
3195 emailAddress, status, params, andSearch, start, end, obc);
3196 }
3197
3198
3237 public Hits search(
3238 long companyId, String firstName, String middleName,
3239 String lastName, String screenName, String emailAddress, int status,
3240 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3241 int end, Sort sort)
3242 throws SystemException {
3243
3244 return search(
3245 companyId, firstName, middleName, lastName, null, screenName,
3246 emailAddress, null, null, null, null, null, status, params,
3247 andSearch, start, end, sort);
3248 }
3249
3250
3264 public int searchCount(
3265 long companyId, String keywords, int status,
3266 LinkedHashMap<String, Object> params)
3267 throws SystemException {
3268
3269 return userFinder.countByKeywords(companyId, keywords, status, params);
3270 }
3271
3272
3294 public int searchCount(
3295 long companyId, String firstName, String middleName,
3296 String lastName, String screenName, String emailAddress, int status,
3297 LinkedHashMap<String, Object> params, boolean andSearch)
3298 throws SystemException {
3299
3300 return userFinder.countByC_FN_MN_LN_SN_EA_S(
3301 companyId, firstName, middleName, lastName, screenName,
3302 emailAddress, status, params, andSearch);
3303 }
3304
3305
3316 public void sendEmailAddressVerification(
3317 User user, String emailAddress, ServiceContext serviceContext)
3318 throws PortalException, SystemException {
3319
3320 if (user.isEmailAddressVerified() &&
3321 emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
3322
3323 return;
3324 }
3325
3326 Ticket ticket = ticketLocalService.addTicket(
3327 user.getCompanyId(), User.class.getName(), user.getUserId(),
3328 TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3329 serviceContext);
3330
3331 String verifyEmailAddressURL =
3332 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3333 "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3334
3335 Layout layout = layoutLocalService.getLayout(serviceContext.getPlid());
3336
3337 Group group = layout.getGroup();
3338
3339 if (!layout.isPrivateLayout() && !group.isUser()) {
3340 verifyEmailAddressURL += "&p_l_id=" + serviceContext.getPlid();
3341 }
3342
3343 String fromName = PrefsPropsUtil.getString(
3344 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3345 String fromAddress = PrefsPropsUtil.getString(
3346 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3347
3348 String toName = user.getFullName();
3349 String toAddress = emailAddress;
3350
3351 String subject = PrefsPropsUtil.getContent(
3352 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3353
3354 String body = PrefsPropsUtil.getContent(
3355 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3356
3357 SubscriptionSender subscriptionSender = new SubscriptionSender();
3358
3359 subscriptionSender.setBody(body);
3360 subscriptionSender.setCompanyId(user.getCompanyId());
3361 subscriptionSender.setContextAttributes(
3362 "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3363 "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3364 "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3365 "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_ID$]",
3366 user.getUserId(), "[$USER_SCREENNAME$]", user.getScreenName());
3367 subscriptionSender.setFrom(fromAddress, fromName);
3368 subscriptionSender.setHtmlFormat(true);
3369 subscriptionSender.setMailId("user", user.getUserId());
3370 subscriptionSender.setServiceContext(serviceContext);
3371 subscriptionSender.setSubject(subject);
3372 subscriptionSender.setUserId(user.getUserId());
3373
3374 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3375
3376 subscriptionSender.flushNotificationsAsync();
3377 }
3378
3379
3398 public void sendPassword(
3399 long companyId, String emailAddress, String fromName,
3400 String fromAddress, String subject, String body,
3401 ServiceContext serviceContext)
3402 throws PortalException, SystemException {
3403
3404 Company company = companyPersistence.findByPrimaryKey(companyId);
3405
3406 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3407 return;
3408 }
3409
3410 emailAddress = emailAddress.trim().toLowerCase();
3411
3412 if (Validator.isNull(emailAddress)) {
3413 throw new UserEmailAddressException();
3414 }
3415
3416 User user = userPersistence.findByC_EA(companyId, emailAddress);
3417
3418 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3419
3420 String newPassword = StringPool.BLANK;
3421 String passwordResetURL = StringPool.BLANK;
3422
3423 if (company.isSendPasswordResetLink()) {
3424 Date expirationDate = null;
3425
3426 if ((passwordPolicy != null) &&
3427 (passwordPolicy.getResetTicketMaxAge() > 0)) {
3428 expirationDate = new Date(
3429 System.currentTimeMillis() +
3430 (passwordPolicy.getResetTicketMaxAge() * 1000));
3431 }
3432
3433 Ticket ticket = ticketLocalService.addTicket(
3434 companyId, User.class.getName(), user.getUserId(),
3435 TicketConstants.TYPE_PASSWORD, null, expirationDate,
3436 serviceContext);
3437
3438 passwordResetURL =
3439 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3440 "/portal/update_password?p_l_id="+
3441 serviceContext.getPlid() +
3442 "&ticketKey=" + ticket.getKey();
3443 }
3444 else {
3445 if (!PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
3446 PwdEncryptor.TYPE_NONE)) {
3447
3448 if (LDAPSettingsUtil.isPasswordPolicyEnabled(
3449 user.getCompanyId())) {
3450
3451 if (_log.isWarnEnabled()) {
3452 StringBundler sb = new StringBundler(5);
3453
3454 sb.append("When LDAP password policy is enabled, ");
3455 sb.append("it is possible that portal generated ");
3456 sb.append("passwords will not match the LDAP policy.");
3457 sb.append("Using RegExpToolkit to generate new ");
3458 sb.append("password.");
3459
3460 _log.warn(sb.toString());
3461 }
3462
3463 RegExpToolkit regExpToolkit = new RegExpToolkit();
3464
3465 newPassword = regExpToolkit.generate(null);
3466 }
3467 else {
3468 newPassword = PwdToolkitUtil.generate(passwordPolicy);
3469 }
3470
3471 boolean passwordReset = false;
3472
3473 if (passwordPolicy.getChangeable() &&
3474 passwordPolicy.getChangeRequired()) {
3475
3476 passwordReset = true;
3477 }
3478
3479 user.setPassword(PwdEncryptor.encrypt(newPassword));
3480 user.setPasswordUnencrypted(newPassword);
3481 user.setPasswordEncrypted(true);
3482 user.setPasswordReset(passwordReset);
3483 user.setPasswordModified(true);
3484 user.setPasswordModifiedDate(new Date());
3485
3486 userPersistence.update(user);
3487
3488 user.setPasswordModified(false);
3489 }
3490 else {
3491 newPassword = user.getPassword();
3492 }
3493 }
3494
3495 if (Validator.isNull(fromName)) {
3496 fromName = PrefsPropsUtil.getString(
3497 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3498 }
3499
3500 if (Validator.isNull(fromAddress)) {
3501 fromAddress = PrefsPropsUtil.getString(
3502 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3503 }
3504
3505 String toName = user.getFullName();
3506 String toAddress = user.getEmailAddress();
3507
3508 if (Validator.isNull(subject)) {
3509 if (company.isSendPasswordResetLink()) {
3510 subject = PrefsPropsUtil.getContent(
3511 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
3512 }
3513 else {
3514 subject = PrefsPropsUtil.getContent(
3515 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
3516 }
3517 }
3518
3519 if (Validator.isNull(body)) {
3520 if (company.isSendPasswordResetLink()) {
3521 body = PrefsPropsUtil.getContent(
3522 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
3523 }
3524 else {
3525 body = PrefsPropsUtil.getContent(
3526 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
3527 }
3528 }
3529
3530 SubscriptionSender subscriptionSender = new SubscriptionSender();
3531
3532 subscriptionSender.setBody(body);
3533 subscriptionSender.setCompanyId(companyId);
3534 subscriptionSender.setContextAttributes(
3535 "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
3536 serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
3537 serviceContext.getRemoteHost(), "[$USER_ID$]", user.getUserId(),
3538 "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
3539 user.getScreenName());
3540 subscriptionSender.setFrom(fromAddress, fromName);
3541 subscriptionSender.setHtmlFormat(true);
3542 subscriptionSender.setMailId("user", user.getUserId());
3543 subscriptionSender.setServiceContext(serviceContext);
3544 subscriptionSender.setSubject(subject);
3545 subscriptionSender.setUserId(user.getUserId());
3546
3547 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3548
3549 subscriptionSender.flushNotificationsAsync();
3550 }
3551
3552
3561 public void setRoleUsers(long roleId, long[] userIds)
3562 throws PortalException, SystemException {
3563
3564 rolePersistence.setUsers(roleId, userIds);
3565
3566 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3567
3568 indexer.reindex(userIds);
3569
3570 PermissionCacheUtil.clearCache();
3571 }
3572
3573
3582 @SuppressWarnings("deprecation")
3583 public void setUserGroupUsers(long userGroupId, long[] userIds)
3584 throws PortalException, SystemException {
3585
3586 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3587 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3588 }
3589
3590 userGroupPersistence.setUsers(userGroupId, userIds);
3591
3592 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3593
3594 indexer.reindex(userIds);
3595
3596 PermissionCacheUtil.clearCache();
3597 }
3598
3599
3607 public void unsetGroupTeamsUsers(long groupId, long[] userIds)
3608 throws PortalException, SystemException {
3609
3610 List<Team> teams = teamPersistence.findByGroupId(groupId);
3611
3612 for (Team team : teams) {
3613 unsetTeamUsers(team.getTeamId(), userIds);
3614 }
3615
3616 PermissionCacheUtil.clearCache();
3617 }
3618
3619
3628 public void unsetGroupUsers(
3629 long groupId, long[] userIds, ServiceContext serviceContext)
3630 throws PortalException, SystemException {
3631
3632 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
3633
3634 userLocalService.unsetGroupTeamsUsers(groupId, userIds);
3635
3636 groupPersistence.removeUsers(groupId, userIds);
3637
3638 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3639
3640 indexer.reindex(userIds);
3641
3642 PermissionCacheUtil.clearCache();
3643 }
3644
3645
3653 public void unsetOrganizationUsers(long organizationId, long[] userIds)
3654 throws PortalException, SystemException {
3655
3656 Organization organization = organizationPersistence.findByPrimaryKey(
3657 organizationId);
3658
3659 Group group = organization.getGroup();
3660
3661 long groupId = group.getGroupId();
3662
3663 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
3664
3665 organizationPersistence.removeUsers(organizationId, userIds);
3666
3667 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3668
3669 indexer.reindex(userIds);
3670
3671 PermissionCacheUtil.clearCache();
3672 }
3673
3674
3681 public void unsetPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
3682 throws SystemException {
3683
3684 passwordPolicyRelLocalService.deletePasswordPolicyRels(
3685 passwordPolicyId, User.class.getName(), userIds);
3686 }
3687
3688
3696 public void unsetRoleUsers(long roleId, List<User> users)
3697 throws PortalException, SystemException {
3698
3699 Role role = rolePersistence.findByPrimaryKey(roleId);
3700
3701 if (role.getName().equals(RoleConstants.USER)) {
3702 return;
3703 }
3704
3705 rolePersistence.removeUsers(roleId, users);
3706
3707 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3708
3709 indexer.reindex(users);
3710
3711 PermissionCacheUtil.clearCache();
3712 }
3713
3714
3722 public void unsetRoleUsers(long roleId, long[] userIds)
3723 throws PortalException, SystemException {
3724
3725 Role role = rolePersistence.findByPrimaryKey(roleId);
3726
3727 if (role.getName().equals(RoleConstants.USER)) {
3728 return;
3729 }
3730
3731 rolePersistence.removeUsers(roleId, userIds);
3732
3733 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3734
3735 indexer.reindex(userIds);
3736
3737 PermissionCacheUtil.clearCache();
3738 }
3739
3740
3748 public void unsetTeamUsers(long teamId, long[] userIds)
3749 throws PortalException, SystemException {
3750
3751 teamPersistence.removeUsers(teamId, userIds);
3752
3753 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3754
3755 indexer.reindex(userIds);
3756
3757 PermissionCacheUtil.clearCache();
3758 }
3759
3760
3768 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
3769 throws PortalException, SystemException {
3770
3771 userGroupPersistence.removeUsers(userGroupId, userIds);
3772
3773 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3774
3775 indexer.reindex(userIds);
3776
3777 PermissionCacheUtil.clearCache();
3778 }
3779
3780
3790 public User updateAgreedToTermsOfUse(
3791 long userId, boolean agreedToTermsOfUse)
3792 throws PortalException, SystemException {
3793
3794 User user = userPersistence.findByPrimaryKey(userId);
3795
3796 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
3797
3798 userPersistence.update(user);
3799
3800 return user;
3801 }
3802
3803
3814 public void updateAsset(
3815 long userId, User user, long[] assetCategoryIds,
3816 String[] assetTagNames)
3817 throws PortalException, SystemException {
3818
3819 User owner = userPersistence.findByPrimaryKey(userId);
3820
3821 Company company = companyPersistence.findByPrimaryKey(
3822 owner.getCompanyId());
3823
3824 Group companyGroup = company.getGroup();
3825
3826 assetEntryLocalService.updateEntry(
3827 userId, companyGroup.getGroupId(), user.getCreateDate(),
3828 user.getModifiedDate(), User.class.getName(), user.getUserId(),
3829 user.getUuid(), 0, assetCategoryIds, assetTagNames, false, null,
3830 null, null, null, user.getFullName(), null, null, null, null, 0, 0,
3831 null, false);
3832 }
3833
3834
3843 public User updateCreateDate(long userId, Date createDate)
3844 throws PortalException, SystemException {
3845
3846 User user = userPersistence.findByPrimaryKey(userId);
3847
3848 user.setCreateDate(createDate);
3849
3850 userPersistence.update(user);
3851
3852 return user;
3853 }
3854
3855
3866 public User updateEmailAddress(
3867 long userId, String password, String emailAddress1,
3868 String emailAddress2)
3869 throws PortalException, SystemException {
3870
3871 emailAddress1 = emailAddress1.trim().toLowerCase();
3872 emailAddress2 = emailAddress2.trim().toLowerCase();
3873
3874 User user = userPersistence.findByPrimaryKey(userId);
3875
3876 validateEmailAddress(user, emailAddress1, emailAddress2);
3877
3878 setEmailAddress(
3879 user, password, user.getFirstName(), user.getMiddleName(),
3880 user.getLastName(), emailAddress1);
3881
3882 userPersistence.update(user);
3883
3884 Contact contact = user.getContact();
3885
3886 contact.setEmailAddress(user.getEmailAddress());
3887
3888 contactPersistence.update(contact);
3889
3890 return user;
3891 }
3892
3893
3907 public User updateEmailAddress(
3908 long userId, String password, String emailAddress1,
3909 String emailAddress2, ServiceContext serviceContext)
3910 throws PortalException, SystemException {
3911
3912 emailAddress1 = emailAddress1.trim().toLowerCase();
3913 emailAddress2 = emailAddress2.trim().toLowerCase();
3914
3915 User user = userPersistence.findByPrimaryKey(userId);
3916
3917 validateEmailAddress(user, emailAddress1, emailAddress2);
3918
3919 Company company = companyPersistence.findByPrimaryKey(
3920 user.getCompanyId());
3921
3922 if (!company.isStrangersVerify()) {
3923 setEmailAddress(
3924 user, password, user.getFirstName(), user.getMiddleName(),
3925 user.getLastName(), emailAddress1);
3926
3927 userPersistence.update(user);
3928
3929 Contact contact = user.getContact();
3930
3931 contact.setEmailAddress(user.getEmailAddress());
3932
3933 contactPersistence.update(contact);
3934 }
3935 else {
3936 sendEmailAddressVerification(user, emailAddress1, serviceContext);
3937 }
3938
3939 return user;
3940 }
3941
3942
3951 public User updateEmailAddressVerified(
3952 long userId, boolean emailAddressVerified)
3953 throws PortalException, SystemException {
3954
3955 User user = userPersistence.findByPrimaryKey(userId);
3956
3957 user.setEmailAddressVerified(emailAddressVerified);
3958
3959 userPersistence.update(user);
3960
3961 return user;
3962 }
3963
3964
3973 public User updateFacebookId(long userId, long facebookId)
3974 throws PortalException, SystemException {
3975
3976 User user = userPersistence.findByPrimaryKey(userId);
3977
3978 user.setFacebookId(facebookId);
3979
3980 userPersistence.update(user);
3981
3982 return user;
3983 }
3984
3985
3994 public void updateGroups(
3995 long userId, long[] newGroupIds, ServiceContext serviceContext)
3996 throws PortalException, SystemException {
3997
3998 updateGroups(
3999 userId, newGroupIds, serviceContext,
4000 serviceContext.isIndexingEnabled());
4001 }
4002
4003
4042 public User updateIncompleteUser(
4043 long creatorUserId, long companyId, boolean autoPassword,
4044 String password1, String password2, boolean autoScreenName,
4045 String screenName, String emailAddress, long facebookId,
4046 String openId, Locale locale, String firstName, String middleName,
4047 String lastName, int prefixId, int suffixId, boolean male,
4048 int birthdayMonth, int birthdayDay, int birthdayYear,
4049 String jobTitle, boolean updateUserInformation, boolean sendEmail,
4050 ServiceContext serviceContext)
4051 throws PortalException, SystemException {
4052
4053 User user = getUserByEmailAddress(companyId, emailAddress);
4054
4055 if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
4056 throw new PortalException("Invalid user status");
4057 }
4058
4059 User defaultUser = getDefaultUser(companyId);
4060
4061 if (updateUserInformation) {
4062 autoScreenName = false;
4063
4064 if (PrefsPropsUtil.getBoolean(
4065 companyId,
4066 PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
4067
4068 autoScreenName = true;
4069 }
4070
4071 validate(
4072 companyId, user.getUserId(), autoPassword, password1, password2,
4073 autoScreenName, screenName, emailAddress, openId, firstName,
4074 middleName, lastName, null);
4075
4076 if (!autoPassword) {
4077 if (Validator.isNull(password1) ||
4078 Validator.isNull(password2)) {
4079 throw new UserPasswordException(
4080 UserPasswordException.PASSWORD_INVALID);
4081 }
4082 }
4083
4084 if (autoScreenName) {
4085 ScreenNameGenerator screenNameGenerator =
4086 ScreenNameGeneratorFactory.getInstance();
4087
4088 try {
4089 screenName = screenNameGenerator.generate(
4090 companyId, user.getUserId(), emailAddress);
4091 }
4092 catch (Exception e) {
4093 throw new SystemException(e);
4094 }
4095 }
4096
4097 FullNameGenerator fullNameGenerator =
4098 FullNameGeneratorFactory.getInstance();
4099
4100 String fullName = fullNameGenerator.getFullName(
4101 firstName, middleName, lastName);
4102
4103 String greeting = LanguageUtil.format(
4104 locale, "welcome-x", " " + fullName, false);
4105
4106 if (Validator.isNotNull(password1)) {
4107 user.setPassword(PwdEncryptor.encrypt(password1));
4108 user.setPasswordUnencrypted(password1);
4109 }
4110
4111 user.setPasswordEncrypted(true);
4112
4113 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
4114
4115 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
4116 passwordPolicy.isChangeRequired()) {
4117
4118 user.setPasswordReset(true);
4119 }
4120 else {
4121 user.setPasswordReset(false);
4122 }
4123
4124 user.setScreenName(screenName);
4125 user.setFacebookId(facebookId);
4126 user.setOpenId(openId);
4127 user.setLanguageId(locale.toString());
4128 user.setTimeZoneId(defaultUser.getTimeZoneId());
4129 user.setGreeting(greeting);
4130 user.setFirstName(firstName);
4131 user.setMiddleName(middleName);
4132 user.setLastName(lastName);
4133 user.setJobTitle(jobTitle);
4134 user.setExpandoBridgeAttributes(serviceContext);
4135
4136 Date birthday = getBirthday(
4137 birthdayMonth, birthdayDay, birthdayYear);
4138
4139 Contact contact = user.getContact();
4140
4141 contact.setFirstName(firstName);
4142 contact.setMiddleName(middleName);
4143 contact.setLastName(lastName);
4144 contact.setPrefixId(prefixId);
4145 contact.setSuffixId(suffixId);
4146 contact.setMale(male);
4147 contact.setBirthday(birthday);
4148 contact.setJobTitle(jobTitle);
4149
4150 contactPersistence.update(contact, serviceContext);
4151
4152
4153
4154 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4155 User.class);
4156
4157 indexer.reindex(user);
4158 }
4159
4160 user.setStatus(WorkflowConstants.STATUS_DRAFT);
4161
4162 userPersistence.update(user, serviceContext);
4163
4164
4165
4166 long workflowUserId = creatorUserId;
4167
4168 if (workflowUserId == user.getUserId()) {
4169 workflowUserId = defaultUser.getUserId();
4170 }
4171
4172 ServiceContext workflowServiceContext = serviceContext;
4173
4174 if (workflowServiceContext == null) {
4175 workflowServiceContext = new ServiceContext();
4176 }
4177
4178 workflowServiceContext.setAttribute("autoPassword", autoPassword);
4179 workflowServiceContext.setAttribute("sendEmail", sendEmail);
4180
4181 WorkflowHandlerRegistryUtil.startWorkflowInstance(
4182 companyId, workflowUserId, User.class.getName(), user.getUserId(),
4183 user, workflowServiceContext);
4184
4185 return getUserByEmailAddress(companyId, emailAddress);
4186 }
4187
4188
4198 public User updateJobTitle(long userId, String jobTitle)
4199 throws PortalException, SystemException {
4200
4201 User user = userPersistence.findByPrimaryKey(userId);
4202
4203 user.setJobTitle(jobTitle);
4204
4205 userPersistence.update(user);
4206
4207 Contact contact = contactPersistence.findByPrimaryKey(
4208 user.getContactId());
4209
4210 contact.setJobTitle(jobTitle);
4211
4212 contactPersistence.update(contact);
4213
4214 return user;
4215 }
4216
4217
4226 public User updateLastLogin(long userId, String loginIP)
4227 throws PortalException, SystemException {
4228
4229 User user = userPersistence.findByPrimaryKey(userId);
4230
4231 Date lastLoginDate = user.getLoginDate();
4232
4233 if (lastLoginDate == null) {
4234 lastLoginDate = new Date();
4235 }
4236
4237 user.setLoginDate(new Date());
4238 user.setLoginIP(loginIP);
4239 user.setLastLoginDate(lastLoginDate);
4240 user.setLastLoginIP(user.getLoginIP());
4241 user.setLastFailedLoginDate(null);
4242 user.setFailedLoginAttempts(0);
4243
4244 userPersistence.update(user);
4245
4246 return user;
4247 }
4248
4249
4258 public User updateLockout(User user, boolean lockout)
4259 throws PortalException, SystemException {
4260
4261 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
4262
4263 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
4264 return user;
4265 }
4266
4267 Date lockoutDate = null;
4268
4269 if (lockout) {
4270 lockoutDate = new Date();
4271 }
4272
4273 user.setLockout(lockout);
4274 user.setLockoutDate(lockoutDate);
4275
4276 if (!lockout) {
4277 user.setLastFailedLoginDate(lockoutDate);
4278 user.setFailedLoginAttempts(0);
4279 }
4280
4281 userPersistence.update(user);
4282
4283 return user;
4284 }
4285
4286
4297 public User updateLockoutByEmailAddress(
4298 long companyId, String emailAddress, boolean lockout)
4299 throws PortalException, SystemException {
4300
4301 User user = getUserByEmailAddress(companyId, emailAddress);
4302
4303 return updateLockout(user, lockout);
4304 }
4305
4306
4315 public User updateLockoutById(long userId, boolean lockout)
4316 throws PortalException, SystemException {
4317
4318 User user = userPersistence.findByPrimaryKey(userId);
4319
4320 return updateLockout(user, lockout);
4321 }
4322
4323
4333 public User updateLockoutByScreenName(
4334 long companyId, String screenName, boolean lockout)
4335 throws PortalException, SystemException {
4336
4337 User user = getUserByScreenName(companyId, screenName);
4338
4339 return updateLockout(user, lockout);
4340 }
4341
4342
4351 public User updateModifiedDate(long userId, Date modifiedDate)
4352 throws PortalException, SystemException {
4353
4354 User user = userPersistence.findByPrimaryKey(userId);
4355
4356 user.setModifiedDate(modifiedDate);
4357
4358 userPersistence.update(user);
4359
4360 return user;
4361 }
4362
4363
4372 public User updateOpenId(long userId, String openId)
4373 throws PortalException, SystemException {
4374
4375 openId = openId.trim();
4376
4377 User user = userPersistence.findByPrimaryKey(userId);
4378
4379 user.setOpenId(openId);
4380
4381 userPersistence.update(user);
4382
4383 return user;
4384 }
4385
4386
4397 public void updateOrganizations(
4398 long userId, long[] newOrganizationIds,
4399 ServiceContext serviceContext)
4400 throws PortalException, SystemException {
4401
4402 updateOrganizations(
4403 userId, newOrganizationIds, serviceContext.isIndexingEnabled());
4404 }
4405
4406
4418 public User updatePassword(
4419 long userId, String password1, String password2,
4420 boolean passwordReset)
4421 throws PortalException, SystemException {
4422
4423 return updatePassword(
4424 userId, password1, password2, passwordReset, false);
4425 }
4426
4427
4442 public User updatePassword(
4443 long userId, String password1, String password2,
4444 boolean passwordReset, boolean silentUpdate)
4445 throws PortalException, SystemException {
4446
4447 User user = userPersistence.findByPrimaryKey(userId);
4448
4449 if (!silentUpdate) {
4450 validatePassword(user.getCompanyId(), userId, password1, password2);
4451 }
4452
4453 String oldEncPwd = user.getPassword();
4454
4455 if (!user.isPasswordEncrypted()) {
4456 oldEncPwd = PwdEncryptor.encrypt(user.getPassword());
4457 }
4458
4459 String newEncPwd = PwdEncryptor.encrypt(password1);
4460
4461 if (user.hasCompanyMx()) {
4462 mailService.updatePassword(user.getCompanyId(), userId, password1);
4463 }
4464
4465 user.setPassword(newEncPwd);
4466 user.setPasswordUnencrypted(password1);
4467 user.setPasswordEncrypted(true);
4468 user.setPasswordReset(passwordReset);
4469 user.setPasswordModifiedDate(new Date());
4470 user.setDigest(StringPool.BLANK);
4471 user.setGraceLoginCount(0);
4472
4473 if (!silentUpdate) {
4474 user.setPasswordModified(true);
4475 }
4476
4477 try {
4478 userPersistence.update(user);
4479 }
4480 catch (ModelListenerException mle) {
4481 String msg = GetterUtil.getString(mle.getCause().getMessage());
4482
4483 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
4484 String passwordHistory = PrefsPropsUtil.getString(
4485 user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
4486
4487 if (msg.contains(passwordHistory)) {
4488 throw new UserPasswordException(
4489 UserPasswordException.PASSWORD_ALREADY_USED);
4490 }
4491 }
4492
4493 throw new UserPasswordException(
4494 UserPasswordException.PASSWORD_INVALID);
4495 }
4496
4497 if (!silentUpdate) {
4498 user.setPasswordModified(false);
4499
4500 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
4501 }
4502
4503 return user;
4504 }
4505
4506
4520 public User updatePasswordManually(
4521 long userId, String password, boolean passwordEncrypted,
4522 boolean passwordReset, Date passwordModifiedDate)
4523 throws PortalException, SystemException {
4524
4525
4526
4527 User user = userPersistence.findByPrimaryKey(userId);
4528
4529 user.setPassword(password);
4530 user.setPasswordEncrypted(passwordEncrypted);
4531 user.setPasswordReset(passwordReset);
4532 user.setPasswordModifiedDate(passwordModifiedDate);
4533 user.setDigest(StringPool.BLANK);
4534
4535 userPersistence.update(user);
4536
4537 return user;
4538 }
4539
4540
4551 public User updatePasswordReset(long userId, boolean passwordReset)
4552 throws PortalException, SystemException {
4553
4554 User user = userPersistence.findByPrimaryKey(userId);
4555
4556 user.setPasswordReset(passwordReset);
4557
4558 userPersistence.update(user);
4559
4560 return user;
4561 }
4562
4563
4573 public User updatePortrait(long userId, byte[] bytes)
4574 throws PortalException, SystemException {
4575
4576 User user = userPersistence.findByPrimaryKey(userId);
4577
4578 long imageMaxSize = PrefsPropsUtil.getLong(
4579 PropsKeys.USERS_IMAGE_MAX_SIZE);
4580
4581 if ((imageMaxSize > 0) &&
4582 ((bytes == null) || (bytes.length > imageMaxSize))) {
4583
4584 throw new UserPortraitSizeException();
4585 }
4586
4587 long portraitId = user.getPortraitId();
4588
4589 if (portraitId <= 0) {
4590 portraitId = counterLocalService.increment();
4591
4592 user.setPortraitId(portraitId);
4593 }
4594
4595 try {
4596 ImageBag imageBag = ImageToolUtil.read(bytes);
4597
4598 RenderedImage renderedImage = imageBag.getRenderedImage();
4599
4600 if (renderedImage == null) {
4601 throw new UserPortraitTypeException();
4602 }
4603
4604 renderedImage = ImageToolUtil.scale(
4605 renderedImage, PropsValues.USERS_IMAGE_MAX_HEIGHT,
4606 PropsValues.USERS_IMAGE_MAX_WIDTH);
4607
4608 String contentType = imageBag.getType();
4609
4610 imageLocalService.updateImage(
4611 portraitId,
4612 ImageToolUtil.getBytes(renderedImage, contentType));
4613 }
4614 catch (IOException ioe) {
4615 throw new ImageSizeException(ioe);
4616 }
4617
4618 userPersistence.update(user);
4619
4620 return user;
4621 }
4622
4623
4634 public User updateReminderQuery(long userId, String question, String answer)
4635 throws PortalException, SystemException {
4636
4637 validateReminderQuery(question, answer);
4638
4639 User user = userPersistence.findByPrimaryKey(userId);
4640
4641 user.setReminderQueryQuestion(question);
4642 user.setReminderQueryAnswer(answer);
4643
4644 userPersistence.update(user);
4645
4646 return user;
4647 }
4648
4649
4659 public User updateScreenName(long userId, String screenName)
4660 throws PortalException, SystemException {
4661
4662
4663
4664 User user = userPersistence.findByPrimaryKey(userId);
4665
4666 screenName = getScreenName(screenName);
4667
4668 validateScreenName(user.getCompanyId(), userId, screenName);
4669
4670 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
4671 user.setDigest(StringPool.BLANK);
4672 }
4673
4674 user.setScreenName(screenName);
4675
4676 userPersistence.update(user);
4677
4678
4679
4680 Group group = groupLocalService.getUserGroup(
4681 user.getCompanyId(), userId);
4682
4683 group.setFriendlyURL(StringPool.SLASH + screenName);
4684
4685 groupPersistence.update(group);
4686
4687 return user;
4688 }
4689
4690
4699 public User updateStatus(long userId, int status)
4700 throws PortalException, SystemException {
4701
4702 User user = userPersistence.findByPrimaryKey(userId);
4703
4704 user.setStatus(status);
4705
4706 userPersistence.update(user);
4707
4708 reindex(user);
4709
4710 return user;
4711 }
4712
4713
4769 @SuppressWarnings("deprecation")
4770 public User updateUser(
4771 long userId, String oldPassword, String newPassword1,
4772 String newPassword2, boolean passwordReset,
4773 String reminderQueryQuestion, String reminderQueryAnswer,
4774 String screenName, String emailAddress, long facebookId,
4775 String openId, String languageId, String timeZoneId,
4776 String greeting, String comments, String firstName,
4777 String middleName, String lastName, int prefixId, int suffixId,
4778 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
4779 String smsSn, String aimSn, String facebookSn, String icqSn,
4780 String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
4781 String twitterSn, String ymSn, String jobTitle, long[] groupIds,
4782 long[] organizationIds, long[] roleIds,
4783 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
4784 ServiceContext serviceContext)
4785 throws PortalException, SystemException {
4786
4787
4788
4789 User user = userPersistence.findByPrimaryKey(userId);
4790 Company company = companyPersistence.findByPrimaryKey(
4791 user.getCompanyId());
4792 String password = oldPassword;
4793 screenName = getScreenName(screenName);
4794 emailAddress = emailAddress.trim().toLowerCase();
4795 openId = openId.trim();
4796 String oldFullName = user.getFullName();
4797 aimSn = aimSn.trim().toLowerCase();
4798 facebookSn = facebookSn.trim().toLowerCase();
4799 icqSn = icqSn.trim().toLowerCase();
4800 jabberSn = jabberSn.trim().toLowerCase();
4801 msnSn = msnSn.trim().toLowerCase();
4802 mySpaceSn = mySpaceSn.trim().toLowerCase();
4803 skypeSn = skypeSn.trim().toLowerCase();
4804 twitterSn = twitterSn.trim().toLowerCase();
4805 ymSn = ymSn.trim().toLowerCase();
4806 Date now = new Date();
4807
4808 EmailAddressGenerator emailAddressGenerator =
4809 EmailAddressGeneratorFactory.getInstance();
4810
4811 if (emailAddressGenerator.isGenerated(emailAddress)) {
4812 emailAddress = StringPool.BLANK;
4813 }
4814
4815 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
4816 Validator.isNull(emailAddress)) {
4817
4818 emailAddress = emailAddressGenerator.generate(
4819 user.getCompanyId(), userId);
4820 }
4821
4822 validate(
4823 userId, screenName, emailAddress, openId, firstName, middleName,
4824 lastName, smsSn);
4825
4826 if (Validator.isNotNull(newPassword1) ||
4827 Validator.isNotNull(newPassword2)) {
4828
4829 user = updatePassword(
4830 userId, newPassword1, newPassword2, passwordReset);
4831
4832 password = newPassword1;
4833
4834 user.setDigest(StringPool.BLANK);
4835 }
4836
4837 user.setModifiedDate(now);
4838
4839 if (user.getContactId() <= 0) {
4840 user.setContactId(counterLocalService.increment());
4841 }
4842
4843 user.setPasswordReset(passwordReset);
4844
4845 if (Validator.isNotNull(reminderQueryQuestion) &&
4846 Validator.isNotNull(reminderQueryAnswer)) {
4847
4848 user.setReminderQueryQuestion(reminderQueryQuestion);
4849 user.setReminderQueryAnswer(reminderQueryAnswer);
4850 }
4851
4852 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
4853 user.setScreenName(screenName);
4854
4855 user.setDigest(StringPool.BLANK);
4856 }
4857
4858 boolean sendEmailAddressVerification = false;
4859
4860 if (!company.isStrangersVerify()) {
4861 setEmailAddress(
4862 user, password, firstName, middleName, lastName, emailAddress);
4863 }
4864 else {
4865 sendEmailAddressVerification = true;
4866 }
4867
4868 if (serviceContext != null) {
4869 String uuid = serviceContext.getUuid();
4870
4871 if (Validator.isNotNull(uuid)) {
4872 user.setUuid(uuid);
4873 }
4874 }
4875
4876 user.setFacebookId(facebookId);
4877
4878 Long ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
4879
4880 if (ldapServerId != null) {
4881 user.setLdapServerId(ldapServerId);
4882 }
4883
4884 user.setOpenId(openId);
4885 user.setLanguageId(languageId);
4886 user.setTimeZoneId(timeZoneId);
4887 user.setGreeting(greeting);
4888 user.setComments(comments);
4889 user.setFirstName(firstName);
4890 user.setMiddleName(middleName);
4891 user.setLastName(lastName);
4892 user.setJobTitle(jobTitle);
4893 user.setExpandoBridgeAttributes(serviceContext);
4894
4895 userPersistence.update(user, serviceContext);
4896
4897
4898
4899 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
4900
4901 long contactId = user.getContactId();
4902
4903 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
4904
4905 if (contact == null) {
4906 contact = contactPersistence.create(contactId);
4907
4908 contact.setCompanyId(user.getCompanyId());
4909 contact.setUserName(StringPool.BLANK);
4910 contact.setCreateDate(now);
4911 contact.setClassName(User.class.getName());
4912 contact.setClassPK(user.getUserId());
4913 contact.setAccountId(company.getAccountId());
4914 contact.setParentContactId(
4915 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
4916 }
4917
4918 contact.setModifiedDate(now);
4919 contact.setEmailAddress(user.getEmailAddress());
4920 contact.setFirstName(firstName);
4921 contact.setMiddleName(middleName);
4922 contact.setLastName(lastName);
4923 contact.setPrefixId(prefixId);
4924 contact.setSuffixId(suffixId);
4925 contact.setMale(male);
4926 contact.setBirthday(birthday);
4927 contact.setSmsSn(smsSn);
4928 contact.setAimSn(aimSn);
4929 contact.setFacebookSn(facebookSn);
4930 contact.setIcqSn(icqSn);
4931 contact.setJabberSn(jabberSn);
4932 contact.setMsnSn(msnSn);
4933 contact.setMySpaceSn(mySpaceSn);
4934 contact.setSkypeSn(skypeSn);
4935 contact.setTwitterSn(twitterSn);
4936 contact.setYmSn(ymSn);
4937 contact.setJobTitle(jobTitle);
4938
4939 contactPersistence.update(contact, serviceContext);
4940
4941
4942
4943 Group group = groupLocalService.getUserGroup(
4944 user.getCompanyId(), userId);
4945
4946 group.setFriendlyURL(StringPool.SLASH + screenName);
4947
4948 groupPersistence.update(group);
4949
4950
4951
4952 updateGroups(userId, groupIds, serviceContext, false);
4953 updateOrganizations(userId, organizationIds, false);
4954
4955
4956
4957 if (roleIds != null) {
4958 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
4959
4960 userPersistence.setRoles(userId, roleIds);
4961 }
4962
4963
4964
4965 updateUserGroupRoles(user, groupIds, organizationIds, userGroupRoles);
4966
4967
4968
4969 if (userGroupIds != null) {
4970 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
4971 userGroupLocalService.copyUserGroupLayouts(
4972 userGroupIds, userId);
4973 }
4974
4975 userPersistence.setUserGroups(userId, userGroupIds);
4976 }
4977
4978
4979
4980 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
4981
4982
4983
4984 if (serviceContext != null) {
4985 updateAsset(
4986 userId, user, serviceContext.getAssetCategoryIds(),
4987 serviceContext.getAssetTagNames());
4988 }
4989
4990
4991
4992 if (GetterUtil.getBoolean(
4993 PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
4994 !oldFullName.equals(user.getFullName())) {
4995
4996 mbMessageLocalService.updateUserName(userId, user.getFullName());
4997 }
4998
4999
5000
5001 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
5002 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5003 User.class);
5004
5005 indexer.reindex(user);
5006 }
5007
5008
5009
5010 if ((serviceContext != null) && sendEmailAddressVerification) {
5011 sendEmailAddressVerification(user, emailAddress, serviceContext);
5012 }
5013
5014
5015
5016 PermissionCacheUtil.clearCache();
5017
5018 return user;
5019 }
5020
5021
5030 public void verifyEmailAddress(String ticketKey)
5031 throws PortalException, SystemException {
5032
5033 Ticket ticket = ticketLocalService.getTicket(ticketKey);
5034
5035 if (ticket.isExpired() ||
5036 (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
5037
5038 throw new NoSuchTicketException();
5039 }
5040
5041 User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
5042
5043 String emailAddress = ticket.getExtraInfo();
5044
5045 emailAddress = emailAddress.toLowerCase().trim();
5046
5047 if (!emailAddress.equals(user.getEmailAddress())) {
5048 if (userPersistence.fetchByC_EA(
5049 user.getCompanyId(), emailAddress) != null) {
5050
5051 throw new DuplicateUserEmailAddressException();
5052 }
5053
5054 setEmailAddress(
5055 user, StringPool.BLANK, user.getFirstName(),
5056 user.getMiddleName(), user.getLastName(), emailAddress);
5057
5058 Contact contact = user.getContact();
5059
5060 contact.setEmailAddress(user.getEmailAddress());
5061
5062 contactPersistence.update(contact);
5063 }
5064
5065 user.setEmailAddressVerified(true);
5066
5067 userPersistence.update(user);
5068
5069 ticketLocalService.deleteTicket(ticket);
5070 }
5071
5072 protected void addDefaultRolesAndTeams(long groupId, long[] userIds)
5073 throws PortalException, SystemException {
5074
5075 List<Role> defaultSiteRoles = new ArrayList<Role>();
5076
5077 Group group = groupLocalService.getGroup(groupId);
5078
5079 UnicodeProperties typeSettingsProperties =
5080 group.getTypeSettingsProperties();
5081
5082 long[] defaultSiteRoleIds = StringUtil.split(
5083 typeSettingsProperties.getProperty("defaultSiteRoleIds"), 0L);
5084
5085 for (long defaultSiteRoleId : defaultSiteRoleIds) {
5086 Role defaultSiteRole = rolePersistence.fetchByPrimaryKey(
5087 defaultSiteRoleId);
5088
5089 if (defaultSiteRole == null) {
5090 if (_log.isWarnEnabled()) {
5091 _log.warn("Unable to find role " + defaultSiteRoleId);
5092 }
5093
5094 continue;
5095 }
5096
5097 defaultSiteRoles.add(defaultSiteRole);
5098 }
5099
5100 List<Team> defaultTeams = new ArrayList<Team>();
5101
5102 long[] defaultTeamIds = StringUtil.split(
5103 typeSettingsProperties.getProperty("defaultTeamIds"), 0L);
5104
5105 for (long defaultTeamId : defaultTeamIds) {
5106 Team defaultTeam = teamPersistence.findByPrimaryKey(defaultTeamId);
5107
5108 if (defaultTeam == null) {
5109 if (_log.isWarnEnabled()) {
5110 _log.warn("Unable to find team " + defaultTeamId);
5111 }
5112
5113 continue;
5114 }
5115
5116 defaultTeams.add(defaultTeam);
5117 }
5118
5119 for (long userId : userIds) {
5120 Set<Long> userRoleIdsSet = new HashSet<Long>();
5121
5122 for (Role role : defaultSiteRoles) {
5123 if (!userPersistence.containsRole(userId, role.getRoleId())) {
5124 userRoleIdsSet.add(role.getRoleId());
5125 }
5126 }
5127
5128 long[] userRoleIds = ArrayUtil.toArray(
5129 userRoleIdsSet.toArray(new Long[userRoleIdsSet.size()]));
5130
5131 userGroupRoleLocalService.addUserGroupRoles(
5132 userId, groupId, userRoleIds);
5133
5134 Set<Long> userTeamIdsSet = new HashSet<Long>();
5135
5136 for (Team team : defaultTeams) {
5137 if (!userPersistence.containsTeam(userId, team.getTeamId())) {
5138 userTeamIdsSet.add(team.getTeamId());
5139 }
5140 }
5141
5142 long[] userTeamIds = ArrayUtil.toArray(
5143 userTeamIdsSet.toArray(new Long[userTeamIdsSet.size()]));
5144
5145 userPersistence.addTeams(userId, userTeamIds);
5146 }
5147 }
5148
5149
5195 protected int authenticate(
5196 long companyId, String login, String password, String authType,
5197 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
5198 Map<String, Object> resultsMap)
5199 throws PortalException, SystemException {
5200
5201 if (PropsValues.AUTH_LOGIN_DISABLED) {
5202 return Authenticator.FAILURE;
5203 }
5204
5205 login = login.trim().toLowerCase();
5206
5207 long userId = GetterUtil.getLong(login);
5208
5209
5210
5211 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5212 if (Validator.isNull(login)) {
5213 throw new UserEmailAddressException();
5214 }
5215 }
5216 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5217 if (Validator.isNull(login)) {
5218 throw new UserScreenNameException();
5219 }
5220 }
5221 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5222 if (Validator.isNull(login)) {
5223 throw new UserIdException();
5224 }
5225 }
5226
5227 if (Validator.isNull(password)) {
5228 throw new UserPasswordException(
5229 UserPasswordException.PASSWORD_INVALID);
5230 }
5231
5232 int authResult = Authenticator.FAILURE;
5233
5234
5235
5236 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5237 authResult = AuthPipeline.authenticateByEmailAddress(
5238 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5239 headerMap, parameterMap);
5240 }
5241 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5242 authResult = AuthPipeline.authenticateByScreenName(
5243 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5244 headerMap, parameterMap);
5245 }
5246 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5247 authResult = AuthPipeline.authenticateByUserId(
5248 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
5249 headerMap, parameterMap);
5250 }
5251
5252
5253
5254 User user = null;
5255
5256 try {
5257 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5258 user = userPersistence.findByC_EA(companyId, login);
5259 }
5260 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5261 user = userPersistence.findByC_SN(companyId, login);
5262 }
5263 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5264 user = userPersistence.findByC_U(
5265 companyId, GetterUtil.getLong(login));
5266 }
5267 }
5268 catch (NoSuchUserException nsue) {
5269 return Authenticator.DNE;
5270 }
5271
5272 if (user.isDefaultUser()) {
5273 if (_log.isInfoEnabled()) {
5274 _log.info("Authentication is disabled for the default user");
5275 }
5276
5277 return Authenticator.DNE;
5278 }
5279 else if (!user.isActive()) {
5280 if (_log.isInfoEnabled()) {
5281 _log.info(
5282 "Authentication is disabled for inactive user " +
5283 user.getUserId());
5284 }
5285
5286 return Authenticator.FAILURE;
5287 }
5288
5289 if (!user.isPasswordEncrypted()) {
5290 user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
5291 user.setPasswordEncrypted(true);
5292
5293 userPersistence.update(user);
5294 }
5295
5296
5297
5298
5299 checkLockout(user);
5300
5301 checkPasswordExpired(user);
5302
5303
5304
5305 if ((authResult == Authenticator.SUCCESS) &&
5306 PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5307
5308 boolean authenticated = PwdAuthenticator.authenticate(
5309 login, password, user.getPassword());
5310
5311 if (authenticated) {
5312 authResult = Authenticator.SUCCESS;
5313 }
5314 else {
5315 authResult = Authenticator.FAILURE;
5316 }
5317 }
5318
5319
5320
5321 if (authResult == Authenticator.SUCCESS) {
5322 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5323 authResult = AuthPipeline.authenticateByEmailAddress(
5324 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5325 headerMap, parameterMap);
5326 }
5327 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5328 authResult = AuthPipeline.authenticateByScreenName(
5329 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5330 headerMap, parameterMap);
5331 }
5332 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5333 authResult = AuthPipeline.authenticateByUserId(
5334 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5335 headerMap, parameterMap);
5336 }
5337 }
5338
5339 if (authResult == Authenticator.SUCCESS) {
5340 if (resultsMap != null) {
5341 resultsMap.put("userId", user.getUserId());
5342 }
5343
5344
5345
5346 boolean updateDigest = true;
5347
5348 if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5349 if (Validator.isNotNull(user.getDigest())) {
5350 updateDigest = false;
5351 }
5352 }
5353
5354 if (updateDigest) {
5355 String digest = user.getDigest(password);
5356
5357 user.setDigest(digest);
5358
5359 userPersistence.update(user);
5360 }
5361 }
5362
5363
5364
5365 if (authResult == Authenticator.FAILURE) {
5366 try {
5367 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5368 AuthPipeline.onFailureByEmailAddress(
5369 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5370 parameterMap);
5371 }
5372 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5373 AuthPipeline.onFailureByScreenName(
5374 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5375 parameterMap);
5376 }
5377 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5378 AuthPipeline.onFailureByUserId(
5379 PropsKeys.AUTH_FAILURE, companyId, userId, headerMap,
5380 parameterMap);
5381 }
5382
5383 try {
5384 user = userPersistence.findByPrimaryKey(user.getUserId());
5385 }
5386 catch (NoSuchUserException nsue) {
5387 return Authenticator.DNE;
5388 }
5389
5390
5391
5392 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5393 user.getCompanyId())) {
5394
5395 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5396
5397 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5398
5399 int failedLoginAttempts = user.getFailedLoginAttempts();
5400 int maxFailures = passwordPolicy.getMaxFailure();
5401
5402 if ((failedLoginAttempts >= maxFailures) &&
5403 (maxFailures != 0)) {
5404
5405 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5406 AuthPipeline.onMaxFailuresByEmailAddress(
5407 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5408 headerMap, parameterMap);
5409 }
5410 else if (authType.equals(
5411 CompanyConstants.AUTH_TYPE_SN)) {
5412
5413 AuthPipeline.onMaxFailuresByScreenName(
5414 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5415 headerMap, parameterMap);
5416 }
5417 else if (authType.equals(
5418 CompanyConstants.AUTH_TYPE_ID)) {
5419
5420 AuthPipeline.onMaxFailuresByUserId(
5421 PropsKeys.AUTH_MAX_FAILURES, companyId, userId,
5422 headerMap, parameterMap);
5423 }
5424 }
5425 }
5426 }
5427 catch (Exception e) {
5428 _log.error(e, e);
5429 }
5430 }
5431
5432
5433
5434 return authResult;
5435 }
5436
5437 protected Date getBirthday(
5438 int birthdayMonth, int birthdayDay, int birthdayYear)
5439 throws PortalException {
5440
5441 Date birthday = PortalUtil.getDate(
5442 birthdayMonth, birthdayDay, birthdayYear,
5443 ContactBirthdayException.class);
5444
5445 Date now = new Date();
5446
5447 if (birthday.after(now)) {
5448 throw new ContactBirthdayException();
5449 }
5450
5451 return birthday;
5452 }
5453
5454 protected String getScreenName(String screenName) {
5455 return StringUtil.lowerCase(StringUtil.trim(screenName));
5456 }
5457
5458 protected long[] getUserIds(List<User> users) {
5459 long[] userIds = new long[users.size()];
5460
5461 for (int i = 0; i < users.size(); i++) {
5462 User user = users.get(i);
5463
5464 userIds[i] = user.getUserId();
5465 }
5466
5467 return userIds;
5468 }
5469
5470 protected void reindex(final User user) {
5471 final Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5472 User.class);
5473
5474 Callable<Void> callable = new PortalCallable<Void>(
5475 user.getCompanyId()) {
5476
5477 @Override
5478 protected Void doCall() throws Exception {
5479 indexer.reindex(user);
5480
5481 return null;
5482 }
5483
5484 };
5485
5486 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
5487 }
5488
5489 protected Hits search(
5490 long companyId, String firstName, String middleName,
5491 String lastName, String fullName, String screenName,
5492 String emailAddress, String street, String city, String zip,
5493 String region, String country, int status,
5494 LinkedHashMap<String, Object> params, boolean andSearch, int start,
5495 int end, Sort sort)
5496 throws SystemException {
5497
5498 try {
5499 SearchContext searchContext = new SearchContext();
5500
5501 searchContext.setAndSearch(andSearch);
5502
5503 Map<String, Serializable> attributes =
5504 new HashMap<String, Serializable>();
5505
5506 attributes.put("city", city);
5507 attributes.put("country", country);
5508 attributes.put("emailAddress", emailAddress);
5509 attributes.put("firstName", firstName);
5510 attributes.put("fullName", fullName);
5511 attributes.put("lastName", lastName);
5512 attributes.put("middleName", middleName);
5513 attributes.put("params", params);
5514 attributes.put("region", region);
5515 attributes.put("screenName", screenName);
5516 attributes.put("street", street);
5517 attributes.put("status", status);
5518 attributes.put("zip", zip);
5519
5520 searchContext.setAttributes(attributes);
5521
5522 searchContext.setCompanyId(companyId);
5523 searchContext.setEnd(end);
5524
5525 if (params != null) {
5526 String keywords = (String)params.remove("keywords");
5527
5528 if (Validator.isNotNull(keywords)) {
5529 searchContext.setKeywords(keywords);
5530 }
5531 }
5532
5533 QueryConfig queryConfig = new QueryConfig();
5534
5535 queryConfig.setHighlightEnabled(false);
5536 queryConfig.setScoreEnabled(false);
5537
5538 searchContext.setQueryConfig(queryConfig);
5539
5540 if (sort != null) {
5541 searchContext.setSorts(new Sort[] {sort});
5542 }
5543
5544 searchContext.setStart(start);
5545
5546 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5547 User.class);
5548
5549 return indexer.search(searchContext);
5550 }
5551 catch (Exception e) {
5552 throw new SystemException(e);
5553 }
5554 }
5555
5556 protected void sendEmail(
5557 User user, String password, ServiceContext serviceContext)
5558 throws SystemException {
5559
5560 if (!PrefsPropsUtil.getBoolean(
5561 user.getCompanyId(),
5562 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
5563
5564 return;
5565 }
5566
5567 String fromName = PrefsPropsUtil.getString(
5568 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
5569 String fromAddress = PrefsPropsUtil.getString(
5570 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
5571
5572 String toName = user.getFullName();
5573 String toAddress = user.getEmailAddress();
5574
5575 String subject = PrefsPropsUtil.getContent(
5576 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
5577
5578 String body = null;
5579
5580 if (Validator.isNotNull(password)) {
5581 body = PrefsPropsUtil.getContent(
5582 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
5583 }
5584 else {
5585 body = PrefsPropsUtil.getContent(
5586 user.getCompanyId(),
5587 PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
5588 }
5589
5590 SubscriptionSender subscriptionSender = new SubscriptionSender();
5591
5592 subscriptionSender.setBody(body);
5593 subscriptionSender.setCompanyId(user.getCompanyId());
5594 subscriptionSender.setContextAttributes(
5595 "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
5596 "[$USER_SCREENNAME$]", user.getScreenName());
5597 subscriptionSender.setFrom(fromAddress, fromName);
5598 subscriptionSender.setHtmlFormat(true);
5599 subscriptionSender.setMailId("user", user.getUserId());
5600 subscriptionSender.setServiceContext(serviceContext);
5601 subscriptionSender.setSubject(subject);
5602 subscriptionSender.setUserId(user.getUserId());
5603
5604 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
5605
5606 subscriptionSender.flushNotificationsAsync();
5607 }
5608
5609 protected void setEmailAddress(
5610 User user, String password, String firstName, String middleName,
5611 String lastName, String emailAddress)
5612 throws PortalException, SystemException {
5613
5614 if (emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
5615 return;
5616 }
5617
5618 long userId = user.getUserId();
5619
5620
5621
5622 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
5623 Validator.isNotNull(password)) {
5624
5625 mailService.addUser(
5626 user.getCompanyId(), userId, password, firstName, middleName,
5627 lastName, emailAddress);
5628 }
5629
5630
5631
5632 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
5633 mailService.updateEmailAddress(
5634 user.getCompanyId(), userId, emailAddress);
5635 }
5636
5637
5638
5639 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
5640 mailService.deleteEmailAddress(user.getCompanyId(), userId);
5641 }
5642
5643 user.setEmailAddress(emailAddress);
5644 user.setDigest(StringPool.BLANK);
5645 }
5646
5647 protected void updateGroups(
5648 long userId, long[] newGroupIds, ServiceContext serviceContext,
5649 boolean indexingEnabled)
5650 throws PortalException, SystemException {
5651
5652 if (newGroupIds == null) {
5653 return;
5654 }
5655
5656 List<Group> oldGroups = userPersistence.getGroups(userId);
5657
5658 Set<Long> oldGroupIds = new HashSet<Long>(oldGroups.size());
5659
5660 for (Group oldGroup : oldGroups) {
5661 long oldGroupId = oldGroup.getGroupId();
5662
5663 oldGroupIds.add(oldGroupId);
5664
5665 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
5666 unsetGroupUsers(
5667 oldGroupId, new long[] {userId}, serviceContext);
5668 }
5669 }
5670
5671 for (long newGroupId : newGroupIds) {
5672 if (!oldGroupIds.contains(newGroupId)) {
5673 addGroupUsers(newGroupId, new long[] {userId});
5674 }
5675 }
5676
5677 if (indexingEnabled) {
5678 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5679 User.class);
5680
5681 indexer.reindex(new long[] {userId});
5682 }
5683
5684 PermissionCacheUtil.clearCache();
5685 }
5686
5687 protected void updateOrganizations(
5688 long userId, long[] newOrganizationIds, boolean indexingEnabled)
5689 throws PortalException, SystemException {
5690
5691 if (newOrganizationIds == null) {
5692 return;
5693 }
5694
5695 List<Organization> oldOrganizations = userPersistence.getOrganizations(
5696 userId);
5697
5698 Set<Long> oldOrganizationIds = new HashSet<Long>(
5699 oldOrganizations.size());
5700
5701 for (Organization oldOrganization : oldOrganizations) {
5702 long oldOrganizationId = oldOrganization.getOrganizationId();
5703
5704 oldOrganizationIds.add(oldOrganizationId);
5705
5706 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
5707 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
5708 }
5709 }
5710
5711 for (long newOrganizationId : newOrganizationIds) {
5712 if (!oldOrganizationIds.contains(newOrganizationId)) {
5713 addOrganizationUsers(newOrganizationId, new long[] {userId});
5714 }
5715 }
5716
5717 if (indexingEnabled) {
5718 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5719 User.class);
5720
5721 indexer.reindex(new long[] {userId});
5722 }
5723
5724 PermissionCacheUtil.clearCache();
5725 }
5726
5727 protected void updateUserGroupRoles(
5728 User user, long[] groupIds, long[] organizationIds,
5729 List<UserGroupRole> userGroupRoles)
5730 throws PortalException, SystemException {
5731
5732 if (userGroupRoles == null) {
5733 return;
5734 }
5735
5736 List<UserGroupRole> previousUserGroupRoles =
5737 userGroupRolePersistence.findByUserId(user.getUserId());
5738
5739 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
5740 if (userGroupRoles.contains(userGroupRole)) {
5741 userGroupRoles.remove(userGroupRole);
5742 }
5743 else {
5744 userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
5745 }
5746 }
5747
5748 long[] validGroupIds = null;
5749
5750 if (groupIds != null) {
5751 validGroupIds = ArrayUtil.clone(groupIds);
5752 }
5753 else {
5754 validGroupIds = user.getGroupIds();
5755 }
5756
5757 if (organizationIds == null) {
5758 organizationIds = user.getOrganizationIds();
5759 }
5760
5761 long[] organizationGroupIds = new long[organizationIds.length];
5762
5763 for (int i = 0; i < organizationIds.length; i++) {
5764 long organizationId = organizationIds[i];
5765
5766 Organization organization =
5767 organizationPersistence.findByPrimaryKey(organizationId);
5768
5769 Group organizationGroup = organization.getGroup();
5770
5771 organizationGroupIds[i] = organizationGroup.getGroupId();
5772 }
5773
5774 validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
5775
5776 Arrays.sort(validGroupIds);
5777
5778 for (UserGroupRole userGroupRole : userGroupRoles) {
5779 if (Arrays.binarySearch(
5780 validGroupIds, userGroupRole.getGroupId()) >= 0) {
5781
5782 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
5783 }
5784 }
5785 }
5786
5787 protected void validate(
5788 long companyId, long userId, boolean autoPassword, String password1,
5789 String password2, boolean autoScreenName, String screenName,
5790 String emailAddress, String openId, String firstName,
5791 String middleName, String lastName, long[] organizationIds)
5792 throws PortalException, SystemException {
5793
5794 Company company = companyPersistence.findByPrimaryKey(companyId);
5795
5796 if (company.isSystem()) {
5797 return;
5798 }
5799
5800 if ((company.getMaxUsers() > 0) &&
5801 (company.getMaxUsers() <=
5802 searchCount(
5803 companyId, null, WorkflowConstants.STATUS_APPROVED,
5804 null))) {
5805
5806 throw new CompanyMaxUsersException();
5807 }
5808
5809 if (!autoScreenName) {
5810 validateScreenName(companyId, userId, screenName);
5811 }
5812
5813 if (!autoPassword) {
5814 PasswordPolicy passwordPolicy =
5815 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
5816
5817 PwdToolkitUtil.validate(
5818 companyId, 0, password1, password2, passwordPolicy);
5819 }
5820
5821 validateEmailAddress(companyId, emailAddress);
5822
5823 if (Validator.isNotNull(emailAddress)) {
5824 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
5825
5826 if ((user != null) && (user.getUserId() != userId)) {
5827 throw new DuplicateUserEmailAddressException();
5828 }
5829 }
5830
5831 validateOpenId(companyId, userId, openId);
5832
5833 validateFullName(companyId, firstName, middleName, lastName);
5834
5835 if (organizationIds != null) {
5836 for (long organizationId : organizationIds) {
5837 Organization organization =
5838 organizationPersistence.fetchByPrimaryKey(organizationId);
5839
5840 if (organization == null) {
5841 throw new NoSuchOrganizationException();
5842 }
5843 }
5844 }
5845 }
5846
5847 protected void validate(
5848 long userId, String screenName, String emailAddress, String openId,
5849 String firstName, String middleName, String lastName, String smsSn)
5850 throws PortalException, SystemException {
5851
5852 User user = userPersistence.findByPrimaryKey(userId);
5853
5854 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
5855 validateScreenName(user.getCompanyId(), userId, screenName);
5856 }
5857
5858 validateEmailAddress(user.getCompanyId(), emailAddress);
5859
5860 validateOpenId(user.getCompanyId(), userId, openId);
5861
5862 if (!user.isDefaultUser()) {
5863 if (Validator.isNotNull(emailAddress) &&
5864 !user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
5865
5866 if (userPersistence.fetchByC_EA(
5867 user.getCompanyId(), emailAddress) != null) {
5868
5869 throw new DuplicateUserEmailAddressException();
5870 }
5871 }
5872
5873 validateFullName(
5874 user.getCompanyId(), firstName, middleName, lastName);
5875 }
5876
5877 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
5878 throw new UserSmsException();
5879 }
5880 }
5881
5882 protected void validateEmailAddress(long companyId, String emailAddress)
5883 throws PortalException, SystemException {
5884
5885 if (Validator.isNull(emailAddress) &&
5886 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
5887
5888 return;
5889 }
5890
5891 EmailAddressValidator emailAddressValidator =
5892 EmailAddressValidatorFactory.getInstance();
5893
5894 if (!emailAddressValidator.validate(companyId, emailAddress)) {
5895 throw new UserEmailAddressException();
5896 }
5897
5898 String pop3User = PrefsPropsUtil.getString(
5899 PropsKeys.MAIL_SESSION_MAIL_POP3_USER,
5900 PropsValues.MAIL_SESSION_MAIL_POP3_USER);
5901
5902 if (emailAddress.equalsIgnoreCase(pop3User)) {
5903 throw new ReservedUserEmailAddressException();
5904 }
5905
5906 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
5907 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
5908 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
5909
5910 for (String reservedEmailAddress : reservedEmailAddresses) {
5911 if (emailAddress.equalsIgnoreCase(reservedEmailAddress)) {
5912 throw new ReservedUserEmailAddressException();
5913 }
5914 }
5915 }
5916
5917 protected void validateEmailAddress(
5918 User user, String emailAddress1, String emailAddress2)
5919 throws PortalException, SystemException {
5920
5921 if (!emailAddress1.equals(emailAddress2)) {
5922 throw new UserEmailAddressException();
5923 }
5924
5925 validateEmailAddress(user.getCompanyId(), emailAddress1);
5926 validateEmailAddress(user.getCompanyId(), emailAddress2);
5927
5928 if (!emailAddress1.equalsIgnoreCase(user.getEmailAddress())) {
5929 if (userPersistence.fetchByC_EA(
5930 user.getCompanyId(), emailAddress1) != null) {
5931
5932 throw new DuplicateUserEmailAddressException();
5933 }
5934 }
5935 }
5936
5937 protected void validateFullName(
5938 long companyId, String firstName, String middleName,
5939 String lastName)
5940 throws PortalException, SystemException {
5941
5942 if (Validator.isNull(firstName)) {
5943 throw new ContactFirstNameException();
5944 }
5945 else if (Validator.isNull(lastName) &&
5946 PrefsPropsUtil.getBoolean(
5947 companyId, PropsKeys.USERS_LAST_NAME_REQUIRED,
5948 PropsValues.USERS_LAST_NAME_REQUIRED)) {
5949
5950 throw new ContactLastNameException();
5951 }
5952
5953 FullNameValidator fullNameValidator =
5954 FullNameValidatorFactory.getInstance();
5955
5956 if (!fullNameValidator.validate(
5957 companyId, firstName, middleName, lastName)) {
5958
5959 throw new ContactFullNameException();
5960 }
5961 }
5962
5963 protected void validateOpenId(long companyId, long userId, String openId)
5964 throws PortalException, SystemException {
5965
5966 if (Validator.isNull(openId)) {
5967 return;
5968 }
5969
5970 User user = userPersistence.fetchByC_O(companyId, openId);
5971
5972 if ((user != null) && (user.getUserId() != userId)) {
5973 throw new DuplicateOpenIdException();
5974 }
5975 }
5976
5977 protected void validatePassword(
5978 long companyId, long userId, String password1, String password2)
5979 throws PortalException, SystemException {
5980
5981 if (Validator.isNull(password1) || Validator.isNull(password2)) {
5982 throw new UserPasswordException(
5983 UserPasswordException.PASSWORD_INVALID);
5984 }
5985
5986 if (!password1.equals(password2)) {
5987 throw new UserPasswordException(
5988 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
5989 }
5990
5991 PasswordPolicy passwordPolicy =
5992 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
5993
5994 PwdToolkitUtil.validate(
5995 companyId, userId, password1, password2, passwordPolicy);
5996 }
5997
5998 protected void validateReminderQuery(String question, String answer)
5999 throws PortalException {
6000
6001 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
6002 return;
6003 }
6004
6005 if (Validator.isNull(question)) {
6006 throw new UserReminderQueryException("Question cannot be null");
6007 }
6008
6009 if (Validator.isNull(answer)) {
6010 throw new UserReminderQueryException("Answer cannot be null");
6011 }
6012 }
6013
6014 protected void validateScreenName(
6015 long companyId, long userId, String screenName)
6016 throws PortalException, SystemException {
6017
6018 if (Validator.isNull(screenName)) {
6019 throw new UserScreenNameException();
6020 }
6021
6022 ScreenNameValidator screenNameValidator =
6023 ScreenNameValidatorFactory.getInstance();
6024
6025 if (!screenNameValidator.validate(companyId, screenName)) {
6026 throw new UserScreenNameException();
6027 }
6028
6029 if (Validator.isNumber(screenName)) {
6030 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
6031 throw new UserScreenNameException();
6032 }
6033
6034 if (!screenName.equals(String.valueOf(userId))) {
6035 Group group = groupPersistence.fetchByPrimaryKey(
6036 GetterUtil.getLong(screenName));
6037
6038 if (group != null) {
6039 throw new UserScreenNameException();
6040 }
6041 }
6042 }
6043
6044 for (char c : screenName.toCharArray()) {
6045 if (!Validator.isChar(c) && !Validator.isDigit(c) &&
6046 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
6047 (c != CharPool.UNDERLINE)) {
6048
6049 throw new UserScreenNameException();
6050 }
6051 }
6052
6053 String[] anonymousNames = BaseServiceImpl.ANONYMOUS_NAMES;
6054
6055 for (String anonymousName : anonymousNames) {
6056 if (screenName.equalsIgnoreCase(anonymousName)) {
6057 throw new UserScreenNameException();
6058 }
6059 }
6060
6061 User user = userPersistence.fetchByC_SN(companyId, screenName);
6062
6063 if ((user != null) && (user.getUserId() != userId)) {
6064 throw new DuplicateUserScreenNameException();
6065 }
6066
6067 String friendlyURL = StringPool.SLASH + screenName;
6068
6069 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
6070
6071 if ((group != null) && (group.getClassPK() != userId)) {
6072 throw new GroupFriendlyURLException(
6073 GroupFriendlyURLException.DUPLICATE);
6074 }
6075
6076 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
6077
6078 if (exceptionType != -1) {
6079 throw new UserScreenNameException(
6080 new GroupFriendlyURLException(exceptionType));
6081 }
6082
6083 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
6084 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
6085 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
6086
6087 for (String reservedScreenName : reservedScreenNames) {
6088 if (screenName.equalsIgnoreCase(reservedScreenName)) {
6089 throw new ReservedUserScreenNameException();
6090 }
6091 }
6092 }
6093
6094 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
6095
6096 private Map<Long, User> _defaultUsers = new ConcurrentHashMap<Long, User>();
6097
6098 }