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.LocaleUtil;
072 import com.liferay.portal.kernel.util.OrderByComparator;
073 import com.liferay.portal.kernel.util.ParamUtil;
074 import com.liferay.portal.kernel.util.PropsKeys;
075 import com.liferay.portal.kernel.util.StringBundler;
076 import com.liferay.portal.kernel.util.StringPool;
077 import com.liferay.portal.kernel.util.StringUtil;
078 import com.liferay.portal.kernel.util.UnicodeProperties;
079 import com.liferay.portal.kernel.util.Validator;
080 import com.liferay.portal.kernel.workflow.WorkflowConstants;
081 import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil;
082 import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
083 import com.liferay.portal.model.Account;
084 import com.liferay.portal.model.Company;
085 import com.liferay.portal.model.CompanyConstants;
086 import com.liferay.portal.model.Contact;
087 import com.liferay.portal.model.ContactConstants;
088 import com.liferay.portal.model.Group;
089 import com.liferay.portal.model.GroupConstants;
090 import com.liferay.portal.model.Layout;
091 import com.liferay.portal.model.Organization;
092 import com.liferay.portal.model.PasswordPolicy;
093 import com.liferay.portal.model.ResourceConstants;
094 import com.liferay.portal.model.Role;
095 import com.liferay.portal.model.RoleConstants;
096 import com.liferay.portal.model.Team;
097 import com.liferay.portal.model.Ticket;
098 import com.liferay.portal.model.TicketConstants;
099 import com.liferay.portal.model.User;
100 import com.liferay.portal.model.UserGroup;
101 import com.liferay.portal.model.UserGroupRole;
102 import com.liferay.portal.model.impl.LayoutImpl;
103 import com.liferay.portal.security.auth.AuthPipeline;
104 import com.liferay.portal.security.auth.Authenticator;
105 import com.liferay.portal.security.auth.EmailAddressGenerator;
106 import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
107 import com.liferay.portal.security.auth.EmailAddressValidator;
108 import com.liferay.portal.security.auth.EmailAddressValidatorFactory;
109 import com.liferay.portal.security.auth.FullNameGenerator;
110 import com.liferay.portal.security.auth.FullNameGeneratorFactory;
111 import com.liferay.portal.security.auth.FullNameValidator;
112 import com.liferay.portal.security.auth.FullNameValidatorFactory;
113 import com.liferay.portal.security.auth.PrincipalException;
114 import com.liferay.portal.security.auth.ScreenNameGenerator;
115 import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
116 import com.liferay.portal.security.auth.ScreenNameValidator;
117 import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
118 import com.liferay.portal.security.ldap.LDAPSettingsUtil;
119 import com.liferay.portal.security.permission.PermissionCacheUtil;
120 import com.liferay.portal.security.pwd.PwdAuthenticator;
121 import com.liferay.portal.security.pwd.PwdEncryptor;
122 import com.liferay.portal.security.pwd.PwdToolkitUtil;
123 import com.liferay.portal.security.pwd.RegExpToolkit;
124 import com.liferay.portal.service.BaseServiceImpl;
125 import com.liferay.portal.service.ServiceContext;
126 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
127 import com.liferay.portal.util.PortalUtil;
128 import com.liferay.portal.util.PrefsPropsUtil;
129 import com.liferay.portal.util.PropsValues;
130 import com.liferay.portal.util.SubscriptionSender;
131 import com.liferay.portlet.documentlibrary.ImageSizeException;
132 import com.liferay.portlet.messageboards.model.MBMessage;
133 import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
134 import com.liferay.util.Encryptor;
135 import com.liferay.util.EncryptorException;
136
137 import java.awt.image.RenderedImage;
138
139 import java.io.IOException;
140 import java.io.Serializable;
141
142 import java.util.ArrayList;
143 import java.util.Arrays;
144 import java.util.Calendar;
145 import java.util.Date;
146 import java.util.HashMap;
147 import java.util.HashSet;
148 import java.util.LinkedHashMap;
149 import java.util.List;
150 import java.util.Locale;
151 import java.util.Map;
152 import java.util.Set;
153 import java.util.concurrent.Callable;
154 import java.util.concurrent.ConcurrentHashMap;
155
156
167 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
168
169
183 public User addDefaultAdminUser(
184 long companyId, String screenName, String emailAddress,
185 Locale locale, String firstName, String middleName, String lastName)
186 throws PortalException, SystemException {
187
188 long creatorUserId = 0;
189 boolean autoPassword = false;
190 String password1 = PropsValues.DEFAULT_ADMIN_PASSWORD;
191 String password2 = password1;
192 boolean autoScreenName = false;
193
194 screenName = getScreenName(screenName);
195
196 for (int i = 1;; i++) {
197 User screenNameUser = userPersistence.fetchByC_SN(
198 companyId, screenName);
199
200 if (screenNameUser == null) {
201 break;
202 }
203
204 screenName = screenName + i;
205 }
206
207 long facebookId = 0;
208 String openId = StringPool.BLANK;
209 int prefixId = 0;
210 int suffixId = 0;
211 boolean male = true;
212 int birthdayMonth = Calendar.JANUARY;
213 int birthdayDay = 1;
214 int birthdayYear = 1970;
215 String jobTitle = StringPool.BLANK;
216
217 Group guestGroup = groupLocalService.getGroup(
218 companyId, GroupConstants.GUEST);
219
220 long[] groupIds = {guestGroup.getGroupId()};
221
222 long[] organizationIds = null;
223
224 Role adminRole = roleLocalService.getRole(
225 companyId, RoleConstants.ADMINISTRATOR);
226
227 Role powerUserRole = roleLocalService.getRole(
228 companyId, RoleConstants.POWER_USER);
229
230 long[] roleIds = {adminRole.getRoleId(), powerUserRole.getRoleId()};
231
232 long[] userGroupIds = null;
233 boolean sendEmail = false;
234 ServiceContext serviceContext = new ServiceContext();
235
236 User defaultAdminUser = addUser(
237 creatorUserId, companyId, autoPassword, password1, password2,
238 autoScreenName, screenName, emailAddress, facebookId, openId,
239 locale, firstName, middleName, lastName, prefixId, suffixId, male,
240 birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
241 organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
242
243 updateEmailAddressVerified(defaultAdminUser.getUserId(), true);
244
245 updateLastLogin(
246 defaultAdminUser.getUserId(), defaultAdminUser.getLoginIP());
247
248 updatePasswordReset(defaultAdminUser.getUserId(), false);
249
250 return defaultAdminUser;
251 }
252
253
263 public void addDefaultGroups(long userId)
264 throws PortalException, SystemException {
265
266 User user = userPersistence.findByPrimaryKey(userId);
267
268 Set<Long> groupIdsSet = new HashSet<Long>();
269
270 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
271 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
272 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
273
274 for (String defaultGroupName : defaultGroupNames) {
275 Company company = companyPersistence.findByPrimaryKey(
276 user.getCompanyId());
277
278 Account account = company.getAccount();
279
280 if (defaultGroupName.equalsIgnoreCase(account.getName())) {
281 defaultGroupName = GroupConstants.GUEST;
282 }
283
284 try {
285 Group group = groupPersistence.findByC_N(
286 user.getCompanyId(), defaultGroupName);
287
288 if (!userPersistence.containsGroup(
289 userId, group.getGroupId())) {
290
291 groupIdsSet.add(group.getGroupId());
292 }
293 }
294 catch (NoSuchGroupException nsge) {
295 }
296 }
297
298 String[] defaultOrganizationGroupNames = PrefsPropsUtil.getStringArray(
299 user.getCompanyId(),
300 PropsKeys.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES,
301 StringPool.NEW_LINE,
302 PropsValues.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES);
303
304 for (String defaultOrganizationGroupName :
305 defaultOrganizationGroupNames) {
306
307 defaultOrganizationGroupName +=
308 GroupLocalServiceImpl.ORGANIZATION_NAME_SUFFIX;
309
310 try {
311 Group group = groupPersistence.findByC_N(
312 user.getCompanyId(), defaultOrganizationGroupName);
313
314 if (!userPersistence.containsGroup(
315 userId, group.getGroupId())) {
316
317 groupIdsSet.add(group.getGroupId());
318 }
319 }
320 catch (NoSuchGroupException nsge) {
321 }
322 }
323
324 long[] groupIds = ArrayUtil.toArray(
325 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
326
327 groupLocalService.addUserGroups(userId, groupIds);
328 }
329
330
340 public void addDefaultRoles(long userId)
341 throws PortalException, SystemException {
342
343 User user = userPersistence.findByPrimaryKey(userId);
344
345 Set<Long> roleIdSet = new HashSet<Long>();
346
347 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
348 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
349 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
350
351 for (String defaultRoleName : defaultRoleNames) {
352 try {
353 Role role = rolePersistence.findByC_N(
354 user.getCompanyId(), defaultRoleName);
355
356 if (!userPersistence.containsRole(userId, role.getRoleId())) {
357 roleIdSet.add(role.getRoleId());
358 }
359 }
360 catch (NoSuchRoleException nsre) {
361 }
362 }
363
364 long[] roleIds = ArrayUtil.toArray(
365 roleIdSet.toArray(new Long[roleIdSet.size()]));
366
367 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
368
369 userPersistence.addRoles(userId, roleIds);
370 }
371
372
382 @SuppressWarnings("deprecation")
383 public void addDefaultUserGroups(long userId)
384 throws PortalException, SystemException {
385
386 User user = userPersistence.findByPrimaryKey(userId);
387
388 Set<Long> userGroupIdSet = new HashSet<Long>();
389
390 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
391 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
392 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
393
394 for (String defaultUserGroupName : defaultUserGroupNames) {
395 try {
396 UserGroup userGroup = userGroupPersistence.findByC_N(
397 user.getCompanyId(), defaultUserGroupName);
398
399 if (!userPersistence.containsUserGroup(
400 userId, userGroup.getUserGroupId())) {
401
402 userGroupIdSet.add(userGroup.getUserGroupId());
403 }
404 }
405 catch (NoSuchUserGroupException nsuge) {
406 }
407 }
408
409 long[] userGroupIds = ArrayUtil.toArray(
410 userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
411
412 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
413 for (long userGroupId : userGroupIds) {
414 userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
415 }
416 }
417
418 userPersistence.addUserGroups(userId, userGroupIds);
419 }
420
421
430 public void addGroupUsers(long groupId, long[] userIds)
431 throws PortalException, SystemException {
432
433 groupPersistence.addUsers(groupId, userIds);
434
435 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
436
437 indexer.reindex(userIds);
438
439 PermissionCacheUtil.clearCache();
440
441 addDefaultRolesAndTeams(groupId, userIds);
442 }
443
444
453 public void addOrganizationUsers(long organizationId, long[] userIds)
454 throws PortalException, SystemException {
455
456 organizationPersistence.addUsers(organizationId, userIds);
457
458 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
459
460 indexer.reindex(userIds);
461
462 PermissionCacheUtil.clearCache();
463 }
464
465
473 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
474 throws SystemException {
475
476 passwordPolicyRelLocalService.addPasswordPolicyRels(
477 passwordPolicyId, User.class.getName(), userIds);
478 }
479
480
489 public void addRoleUsers(long roleId, long[] userIds)
490 throws PortalException, SystemException {
491
492 rolePersistence.addUsers(roleId, userIds);
493
494 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
495
496 indexer.reindex(userIds);
497
498 PermissionCacheUtil.clearCache();
499 }
500
501
510 public void addTeamUsers(long teamId, long[] userIds)
511 throws PortalException, SystemException {
512
513 teamPersistence.addUsers(teamId, userIds);
514
515 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
516
517 indexer.reindex(userIds);
518
519 PermissionCacheUtil.clearCache();
520 }
521
522
570 public User addUser(
571 long creatorUserId, long companyId, boolean autoPassword,
572 String password1, String password2, boolean autoScreenName,
573 String screenName, String emailAddress, long facebookId,
574 String openId, Locale locale, String firstName, String middleName,
575 String lastName, int prefixId, int suffixId, boolean male,
576 int birthdayMonth, int birthdayDay, int birthdayYear,
577 String jobTitle, long[] groupIds, long[] organizationIds,
578 long[] roleIds, long[] userGroupIds, boolean sendEmail,
579 ServiceContext serviceContext)
580 throws PortalException, SystemException {
581
582 boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
583
584 try {
585 WorkflowThreadLocal.setEnabled(false);
586
587 return addUserWithWorkflow(
588 creatorUserId, companyId, autoPassword, password1, password2,
589 autoScreenName, screenName, emailAddress, facebookId, openId,
590 locale, firstName, middleName, lastName, prefixId, suffixId,
591 male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
592 groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
593 serviceContext);
594 }
595 finally {
596 WorkflowThreadLocal.setEnabled(workflowEnabled);
597 }
598 }
599
600
609 @SuppressWarnings("deprecation")
610 public void addUserGroupUsers(long userGroupId, long[] userIds)
611 throws PortalException, SystemException {
612
613 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
614 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
615 }
616
617 userGroupPersistence.addUsers(userGroupId, userIds);
618
619 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
620
621 indexer.reindex(userIds);
622
623 PermissionCacheUtil.clearCache();
624 }
625
626
674 @SuppressWarnings("deprecation")
675 public User addUserWithWorkflow(
676 long creatorUserId, long companyId, boolean autoPassword,
677 String password1, String password2, boolean autoScreenName,
678 String screenName, String emailAddress, long facebookId,
679 String openId, Locale locale, String firstName, String middleName,
680 String lastName, int prefixId, int suffixId, boolean male,
681 int birthdayMonth, int birthdayDay, int birthdayYear,
682 String jobTitle, long[] groupIds, long[] organizationIds,
683 long[] roleIds, long[] userGroupIds, boolean sendEmail,
684 ServiceContext serviceContext)
685 throws PortalException, SystemException {
686
687
688
689 Company company = companyPersistence.findByPrimaryKey(companyId);
690 screenName = getScreenName(screenName);
691 openId = StringUtil.trim(openId);
692 Date now = new Date();
693
694 if (PrefsPropsUtil.getBoolean(
695 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
696
697 autoScreenName = true;
698 }
699
700
701
702 long userId = counterLocalService.increment();
703
704 EmailAddressGenerator emailAddressGenerator =
705 EmailAddressGeneratorFactory.getInstance();
706
707 if ((emailAddress == null) ||
708 emailAddressGenerator.isGenerated(emailAddress)) {
709
710 emailAddress = StringPool.BLANK;
711 }
712 else {
713 emailAddress = emailAddress.trim().toLowerCase();
714 }
715
716 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
717 Validator.isNull(emailAddress)) {
718
719 emailAddress = emailAddressGenerator.generate(companyId, userId);
720 }
721
722 validate(
723 companyId, userId, autoPassword, password1, password2,
724 autoScreenName, screenName, emailAddress, openId, firstName,
725 middleName, lastName, organizationIds);
726
727 if (!autoPassword) {
728 if (Validator.isNull(password1) || Validator.isNull(password2)) {
729 throw new UserPasswordException(
730 UserPasswordException.PASSWORD_INVALID);
731 }
732 }
733
734 if (autoScreenName) {
735 ScreenNameGenerator screenNameGenerator =
736 ScreenNameGeneratorFactory.getInstance();
737
738 try {
739 screenName = screenNameGenerator.generate(
740 companyId, userId, emailAddress);
741 }
742 catch (Exception e) {
743 throw new SystemException(e);
744 }
745 }
746
747 User defaultUser = getDefaultUser(companyId);
748
749 FullNameGenerator fullNameGenerator =
750 FullNameGeneratorFactory.getInstance();
751
752 String fullName = fullNameGenerator.getFullName(
753 firstName, middleName, lastName);
754
755 String greeting = LanguageUtil.format(
756 locale, "welcome-x", " " + fullName, false);
757
758 User user = userPersistence.create(userId);
759
760 if (serviceContext != null) {
761 String uuid = serviceContext.getUuid();
762
763 if (Validator.isNotNull(uuid)) {
764 user.setUuid(uuid);
765 }
766 }
767
768 user.setCompanyId(companyId);
769 user.setCreateDate(now);
770 user.setModifiedDate(now);
771 user.setDefaultUser(false);
772 user.setContactId(counterLocalService.increment());
773
774 if (Validator.isNotNull(password1)) {
775 user.setPassword(PwdEncryptor.encrypt(password1));
776 user.setPasswordUnencrypted(password1);
777 }
778
779 user.setPasswordEncrypted(true);
780
781 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
782
783 boolean passwordReset = false;
784
785 if (passwordPolicy != null) {
786 if (passwordPolicy.isChangeable() &&
787 passwordPolicy.isChangeRequired()) {
788
789 passwordReset = true;
790 }
791
792 addPasswordPolicyUsers(
793 passwordPolicy.getPasswordPolicyId(), new long[] {userId});
794 }
795
796 user.setPasswordReset(passwordReset);
797
798 user.setDigest(StringPool.BLANK);
799 user.setScreenName(screenName);
800 user.setEmailAddress(emailAddress);
801 user.setFacebookId(facebookId);
802
803 Long ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
804
805 if (ldapServerId != null) {
806 user.setLdapServerId(ldapServerId);
807 }
808 else {
809 user.setLdapServerId(-1);
810 }
811
812 user.setOpenId(openId);
813 user.setLanguageId(LocaleUtil.toLanguageId(locale));
814 user.setTimeZoneId(defaultUser.getTimeZoneId());
815 user.setGreeting(greeting);
816 user.setFirstName(firstName);
817 user.setMiddleName(middleName);
818 user.setLastName(lastName);
819 user.setJobTitle(jobTitle);
820 user.setStatus(WorkflowConstants.STATUS_DRAFT);
821 user.setExpandoBridgeAttributes(serviceContext);
822
823 userPersistence.update(user, serviceContext);
824
825
826
827 String creatorUserName = StringPool.BLANK;
828
829 if (creatorUserId <= 0) {
830 creatorUserId = user.getUserId();
831
832
833
834
835
836 }
837 else {
838 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
839
840 creatorUserName = creatorUser.getFullName();
841 }
842
843 resourceLocalService.addResources(
844 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
845 false, false, false);
846
847
848
849 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
850
851 Contact contact = contactPersistence.create(user.getContactId());
852
853 contact.setCompanyId(user.getCompanyId());
854 contact.setUserId(creatorUserId);
855 contact.setUserName(creatorUserName);
856 contact.setCreateDate(now);
857 contact.setModifiedDate(now);
858 contact.setClassName(User.class.getName());
859 contact.setClassPK(user.getUserId());
860 contact.setAccountId(company.getAccountId());
861 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
862 contact.setEmailAddress(user.getEmailAddress());
863 contact.setFirstName(firstName);
864 contact.setMiddleName(middleName);
865 contact.setLastName(lastName);
866 contact.setPrefixId(prefixId);
867 contact.setSuffixId(suffixId);
868 contact.setMale(male);
869 contact.setBirthday(birthday);
870 contact.setJobTitle(jobTitle);
871
872 contactPersistence.update(contact, serviceContext);
873
874
875
876 groupLocalService.addGroup(
877 user.getUserId(), GroupConstants.DEFAULT_PARENT_GROUP_ID,
878 User.class.getName(), user.getUserId(), null, null, 0,
879 StringPool.SLASH + screenName, false, true, null);
880
881
882
883 if (groupIds != null) {
884 groupLocalService.addUserGroups(userId, groupIds);
885 }
886
887 addDefaultGroups(userId);
888
889
890
891 updateOrganizations(userId, organizationIds, false);
892
893
894
895 if (roleIds != null) {
896 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
897
898 userPersistence.setRoles(userId, roleIds);
899 }
900
901 addDefaultRoles(userId);
902
903
904
905 if (userGroupIds != null) {
906 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
907 for (long userGroupId : userGroupIds) {
908 userGroupLocalService.copyUserGroupLayouts(
909 userGroupId, new long[] {userId});
910 }
911 }
912
913 userPersistence.setUserGroups(userId, userGroupIds);
914 }
915
916 addDefaultUserGroups(userId);
917
918
919
920 if (serviceContext != null) {
921 updateAsset(
922 creatorUserId, user, serviceContext.getAssetCategoryIds(),
923 serviceContext.getAssetTagNames());
924 }
925
926
927
928 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
929 reindex(user);
930 }
931
932
933
934 long workflowUserId = creatorUserId;
935
936 if (workflowUserId == userId) {
937 workflowUserId = defaultUser.getUserId();
938 }
939
940 ServiceContext workflowServiceContext = serviceContext;
941
942 if (workflowServiceContext == null) {
943 workflowServiceContext = new ServiceContext();
944 }
945
946 workflowServiceContext.setAttribute("autoPassword", autoPassword);
947 workflowServiceContext.setAttribute("sendEmail", sendEmail);
948
949 WorkflowHandlerRegistryUtil.startWorkflowInstance(
950 companyId, workflowUserId, User.class.getName(), userId, user,
951 workflowServiceContext);
952
953 if (serviceContext != null) {
954 String passwordUnencrypted = (String)serviceContext.getAttribute(
955 "passwordUnencrypted");
956
957 if (Validator.isNotNull(passwordUnencrypted)) {
958 user.setPasswordUnencrypted(passwordUnencrypted);
959 }
960 }
961
962 return user;
963 }
964
965
989 public int authenticateByEmailAddress(
990 long companyId, String emailAddress, String password,
991 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
992 Map<String, Object> resultsMap)
993 throws PortalException, SystemException {
994
995 return authenticate(
996 companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
997 headerMap, parameterMap, resultsMap);
998 }
999
1000
1024 public int authenticateByScreenName(
1025 long companyId, String screenName, String password,
1026 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1027 Map<String, Object> resultsMap)
1028 throws PortalException, SystemException {
1029
1030 return authenticate(
1031 companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
1032 headerMap, parameterMap, resultsMap);
1033 }
1034
1035
1059 public int authenticateByUserId(
1060 long companyId, long userId, String password,
1061 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1062 Map<String, Object> resultsMap)
1063 throws PortalException, SystemException {
1064
1065 return authenticate(
1066 companyId, String.valueOf(userId), password,
1067 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap, resultsMap);
1068 }
1069
1070
1110 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1111 public long authenticateForBasic(
1112 long companyId, String authType, String login, String password)
1113 throws PortalException, SystemException {
1114
1115 if (PropsValues.AUTH_LOGIN_DISABLED) {
1116 return 0;
1117 }
1118
1119 try {
1120 User user = null;
1121
1122 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1123 user = getUserByEmailAddress(companyId, login);
1124 }
1125 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1126 user = getUserByScreenName(companyId, login);
1127 }
1128 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1129 user = getUserById(companyId, GetterUtil.getLong(login));
1130 }
1131
1132 if (user.isDefaultUser()) {
1133 if (_log.isInfoEnabled()) {
1134 _log.info(
1135 "Basic authentication is disabled for the default " +
1136 "user");
1137 }
1138
1139 return 0;
1140 }
1141 else if (!user.isActive()) {
1142 if (_log.isInfoEnabled()) {
1143 _log.info(
1144 "Basic authentication is disabled for inactive user " +
1145 user.getUserId());
1146 }
1147
1148 return 0;
1149 }
1150
1151 if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
1152 return user.getUserId();
1153 }
1154
1155 String userPassword = user.getPassword();
1156
1157 if (!user.isPasswordEncrypted()) {
1158 userPassword = PwdEncryptor.encrypt(userPassword);
1159 }
1160
1161 String encPassword = PwdEncryptor.encrypt(password);
1162
1163 if (userPassword.equals(password) ||
1164 userPassword.equals(encPassword)) {
1165
1166 return user.getUserId();
1167 }
1168 }
1169 catch (NoSuchUserException nsue) {
1170 }
1171
1172 return 0;
1173 }
1174
1175
1193 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1194 public long authenticateForDigest(
1195 long companyId, String username, String realm, String nonce,
1196 String method, String uri, String response)
1197 throws PortalException, SystemException {
1198
1199 if (PropsValues.AUTH_LOGIN_DISABLED) {
1200 return 0;
1201 }
1202
1203
1204
1205 User user = null;
1206
1207 try {
1208 user = getUserByEmailAddress(companyId, username);
1209 }
1210 catch (NoSuchUserException nsue) {
1211 }
1212
1213 if (user == null) {
1214 try {
1215 user = getUserByScreenName(companyId, username);
1216 }
1217 catch (NoSuchUserException nsue) {
1218 }
1219 }
1220
1221 if (user == null) {
1222 try {
1223 user = getUserById(GetterUtil.getLong(username));
1224 }
1225 catch (NoSuchUserException nsue) {
1226 return 0;
1227 }
1228 }
1229
1230 if (user.isDefaultUser()) {
1231 if (_log.isInfoEnabled()) {
1232 _log.info(
1233 "Digest authentication is disabled for the default user");
1234 }
1235
1236 return 0;
1237 }
1238 else if (!user.isActive()) {
1239 if (_log.isInfoEnabled()) {
1240 _log.info(
1241 "Digest authentication is disabled for inactive user " +
1242 user.getUserId());
1243 }
1244
1245 return 0;
1246 }
1247
1248
1249
1250 String digest = user.getDigest();
1251
1252 if (Validator.isNull(digest)) {
1253 _log.error(
1254 "User must first login through the portal " + user.getUserId());
1255
1256 return 0;
1257 }
1258
1259 String[] digestArray = StringUtil.split(user.getDigest());
1260
1261 for (String ha1 : digestArray) {
1262 String ha2 = DigesterUtil.digestHex(Digester.MD5, method, uri);
1263
1264 String curResponse = DigesterUtil.digestHex(
1265 Digester.MD5, ha1, nonce, ha2);
1266
1267 if (response.equals(curResponse)) {
1268 return user.getUserId();
1269 }
1270 }
1271
1272 return 0;
1273 }
1274
1275
1284 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1285 public boolean authenticateForJAAS(long userId, String encPassword) {
1286 if (PropsValues.AUTH_LOGIN_DISABLED) {
1287 return false;
1288 }
1289
1290 try {
1291 User user = userPersistence.findByPrimaryKey(userId);
1292
1293 if (user.isDefaultUser()) {
1294 if (_log.isInfoEnabled()) {
1295 _log.info(
1296 "JAAS authentication is disabled for the default user");
1297 }
1298
1299 return false;
1300 }
1301 else if (!user.isActive()) {
1302 if (_log.isInfoEnabled()) {
1303 _log.info(
1304 "JAAS authentication is disabled for inactive user " +
1305 userId);
1306 }
1307
1308 return false;
1309 }
1310
1311 String password = user.getPassword();
1312
1313 if (user.isPasswordEncrypted()) {
1314 if (password.equals(encPassword)) {
1315 return true;
1316 }
1317
1318 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1319 encPassword = PwdEncryptor.encrypt(encPassword, password);
1320
1321 if (password.equals(encPassword)) {
1322 return true;
1323 }
1324 }
1325 }
1326 else {
1327 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1328 if (password.equals(encPassword)) {
1329 return true;
1330 }
1331 }
1332
1333 password = PwdEncryptor.encrypt(password);
1334
1335 if (password.equals(encPassword)) {
1336 return true;
1337 }
1338 }
1339 }
1340 catch (Exception e) {
1341 _log.error(e);
1342 }
1343
1344 return false;
1345 }
1346
1347
1355 public void checkLockout(User user)
1356 throws PortalException, SystemException {
1357
1358 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1359 return;
1360 }
1361
1362 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1363
1364 if (passwordPolicy.isLockout()) {
1365
1366
1367
1368 Date now = new Date();
1369 int failedLoginAttempts = user.getFailedLoginAttempts();
1370
1371 if (failedLoginAttempts > 0) {
1372 long failedLoginTime = user.getLastFailedLoginDate().getTime();
1373 long elapsedTime = now.getTime() - failedLoginTime;
1374 long requiredElapsedTime =
1375 passwordPolicy.getResetFailureCount() * 1000;
1376
1377 if ((requiredElapsedTime != 0) &&
1378 (elapsedTime > requiredElapsedTime)) {
1379
1380 user.setLastFailedLoginDate(null);
1381 user.setFailedLoginAttempts(0);
1382
1383 userPersistence.update(user);
1384 }
1385 }
1386
1387
1388
1389 if (user.isLockout()) {
1390 long lockoutTime = user.getLockoutDate().getTime();
1391 long elapsedTime = now.getTime() - lockoutTime;
1392 long requiredElapsedTime =
1393 passwordPolicy.getLockoutDuration() * 1000;
1394
1395 if ((requiredElapsedTime != 0) &&
1396 (elapsedTime > requiredElapsedTime)) {
1397
1398 user.setLockout(false);
1399 user.setLockoutDate(null);
1400
1401 userPersistence.update(user);
1402 }
1403 }
1404
1405 if (user.isLockout()) {
1406 throw new UserLockoutException();
1407 }
1408 }
1409 }
1410
1411
1418 public void checkLoginFailure(User user) throws SystemException {
1419 Date now = new Date();
1420
1421 int failedLoginAttempts = user.getFailedLoginAttempts();
1422
1423 user.setLastFailedLoginDate(now);
1424 user.setFailedLoginAttempts(++failedLoginAttempts);
1425
1426 userPersistence.update(user);
1427 }
1428
1429
1439 public void checkLoginFailureByEmailAddress(
1440 long companyId, String emailAddress)
1441 throws PortalException, SystemException {
1442
1443 User user = getUserByEmailAddress(companyId, emailAddress);
1444
1445 checkLoginFailure(user);
1446 }
1447
1448
1456 public void checkLoginFailureById(long userId)
1457 throws PortalException, SystemException {
1458
1459 User user = userPersistence.findByPrimaryKey(userId);
1460
1461 checkLoginFailure(user);
1462 }
1463
1464
1473 public void checkLoginFailureByScreenName(long companyId, String screenName)
1474 throws PortalException, SystemException {
1475
1476 User user = getUserByScreenName(companyId, screenName);
1477
1478 checkLoginFailure(user);
1479 }
1480
1481
1491 public void checkPasswordExpired(User user)
1492 throws PortalException, SystemException {
1493
1494 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1495 return;
1496 }
1497
1498 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1499
1500
1501
1502 if (isPasswordExpired(user)) {
1503 int graceLoginCount = user.getGraceLoginCount();
1504
1505 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
1506 user.setGraceLoginCount(++graceLoginCount);
1507
1508 userPersistence.update(user);
1509 }
1510 else {
1511 user.setDigest(StringPool.BLANK);
1512
1513 userPersistence.update(user);
1514
1515 throw new PasswordExpiredException();
1516 }
1517 }
1518
1519
1520
1521 if (passwordPolicy.isChangeable() &&
1522 passwordPolicy.isChangeRequired()) {
1523
1524 if (user.getLastLoginDate() == null) {
1525 user.setPasswordReset(true);
1526
1527 userPersistence.update(user);
1528 }
1529 }
1530 }
1531
1532
1538 public void clearOrganizationUsers(long organizationId)
1539 throws SystemException {
1540
1541 organizationPersistence.clearUsers(organizationId);
1542
1543 PermissionCacheUtil.clearCache();
1544 }
1545
1546
1552 public void clearUserGroupUsers(long userGroupId) throws SystemException {
1553 userGroupPersistence.clearUsers(userGroupId);
1554
1555 PermissionCacheUtil.clearCache();
1556 }
1557
1558
1570 public void completeUserRegistration(
1571 User user, ServiceContext serviceContext)
1572 throws PortalException, SystemException {
1573
1574 boolean autoPassword = ParamUtil.getBoolean(
1575 serviceContext, "autoPassword");
1576
1577 String password = null;
1578
1579 if (autoPassword) {
1580 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1581 if (_log.isWarnEnabled()) {
1582 StringBundler sb = new StringBundler(4);
1583
1584 sb.append("When LDAP password policy is enabled, it is ");
1585 sb.append("possible that portal generated passwords will ");
1586 sb.append("not match the LDAP policy. Using ");
1587 sb.append("RegExpToolkit to generate new password.");
1588
1589 _log.warn(sb.toString());
1590 }
1591
1592 RegExpToolkit regExpToolkit = new RegExpToolkit();
1593
1594 password = regExpToolkit.generate(null);
1595 }
1596 else {
1597 PasswordPolicy passwordPolicy =
1598 passwordPolicyLocalService.getPasswordPolicy(
1599 user.getCompanyId(), user.getOrganizationIds());
1600
1601 password = PwdToolkitUtil.generate(passwordPolicy);
1602 }
1603
1604 user.setPassword(PwdEncryptor.encrypt(password));
1605 user.setPasswordEncrypted(true);
1606 user.setPasswordUnencrypted(password);
1607
1608 userPersistence.update(user);
1609 }
1610
1611 if (user.hasCompanyMx()) {
1612 String mailPassword = password;
1613
1614 if (Validator.isNull(mailPassword)) {
1615 mailPassword = user.getPasswordUnencrypted();
1616 }
1617
1618 mailService.addUser(
1619 user.getCompanyId(), user.getUserId(), mailPassword,
1620 user.getFirstName(), user.getMiddleName(), user.getLastName(),
1621 user.getEmailAddress());
1622 }
1623
1624 boolean sendEmail = ParamUtil.getBoolean(serviceContext, "sendEmail");
1625
1626 if (sendEmail) {
1627 sendEmail(user, password, serviceContext);
1628 }
1629
1630 Company company = companyPersistence.findByPrimaryKey(
1631 user.getCompanyId());
1632
1633 if (company.isStrangersVerify() && (serviceContext.getPlid() > 0)) {
1634 sendEmailAddressVerification(
1635 user, user.getEmailAddress(), serviceContext);
1636 }
1637 }
1638
1639
1652 public KeyValuePair decryptUserId(
1653 long companyId, String name, String password)
1654 throws PortalException, SystemException {
1655
1656 Company company = companyPersistence.findByPrimaryKey(companyId);
1657
1658 try {
1659 name = Encryptor.decrypt(company.getKeyObj(), name);
1660 }
1661 catch (EncryptorException ee) {
1662 throw new SystemException(ee);
1663 }
1664
1665 long userId = GetterUtil.getLong(name);
1666
1667 User user = userPersistence.findByPrimaryKey(userId);
1668
1669 try {
1670 password = Encryptor.decrypt(company.getKeyObj(), password);
1671 }
1672 catch (EncryptorException ee) {
1673 throw new SystemException(ee);
1674 }
1675
1676 String encPassword = PwdEncryptor.encrypt(password);
1677
1678 if (user.getPassword().equals(encPassword)) {
1679 if (isPasswordExpired(user)) {
1680 user.setPasswordReset(true);
1681
1682 userPersistence.update(user);
1683 }
1684
1685 return new KeyValuePair(name, password);
1686 }
1687 else {
1688 throw new PrincipalException();
1689 }
1690 }
1691
1692
1700 public void deletePortrait(long userId)
1701 throws PortalException, SystemException {
1702
1703 User user = userPersistence.findByPrimaryKey(userId);
1704
1705 long portraitId = user.getPortraitId();
1706
1707 if (portraitId > 0) {
1708 user.setPortraitId(0);
1709
1710 userPersistence.update(user);
1711
1712 imageLocalService.deleteImage(portraitId);
1713 }
1714 }
1715
1716
1725 public void deleteRoleUser(long roleId, long userId)
1726 throws PortalException, SystemException {
1727
1728 rolePersistence.removeUser(roleId, userId);
1729
1730 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1731
1732 indexer.reindex(userId);
1733
1734 PermissionCacheUtil.clearCache();
1735 }
1736
1737
1745 @Override
1746 public User deleteUser(long userId)
1747 throws PortalException, SystemException {
1748
1749 User user = userPersistence.findByPrimaryKey(userId);
1750
1751 return deleteUser(user);
1752 }
1753
1754
1762 @Override
1763 public User deleteUser(User user) throws PortalException, SystemException {
1764 if (!PropsValues.USERS_DELETE) {
1765 throw new RequiredUserException();
1766 }
1767
1768
1769
1770 browserTrackerLocalService.deleteUserBrowserTracker(user.getUserId());
1771
1772
1773
1774 Group group = user.getGroup();
1775
1776 if (group != null) {
1777 groupLocalService.deleteGroup(group);
1778 }
1779
1780
1781
1782 imageLocalService.deleteImage(user.getPortraitId());
1783
1784
1785
1786 passwordPolicyRelLocalService.deletePasswordPolicyRel(
1787 User.class.getName(), user.getUserId());
1788
1789
1790
1791 passwordTrackerLocalService.deletePasswordTrackers(user.getUserId());
1792
1793
1794
1795 subscriptionLocalService.deleteSubscriptions(user.getUserId());
1796
1797
1798
1799 userIdMapperLocalService.deleteUserIdMappers(user.getUserId());
1800
1801
1802
1803 announcementsDeliveryLocalService.deleteDeliveries(user.getUserId());
1804
1805
1806
1807 assetEntryLocalService.deleteEntry(
1808 User.class.getName(), user.getUserId());
1809
1810
1811
1812 blogsStatsUserLocalService.deleteStatsUserByUserId(user.getUserId());
1813
1814
1815
1816 dlFileRankLocalService.deleteFileRanksByUserId(user.getUserId());
1817
1818
1819
1820 expandoValueLocalService.deleteValues(
1821 User.class.getName(), user.getUserId());
1822
1823
1824
1825 mbBanLocalService.deleteBansByBanUserId(user.getUserId());
1826 mbStatsUserLocalService.deleteStatsUsersByUserId(user.getUserId());
1827 mbThreadFlagLocalService.deleteThreadFlagsByUserId(user.getUserId());
1828
1829
1830
1831 membershipRequestLocalService.deleteMembershipRequestsByUserId(
1832 user.getUserId());
1833
1834
1835
1836 shoppingCartLocalService.deleteUserCarts(user.getUserId());
1837
1838
1839
1840 socialActivityLocalService.deleteUserActivities(user.getUserId());
1841 socialRequestLocalService.deleteReceiverUserRequests(user.getUserId());
1842 socialRequestLocalService.deleteUserRequests(user.getUserId());
1843
1844
1845
1846 mailService.deleteUser(user.getCompanyId(), user.getUserId());
1847
1848
1849
1850 try {
1851 contactLocalService.deleteContact(user.getContactId());
1852 }
1853 catch (NoSuchContactException nsce) {
1854 }
1855
1856
1857
1858 resourceLocalService.deleteResource(
1859 user.getCompanyId(), User.class.getName(),
1860 ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
1861
1862
1863
1864 userGroupRoleLocalService.deleteUserGroupRolesByUserId(
1865 user.getUserId());
1866
1867
1868
1869 userPersistence.remove(user);
1870
1871
1872
1873 PermissionCacheUtil.clearCache();
1874
1875
1876
1877 workflowInstanceLinkLocalService.deleteWorkflowInstanceLinks(
1878 user.getCompanyId(), 0, User.class.getName(), user.getUserId());
1879
1880 return user;
1881 }
1882
1883
1891 public void deleteUserGroupUser(long userGroupId, long userId)
1892 throws PortalException, SystemException {
1893
1894 userGroupPersistence.removeUser(userGroupId, userId);
1895
1896 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1897
1898 indexer.reindex(userId);
1899
1900 PermissionCacheUtil.clearCache();
1901 }
1902
1903
1912 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1913 public String encryptUserId(String name)
1914 throws PortalException, SystemException {
1915
1916 long userId = GetterUtil.getLong(name);
1917
1918 User user = userPersistence.findByPrimaryKey(userId);
1919
1920 Company company = companyPersistence.findByPrimaryKey(
1921 user.getCompanyId());
1922
1923 try {
1924 return Encryptor.encrypt(company.getKeyObj(), name);
1925 }
1926 catch (EncryptorException ee) {
1927 throw new SystemException(ee);
1928 }
1929 }
1930
1931
1940 public User fetchUserByEmailAddress(long companyId, String emailAddress)
1941 throws SystemException {
1942
1943 return userPersistence.fetchByC_EA(companyId, emailAddress);
1944 }
1945
1946
1954 public User fetchUserById(long userId) throws SystemException {
1955 return userPersistence.fetchByPrimaryKey(userId);
1956 }
1957
1958
1967 public User fetchUserByScreenName(long companyId, String screenName)
1968 throws SystemException {
1969
1970 screenName = getScreenName(screenName);
1971
1972 return userPersistence.fetchByC_SN(companyId, screenName);
1973 }
1974
1975
1994 public List<User> getCompanyUsers(long companyId, int start, int end)
1995 throws SystemException {
1996
1997 return userPersistence.findByCompanyId(companyId, start, end);
1998 }
1999
2000
2007 public int getCompanyUsersCount(long companyId) throws SystemException {
2008 return userPersistence.countByCompanyId(companyId);
2009 }
2010
2011
2020 @Skip
2021 public User getDefaultUser(long companyId)
2022 throws PortalException, SystemException {
2023
2024 User userModel = _defaultUsers.get(companyId);
2025
2026 if (userModel == null) {
2027 userModel = userLocalService.loadGetDefaultUser(companyId);
2028
2029 _defaultUsers.put(companyId, userModel);
2030 }
2031
2032 return userModel;
2033 }
2034
2035
2044 @Skip
2045 public long getDefaultUserId(long companyId)
2046 throws PortalException, SystemException {
2047
2048 User user = getDefaultUser(companyId);
2049
2050 return user.getUserId();
2051 }
2052
2053
2060 public long[] getGroupUserIds(long groupId) throws SystemException {
2061 return getUserIds(getGroupUsers(groupId));
2062 }
2063
2064
2071 public List<User> getGroupUsers(long groupId) throws SystemException {
2072 return groupPersistence.getUsers(groupId);
2073 }
2074
2075
2082 public int getGroupUsersCount(long groupId) throws SystemException {
2083 return groupPersistence.getUsersSize(groupId);
2084 }
2085
2086
2096 public int getGroupUsersCount(long groupId, int status)
2097 throws PortalException, SystemException {
2098
2099 Group group = groupPersistence.findByPrimaryKey(groupId);
2100
2101 LinkedHashMap<String, Object> params =
2102 new LinkedHashMap<String, Object>();
2103
2104 params.put("usersGroups", new Long(groupId));
2105
2106 return searchCount(group.getCompanyId(), null, status, params);
2107 }
2108
2109
2117 public List<User> getNoAnnouncementsDeliveries(String type)
2118 throws SystemException {
2119
2120 return userFinder.findByNoAnnouncementsDeliveries(type);
2121 }
2122
2123
2129 public List<User> getNoContacts() throws SystemException {
2130 return userFinder.findByNoContacts();
2131 }
2132
2133
2140 public List<User> getNoGroups() throws SystemException {
2141 return userFinder.findByNoGroups();
2142 }
2143
2144
2151 public long[] getOrganizationUserIds(long organizationId)
2152 throws SystemException {
2153
2154 return getUserIds(getOrganizationUsers(organizationId));
2155 }
2156
2157
2164 public List<User> getOrganizationUsers(long organizationId)
2165 throws SystemException {
2166
2167 return organizationPersistence.getUsers(organizationId);
2168 }
2169
2170
2177 public int getOrganizationUsersCount(long organizationId)
2178 throws SystemException {
2179
2180 return organizationPersistence.getUsersSize(organizationId);
2181 }
2182
2183
2194 public int getOrganizationUsersCount(long organizationId, int status)
2195 throws PortalException, SystemException {
2196
2197 Organization organization = organizationPersistence.findByPrimaryKey(
2198 organizationId);
2199
2200 LinkedHashMap<String, Object> params =
2201 new LinkedHashMap<String, Object>();
2202
2203 params.put("usersOrgs", new Long(organizationId));
2204
2205 return searchCount(organization.getCompanyId(), null, status, params);
2206 }
2207
2208
2215 public long[] getRoleUserIds(long roleId) throws SystemException {
2216 return getUserIds(getRoleUsers(roleId));
2217 }
2218
2219
2226 public List<User> getRoleUsers(long roleId) throws SystemException {
2227 return rolePersistence.getUsers(roleId);
2228 }
2229
2230
2249 public List<User> getRoleUsers(long roleId, int start, int end)
2250 throws SystemException {
2251
2252 return rolePersistence.getUsers(roleId, start, end);
2253 }
2254
2255
2262 public int getRoleUsersCount(long roleId) throws SystemException {
2263 return rolePersistence.getUsersSize(roleId);
2264 }
2265
2266
2276 public int getRoleUsersCount(long roleId, int status)
2277 throws PortalException, SystemException {
2278
2279 Role role = rolePersistence.findByPrimaryKey(roleId);
2280
2281 LinkedHashMap<String, Object> params =
2282 new LinkedHashMap<String, Object>();
2283
2284 params.put("usersRoles", new Long(roleId));
2285
2286 return searchCount(role.getCompanyId(), null, status, params);
2287 }
2288
2289
2316 public List<User> getSocialUsers(
2317 long userId, int type, int start, int end, OrderByComparator obc)
2318 throws PortalException, SystemException {
2319
2320 User user = userPersistence.findByPrimaryKey(userId);
2321
2322 LinkedHashMap<String, Object> params =
2323 new LinkedHashMap<String, Object>();
2324
2325 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2326
2327 return search(
2328 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2329 params, start, end, obc);
2330 }
2331
2332
2355 public List<User> getSocialUsers(
2356 long userId, int start, int end, OrderByComparator obc)
2357 throws PortalException, SystemException {
2358
2359 User user = userPersistence.findByPrimaryKey(userId);
2360
2361 LinkedHashMap<String, Object> params =
2362 new LinkedHashMap<String, Object>();
2363
2364 params.put("socialRelation", new Long[] {userId});
2365
2366 return search(
2367 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2368 params, start, end, obc);
2369 }
2370
2371
2399 public List<User> getSocialUsers(
2400 long userId1, long userId2, int type, int start, int end,
2401 OrderByComparator obc)
2402 throws PortalException, SystemException {
2403
2404 User user1 = userPersistence.findByPrimaryKey(userId1);
2405
2406 LinkedHashMap<String, Object> params =
2407 new LinkedHashMap<String, Object>();
2408
2409 params.put(
2410 "socialMutualRelationType",
2411 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2412
2413 return search(
2414 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2415 params, start, end, obc);
2416 }
2417
2418
2443 public List<User> getSocialUsers(
2444 long userId1, long userId2, int start, int end,
2445 OrderByComparator obc)
2446 throws PortalException, SystemException {
2447
2448 User user1 = userPersistence.findByPrimaryKey(userId1);
2449
2450 LinkedHashMap<String, Object> params =
2451 new LinkedHashMap<String, Object>();
2452
2453 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2454
2455 return search(
2456 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2457 params, start, end, obc);
2458 }
2459
2460
2468 public int getSocialUsersCount(long userId)
2469 throws PortalException, SystemException {
2470
2471 User user = userPersistence.findByPrimaryKey(userId);
2472
2473 LinkedHashMap<String, Object> params =
2474 new LinkedHashMap<String, Object>();
2475
2476 params.put("socialRelation", new Long[] {userId});
2477
2478 return searchCount(
2479 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2480 params);
2481 }
2482
2483
2496 public int getSocialUsersCount(long userId, int type)
2497 throws PortalException, SystemException {
2498
2499 User user = userPersistence.findByPrimaryKey(userId);
2500
2501 LinkedHashMap<String, Object> params =
2502 new LinkedHashMap<String, Object>();
2503
2504 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2505
2506 return searchCount(
2507 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2508 params);
2509 }
2510
2511
2521 public int getSocialUsersCount(long userId1, long userId2)
2522 throws PortalException, SystemException {
2523
2524 User user1 = userPersistence.findByPrimaryKey(userId1);
2525
2526 LinkedHashMap<String, Object> params =
2527 new LinkedHashMap<String, Object>();
2528
2529 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2530
2531 return searchCount(
2532 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2533 params);
2534 }
2535
2536
2550 public int getSocialUsersCount(long userId1, long userId2, int type)
2551 throws PortalException, SystemException {
2552
2553 User user1 = userPersistence.findByPrimaryKey(userId1);
2554
2555 LinkedHashMap<String, Object> params =
2556 new LinkedHashMap<String, Object>();
2557
2558 params.put(
2559 "socialMutualRelationType",
2560 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2561
2562 return searchCount(
2563 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2564 params);
2565 }
2566
2567
2575 public User getUserByContactId(long contactId)
2576 throws PortalException, SystemException {
2577
2578 return userPersistence.findByContactId(contactId);
2579 }
2580
2581
2591 public User getUserByEmailAddress(long companyId, String emailAddress)
2592 throws PortalException, SystemException {
2593
2594 emailAddress = emailAddress.trim().toLowerCase();
2595
2596 return userPersistence.findByC_EA(companyId, emailAddress);
2597 }
2598
2599
2608 public User getUserByFacebookId(long companyId, long facebookId)
2609 throws PortalException, SystemException {
2610
2611 return userPersistence.findByC_FID(companyId, facebookId);
2612 }
2613
2614
2622 public User getUserById(long userId)
2623 throws PortalException, SystemException {
2624
2625 return userPersistence.findByPrimaryKey(userId);
2626 }
2627
2628
2638 public User getUserById(long companyId, long userId)
2639 throws PortalException, SystemException {
2640
2641 return userPersistence.findByC_U(companyId, userId);
2642 }
2643
2644
2653 public User getUserByOpenId(long companyId, String openId)
2654 throws PortalException, SystemException {
2655
2656 return userPersistence.findByC_O(companyId, openId);
2657 }
2658
2659
2667 public User getUserByPortraitId(long portraitId)
2668 throws PortalException, SystemException {
2669
2670 return userPersistence.findByPortraitId(portraitId);
2671 }
2672
2673
2682 public User getUserByScreenName(long companyId, String screenName)
2683 throws PortalException, SystemException {
2684
2685 screenName = getScreenName(screenName);
2686
2687 return userPersistence.findByC_SN(companyId, screenName);
2688 }
2689
2690
2699 public User getUserByUuid(String uuid)
2700 throws PortalException, SystemException {
2701
2702 List<User> users = userPersistence.findByUuid(uuid);
2703
2704 if (users.isEmpty()) {
2705 throw new NoSuchUserException();
2706 }
2707 else {
2708 return users.get(0);
2709 }
2710 }
2711
2712
2721 public User getUserByUuidAndCompanyId(String uuid, long companyId)
2722 throws PortalException, SystemException {
2723
2724 List<User> users = userPersistence.findByUuid_C(uuid, companyId);
2725
2726 if (users.isEmpty()) {
2727 throw new NoSuchUserException();
2728 }
2729 else {
2730 return users.get(0);
2731 }
2732 }
2733
2734
2741 public List<User> getUserGroupUsers(long userGroupId)
2742 throws SystemException {
2743
2744 return userGroupPersistence.getUsers(userGroupId);
2745 }
2746
2747
2754 public int getUserGroupUsersCount(long userGroupId) throws SystemException {
2755 return userGroupPersistence.getUsersSize(userGroupId);
2756 }
2757
2758
2768 public int getUserGroupUsersCount(long userGroupId, int status)
2769 throws PortalException, SystemException {
2770
2771 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
2772 userGroupId);
2773
2774 LinkedHashMap<String, Object> params =
2775 new LinkedHashMap<String, Object>();
2776
2777 params.put("usersUserGroups", new Long(userGroupId));
2778
2779 return searchCount(userGroup.getCompanyId(), null, status, params);
2780 }
2781
2782
2792 public long getUserIdByEmailAddress(long companyId, String emailAddress)
2793 throws PortalException, SystemException {
2794
2795 emailAddress = emailAddress.trim().toLowerCase();
2796
2797 User user = userPersistence.findByC_EA(companyId, emailAddress);
2798
2799 return user.getUserId();
2800 }
2801
2802
2811 public long getUserIdByScreenName(long companyId, String screenName)
2812 throws PortalException, SystemException {
2813
2814 screenName = getScreenName(screenName);
2815
2816 User user = userPersistence.findByC_SN(companyId, screenName);
2817
2818 return user.getUserId();
2819 }
2820
2821
2830 public boolean hasGroupUser(long groupId, long userId)
2831 throws SystemException {
2832
2833 return groupPersistence.containsUser(groupId, userId);
2834 }
2835
2836
2845 public boolean hasOrganizationUser(long organizationId, long userId)
2846 throws SystemException {
2847
2848 return organizationPersistence.containsUser(organizationId, userId);
2849 }
2850
2851
2861 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
2862 throws SystemException {
2863
2864 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
2865 passwordPolicyId, User.class.getName(), userId);
2866 }
2867
2868
2877 public boolean hasRoleUser(long roleId, long userId)
2878 throws SystemException {
2879
2880 return rolePersistence.containsUser(roleId, userId);
2881 }
2882
2883
2898 public boolean hasRoleUser(
2899 long companyId, String name, long userId, boolean inherited)
2900 throws PortalException, SystemException {
2901
2902 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
2903 }
2904
2905
2914 public boolean hasTeamUser(long teamId, long userId)
2915 throws SystemException {
2916
2917 return teamPersistence.containsUser(teamId, userId);
2918 }
2919
2920
2929 public boolean hasUserGroupUser(long userGroupId, long userId)
2930 throws SystemException {
2931
2932 return userGroupPersistence.containsUser(userGroupId, userId);
2933 }
2934
2935
2945 public boolean isPasswordExpired(User user)
2946 throws PortalException, SystemException {
2947
2948 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2949
2950 if ((passwordPolicy != null) && passwordPolicy.getExpireable()) {
2951 Date now = new Date();
2952
2953 if (user.getPasswordModifiedDate() == null) {
2954 user.setPasswordModifiedDate(now);
2955
2956 userLocalService.updateUser(user);
2957 }
2958
2959 long passwordStartTime = user.getPasswordModifiedDate().getTime();
2960 long elapsedTime = now.getTime() - passwordStartTime;
2961
2962 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
2963 return true;
2964 }
2965 else {
2966 return false;
2967 }
2968 }
2969
2970 return false;
2971 }
2972
2973
2985 public boolean isPasswordExpiringSoon(User user)
2986 throws PortalException, SystemException {
2987
2988 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2989
2990 if ((passwordPolicy != null) && passwordPolicy.isExpireable() &&
2991 (passwordPolicy.getWarningTime() > 0)) {
2992
2993 Date now = new Date();
2994
2995 if (user.getPasswordModifiedDate() == null) {
2996 user.setPasswordModifiedDate(now);
2997
2998 userLocalService.updateUser(user);
2999 }
3000
3001 long timeModified = user.getPasswordModifiedDate().getTime();
3002 long passwordExpiresOn =
3003 (passwordPolicy.getMaxAge() * 1000) + timeModified;
3004
3005 long timeStartWarning =
3006 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
3007
3008 if (now.getTime() > timeStartWarning) {
3009 return true;
3010 }
3011 else {
3012 return false;
3013 }
3014 }
3015
3016 return false;
3017 }
3018
3019
3027 public User loadGetDefaultUser(long companyId)
3028 throws PortalException, SystemException {
3029
3030 return userPersistence.findByC_DU(companyId, true);
3031 }
3032
3033
3065 public List<User> search(
3066 long companyId, String keywords, int status,
3067 LinkedHashMap<String, Object> params, int start, int end,
3068 OrderByComparator obc)
3069 throws SystemException {
3070
3071 return userFinder.findByKeywords(
3072 companyId, keywords, status, params, start, end, obc);
3073 }
3074
3075
3106 public Hits search(
3107 long companyId, String keywords, int status,
3108 LinkedHashMap<String, Object> params, int start, int end, Sort sort)
3109 throws SystemException {
3110
3111 String firstName = null;
3112 String middleName = null;
3113 String lastName = null;
3114 String fullName = null;
3115 String screenName = null;
3116 String emailAddress = null;
3117 String street = null;
3118 String city = null;
3119 String zip = null;
3120 String region = null;
3121 String country = null;
3122 boolean andOperator = false;
3123
3124 if (Validator.isNotNull(keywords)) {
3125 firstName = keywords;
3126 middleName = keywords;
3127 lastName = keywords;
3128 fullName = keywords;
3129 screenName = keywords;
3130 emailAddress = keywords;
3131 street = keywords;
3132 city = keywords;
3133 zip = keywords;
3134 region = keywords;
3135 country = keywords;
3136 }
3137 else {
3138 andOperator = true;
3139 }
3140
3141 if (params != null) {
3142 params.put("keywords", keywords);
3143 }
3144
3145 return search(
3146 companyId, firstName, middleName, lastName, fullName, screenName,
3147 emailAddress, street, city, zip, region, country, status, params,
3148 andOperator, start, end, sort);
3149 }
3150
3151
3191 public List<User> search(
3192 long companyId, String firstName, String middleName,
3193 String lastName, String screenName, String emailAddress, int status,
3194 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3195 int end, OrderByComparator obc)
3196 throws SystemException {
3197
3198 return userFinder.findByC_FN_MN_LN_SN_EA_S(
3199 companyId, firstName, middleName, lastName, screenName,
3200 emailAddress, status, params, andSearch, start, end, obc);
3201 }
3202
3203
3242 public Hits search(
3243 long companyId, String firstName, String middleName,
3244 String lastName, String screenName, String emailAddress, int status,
3245 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3246 int end, Sort sort)
3247 throws SystemException {
3248
3249 return search(
3250 companyId, firstName, middleName, lastName, null, screenName,
3251 emailAddress, null, null, null, null, null, status, params,
3252 andSearch, start, end, sort);
3253 }
3254
3255
3269 public int searchCount(
3270 long companyId, String keywords, int status,
3271 LinkedHashMap<String, Object> params)
3272 throws SystemException {
3273
3274 return userFinder.countByKeywords(companyId, keywords, status, params);
3275 }
3276
3277
3299 public int searchCount(
3300 long companyId, String firstName, String middleName,
3301 String lastName, String screenName, String emailAddress, int status,
3302 LinkedHashMap<String, Object> params, boolean andSearch)
3303 throws SystemException {
3304
3305 return userFinder.countByC_FN_MN_LN_SN_EA_S(
3306 companyId, firstName, middleName, lastName, screenName,
3307 emailAddress, status, params, andSearch);
3308 }
3309
3310
3321 public void sendEmailAddressVerification(
3322 User user, String emailAddress, ServiceContext serviceContext)
3323 throws PortalException, SystemException {
3324
3325 if (user.isEmailAddressVerified() &&
3326 emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
3327
3328 return;
3329 }
3330
3331 Ticket ticket = ticketLocalService.addTicket(
3332 user.getCompanyId(), User.class.getName(), user.getUserId(),
3333 TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3334 serviceContext);
3335
3336 String verifyEmailAddressURL =
3337 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3338 "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3339
3340 Layout layout = layoutLocalService.getLayout(serviceContext.getPlid());
3341
3342 Group group = layout.getGroup();
3343
3344 if (!layout.isPrivateLayout() && !group.isUser()) {
3345 verifyEmailAddressURL += "&p_l_id=" + serviceContext.getPlid();
3346 }
3347
3348 String fromName = PrefsPropsUtil.getString(
3349 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3350 String fromAddress = PrefsPropsUtil.getString(
3351 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3352
3353 String toName = user.getFullName();
3354 String toAddress = emailAddress;
3355
3356 String subject = PrefsPropsUtil.getContent(
3357 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3358
3359 String body = PrefsPropsUtil.getContent(
3360 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3361
3362 SubscriptionSender subscriptionSender = new SubscriptionSender();
3363
3364 subscriptionSender.setBody(body);
3365 subscriptionSender.setCompanyId(user.getCompanyId());
3366 subscriptionSender.setContextAttributes(
3367 "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3368 "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3369 "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3370 "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_ID$]",
3371 user.getUserId(), "[$USER_SCREENNAME$]", user.getScreenName());
3372 subscriptionSender.setFrom(fromAddress, fromName);
3373 subscriptionSender.setHtmlFormat(true);
3374 subscriptionSender.setMailId("user", user.getUserId());
3375 subscriptionSender.setServiceContext(serviceContext);
3376 subscriptionSender.setSubject(subject);
3377 subscriptionSender.setUserId(user.getUserId());
3378
3379 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3380
3381 subscriptionSender.flushNotificationsAsync();
3382 }
3383
3384
3403 public void sendPassword(
3404 long companyId, String emailAddress, String fromName,
3405 String fromAddress, String subject, String body,
3406 ServiceContext serviceContext)
3407 throws PortalException, SystemException {
3408
3409 Company company = companyPersistence.findByPrimaryKey(companyId);
3410
3411 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3412 return;
3413 }
3414
3415 emailAddress = emailAddress.trim().toLowerCase();
3416
3417 if (Validator.isNull(emailAddress)) {
3418 throw new UserEmailAddressException();
3419 }
3420
3421 User user = userPersistence.findByC_EA(companyId, emailAddress);
3422
3423 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3424
3425 String newPassword = StringPool.BLANK;
3426 String passwordResetURL = StringPool.BLANK;
3427
3428 if (company.isSendPasswordResetLink()) {
3429 Date expirationDate = null;
3430
3431 if ((passwordPolicy != null) &&
3432 (passwordPolicy.getResetTicketMaxAge() > 0)) {
3433
3434 expirationDate = new Date(
3435 System.currentTimeMillis() +
3436 (passwordPolicy.getResetTicketMaxAge() * 1000));
3437 }
3438
3439 Ticket ticket = ticketLocalService.addTicket(
3440 companyId, User.class.getName(), user.getUserId(),
3441 TicketConstants.TYPE_PASSWORD, null, expirationDate,
3442 serviceContext);
3443
3444 passwordResetURL =
3445 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3446 "/portal/update_password?p_l_id="+
3447 serviceContext.getPlid() +
3448 "&ticketKey=" + ticket.getKey();
3449 }
3450 else {
3451 if (!PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
3452 PwdEncryptor.TYPE_NONE)) {
3453
3454 if (LDAPSettingsUtil.isPasswordPolicyEnabled(
3455 user.getCompanyId())) {
3456
3457 if (_log.isWarnEnabled()) {
3458 StringBundler sb = new StringBundler(5);
3459
3460 sb.append("When LDAP password policy is enabled, ");
3461 sb.append("it is possible that portal generated ");
3462 sb.append("passwords will not match the LDAP policy.");
3463 sb.append("Using RegExpToolkit to generate new ");
3464 sb.append("password.");
3465
3466 _log.warn(sb.toString());
3467 }
3468
3469 RegExpToolkit regExpToolkit = new RegExpToolkit();
3470
3471 newPassword = regExpToolkit.generate(null);
3472 }
3473 else {
3474 newPassword = PwdToolkitUtil.generate(passwordPolicy);
3475 }
3476
3477 boolean passwordReset = false;
3478
3479 if (passwordPolicy.getChangeable() &&
3480 passwordPolicy.getChangeRequired()) {
3481
3482 passwordReset = true;
3483 }
3484
3485 user.setPassword(PwdEncryptor.encrypt(newPassword));
3486 user.setPasswordUnencrypted(newPassword);
3487 user.setPasswordEncrypted(true);
3488 user.setPasswordReset(passwordReset);
3489 user.setPasswordModified(true);
3490 user.setPasswordModifiedDate(new Date());
3491
3492 userPersistence.update(user);
3493
3494 user.setPasswordModified(false);
3495 }
3496 else {
3497 newPassword = user.getPassword();
3498 }
3499 }
3500
3501 if (Validator.isNull(fromName)) {
3502 fromName = PrefsPropsUtil.getString(
3503 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3504 }
3505
3506 if (Validator.isNull(fromAddress)) {
3507 fromAddress = PrefsPropsUtil.getString(
3508 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3509 }
3510
3511 String toName = user.getFullName();
3512 String toAddress = user.getEmailAddress();
3513
3514 if (Validator.isNull(subject)) {
3515 if (company.isSendPasswordResetLink()) {
3516 subject = PrefsPropsUtil.getContent(
3517 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
3518 }
3519 else {
3520 subject = PrefsPropsUtil.getContent(
3521 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
3522 }
3523 }
3524
3525 if (Validator.isNull(body)) {
3526 if (company.isSendPasswordResetLink()) {
3527 body = PrefsPropsUtil.getContent(
3528 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
3529 }
3530 else {
3531 body = PrefsPropsUtil.getContent(
3532 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
3533 }
3534 }
3535
3536 SubscriptionSender subscriptionSender = new SubscriptionSender();
3537
3538 subscriptionSender.setBody(body);
3539 subscriptionSender.setCompanyId(companyId);
3540 subscriptionSender.setContextAttributes(
3541 "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
3542 serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
3543 serviceContext.getRemoteHost(), "[$USER_ID$]", user.getUserId(),
3544 "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
3545 user.getScreenName());
3546 subscriptionSender.setFrom(fromAddress, fromName);
3547 subscriptionSender.setHtmlFormat(true);
3548 subscriptionSender.setMailId("user", user.getUserId());
3549 subscriptionSender.setServiceContext(serviceContext);
3550 subscriptionSender.setSubject(subject);
3551 subscriptionSender.setUserId(user.getUserId());
3552
3553 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3554
3555 subscriptionSender.flushNotificationsAsync();
3556 }
3557
3558
3567 public void setRoleUsers(long roleId, long[] userIds)
3568 throws PortalException, SystemException {
3569
3570 rolePersistence.setUsers(roleId, userIds);
3571
3572 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3573
3574 indexer.reindex(userIds);
3575
3576 PermissionCacheUtil.clearCache();
3577 }
3578
3579
3588 @SuppressWarnings("deprecation")
3589 public void setUserGroupUsers(long userGroupId, long[] userIds)
3590 throws PortalException, SystemException {
3591
3592 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3593 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3594 }
3595
3596 userGroupPersistence.setUsers(userGroupId, userIds);
3597
3598 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3599
3600 indexer.reindex(userIds);
3601
3602 PermissionCacheUtil.clearCache();
3603 }
3604
3605
3613 public void unsetGroupTeamsUsers(long groupId, long[] userIds)
3614 throws PortalException, SystemException {
3615
3616 List<Team> teams = teamPersistence.findByGroupId(groupId);
3617
3618 for (Team team : teams) {
3619 unsetTeamUsers(team.getTeamId(), userIds);
3620 }
3621
3622 PermissionCacheUtil.clearCache();
3623 }
3624
3625
3634 public void unsetGroupUsers(
3635 long groupId, long[] userIds, ServiceContext serviceContext)
3636 throws PortalException, SystemException {
3637
3638 userGroupRoleLocalService.deleteUserGroupRoles(
3639 userIds, groupId, RoleConstants.TYPE_SITE);
3640
3641 userLocalService.unsetGroupTeamsUsers(groupId, userIds);
3642
3643 groupPersistence.removeUsers(groupId, userIds);
3644
3645 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3646
3647 indexer.reindex(userIds);
3648
3649 PermissionCacheUtil.clearCache();
3650 }
3651
3652
3660 public void unsetOrganizationUsers(long organizationId, long[] userIds)
3661 throws PortalException, SystemException {
3662
3663 Organization organization = organizationPersistence.findByPrimaryKey(
3664 organizationId);
3665
3666 Group group = organization.getGroup();
3667
3668 userGroupRoleLocalService.deleteUserGroupRoles(
3669 userIds, group.getGroupId(), RoleConstants.TYPE_ORGANIZATION);
3670
3671 organizationPersistence.removeUsers(organizationId, userIds);
3672
3673 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3674
3675 indexer.reindex(userIds);
3676
3677 PermissionCacheUtil.clearCache();
3678 }
3679
3680
3687 public void unsetPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
3688 throws SystemException {
3689
3690 passwordPolicyRelLocalService.deletePasswordPolicyRels(
3691 passwordPolicyId, User.class.getName(), userIds);
3692 }
3693
3694
3702 public void unsetRoleUsers(long roleId, List<User> users)
3703 throws PortalException, SystemException {
3704
3705 Role role = rolePersistence.findByPrimaryKey(roleId);
3706
3707 String roleName = role.getName();
3708
3709 if ((roleName.equals(RoleConstants.ADMINISTRATOR) &&
3710 (getRoleUsersCount(role.getRoleId()) <= 1)) ||
3711 roleName.equals(RoleConstants.USER)) {
3712
3713 return;
3714 }
3715
3716 rolePersistence.removeUsers(roleId, users);
3717
3718 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3719
3720 indexer.reindex(users);
3721
3722 PermissionCacheUtil.clearCache();
3723 }
3724
3725
3733 public void unsetRoleUsers(long roleId, long[] userIds)
3734 throws PortalException, SystemException {
3735
3736 Role role = rolePersistence.findByPrimaryKey(roleId);
3737
3738 String roleName = role.getName();
3739
3740 if (roleName.equals(RoleConstants.USER) ||
3741 (roleName.equals(RoleConstants.ADMINISTRATOR) &&
3742 getRoleUsersCount(role.getRoleId()) <= 1)) {
3743
3744 return;
3745 }
3746
3747 rolePersistence.removeUsers(roleId, userIds);
3748
3749 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3750
3751 indexer.reindex(userIds);
3752
3753 PermissionCacheUtil.clearCache();
3754 }
3755
3756
3764 public void unsetTeamUsers(long teamId, long[] userIds)
3765 throws PortalException, SystemException {
3766
3767 teamPersistence.removeUsers(teamId, userIds);
3768
3769 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3770
3771 indexer.reindex(userIds);
3772
3773 PermissionCacheUtil.clearCache();
3774 }
3775
3776
3784 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
3785 throws PortalException, SystemException {
3786
3787 userGroupPersistence.removeUsers(userGroupId, userIds);
3788
3789 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3790
3791 indexer.reindex(userIds);
3792
3793 PermissionCacheUtil.clearCache();
3794 }
3795
3796
3806 public User updateAgreedToTermsOfUse(
3807 long userId, boolean agreedToTermsOfUse)
3808 throws PortalException, SystemException {
3809
3810 User user = userPersistence.findByPrimaryKey(userId);
3811
3812 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
3813
3814 userPersistence.update(user);
3815
3816 return user;
3817 }
3818
3819
3830 public void updateAsset(
3831 long userId, User user, long[] assetCategoryIds,
3832 String[] assetTagNames)
3833 throws PortalException, SystemException {
3834
3835 User owner = userPersistence.findByPrimaryKey(userId);
3836
3837 Company company = companyPersistence.findByPrimaryKey(
3838 owner.getCompanyId());
3839
3840 Group companyGroup = company.getGroup();
3841
3842 assetEntryLocalService.updateEntry(
3843 userId, companyGroup.getGroupId(), user.getCreateDate(),
3844 user.getModifiedDate(), User.class.getName(), user.getUserId(),
3845 user.getUuid(), 0, assetCategoryIds, assetTagNames, false, null,
3846 null, null, null, user.getFullName(), null, null, null, null, 0, 0,
3847 null, false);
3848 }
3849
3850
3859 public User updateCreateDate(long userId, Date createDate)
3860 throws PortalException, SystemException {
3861
3862 User user = userPersistence.findByPrimaryKey(userId);
3863
3864 user.setCreateDate(createDate);
3865
3866 userPersistence.update(user);
3867
3868 return user;
3869 }
3870
3871
3882 public User updateEmailAddress(
3883 long userId, String password, String emailAddress1,
3884 String emailAddress2)
3885 throws PortalException, SystemException {
3886
3887 emailAddress1 = emailAddress1.trim().toLowerCase();
3888 emailAddress2 = emailAddress2.trim().toLowerCase();
3889
3890 User user = userPersistence.findByPrimaryKey(userId);
3891
3892 validateEmailAddress(user, emailAddress1, emailAddress2);
3893
3894 setEmailAddress(
3895 user, password, user.getFirstName(), user.getMiddleName(),
3896 user.getLastName(), emailAddress1);
3897
3898 userPersistence.update(user);
3899
3900 Contact contact = user.getContact();
3901
3902 contact.setEmailAddress(user.getEmailAddress());
3903
3904 contactPersistence.update(contact);
3905
3906 return user;
3907 }
3908
3909
3923 public User updateEmailAddress(
3924 long userId, String password, String emailAddress1,
3925 String emailAddress2, ServiceContext serviceContext)
3926 throws PortalException, SystemException {
3927
3928 emailAddress1 = emailAddress1.trim().toLowerCase();
3929 emailAddress2 = emailAddress2.trim().toLowerCase();
3930
3931 User user = userPersistence.findByPrimaryKey(userId);
3932
3933 validateEmailAddress(user, emailAddress1, emailAddress2);
3934
3935 Company company = companyPersistence.findByPrimaryKey(
3936 user.getCompanyId());
3937
3938 if (!company.isStrangersVerify()) {
3939 setEmailAddress(
3940 user, password, user.getFirstName(), user.getMiddleName(),
3941 user.getLastName(), emailAddress1);
3942
3943 userPersistence.update(user);
3944
3945 Contact contact = user.getContact();
3946
3947 contact.setEmailAddress(user.getEmailAddress());
3948
3949 contactPersistence.update(contact);
3950 }
3951 else {
3952 sendEmailAddressVerification(user, emailAddress1, serviceContext);
3953 }
3954
3955 return user;
3956 }
3957
3958
3967 public User updateEmailAddressVerified(
3968 long userId, boolean emailAddressVerified)
3969 throws PortalException, SystemException {
3970
3971 User user = userPersistence.findByPrimaryKey(userId);
3972
3973 user.setEmailAddressVerified(emailAddressVerified);
3974
3975 userPersistence.update(user);
3976
3977 return user;
3978 }
3979
3980
3989 public User updateFacebookId(long userId, long facebookId)
3990 throws PortalException, SystemException {
3991
3992 User user = userPersistence.findByPrimaryKey(userId);
3993
3994 user.setFacebookId(facebookId);
3995
3996 userPersistence.update(user);
3997
3998 return user;
3999 }
4000
4001
4010 public void updateGroups(
4011 long userId, long[] newGroupIds, ServiceContext serviceContext)
4012 throws PortalException, SystemException {
4013
4014 updateGroups(
4015 userId, newGroupIds, serviceContext,
4016 serviceContext.isIndexingEnabled());
4017 }
4018
4019
4058 public User updateIncompleteUser(
4059 long creatorUserId, long companyId, boolean autoPassword,
4060 String password1, String password2, boolean autoScreenName,
4061 String screenName, String emailAddress, long facebookId,
4062 String openId, Locale locale, String firstName, String middleName,
4063 String lastName, int prefixId, int suffixId, boolean male,
4064 int birthdayMonth, int birthdayDay, int birthdayYear,
4065 String jobTitle, boolean updateUserInformation, boolean sendEmail,
4066 ServiceContext serviceContext)
4067 throws PortalException, SystemException {
4068
4069 User user = getUserByEmailAddress(companyId, emailAddress);
4070
4071 if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
4072 throw new PortalException("Invalid user status");
4073 }
4074
4075 User defaultUser = getDefaultUser(companyId);
4076
4077 if (updateUserInformation) {
4078 autoScreenName = false;
4079
4080 if (PrefsPropsUtil.getBoolean(
4081 companyId,
4082 PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
4083
4084 autoScreenName = true;
4085 }
4086
4087 validate(
4088 companyId, user.getUserId(), autoPassword, password1, password2,
4089 autoScreenName, screenName, emailAddress, openId, firstName,
4090 middleName, lastName, null);
4091
4092 if (!autoPassword) {
4093 if (Validator.isNull(password1) ||
4094 Validator.isNull(password2)) {
4095 throw new UserPasswordException(
4096 UserPasswordException.PASSWORD_INVALID);
4097 }
4098 }
4099
4100 if (autoScreenName) {
4101 ScreenNameGenerator screenNameGenerator =
4102 ScreenNameGeneratorFactory.getInstance();
4103
4104 try {
4105 screenName = screenNameGenerator.generate(
4106 companyId, user.getUserId(), emailAddress);
4107 }
4108 catch (Exception e) {
4109 throw new SystemException(e);
4110 }
4111 }
4112
4113 FullNameGenerator fullNameGenerator =
4114 FullNameGeneratorFactory.getInstance();
4115
4116 String fullName = fullNameGenerator.getFullName(
4117 firstName, middleName, lastName);
4118
4119 String greeting = LanguageUtil.format(
4120 locale, "welcome-x", " " + fullName, false);
4121
4122 if (Validator.isNotNull(password1)) {
4123 user.setPassword(PwdEncryptor.encrypt(password1));
4124 user.setPasswordUnencrypted(password1);
4125 }
4126
4127 user.setPasswordEncrypted(true);
4128
4129 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
4130
4131 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
4132 passwordPolicy.isChangeRequired()) {
4133
4134 user.setPasswordReset(true);
4135 }
4136 else {
4137 user.setPasswordReset(false);
4138 }
4139
4140 user.setScreenName(screenName);
4141 user.setFacebookId(facebookId);
4142 user.setOpenId(openId);
4143 user.setLanguageId(locale.toString());
4144 user.setTimeZoneId(defaultUser.getTimeZoneId());
4145 user.setGreeting(greeting);
4146 user.setFirstName(firstName);
4147 user.setMiddleName(middleName);
4148 user.setLastName(lastName);
4149 user.setJobTitle(jobTitle);
4150 user.setExpandoBridgeAttributes(serviceContext);
4151
4152 Date birthday = getBirthday(
4153 birthdayMonth, birthdayDay, birthdayYear);
4154
4155 Contact contact = user.getContact();
4156
4157 contact.setFirstName(firstName);
4158 contact.setMiddleName(middleName);
4159 contact.setLastName(lastName);
4160 contact.setPrefixId(prefixId);
4161 contact.setSuffixId(suffixId);
4162 contact.setMale(male);
4163 contact.setBirthday(birthday);
4164 contact.setJobTitle(jobTitle);
4165
4166 contactPersistence.update(contact, serviceContext);
4167
4168
4169
4170 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4171 User.class);
4172
4173 indexer.reindex(user);
4174 }
4175
4176 user.setStatus(WorkflowConstants.STATUS_DRAFT);
4177
4178 userPersistence.update(user, serviceContext);
4179
4180
4181
4182 long workflowUserId = creatorUserId;
4183
4184 if (workflowUserId == user.getUserId()) {
4185 workflowUserId = defaultUser.getUserId();
4186 }
4187
4188 ServiceContext workflowServiceContext = serviceContext;
4189
4190 if (workflowServiceContext == null) {
4191 workflowServiceContext = new ServiceContext();
4192 }
4193
4194 workflowServiceContext.setAttribute("autoPassword", autoPassword);
4195 workflowServiceContext.setAttribute("sendEmail", sendEmail);
4196
4197 WorkflowHandlerRegistryUtil.startWorkflowInstance(
4198 companyId, workflowUserId, User.class.getName(), user.getUserId(),
4199 user, workflowServiceContext);
4200
4201 return getUserByEmailAddress(companyId, emailAddress);
4202 }
4203
4204
4214 public User updateJobTitle(long userId, String jobTitle)
4215 throws PortalException, SystemException {
4216
4217 User user = userPersistence.findByPrimaryKey(userId);
4218
4219 user.setJobTitle(jobTitle);
4220
4221 userPersistence.update(user);
4222
4223 Contact contact = contactPersistence.findByPrimaryKey(
4224 user.getContactId());
4225
4226 contact.setJobTitle(jobTitle);
4227
4228 contactPersistence.update(contact);
4229
4230 return user;
4231 }
4232
4233
4242 public User updateLastLogin(long userId, String loginIP)
4243 throws PortalException, SystemException {
4244
4245 User user = userPersistence.findByPrimaryKey(userId);
4246
4247 Date lastLoginDate = user.getLoginDate();
4248
4249 if (lastLoginDate == null) {
4250 lastLoginDate = new Date();
4251 }
4252
4253 user.setLoginDate(new Date());
4254 user.setLoginIP(loginIP);
4255 user.setLastLoginDate(lastLoginDate);
4256 user.setLastLoginIP(user.getLoginIP());
4257 user.setLastFailedLoginDate(null);
4258 user.setFailedLoginAttempts(0);
4259
4260 userPersistence.update(user);
4261
4262 return user;
4263 }
4264
4265
4274 public User updateLockout(User user, boolean lockout)
4275 throws PortalException, SystemException {
4276
4277 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
4278
4279 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
4280 return user;
4281 }
4282
4283 Date lockoutDate = null;
4284
4285 if (lockout) {
4286 lockoutDate = new Date();
4287 }
4288
4289 user.setLockout(lockout);
4290 user.setLockoutDate(lockoutDate);
4291
4292 if (!lockout) {
4293 user.setLastFailedLoginDate(lockoutDate);
4294 user.setFailedLoginAttempts(0);
4295 }
4296
4297 userPersistence.update(user);
4298
4299 return user;
4300 }
4301
4302
4313 public User updateLockoutByEmailAddress(
4314 long companyId, String emailAddress, boolean lockout)
4315 throws PortalException, SystemException {
4316
4317 User user = getUserByEmailAddress(companyId, emailAddress);
4318
4319 return updateLockout(user, lockout);
4320 }
4321
4322
4331 public User updateLockoutById(long userId, boolean lockout)
4332 throws PortalException, SystemException {
4333
4334 User user = userPersistence.findByPrimaryKey(userId);
4335
4336 return updateLockout(user, lockout);
4337 }
4338
4339
4349 public User updateLockoutByScreenName(
4350 long companyId, String screenName, boolean lockout)
4351 throws PortalException, SystemException {
4352
4353 User user = getUserByScreenName(companyId, screenName);
4354
4355 return updateLockout(user, lockout);
4356 }
4357
4358
4367 public User updateModifiedDate(long userId, Date modifiedDate)
4368 throws PortalException, SystemException {
4369
4370 User user = userPersistence.findByPrimaryKey(userId);
4371
4372 user.setModifiedDate(modifiedDate);
4373
4374 userPersistence.update(user);
4375
4376 return user;
4377 }
4378
4379
4388 public User updateOpenId(long userId, String openId)
4389 throws PortalException, SystemException {
4390
4391 openId = openId.trim();
4392
4393 User user = userPersistence.findByPrimaryKey(userId);
4394
4395 user.setOpenId(openId);
4396
4397 userPersistence.update(user);
4398
4399 return user;
4400 }
4401
4402
4413 public void updateOrganizations(
4414 long userId, long[] newOrganizationIds,
4415 ServiceContext serviceContext)
4416 throws PortalException, SystemException {
4417
4418 updateOrganizations(
4419 userId, newOrganizationIds, serviceContext.isIndexingEnabled());
4420 }
4421
4422
4434 public User updatePassword(
4435 long userId, String password1, String password2,
4436 boolean passwordReset)
4437 throws PortalException, SystemException {
4438
4439 return updatePassword(
4440 userId, password1, password2, passwordReset, false);
4441 }
4442
4443
4458 public User updatePassword(
4459 long userId, String password1, String password2,
4460 boolean passwordReset, boolean silentUpdate)
4461 throws PortalException, SystemException {
4462
4463 User user = userPersistence.findByPrimaryKey(userId);
4464
4465 if (!silentUpdate) {
4466 validatePassword(user.getCompanyId(), userId, password1, password2);
4467 }
4468
4469 String oldEncPwd = user.getPassword();
4470
4471 if (!user.isPasswordEncrypted()) {
4472 oldEncPwd = PwdEncryptor.encrypt(user.getPassword());
4473 }
4474
4475 String newEncPwd = PwdEncryptor.encrypt(password1);
4476
4477 if (user.hasCompanyMx()) {
4478 mailService.updatePassword(user.getCompanyId(), userId, password1);
4479 }
4480
4481 user.setPassword(newEncPwd);
4482 user.setPasswordUnencrypted(password1);
4483 user.setPasswordEncrypted(true);
4484 user.setPasswordReset(passwordReset);
4485 user.setPasswordModifiedDate(new Date());
4486 user.setDigest(StringPool.BLANK);
4487 user.setGraceLoginCount(0);
4488
4489 if (!silentUpdate) {
4490 user.setPasswordModified(true);
4491 }
4492
4493 try {
4494 userPersistence.update(user);
4495 }
4496 catch (ModelListenerException mle) {
4497 String msg = GetterUtil.getString(mle.getCause().getMessage());
4498
4499 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
4500 String passwordHistory = PrefsPropsUtil.getString(
4501 user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
4502
4503 if (msg.contains(passwordHistory)) {
4504 throw new UserPasswordException(
4505 UserPasswordException.PASSWORD_ALREADY_USED);
4506 }
4507 }
4508
4509 throw new UserPasswordException(
4510 UserPasswordException.PASSWORD_INVALID);
4511 }
4512
4513 if (!silentUpdate) {
4514 user.setPasswordModified(false);
4515
4516 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
4517 }
4518
4519 return user;
4520 }
4521
4522
4536 public User updatePasswordManually(
4537 long userId, String password, boolean passwordEncrypted,
4538 boolean passwordReset, Date passwordModifiedDate)
4539 throws PortalException, SystemException {
4540
4541
4542
4543 User user = userPersistence.findByPrimaryKey(userId);
4544
4545 user.setPassword(password);
4546 user.setPasswordEncrypted(passwordEncrypted);
4547 user.setPasswordReset(passwordReset);
4548 user.setPasswordModifiedDate(passwordModifiedDate);
4549 user.setDigest(StringPool.BLANK);
4550
4551 userPersistence.update(user);
4552
4553 return user;
4554 }
4555
4556
4567 public User updatePasswordReset(long userId, boolean passwordReset)
4568 throws PortalException, SystemException {
4569
4570 User user = userPersistence.findByPrimaryKey(userId);
4571
4572 user.setPasswordReset(passwordReset);
4573
4574 userPersistence.update(user);
4575
4576 return user;
4577 }
4578
4579
4589 public User updatePortrait(long userId, byte[] bytes)
4590 throws PortalException, SystemException {
4591
4592 User user = userPersistence.findByPrimaryKey(userId);
4593
4594 long imageMaxSize = PrefsPropsUtil.getLong(
4595 PropsKeys.USERS_IMAGE_MAX_SIZE);
4596
4597 if ((imageMaxSize > 0) &&
4598 ((bytes == null) || (bytes.length > imageMaxSize))) {
4599
4600 throw new UserPortraitSizeException();
4601 }
4602
4603 long portraitId = user.getPortraitId();
4604
4605 if (portraitId <= 0) {
4606 portraitId = counterLocalService.increment();
4607
4608 user.setPortraitId(portraitId);
4609 }
4610
4611 try {
4612 ImageBag imageBag = ImageToolUtil.read(bytes);
4613
4614 RenderedImage renderedImage = imageBag.getRenderedImage();
4615
4616 if (renderedImage == null) {
4617 throw new UserPortraitTypeException();
4618 }
4619
4620 renderedImage = ImageToolUtil.scale(
4621 renderedImage, PropsValues.USERS_IMAGE_MAX_HEIGHT,
4622 PropsValues.USERS_IMAGE_MAX_WIDTH);
4623
4624 String contentType = imageBag.getType();
4625
4626 imageLocalService.updateImage(
4627 portraitId,
4628 ImageToolUtil.getBytes(renderedImage, contentType));
4629 }
4630 catch (IOException ioe) {
4631 throw new ImageSizeException(ioe);
4632 }
4633
4634 userPersistence.update(user);
4635
4636 return user;
4637 }
4638
4639
4650 public User updateReminderQuery(long userId, String question, String answer)
4651 throws PortalException, SystemException {
4652
4653 validateReminderQuery(question, answer);
4654
4655 User user = userPersistence.findByPrimaryKey(userId);
4656
4657 user.setReminderQueryQuestion(question);
4658 user.setReminderQueryAnswer(answer);
4659
4660 userPersistence.update(user);
4661
4662 return user;
4663 }
4664
4665
4675 public User updateScreenName(long userId, String screenName)
4676 throws PortalException, SystemException {
4677
4678
4679
4680 User user = userPersistence.findByPrimaryKey(userId);
4681
4682 screenName = getScreenName(screenName);
4683
4684 validateScreenName(user.getCompanyId(), userId, screenName);
4685
4686 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
4687 user.setDigest(StringPool.BLANK);
4688 }
4689
4690 user.setScreenName(screenName);
4691
4692 userPersistence.update(user);
4693
4694
4695
4696 Group group = groupLocalService.getUserGroup(
4697 user.getCompanyId(), userId);
4698
4699 group.setFriendlyURL(StringPool.SLASH + screenName);
4700
4701 groupPersistence.update(group);
4702
4703 return user;
4704 }
4705
4706
4715 public User updateStatus(long userId, int status)
4716 throws PortalException, SystemException {
4717
4718 User user = userPersistence.findByPrimaryKey(userId);
4719
4720 user.setStatus(status);
4721
4722 userPersistence.update(user);
4723
4724 reindex(user);
4725
4726 return user;
4727 }
4728
4729
4785 @SuppressWarnings("deprecation")
4786 public User updateUser(
4787 long userId, String oldPassword, String newPassword1,
4788 String newPassword2, boolean passwordReset,
4789 String reminderQueryQuestion, String reminderQueryAnswer,
4790 String screenName, String emailAddress, long facebookId,
4791 String openId, String languageId, String timeZoneId,
4792 String greeting, String comments, String firstName,
4793 String middleName, String lastName, int prefixId, int suffixId,
4794 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
4795 String smsSn, String aimSn, String facebookSn, String icqSn,
4796 String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
4797 String twitterSn, String ymSn, String jobTitle, long[] groupIds,
4798 long[] organizationIds, long[] roleIds,
4799 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
4800 ServiceContext serviceContext)
4801 throws PortalException, SystemException {
4802
4803
4804
4805 User user = userPersistence.findByPrimaryKey(userId);
4806 Company company = companyPersistence.findByPrimaryKey(
4807 user.getCompanyId());
4808 String password = oldPassword;
4809 screenName = getScreenName(screenName);
4810 emailAddress = emailAddress.trim().toLowerCase();
4811 openId = openId.trim();
4812 String oldFullName = user.getFullName();
4813 aimSn = aimSn.trim().toLowerCase();
4814 facebookSn = facebookSn.trim().toLowerCase();
4815 icqSn = icqSn.trim().toLowerCase();
4816 jabberSn = jabberSn.trim().toLowerCase();
4817 msnSn = msnSn.trim().toLowerCase();
4818 mySpaceSn = mySpaceSn.trim().toLowerCase();
4819 skypeSn = skypeSn.trim().toLowerCase();
4820 twitterSn = twitterSn.trim().toLowerCase();
4821 ymSn = ymSn.trim().toLowerCase();
4822 Date now = new Date();
4823
4824 EmailAddressGenerator emailAddressGenerator =
4825 EmailAddressGeneratorFactory.getInstance();
4826
4827 if (emailAddressGenerator.isGenerated(emailAddress)) {
4828 emailAddress = StringPool.BLANK;
4829 }
4830
4831 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
4832 Validator.isNull(emailAddress)) {
4833
4834 emailAddress = emailAddressGenerator.generate(
4835 user.getCompanyId(), userId);
4836 }
4837
4838 validate(
4839 userId, screenName, emailAddress, openId, firstName, middleName,
4840 lastName, smsSn);
4841
4842 if (Validator.isNotNull(newPassword1) ||
4843 Validator.isNotNull(newPassword2)) {
4844
4845 user = updatePassword(
4846 userId, newPassword1, newPassword2, passwordReset);
4847
4848 password = newPassword1;
4849
4850 user.setDigest(StringPool.BLANK);
4851 }
4852
4853 user.setModifiedDate(now);
4854
4855 if (user.getContactId() <= 0) {
4856 user.setContactId(counterLocalService.increment());
4857 }
4858
4859 user.setPasswordReset(passwordReset);
4860
4861 if (Validator.isNotNull(reminderQueryQuestion) &&
4862 Validator.isNotNull(reminderQueryAnswer)) {
4863
4864 user.setReminderQueryQuestion(reminderQueryQuestion);
4865 user.setReminderQueryAnswer(reminderQueryAnswer);
4866 }
4867
4868 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
4869 user.setScreenName(screenName);
4870
4871 user.setDigest(StringPool.BLANK);
4872 }
4873
4874 boolean sendEmailAddressVerification = false;
4875
4876 if (!company.isStrangersVerify()) {
4877 setEmailAddress(
4878 user, password, firstName, middleName, lastName, emailAddress);
4879 }
4880 else {
4881 sendEmailAddressVerification = true;
4882 }
4883
4884 if (serviceContext != null) {
4885 String uuid = serviceContext.getUuid();
4886
4887 if (Validator.isNotNull(uuid)) {
4888 user.setUuid(uuid);
4889 }
4890 }
4891
4892 user.setFacebookId(facebookId);
4893
4894 Long ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
4895
4896 if (ldapServerId != null) {
4897 user.setLdapServerId(ldapServerId);
4898 }
4899
4900 user.setOpenId(openId);
4901 user.setLanguageId(languageId);
4902 user.setTimeZoneId(timeZoneId);
4903 user.setGreeting(greeting);
4904 user.setComments(comments);
4905 user.setFirstName(firstName);
4906 user.setMiddleName(middleName);
4907 user.setLastName(lastName);
4908 user.setJobTitle(jobTitle);
4909 user.setExpandoBridgeAttributes(serviceContext);
4910
4911 userPersistence.update(user, serviceContext);
4912
4913
4914
4915 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
4916
4917 long contactId = user.getContactId();
4918
4919 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
4920
4921 if (contact == null) {
4922 contact = contactPersistence.create(contactId);
4923
4924 contact.setCompanyId(user.getCompanyId());
4925 contact.setUserName(StringPool.BLANK);
4926 contact.setCreateDate(now);
4927 contact.setClassName(User.class.getName());
4928 contact.setClassPK(user.getUserId());
4929 contact.setAccountId(company.getAccountId());
4930 contact.setParentContactId(
4931 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
4932 }
4933
4934 contact.setModifiedDate(now);
4935 contact.setEmailAddress(user.getEmailAddress());
4936 contact.setFirstName(firstName);
4937 contact.setMiddleName(middleName);
4938 contact.setLastName(lastName);
4939 contact.setPrefixId(prefixId);
4940 contact.setSuffixId(suffixId);
4941 contact.setMale(male);
4942 contact.setBirthday(birthday);
4943 contact.setSmsSn(smsSn);
4944 contact.setAimSn(aimSn);
4945 contact.setFacebookSn(facebookSn);
4946 contact.setIcqSn(icqSn);
4947 contact.setJabberSn(jabberSn);
4948 contact.setMsnSn(msnSn);
4949 contact.setMySpaceSn(mySpaceSn);
4950 contact.setSkypeSn(skypeSn);
4951 contact.setTwitterSn(twitterSn);
4952 contact.setYmSn(ymSn);
4953 contact.setJobTitle(jobTitle);
4954
4955 contactPersistence.update(contact, serviceContext);
4956
4957
4958
4959 Group group = groupLocalService.getUserGroup(
4960 user.getCompanyId(), userId);
4961
4962 group.setFriendlyURL(StringPool.SLASH + screenName);
4963
4964 groupPersistence.update(group);
4965
4966
4967
4968 updateGroups(userId, groupIds, serviceContext, false);
4969 updateOrganizations(userId, organizationIds, false);
4970
4971
4972
4973 if (roleIds != null) {
4974 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
4975
4976 userPersistence.setRoles(userId, roleIds);
4977 }
4978
4979
4980
4981 updateUserGroupRoles(user, groupIds, organizationIds, userGroupRoles);
4982
4983
4984
4985 if (userGroupIds != null) {
4986 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
4987 userGroupLocalService.copyUserGroupLayouts(
4988 userGroupIds, userId);
4989 }
4990
4991 userPersistence.setUserGroups(userId, userGroupIds);
4992 }
4993
4994
4995
4996 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
4997
4998
4999
5000 if (serviceContext != null) {
5001 updateAsset(
5002 userId, user, serviceContext.getAssetCategoryIds(),
5003 serviceContext.getAssetTagNames());
5004 }
5005
5006
5007
5008 if (GetterUtil.getBoolean(
5009 PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
5010 !oldFullName.equals(user.getFullName())) {
5011
5012 mbMessageLocalService.updateUserName(userId, user.getFullName());
5013 }
5014
5015
5016
5017 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
5018 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5019 User.class);
5020
5021 indexer.reindex(user);
5022 }
5023
5024
5025
5026 if ((serviceContext != null) && sendEmailAddressVerification) {
5027 sendEmailAddressVerification(user, emailAddress, serviceContext);
5028 }
5029
5030
5031
5032 PermissionCacheUtil.clearCache();
5033
5034 return user;
5035 }
5036
5037
5046 public void verifyEmailAddress(String ticketKey)
5047 throws PortalException, SystemException {
5048
5049 Ticket ticket = ticketLocalService.getTicket(ticketKey);
5050
5051 if (ticket.isExpired() ||
5052 (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
5053
5054 throw new NoSuchTicketException();
5055 }
5056
5057 User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
5058
5059 String emailAddress = ticket.getExtraInfo();
5060
5061 emailAddress = emailAddress.toLowerCase().trim();
5062
5063 if (!emailAddress.equals(user.getEmailAddress())) {
5064 if (userPersistence.fetchByC_EA(
5065 user.getCompanyId(), emailAddress) != null) {
5066
5067 throw new DuplicateUserEmailAddressException();
5068 }
5069
5070 setEmailAddress(
5071 user, StringPool.BLANK, user.getFirstName(),
5072 user.getMiddleName(), user.getLastName(), emailAddress);
5073
5074 Contact contact = user.getContact();
5075
5076 contact.setEmailAddress(user.getEmailAddress());
5077
5078 contactPersistence.update(contact);
5079 }
5080
5081 user.setEmailAddressVerified(true);
5082
5083 userPersistence.update(user);
5084
5085 ticketLocalService.deleteTicket(ticket);
5086 }
5087
5088 protected void addDefaultRolesAndTeams(long groupId, long[] userIds)
5089 throws PortalException, SystemException {
5090
5091 List<Role> defaultSiteRoles = new ArrayList<Role>();
5092
5093 Group group = groupLocalService.getGroup(groupId);
5094
5095 UnicodeProperties typeSettingsProperties =
5096 group.getTypeSettingsProperties();
5097
5098 long[] defaultSiteRoleIds = StringUtil.split(
5099 typeSettingsProperties.getProperty("defaultSiteRoleIds"), 0L);
5100
5101 for (long defaultSiteRoleId : defaultSiteRoleIds) {
5102 Role defaultSiteRole = rolePersistence.fetchByPrimaryKey(
5103 defaultSiteRoleId);
5104
5105 if (defaultSiteRole == null) {
5106 if (_log.isWarnEnabled()) {
5107 _log.warn("Unable to find role " + defaultSiteRoleId);
5108 }
5109
5110 continue;
5111 }
5112
5113 defaultSiteRoles.add(defaultSiteRole);
5114 }
5115
5116 List<Team> defaultTeams = new ArrayList<Team>();
5117
5118 long[] defaultTeamIds = StringUtil.split(
5119 typeSettingsProperties.getProperty("defaultTeamIds"), 0L);
5120
5121 for (long defaultTeamId : defaultTeamIds) {
5122 Team defaultTeam = teamPersistence.findByPrimaryKey(defaultTeamId);
5123
5124 if (defaultTeam == null) {
5125 if (_log.isWarnEnabled()) {
5126 _log.warn("Unable to find team " + defaultTeamId);
5127 }
5128
5129 continue;
5130 }
5131
5132 defaultTeams.add(defaultTeam);
5133 }
5134
5135 for (long userId : userIds) {
5136 Set<Long> userRoleIdsSet = new HashSet<Long>();
5137
5138 for (Role role : defaultSiteRoles) {
5139 if (!userPersistence.containsRole(userId, role.getRoleId())) {
5140 userRoleIdsSet.add(role.getRoleId());
5141 }
5142 }
5143
5144 long[] userRoleIds = ArrayUtil.toArray(
5145 userRoleIdsSet.toArray(new Long[userRoleIdsSet.size()]));
5146
5147 userGroupRoleLocalService.addUserGroupRoles(
5148 userId, groupId, userRoleIds);
5149
5150 Set<Long> userTeamIdsSet = new HashSet<Long>();
5151
5152 for (Team team : defaultTeams) {
5153 if (!userPersistence.containsTeam(userId, team.getTeamId())) {
5154 userTeamIdsSet.add(team.getTeamId());
5155 }
5156 }
5157
5158 long[] userTeamIds = ArrayUtil.toArray(
5159 userTeamIdsSet.toArray(new Long[userTeamIdsSet.size()]));
5160
5161 userPersistence.addTeams(userId, userTeamIds);
5162 }
5163 }
5164
5165
5211 protected int authenticate(
5212 long companyId, String login, String password, String authType,
5213 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
5214 Map<String, Object> resultsMap)
5215 throws PortalException, SystemException {
5216
5217 if (PropsValues.AUTH_LOGIN_DISABLED) {
5218 return Authenticator.FAILURE;
5219 }
5220
5221 login = login.trim().toLowerCase();
5222
5223 long userId = GetterUtil.getLong(login);
5224
5225
5226
5227 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5228 if (Validator.isNull(login)) {
5229 throw new UserEmailAddressException();
5230 }
5231 }
5232 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5233 if (Validator.isNull(login)) {
5234 throw new UserScreenNameException();
5235 }
5236 }
5237 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5238 if (Validator.isNull(login)) {
5239 throw new UserIdException();
5240 }
5241 }
5242
5243 if (Validator.isNull(password)) {
5244 throw new UserPasswordException(
5245 UserPasswordException.PASSWORD_INVALID);
5246 }
5247
5248 int authResult = Authenticator.FAILURE;
5249
5250
5251
5252 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5253 authResult = AuthPipeline.authenticateByEmailAddress(
5254 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5255 headerMap, parameterMap);
5256 }
5257 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5258 authResult = AuthPipeline.authenticateByScreenName(
5259 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5260 headerMap, parameterMap);
5261 }
5262 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5263 authResult = AuthPipeline.authenticateByUserId(
5264 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
5265 headerMap, parameterMap);
5266 }
5267
5268
5269
5270 User user = null;
5271
5272 try {
5273 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5274 user = userPersistence.findByC_EA(companyId, login);
5275 }
5276 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5277 user = userPersistence.findByC_SN(companyId, login);
5278 }
5279 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5280 user = userPersistence.findByC_U(
5281 companyId, GetterUtil.getLong(login));
5282 }
5283 }
5284 catch (NoSuchUserException nsue) {
5285 return Authenticator.DNE;
5286 }
5287
5288 if (user.isDefaultUser()) {
5289 if (_log.isInfoEnabled()) {
5290 _log.info("Authentication is disabled for the default user");
5291 }
5292
5293 return Authenticator.DNE;
5294 }
5295 else if (!user.isActive()) {
5296 if (_log.isInfoEnabled()) {
5297 _log.info(
5298 "Authentication is disabled for inactive user " +
5299 user.getUserId());
5300 }
5301
5302 return Authenticator.FAILURE;
5303 }
5304
5305 if (!user.isPasswordEncrypted()) {
5306 user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
5307 user.setPasswordEncrypted(true);
5308
5309 userPersistence.update(user);
5310 }
5311
5312
5313
5314
5315 checkLockout(user);
5316
5317 checkPasswordExpired(user);
5318
5319
5320
5321 if ((authResult == Authenticator.SUCCESS) &&
5322 PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5323
5324 boolean authenticated = PwdAuthenticator.authenticate(
5325 login, password, user.getPassword());
5326
5327 if (authenticated) {
5328 authResult = Authenticator.SUCCESS;
5329 }
5330 else {
5331 authResult = Authenticator.FAILURE;
5332 }
5333 }
5334
5335
5336
5337 if (authResult == Authenticator.SUCCESS) {
5338 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5339 authResult = AuthPipeline.authenticateByEmailAddress(
5340 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5341 headerMap, parameterMap);
5342 }
5343 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5344 authResult = AuthPipeline.authenticateByScreenName(
5345 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5346 headerMap, parameterMap);
5347 }
5348 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5349 authResult = AuthPipeline.authenticateByUserId(
5350 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5351 headerMap, parameterMap);
5352 }
5353 }
5354
5355 if (authResult == Authenticator.SUCCESS) {
5356 if (resultsMap != null) {
5357 resultsMap.put("userId", user.getUserId());
5358 }
5359
5360
5361
5362 boolean updateDigest = true;
5363
5364 if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5365 if (Validator.isNotNull(user.getDigest())) {
5366 updateDigest = false;
5367 }
5368 }
5369
5370 if (updateDigest) {
5371 String digest = user.getDigest(password);
5372
5373 user.setDigest(digest);
5374
5375 userPersistence.update(user);
5376 }
5377 }
5378
5379
5380
5381 if (authResult == Authenticator.FAILURE) {
5382 try {
5383 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5384 AuthPipeline.onFailureByEmailAddress(
5385 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5386 parameterMap);
5387 }
5388 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5389 AuthPipeline.onFailureByScreenName(
5390 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5391 parameterMap);
5392 }
5393 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5394 AuthPipeline.onFailureByUserId(
5395 PropsKeys.AUTH_FAILURE, companyId, userId, headerMap,
5396 parameterMap);
5397 }
5398
5399 try {
5400 user = userPersistence.findByPrimaryKey(user.getUserId());
5401 }
5402 catch (NoSuchUserException nsue) {
5403 return Authenticator.DNE;
5404 }
5405
5406
5407
5408 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5409 user.getCompanyId())) {
5410
5411 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5412
5413 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5414
5415 int failedLoginAttempts = user.getFailedLoginAttempts();
5416 int maxFailures = passwordPolicy.getMaxFailure();
5417
5418 if ((failedLoginAttempts >= maxFailures) &&
5419 (maxFailures != 0)) {
5420
5421 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5422 AuthPipeline.onMaxFailuresByEmailAddress(
5423 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5424 headerMap, parameterMap);
5425 }
5426 else if (authType.equals(
5427 CompanyConstants.AUTH_TYPE_SN)) {
5428
5429 AuthPipeline.onMaxFailuresByScreenName(
5430 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5431 headerMap, parameterMap);
5432 }
5433 else if (authType.equals(
5434 CompanyConstants.AUTH_TYPE_ID)) {
5435
5436 AuthPipeline.onMaxFailuresByUserId(
5437 PropsKeys.AUTH_MAX_FAILURES, companyId, userId,
5438 headerMap, parameterMap);
5439 }
5440 }
5441 }
5442 }
5443 catch (Exception e) {
5444 _log.error(e, e);
5445 }
5446 }
5447
5448
5449
5450 return authResult;
5451 }
5452
5453 protected Date getBirthday(
5454 int birthdayMonth, int birthdayDay, int birthdayYear)
5455 throws PortalException {
5456
5457 Date birthday = PortalUtil.getDate(
5458 birthdayMonth, birthdayDay, birthdayYear,
5459 ContactBirthdayException.class);
5460
5461 Date now = new Date();
5462
5463 if (birthday.after(now)) {
5464 throw new ContactBirthdayException();
5465 }
5466
5467 return birthday;
5468 }
5469
5470 protected String getScreenName(String screenName) {
5471 return StringUtil.lowerCase(StringUtil.trim(screenName));
5472 }
5473
5474 protected long[] getUserIds(List<User> users) {
5475 long[] userIds = new long[users.size()];
5476
5477 for (int i = 0; i < users.size(); i++) {
5478 User user = users.get(i);
5479
5480 userIds[i] = user.getUserId();
5481 }
5482
5483 return userIds;
5484 }
5485
5486 protected void reindex(final User user) {
5487 final Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5488 User.class);
5489
5490 Callable<Void> callable = new PortalCallable<Void>(
5491 user.getCompanyId()) {
5492
5493 @Override
5494 protected Void doCall() throws Exception {
5495 indexer.reindex(user);
5496
5497 return null;
5498 }
5499
5500 };
5501
5502 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
5503 }
5504
5505 protected Hits search(
5506 long companyId, String firstName, String middleName,
5507 String lastName, String fullName, String screenName,
5508 String emailAddress, String street, String city, String zip,
5509 String region, String country, int status,
5510 LinkedHashMap<String, Object> params, boolean andSearch, int start,
5511 int end, Sort sort)
5512 throws SystemException {
5513
5514 try {
5515 SearchContext searchContext = new SearchContext();
5516
5517 searchContext.setAndSearch(andSearch);
5518
5519 Map<String, Serializable> attributes =
5520 new HashMap<String, Serializable>();
5521
5522 attributes.put("city", city);
5523 attributes.put("country", country);
5524 attributes.put("emailAddress", emailAddress);
5525 attributes.put("firstName", firstName);
5526 attributes.put("fullName", fullName);
5527 attributes.put("lastName", lastName);
5528 attributes.put("middleName", middleName);
5529 attributes.put("params", params);
5530 attributes.put("region", region);
5531 attributes.put("screenName", screenName);
5532 attributes.put("street", street);
5533 attributes.put("status", status);
5534 attributes.put("zip", zip);
5535
5536 searchContext.setAttributes(attributes);
5537
5538 searchContext.setCompanyId(companyId);
5539 searchContext.setEnd(end);
5540
5541 if (params != null) {
5542 String keywords = (String)params.remove("keywords");
5543
5544 if (Validator.isNotNull(keywords)) {
5545 searchContext.setKeywords(keywords);
5546 }
5547 }
5548
5549 QueryConfig queryConfig = new QueryConfig();
5550
5551 queryConfig.setHighlightEnabled(false);
5552 queryConfig.setScoreEnabled(false);
5553
5554 searchContext.setQueryConfig(queryConfig);
5555
5556 if (sort != null) {
5557 searchContext.setSorts(new Sort[] {sort});
5558 }
5559
5560 searchContext.setStart(start);
5561
5562 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5563 User.class);
5564
5565 return indexer.search(searchContext);
5566 }
5567 catch (Exception e) {
5568 throw new SystemException(e);
5569 }
5570 }
5571
5572 protected void sendEmail(
5573 User user, String password, ServiceContext serviceContext)
5574 throws SystemException {
5575
5576 if (!PrefsPropsUtil.getBoolean(
5577 user.getCompanyId(),
5578 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
5579
5580 return;
5581 }
5582
5583 String fromName = PrefsPropsUtil.getString(
5584 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
5585 String fromAddress = PrefsPropsUtil.getString(
5586 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
5587
5588 String toName = user.getFullName();
5589 String toAddress = user.getEmailAddress();
5590
5591 String subject = PrefsPropsUtil.getContent(
5592 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
5593
5594 String body = null;
5595
5596 if (Validator.isNotNull(password)) {
5597 body = PrefsPropsUtil.getContent(
5598 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
5599 }
5600 else {
5601 body = PrefsPropsUtil.getContent(
5602 user.getCompanyId(),
5603 PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
5604 }
5605
5606 SubscriptionSender subscriptionSender = new SubscriptionSender();
5607
5608 subscriptionSender.setBody(body);
5609 subscriptionSender.setCompanyId(user.getCompanyId());
5610 subscriptionSender.setContextAttributes(
5611 "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
5612 "[$USER_SCREENNAME$]", user.getScreenName());
5613 subscriptionSender.setFrom(fromAddress, fromName);
5614 subscriptionSender.setHtmlFormat(true);
5615 subscriptionSender.setMailId("user", user.getUserId());
5616 subscriptionSender.setServiceContext(serviceContext);
5617 subscriptionSender.setSubject(subject);
5618 subscriptionSender.setUserId(user.getUserId());
5619
5620 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
5621
5622 subscriptionSender.flushNotificationsAsync();
5623 }
5624
5625 protected void setEmailAddress(
5626 User user, String password, String firstName, String middleName,
5627 String lastName, String emailAddress)
5628 throws PortalException, SystemException {
5629
5630 if (emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
5631 return;
5632 }
5633
5634 long userId = user.getUserId();
5635
5636
5637
5638 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
5639 Validator.isNotNull(password)) {
5640
5641 mailService.addUser(
5642 user.getCompanyId(), userId, password, firstName, middleName,
5643 lastName, emailAddress);
5644 }
5645
5646
5647
5648 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
5649 mailService.updateEmailAddress(
5650 user.getCompanyId(), userId, emailAddress);
5651 }
5652
5653
5654
5655 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
5656 mailService.deleteEmailAddress(user.getCompanyId(), userId);
5657 }
5658
5659 user.setEmailAddress(emailAddress);
5660 user.setDigest(StringPool.BLANK);
5661 }
5662
5663 protected void updateGroups(
5664 long userId, long[] newGroupIds, ServiceContext serviceContext,
5665 boolean indexingEnabled)
5666 throws PortalException, SystemException {
5667
5668 if (newGroupIds == null) {
5669 return;
5670 }
5671
5672 List<Group> oldGroups = userPersistence.getGroups(userId);
5673
5674 Set<Long> oldGroupIds = new HashSet<Long>(oldGroups.size());
5675
5676 for (Group oldGroup : oldGroups) {
5677 long oldGroupId = oldGroup.getGroupId();
5678
5679 oldGroupIds.add(oldGroupId);
5680
5681 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
5682 unsetGroupUsers(
5683 oldGroupId, new long[] {userId}, serviceContext);
5684 }
5685 }
5686
5687 for (long newGroupId : newGroupIds) {
5688 if (!oldGroupIds.contains(newGroupId)) {
5689 addGroupUsers(newGroupId, new long[] {userId});
5690 }
5691 }
5692
5693 if (indexingEnabled) {
5694 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5695 User.class);
5696
5697 indexer.reindex(new long[] {userId});
5698 }
5699
5700 PermissionCacheUtil.clearCache();
5701 }
5702
5703 protected void updateOrganizations(
5704 long userId, long[] newOrganizationIds, boolean indexingEnabled)
5705 throws PortalException, SystemException {
5706
5707 if (newOrganizationIds == null) {
5708 return;
5709 }
5710
5711 List<Organization> oldOrganizations = userPersistence.getOrganizations(
5712 userId);
5713
5714 Set<Long> oldOrganizationIds = new HashSet<Long>(
5715 oldOrganizations.size());
5716
5717 for (Organization oldOrganization : oldOrganizations) {
5718 long oldOrganizationId = oldOrganization.getOrganizationId();
5719
5720 oldOrganizationIds.add(oldOrganizationId);
5721
5722 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
5723 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
5724 }
5725 }
5726
5727 for (long newOrganizationId : newOrganizationIds) {
5728 if (!oldOrganizationIds.contains(newOrganizationId)) {
5729 addOrganizationUsers(newOrganizationId, new long[] {userId});
5730 }
5731 }
5732
5733 if (indexingEnabled) {
5734 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5735 User.class);
5736
5737 indexer.reindex(new long[] {userId});
5738 }
5739
5740 PermissionCacheUtil.clearCache();
5741 }
5742
5743 protected void updateUserGroupRoles(
5744 User user, long[] groupIds, long[] organizationIds,
5745 List<UserGroupRole> userGroupRoles)
5746 throws PortalException, SystemException {
5747
5748 if (userGroupRoles == null) {
5749 return;
5750 }
5751
5752 List<UserGroupRole> previousUserGroupRoles =
5753 userGroupRolePersistence.findByUserId(user.getUserId());
5754
5755 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
5756 if (userGroupRoles.contains(userGroupRole)) {
5757 userGroupRoles.remove(userGroupRole);
5758 }
5759 else {
5760 userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
5761 }
5762 }
5763
5764 long[] validGroupIds = null;
5765
5766 if (groupIds != null) {
5767 validGroupIds = ArrayUtil.clone(groupIds);
5768 }
5769 else {
5770 validGroupIds = user.getGroupIds();
5771 }
5772
5773 if (organizationIds == null) {
5774 organizationIds = user.getOrganizationIds();
5775 }
5776
5777 long[] organizationGroupIds = new long[organizationIds.length];
5778
5779 for (int i = 0; i < organizationIds.length; i++) {
5780 long organizationId = organizationIds[i];
5781
5782 Organization organization =
5783 organizationPersistence.findByPrimaryKey(organizationId);
5784
5785 Group organizationGroup = organization.getGroup();
5786
5787 organizationGroupIds[i] = organizationGroup.getGroupId();
5788 }
5789
5790 validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
5791
5792 Arrays.sort(validGroupIds);
5793
5794 for (UserGroupRole userGroupRole : userGroupRoles) {
5795 if (Arrays.binarySearch(
5796 validGroupIds, userGroupRole.getGroupId()) >= 0) {
5797
5798 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
5799 }
5800 }
5801 }
5802
5803 protected void validate(
5804 long companyId, long userId, boolean autoPassword, String password1,
5805 String password2, boolean autoScreenName, String screenName,
5806 String emailAddress, String openId, String firstName,
5807 String middleName, String lastName, long[] organizationIds)
5808 throws PortalException, SystemException {
5809
5810 Company company = companyPersistence.findByPrimaryKey(companyId);
5811
5812 if (company.isSystem()) {
5813 return;
5814 }
5815
5816 if ((company.getMaxUsers() > 0) &&
5817 (company.getMaxUsers() <=
5818 searchCount(
5819 companyId, null, WorkflowConstants.STATUS_APPROVED,
5820 null))) {
5821
5822 throw new CompanyMaxUsersException();
5823 }
5824
5825 if (!autoScreenName) {
5826 validateScreenName(companyId, userId, screenName);
5827 }
5828
5829 if (!autoPassword) {
5830 PasswordPolicy passwordPolicy =
5831 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
5832
5833 PwdToolkitUtil.validate(
5834 companyId, 0, password1, password2, passwordPolicy);
5835 }
5836
5837 validateEmailAddress(companyId, emailAddress);
5838
5839 if (Validator.isNotNull(emailAddress)) {
5840 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
5841
5842 if ((user != null) && (user.getUserId() != userId)) {
5843 throw new DuplicateUserEmailAddressException();
5844 }
5845 }
5846
5847 validateOpenId(companyId, userId, openId);
5848
5849 validateFullName(companyId, firstName, middleName, lastName);
5850
5851 if (organizationIds != null) {
5852 for (long organizationId : organizationIds) {
5853 Organization organization =
5854 organizationPersistence.fetchByPrimaryKey(organizationId);
5855
5856 if (organization == null) {
5857 throw new NoSuchOrganizationException();
5858 }
5859 }
5860 }
5861 }
5862
5863 protected void validate(
5864 long userId, String screenName, String emailAddress, String openId,
5865 String firstName, String middleName, String lastName, String smsSn)
5866 throws PortalException, SystemException {
5867
5868 User user = userPersistence.findByPrimaryKey(userId);
5869
5870 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
5871 validateScreenName(user.getCompanyId(), userId, screenName);
5872 }
5873
5874 validateEmailAddress(user.getCompanyId(), emailAddress);
5875
5876 validateOpenId(user.getCompanyId(), userId, openId);
5877
5878 if (!user.isDefaultUser()) {
5879 if (Validator.isNotNull(emailAddress) &&
5880 !user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
5881
5882 if (userPersistence.fetchByC_EA(
5883 user.getCompanyId(), emailAddress) != null) {
5884
5885 throw new DuplicateUserEmailAddressException();
5886 }
5887 }
5888
5889 validateFullName(
5890 user.getCompanyId(), firstName, middleName, lastName);
5891 }
5892
5893 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
5894 throw new UserSmsException();
5895 }
5896 }
5897
5898 protected void validateEmailAddress(long companyId, String emailAddress)
5899 throws PortalException, SystemException {
5900
5901 if (Validator.isNull(emailAddress) &&
5902 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
5903
5904 return;
5905 }
5906
5907 EmailAddressValidator emailAddressValidator =
5908 EmailAddressValidatorFactory.getInstance();
5909
5910 if (!emailAddressValidator.validate(companyId, emailAddress)) {
5911 throw new UserEmailAddressException();
5912 }
5913
5914 String pop3User = PrefsPropsUtil.getString(
5915 PropsKeys.MAIL_SESSION_MAIL_POP3_USER,
5916 PropsValues.MAIL_SESSION_MAIL_POP3_USER);
5917
5918 if (emailAddress.equalsIgnoreCase(pop3User)) {
5919 throw new ReservedUserEmailAddressException();
5920 }
5921
5922 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
5923 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
5924 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
5925
5926 for (String reservedEmailAddress : reservedEmailAddresses) {
5927 if (emailAddress.equalsIgnoreCase(reservedEmailAddress)) {
5928 throw new ReservedUserEmailAddressException();
5929 }
5930 }
5931 }
5932
5933 protected void validateEmailAddress(
5934 User user, String emailAddress1, String emailAddress2)
5935 throws PortalException, SystemException {
5936
5937 if (!emailAddress1.equals(emailAddress2)) {
5938 throw new UserEmailAddressException();
5939 }
5940
5941 validateEmailAddress(user.getCompanyId(), emailAddress1);
5942 validateEmailAddress(user.getCompanyId(), emailAddress2);
5943
5944 if (!emailAddress1.equalsIgnoreCase(user.getEmailAddress())) {
5945 if (userPersistence.fetchByC_EA(
5946 user.getCompanyId(), emailAddress1) != null) {
5947
5948 throw new DuplicateUserEmailAddressException();
5949 }
5950 }
5951 }
5952
5953 protected void validateFullName(
5954 long companyId, String firstName, String middleName,
5955 String lastName)
5956 throws PortalException, SystemException {
5957
5958 if (Validator.isNull(firstName)) {
5959 throw new ContactFirstNameException();
5960 }
5961 else if (Validator.isNull(lastName) &&
5962 PrefsPropsUtil.getBoolean(
5963 companyId, PropsKeys.USERS_LAST_NAME_REQUIRED,
5964 PropsValues.USERS_LAST_NAME_REQUIRED)) {
5965
5966 throw new ContactLastNameException();
5967 }
5968
5969 FullNameValidator fullNameValidator =
5970 FullNameValidatorFactory.getInstance();
5971
5972 if (!fullNameValidator.validate(
5973 companyId, firstName, middleName, lastName)) {
5974
5975 throw new ContactFullNameException();
5976 }
5977 }
5978
5979 protected void validateOpenId(long companyId, long userId, String openId)
5980 throws PortalException, SystemException {
5981
5982 if (Validator.isNull(openId)) {
5983 return;
5984 }
5985
5986 User user = userPersistence.fetchByC_O(companyId, openId);
5987
5988 if ((user != null) && (user.getUserId() != userId)) {
5989 throw new DuplicateOpenIdException();
5990 }
5991 }
5992
5993 protected void validatePassword(
5994 long companyId, long userId, String password1, String password2)
5995 throws PortalException, SystemException {
5996
5997 if (Validator.isNull(password1) || Validator.isNull(password2)) {
5998 throw new UserPasswordException(
5999 UserPasswordException.PASSWORD_INVALID);
6000 }
6001
6002 if (!password1.equals(password2)) {
6003 throw new UserPasswordException(
6004 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
6005 }
6006
6007 PasswordPolicy passwordPolicy =
6008 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
6009
6010 PwdToolkitUtil.validate(
6011 companyId, userId, password1, password2, passwordPolicy);
6012 }
6013
6014 protected void validateReminderQuery(String question, String answer)
6015 throws PortalException {
6016
6017 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
6018 return;
6019 }
6020
6021 if (Validator.isNull(question)) {
6022 throw new UserReminderQueryException("Question cannot be null");
6023 }
6024
6025 if (Validator.isNull(answer)) {
6026 throw new UserReminderQueryException("Answer cannot be null");
6027 }
6028 }
6029
6030 protected void validateScreenName(
6031 long companyId, long userId, String screenName)
6032 throws PortalException, SystemException {
6033
6034 if (Validator.isNull(screenName)) {
6035 throw new UserScreenNameException();
6036 }
6037
6038 ScreenNameValidator screenNameValidator =
6039 ScreenNameValidatorFactory.getInstance();
6040
6041 if (!screenNameValidator.validate(companyId, screenName)) {
6042 throw new UserScreenNameException();
6043 }
6044
6045 if (Validator.isNumber(screenName)) {
6046 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
6047 throw new UserScreenNameException();
6048 }
6049
6050 if (!screenName.equals(String.valueOf(userId))) {
6051 Group group = groupPersistence.fetchByPrimaryKey(
6052 GetterUtil.getLong(screenName));
6053
6054 if (group != null) {
6055 throw new UserScreenNameException();
6056 }
6057 }
6058 }
6059
6060 for (char c : screenName.toCharArray()) {
6061 if (!Validator.isChar(c) && !Validator.isDigit(c) &&
6062 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
6063 (c != CharPool.UNDERLINE)) {
6064
6065 throw new UserScreenNameException();
6066 }
6067 }
6068
6069 String[] anonymousNames = BaseServiceImpl.ANONYMOUS_NAMES;
6070
6071 for (String anonymousName : anonymousNames) {
6072 if (screenName.equalsIgnoreCase(anonymousName)) {
6073 throw new UserScreenNameException();
6074 }
6075 }
6076
6077 User user = userPersistence.fetchByC_SN(companyId, screenName);
6078
6079 if ((user != null) && (user.getUserId() != userId)) {
6080 throw new DuplicateUserScreenNameException();
6081 }
6082
6083 String friendlyURL = StringPool.SLASH + screenName;
6084
6085 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
6086
6087 if ((group != null) && (group.getClassPK() != userId)) {
6088 throw new GroupFriendlyURLException(
6089 GroupFriendlyURLException.DUPLICATE);
6090 }
6091
6092 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
6093
6094 if (exceptionType != -1) {
6095 throw new UserScreenNameException(
6096 new GroupFriendlyURLException(exceptionType));
6097 }
6098
6099 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
6100 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
6101 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
6102
6103 for (String reservedScreenName : reservedScreenNames) {
6104 if (screenName.equalsIgnoreCase(reservedScreenName)) {
6105 throw new ReservedUserScreenNameException();
6106 }
6107 }
6108 }
6109
6110 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
6111
6112 private Map<Long, User> _defaultUsers = new ConcurrentHashMap<Long, User>();
6113
6114 }