001
014
015 package com.liferay.portal.service.impl;
016
017 import com.liferay.portal.CompanyMaxUsersException;
018 import com.liferay.portal.ContactBirthdayException;
019 import com.liferay.portal.ContactFirstNameException;
020 import com.liferay.portal.ContactFullNameException;
021 import com.liferay.portal.ContactLastNameException;
022 import com.liferay.portal.DuplicateUserEmailAddressException;
023 import com.liferay.portal.DuplicateUserScreenNameException;
024 import com.liferay.portal.GroupFriendlyURLException;
025 import com.liferay.portal.ModelListenerException;
026 import com.liferay.portal.NoSuchContactException;
027 import com.liferay.portal.NoSuchGroupException;
028 import com.liferay.portal.NoSuchOrganizationException;
029 import com.liferay.portal.NoSuchRoleException;
030 import com.liferay.portal.NoSuchTicketException;
031 import com.liferay.portal.NoSuchUserException;
032 import com.liferay.portal.NoSuchUserGroupException;
033 import com.liferay.portal.PasswordExpiredException;
034 import com.liferay.portal.RequiredUserException;
035 import com.liferay.portal.ReservedUserEmailAddressException;
036 import com.liferay.portal.ReservedUserScreenNameException;
037 import com.liferay.portal.UserEmailAddressException;
038 import com.liferay.portal.UserIdException;
039 import com.liferay.portal.UserLockoutException;
040 import com.liferay.portal.UserPasswordException;
041 import com.liferay.portal.UserPortraitSizeException;
042 import com.liferay.portal.UserPortraitTypeException;
043 import com.liferay.portal.UserReminderQueryException;
044 import com.liferay.portal.UserScreenNameException;
045 import com.liferay.portal.UserSmsException;
046 import com.liferay.portal.kernel.exception.PortalException;
047 import com.liferay.portal.kernel.exception.SystemException;
048 import com.liferay.portal.kernel.image.ImageBag;
049 import com.liferay.portal.kernel.image.ImageToolUtil;
050 import com.liferay.portal.kernel.language.LanguageUtil;
051 import com.liferay.portal.kernel.log.Log;
052 import com.liferay.portal.kernel.log.LogFactoryUtil;
053 import com.liferay.portal.kernel.search.Hits;
054 import com.liferay.portal.kernel.search.Indexer;
055 import com.liferay.portal.kernel.search.IndexerRegistryUtil;
056 import com.liferay.portal.kernel.search.QueryConfig;
057 import com.liferay.portal.kernel.search.SearchContext;
058 import com.liferay.portal.kernel.search.Sort;
059 import com.liferay.portal.kernel.spring.aop.Skip;
060 import com.liferay.portal.kernel.transaction.Propagation;
061 import com.liferay.portal.kernel.transaction.Transactional;
062 import com.liferay.portal.kernel.util.ArrayUtil;
063 import com.liferay.portal.kernel.util.CharPool;
064 import com.liferay.portal.kernel.util.Digester;
065 import com.liferay.portal.kernel.util.DigesterUtil;
066 import com.liferay.portal.kernel.util.GetterUtil;
067 import com.liferay.portal.kernel.util.KeyValuePair;
068 import com.liferay.portal.kernel.util.OrderByComparator;
069 import com.liferay.portal.kernel.util.ParamUtil;
070 import com.liferay.portal.kernel.util.PropsKeys;
071 import com.liferay.portal.kernel.util.StringPool;
072 import com.liferay.portal.kernel.util.StringUtil;
073 import com.liferay.portal.kernel.util.Validator;
074 import com.liferay.portal.kernel.workflow.WorkflowConstants;
075 import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil;
076 import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
077 import com.liferay.portal.model.Account;
078 import com.liferay.portal.model.Company;
079 import com.liferay.portal.model.CompanyConstants;
080 import com.liferay.portal.model.Contact;
081 import com.liferay.portal.model.ContactConstants;
082 import com.liferay.portal.model.Group;
083 import com.liferay.portal.model.GroupConstants;
084 import com.liferay.portal.model.Layout;
085 import com.liferay.portal.model.Organization;
086 import com.liferay.portal.model.PasswordPolicy;
087 import com.liferay.portal.model.ResourceConstants;
088 import com.liferay.portal.model.Role;
089 import com.liferay.portal.model.RoleConstants;
090 import com.liferay.portal.model.Team;
091 import com.liferay.portal.model.Ticket;
092 import com.liferay.portal.model.TicketConstants;
093 import com.liferay.portal.model.User;
094 import com.liferay.portal.model.UserGroup;
095 import com.liferay.portal.model.UserGroupRole;
096 import com.liferay.portal.model.impl.LayoutImpl;
097 import com.liferay.portal.security.auth.AuthPipeline;
098 import com.liferay.portal.security.auth.Authenticator;
099 import com.liferay.portal.security.auth.EmailAddressGenerator;
100 import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
101 import com.liferay.portal.security.auth.EmailAddressValidator;
102 import com.liferay.portal.security.auth.EmailAddressValidatorFactory;
103 import com.liferay.portal.security.auth.FullNameGenerator;
104 import com.liferay.portal.security.auth.FullNameGeneratorFactory;
105 import com.liferay.portal.security.auth.FullNameValidator;
106 import com.liferay.portal.security.auth.FullNameValidatorFactory;
107 import com.liferay.portal.security.auth.PrincipalException;
108 import com.liferay.portal.security.auth.ScreenNameGenerator;
109 import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
110 import com.liferay.portal.security.auth.ScreenNameValidator;
111 import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
112 import com.liferay.portal.security.ldap.LDAPSettingsUtil;
113 import com.liferay.portal.security.permission.PermissionCacheUtil;
114 import com.liferay.portal.security.pwd.PwdAuthenticator;
115 import com.liferay.portal.security.pwd.PwdEncryptor;
116 import com.liferay.portal.security.pwd.PwdToolkitUtil;
117 import com.liferay.portal.service.BaseServiceImpl;
118 import com.liferay.portal.service.ServiceContext;
119 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
120 import com.liferay.portal.spring.transaction.TransactionCommitCallbackUtil;
121 import com.liferay.portal.util.PortalUtil;
122 import com.liferay.portal.util.PrefsPropsUtil;
123 import com.liferay.portal.util.PropsValues;
124 import com.liferay.portal.util.SubscriptionSender;
125 import com.liferay.portlet.documentlibrary.ImageSizeException;
126 import com.liferay.portlet.messageboards.model.MBMessage;
127 import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
128 import com.liferay.util.Encryptor;
129 import com.liferay.util.EncryptorException;
130
131 import java.awt.image.RenderedImage;
132
133 import java.io.IOException;
134 import java.io.Serializable;
135
136 import java.util.ArrayList;
137 import java.util.Arrays;
138 import java.util.Calendar;
139 import java.util.Date;
140 import java.util.HashMap;
141 import java.util.HashSet;
142 import java.util.LinkedHashMap;
143 import java.util.List;
144 import java.util.Locale;
145 import java.util.Map;
146 import java.util.Set;
147 import java.util.concurrent.Callable;
148 import java.util.concurrent.ConcurrentHashMap;
149
150
161 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
162
163 public User addDefaultAdminUser(
164 long companyId, String screenName, String emailAddress,
165 Locale locale, String firstName, String middleName, String lastName)
166 throws PortalException, SystemException {
167
168 long creatorUserId = 0;
169 boolean autoPassword = false;
170 String password1 = PropsValues.DEFAULT_ADMIN_PASSWORD;
171 String password2 = password1;
172 boolean autoScreenName = false;
173
174 screenName = getScreenName(screenName);
175
176 for (int i = 1;; i++) {
177 User screenNameUser = userPersistence.fetchByC_SN(
178 companyId, screenName);
179
180 if (screenNameUser == null) {
181 break;
182 }
183
184 screenName = screenName + i;
185 }
186
187 long facebookId = 0;
188 String openId = StringPool.BLANK;
189 int prefixId = 0;
190 int suffixId = 0;
191 boolean male = true;
192 int birthdayMonth = Calendar.JANUARY;
193 int birthdayDay = 1;
194 int birthdayYear = 1970;
195 String jobTitle = StringPool.BLANK;
196
197 Group guestGroup = groupLocalService.getGroup(
198 companyId, GroupConstants.GUEST);
199
200 long[] groupIds = {guestGroup.getGroupId()};
201
202 long[] organizationIds = null;
203
204 Role adminRole = roleLocalService.getRole(
205 companyId, RoleConstants.ADMINISTRATOR);
206
207 Role powerUserRole = roleLocalService.getRole(
208 companyId, RoleConstants.POWER_USER);
209
210 long[] roleIds = {adminRole.getRoleId(), powerUserRole.getRoleId()};
211
212 long[] userGroupIds = null;
213 boolean sendEmail = false;
214 ServiceContext serviceContext = new ServiceContext();
215
216 User defaultAdminUser = addUser(
217 creatorUserId, companyId, autoPassword, password1, password2,
218 autoScreenName, screenName, emailAddress, facebookId, openId,
219 locale, firstName, middleName, lastName, prefixId, suffixId, male,
220 birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
221 organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
222
223 updateEmailAddressVerified(defaultAdminUser.getUserId(), true);
224
225 updateLastLogin(
226 defaultAdminUser.getUserId(), defaultAdminUser.getLoginIP());
227
228 updatePasswordReset(defaultAdminUser.getUserId(), false);
229
230 return defaultAdminUser;
231 }
232
233
243 public void addDefaultGroups(long userId)
244 throws PortalException, SystemException {
245
246 User user = userPersistence.findByPrimaryKey(userId);
247
248 Set<Long> groupIdsSet = new HashSet<Long>();
249
250 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
251 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
252 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
253
254 for (String defaultGroupName : defaultGroupNames) {
255 Company company = companyPersistence.findByPrimaryKey(
256 user.getCompanyId());
257
258 Account account = company.getAccount();
259
260 if (defaultGroupName.equalsIgnoreCase(account.getName())) {
261 defaultGroupName = GroupConstants.GUEST;
262 }
263
264 try {
265 Group group = groupPersistence.findByC_N(
266 user.getCompanyId(), defaultGroupName);
267
268 if (!userPersistence.containsGroup(
269 userId, group.getGroupId())) {
270
271 groupIdsSet.add(group.getGroupId());
272 }
273 }
274 catch (NoSuchGroupException nsge) {
275 }
276 }
277
278 long[] groupIds = ArrayUtil.toArray(
279 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
280
281 groupLocalService.addUserGroups(userId, groupIds);
282 }
283
284
294 public void addDefaultRoles(long userId)
295 throws PortalException, SystemException {
296
297 User user = userPersistence.findByPrimaryKey(userId);
298
299 Set<Long> roleIdSet = new HashSet<Long>();
300
301 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
302 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
303 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
304
305 for (String defaultRoleName : defaultRoleNames) {
306 try {
307 Role role = rolePersistence.findByC_N(
308 user.getCompanyId(), defaultRoleName);
309
310 if (!userPersistence.containsRole(userId, role.getRoleId())) {
311 roleIdSet.add(role.getRoleId());
312 }
313 }
314 catch (NoSuchRoleException nsre) {
315 }
316 }
317
318 long[] roleIds = ArrayUtil.toArray(
319 roleIdSet.toArray(new Long[roleIdSet.size()]));
320
321 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
322
323 userPersistence.addRoles(userId, roleIds);
324 }
325
326
336 @SuppressWarnings("deprecation")
337 public void addDefaultUserGroups(long userId)
338 throws PortalException, SystemException {
339
340 User user = userPersistence.findByPrimaryKey(userId);
341
342 Set<Long> userGroupIdSet = new HashSet<Long>();
343
344 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
345 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
346 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
347
348 for (String defaultUserGroupName : defaultUserGroupNames) {
349 try {
350 UserGroup userGroup = userGroupPersistence.findByC_N(
351 user.getCompanyId(), defaultUserGroupName);
352
353 if (!userPersistence.containsUserGroup(
354 userId, userGroup.getUserGroupId())) {
355
356 userGroupIdSet.add(userGroup.getUserGroupId());
357 }
358 }
359 catch (NoSuchUserGroupException nsuge) {
360 }
361 }
362
363 long[] userGroupIds = ArrayUtil.toArray(
364 userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
365
366 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
367 for (long userGroupId : userGroupIds) {
368 userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
369 }
370 }
371
372 userPersistence.addUserGroups(userId, userGroupIds);
373 }
374
375
384 public void addGroupUsers(long groupId, long[] userIds)
385 throws PortalException, SystemException {
386
387 groupPersistence.addUsers(groupId, userIds);
388
389 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
390
391 indexer.reindex(userIds);
392
393 PermissionCacheUtil.clearCache();
394 }
395
396
405 public void addOrganizationUsers(long organizationId, long[] userIds)
406 throws PortalException, SystemException {
407
408 organizationPersistence.addUsers(organizationId, userIds);
409
410 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
411
412 indexer.reindex(userIds);
413
414 PermissionCacheUtil.clearCache();
415 }
416
417
425 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
426 throws SystemException {
427
428 passwordPolicyRelLocalService.addPasswordPolicyRels(
429 passwordPolicyId, User.class.getName(), userIds);
430 }
431
432
441 public void addRoleUsers(long roleId, long[] userIds)
442 throws PortalException, SystemException {
443
444 rolePersistence.addUsers(roleId, userIds);
445
446 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
447
448 indexer.reindex(userIds);
449
450 PermissionCacheUtil.clearCache();
451 }
452
453
462 public void addTeamUsers(long teamId, long[] userIds)
463 throws PortalException, SystemException {
464
465 teamPersistence.addUsers(teamId, userIds);
466
467 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
468
469 indexer.reindex(userIds);
470
471 PermissionCacheUtil.clearCache();
472 }
473
474
522 public User addUser(
523 long creatorUserId, long companyId, boolean autoPassword,
524 String password1, String password2, boolean autoScreenName,
525 String screenName, String emailAddress, long facebookId,
526 String openId, Locale locale, String firstName, String middleName,
527 String lastName, int prefixId, int suffixId, boolean male,
528 int birthdayMonth, int birthdayDay, int birthdayYear,
529 String jobTitle, long[] groupIds, long[] organizationIds,
530 long[] roleIds, long[] userGroupIds, boolean sendEmail,
531 ServiceContext serviceContext)
532 throws PortalException, SystemException {
533
534 boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
535
536 try {
537 WorkflowThreadLocal.setEnabled(false);
538
539 return addUserWithWorkflow(
540 creatorUserId, companyId, autoPassword, password1, password2,
541 autoScreenName, screenName, emailAddress, facebookId, openId,
542 locale, firstName, middleName, lastName, prefixId, suffixId,
543 male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
544 groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
545 serviceContext);
546 }
547 finally {
548 WorkflowThreadLocal.setEnabled(workflowEnabled);
549 }
550 }
551
552
561 @SuppressWarnings("deprecation")
562 public void addUserGroupUsers(long userGroupId, long[] userIds)
563 throws PortalException, SystemException {
564
565 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
566 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
567 }
568
569 userGroupPersistence.addUsers(userGroupId, userIds);
570
571 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
572
573 indexer.reindex(userIds);
574
575 PermissionCacheUtil.clearCache();
576 }
577
578
626 @SuppressWarnings("deprecation")
627 public User addUserWithWorkflow(
628 long creatorUserId, long companyId, boolean autoPassword,
629 String password1, String password2, boolean autoScreenName,
630 String screenName, String emailAddress, long facebookId,
631 String openId, Locale locale, String firstName, String middleName,
632 String lastName, int prefixId, int suffixId, boolean male,
633 int birthdayMonth, int birthdayDay, int birthdayYear,
634 String jobTitle, long[] groupIds, long[] organizationIds,
635 long[] roleIds, long[] userGroupIds, boolean sendEmail,
636 ServiceContext serviceContext)
637 throws PortalException, SystemException {
638
639
640
641 Company company = companyPersistence.findByPrimaryKey(companyId);
642 screenName = getScreenName(screenName);
643 emailAddress = emailAddress.trim().toLowerCase();
644 openId = openId.trim();
645 Date now = new Date();
646
647 if (PrefsPropsUtil.getBoolean(
648 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
649
650 autoScreenName = true;
651 }
652
653 long userId = counterLocalService.increment();
654
655 EmailAddressGenerator emailAddressGenerator =
656 EmailAddressGeneratorFactory.getInstance();
657
658 if (emailAddressGenerator.isGenerated(emailAddress)) {
659 emailAddress = StringPool.BLANK;
660 }
661
662 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
663 Validator.isNull(emailAddress)) {
664
665 emailAddress = emailAddressGenerator.generate(companyId, userId);
666 }
667
668 validate(
669 companyId, userId, autoPassword, password1, password2,
670 autoScreenName, screenName, emailAddress, firstName, middleName,
671 lastName, organizationIds);
672
673 if (!autoPassword) {
674 if (Validator.isNull(password1) || Validator.isNull(password2)) {
675 throw new UserPasswordException(
676 UserPasswordException.PASSWORD_INVALID);
677 }
678 }
679
680 if (autoScreenName) {
681 ScreenNameGenerator screenNameGenerator =
682 ScreenNameGeneratorFactory.getInstance();
683
684 try {
685 screenName = screenNameGenerator.generate(
686 companyId, userId, emailAddress);
687 }
688 catch (Exception e) {
689 throw new SystemException(e);
690 }
691 }
692
693 User defaultUser = getDefaultUser(companyId);
694
695 FullNameGenerator fullNameGenerator =
696 FullNameGeneratorFactory.getInstance();
697
698 String fullName = fullNameGenerator.getFullName(
699 firstName, middleName, lastName);
700
701 String greeting = LanguageUtil.format(
702 locale, "welcome-x", " " + fullName, false);
703
704 User user = userPersistence.create(userId);
705
706 if (serviceContext != null) {
707 String uuid = serviceContext.getUuid();
708
709 if (Validator.isNotNull(uuid)) {
710 user.setUuid(uuid);
711 }
712 }
713
714 user.setCompanyId(companyId);
715 user.setCreateDate(now);
716 user.setModifiedDate(now);
717 user.setDefaultUser(false);
718 user.setContactId(counterLocalService.increment());
719
720 if (Validator.isNotNull(password1)) {
721 user.setPassword(PwdEncryptor.encrypt(password1));
722 user.setPasswordUnencrypted(password1);
723 }
724
725 user.setPasswordEncrypted(true);
726
727 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
728
729 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
730 passwordPolicy.isChangeRequired()) {
731
732 user.setPasswordReset(true);
733 }
734 else {
735 user.setPasswordReset(false);
736 }
737
738 user.setDigest(StringPool.BLANK);
739 user.setScreenName(screenName);
740 user.setEmailAddress(emailAddress);
741 user.setFacebookId(facebookId);
742 user.setOpenId(openId);
743 user.setLanguageId(locale.toString());
744 user.setTimeZoneId(defaultUser.getTimeZoneId());
745 user.setGreeting(greeting);
746 user.setFirstName(firstName);
747 user.setMiddleName(middleName);
748 user.setLastName(lastName);
749 user.setJobTitle(jobTitle);
750 user.setStatus(WorkflowConstants.STATUS_DRAFT);
751 user.setExpandoBridgeAttributes(serviceContext);
752
753 userPersistence.update(user, false, serviceContext);
754
755
756
757 String creatorUserName = StringPool.BLANK;
758
759 if (creatorUserId <= 0) {
760 creatorUserId = user.getUserId();
761
762
763
764
765
766 }
767 else {
768 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
769
770 creatorUserName = creatorUser.getFullName();
771 }
772
773 resourceLocalService.addResources(
774 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
775 false, false, false);
776
777
778
779 Date birthday = PortalUtil.getDate(
780 birthdayMonth, birthdayDay, birthdayYear,
781 ContactBirthdayException.class);
782
783 Contact contact = contactPersistence.create(user.getContactId());
784
785 contact.setCompanyId(user.getCompanyId());
786 contact.setUserId(creatorUserId);
787 contact.setUserName(creatorUserName);
788 contact.setCreateDate(now);
789 contact.setModifiedDate(now);
790 contact.setAccountId(company.getAccountId());
791 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
792 contact.setFirstName(firstName);
793 contact.setMiddleName(middleName);
794 contact.setLastName(lastName);
795 contact.setPrefixId(prefixId);
796 contact.setSuffixId(suffixId);
797 contact.setMale(male);
798 contact.setBirthday(birthday);
799 contact.setJobTitle(jobTitle);
800
801 contactPersistence.update(contact, false, serviceContext);
802
803
804
805 groupLocalService.addGroup(
806 user.getUserId(), User.class.getName(), user.getUserId(), null,
807 null, 0, StringPool.SLASH + screenName, false, true, null);
808
809
810
811 if (groupIds != null) {
812 groupLocalService.addUserGroups(userId, groupIds);
813 }
814
815 addDefaultGroups(userId);
816
817
818
819 updateOrganizations(userId, organizationIds, false);
820
821
822
823 if (roleIds != null) {
824 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
825
826 userPersistence.setRoles(userId, roleIds);
827 }
828
829 addDefaultRoles(userId);
830
831
832
833 if (userGroupIds != null) {
834 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
835 for (long userGroupId : userGroupIds) {
836 userGroupLocalService.copyUserGroupLayouts(
837 userGroupId, new long[] {userId});
838 }
839 }
840
841 userPersistence.setUserGroups(userId, userGroupIds);
842 }
843
844 addDefaultUserGroups(userId);
845
846
847
848 if (serviceContext != null) {
849 updateAsset(
850 creatorUserId, user, serviceContext.getAssetCategoryIds(),
851 serviceContext.getAssetTagNames());
852 }
853
854
855
856 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
857 reindex(user);
858 }
859
860
861
862 long workflowUserId = creatorUserId;
863
864 if (workflowUserId == userId) {
865 workflowUserId = defaultUser.getUserId();
866 }
867
868 ServiceContext workflowServiceContext = serviceContext;
869
870 if (workflowServiceContext == null) {
871 workflowServiceContext = new ServiceContext();
872 }
873
874 workflowServiceContext.setAttribute("autoPassword", autoPassword);
875 workflowServiceContext.setAttribute("sendEmail", sendEmail);
876
877 WorkflowHandlerRegistryUtil.startWorkflowInstance(
878 companyId, workflowUserId, User.class.getName(), userId, user,
879 workflowServiceContext);
880
881 if (serviceContext != null) {
882 String passwordUnencrypted =
883 (String)serviceContext.getAttribute("passwordUnencrypted");
884
885 if (Validator.isNotNull(passwordUnencrypted)) {
886 user.setPasswordUnencrypted(passwordUnencrypted);
887 }
888 }
889
890 return user;
891 }
892
893
917 public int authenticateByEmailAddress(
918 long companyId, String emailAddress, String password,
919 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
920 Map<String, Object> resultsMap)
921 throws PortalException, SystemException {
922
923 return authenticate(
924 companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
925 headerMap, parameterMap, resultsMap);
926 }
927
928
952 public int authenticateByScreenName(
953 long companyId, String screenName, String password,
954 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
955 Map<String, Object> resultsMap)
956 throws PortalException, SystemException {
957
958 return authenticate(
959 companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
960 headerMap, parameterMap, resultsMap);
961 }
962
963
987 public int authenticateByUserId(
988 long companyId, long userId, String password,
989 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
990 Map<String, Object> resultsMap)
991 throws PortalException, SystemException {
992
993 return authenticate(
994 companyId, String.valueOf(userId), password,
995 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap, resultsMap);
996 }
997
998
1038 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1039 public long authenticateForBasic(
1040 long companyId, String authType, String login, String password)
1041 throws PortalException, SystemException {
1042
1043 if (PropsValues.AUTH_LOGIN_DISABLED) {
1044 return 0;
1045 }
1046
1047 try {
1048 User user = null;
1049
1050 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1051 user = getUserByEmailAddress(companyId, login);
1052 }
1053 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1054 user = getUserByScreenName(companyId, login);
1055 }
1056 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1057 user = getUserById(companyId, GetterUtil.getLong(login));
1058 }
1059
1060 if (user.isDefaultUser()) {
1061 if (_log.isInfoEnabled()) {
1062 _log.info(
1063 "Basic authentication is disabled for the default " +
1064 "user");
1065 }
1066
1067 return 0;
1068 }
1069 else if (!user.isActive()) {
1070 if (_log.isInfoEnabled()) {
1071 _log.info(
1072 "Basic authentication is disabled for inactive user " +
1073 user.getUserId());
1074 }
1075
1076 return 0;
1077 }
1078
1079 if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
1080 return user.getUserId();
1081 }
1082
1083 String userPassword = user.getPassword();
1084
1085 if (!user.isPasswordEncrypted()) {
1086 userPassword = PwdEncryptor.encrypt(userPassword);
1087 }
1088
1089 String encPassword = PwdEncryptor.encrypt(password);
1090
1091 if (userPassword.equals(password) ||
1092 userPassword.equals(encPassword)) {
1093
1094 return user.getUserId();
1095 }
1096 }
1097 catch (NoSuchUserException nsue) {
1098 }
1099
1100 return 0;
1101 }
1102
1103
1121 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1122 public long authenticateForDigest(
1123 long companyId, String username, String realm, String nonce,
1124 String method, String uri, String response)
1125 throws PortalException, SystemException {
1126
1127 if (PropsValues.AUTH_LOGIN_DISABLED) {
1128 return 0;
1129 }
1130
1131
1132
1133 User user = null;
1134
1135 try {
1136 user = getUserByEmailAddress(companyId, username);
1137 }
1138 catch (NoSuchUserException nsue) {
1139 try {
1140 user = getUserByScreenName(companyId, username);
1141 }
1142 catch (NoSuchUserException nsue2) {
1143 try {
1144 user = getUserById(GetterUtil.getLong(username));
1145 }
1146 catch (NoSuchUserException nsue3) {
1147 return 0;
1148 }
1149 }
1150 }
1151
1152 if (user.isDefaultUser()) {
1153 if (_log.isInfoEnabled()) {
1154 _log.info(
1155 "Digest authentication is disabled for the default user");
1156 }
1157
1158 return 0;
1159 }
1160 else if (!user.isActive()) {
1161 if (_log.isInfoEnabled()) {
1162 _log.info(
1163 "Digest authentication is disabled for inactive user " +
1164 user.getUserId());
1165 }
1166
1167 return 0;
1168 }
1169
1170
1171
1172 String digest = user.getDigest();
1173
1174 if (Validator.isNull(digest)) {
1175 _log.error(
1176 "User must first login through the portal " + user.getUserId());
1177
1178 return 0;
1179 }
1180
1181 String[] digestArray = StringUtil.split(user.getDigest());
1182
1183 for (String ha1 : digestArray) {
1184 String ha2 = DigesterUtil.digestHex(Digester.MD5, method, uri);
1185
1186 String curResponse = DigesterUtil.digestHex(
1187 Digester.MD5, ha1, nonce, ha2);
1188
1189 if (response.equals(curResponse)) {
1190 return user.getUserId();
1191 }
1192 }
1193
1194 return 0;
1195 }
1196
1197
1206 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1207 public boolean authenticateForJAAS(long userId, String encPassword) {
1208 if (PropsValues.AUTH_LOGIN_DISABLED) {
1209 return false;
1210 }
1211
1212 try {
1213 User user = userPersistence.findByPrimaryKey(userId);
1214
1215 if (user.isDefaultUser()) {
1216 if (_log.isInfoEnabled()) {
1217 _log.info(
1218 "JAAS authentication is disabled for the default user");
1219 }
1220
1221 return false;
1222 }
1223 else if (!user.isActive()) {
1224 if (_log.isInfoEnabled()) {
1225 _log.info(
1226 "JAAS authentication is disabled for inactive user " +
1227 userId);
1228 }
1229
1230 return false;
1231 }
1232
1233 String password = user.getPassword();
1234
1235 if (user.isPasswordEncrypted()) {
1236 if (password.equals(encPassword)) {
1237 return true;
1238 }
1239
1240 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1241 encPassword = PwdEncryptor.encrypt(encPassword, password);
1242
1243 if (password.equals(encPassword)) {
1244 return true;
1245 }
1246 }
1247 }
1248 else {
1249 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1250 if (password.equals(encPassword)) {
1251 return true;
1252 }
1253 }
1254
1255 password = PwdEncryptor.encrypt(password);
1256
1257 if (password.equals(encPassword)) {
1258 return true;
1259 }
1260 }
1261 }
1262 catch (Exception e) {
1263 _log.error(e);
1264 }
1265
1266 return false;
1267 }
1268
1269
1277 public void checkLockout(User user)
1278 throws PortalException, SystemException {
1279
1280 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1281 return;
1282 }
1283
1284 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1285
1286 if (passwordPolicy.isLockout()) {
1287
1288
1289
1290 Date now = new Date();
1291 int failedLoginAttempts = user.getFailedLoginAttempts();
1292
1293 if (failedLoginAttempts > 0) {
1294 long failedLoginTime = user.getLastFailedLoginDate().getTime();
1295 long elapsedTime = now.getTime() - failedLoginTime;
1296 long requiredElapsedTime =
1297 passwordPolicy.getResetFailureCount() * 1000;
1298
1299 if ((requiredElapsedTime != 0) &&
1300 (elapsedTime > requiredElapsedTime)) {
1301
1302 user.setLastFailedLoginDate(null);
1303 user.setFailedLoginAttempts(0);
1304
1305 userPersistence.update(user, false);
1306 }
1307 }
1308
1309
1310
1311 if (user.isLockout()) {
1312 long lockoutTime = user.getLockoutDate().getTime();
1313 long elapsedTime = now.getTime() - lockoutTime;
1314 long requiredElapsedTime =
1315 passwordPolicy.getLockoutDuration() * 1000;
1316
1317 if ((requiredElapsedTime != 0) &&
1318 (elapsedTime > requiredElapsedTime)) {
1319
1320 user.setLockout(false);
1321 user.setLockoutDate(null);
1322
1323 userPersistence.update(user, false);
1324 }
1325 }
1326
1327 if (user.isLockout()) {
1328 throw new UserLockoutException();
1329 }
1330 }
1331 }
1332
1333
1340 public void checkLoginFailure(User user) throws SystemException {
1341 Date now = new Date();
1342
1343 int failedLoginAttempts = user.getFailedLoginAttempts();
1344
1345 user.setLastFailedLoginDate(now);
1346 user.setFailedLoginAttempts(++failedLoginAttempts);
1347
1348 userPersistence.update(user, false);
1349 }
1350
1351
1361 public void checkLoginFailureByEmailAddress(
1362 long companyId, String emailAddress)
1363 throws PortalException, SystemException {
1364
1365 User user = getUserByEmailAddress(companyId, emailAddress);
1366
1367 checkLoginFailure(user);
1368 }
1369
1370
1378 public void checkLoginFailureById(long userId)
1379 throws PortalException, SystemException {
1380
1381 User user = userPersistence.findByPrimaryKey(userId);
1382
1383 checkLoginFailure(user);
1384 }
1385
1386
1395 public void checkLoginFailureByScreenName(long companyId, String screenName)
1396 throws PortalException, SystemException {
1397
1398 User user = getUserByScreenName(companyId, screenName);
1399
1400 checkLoginFailure(user);
1401 }
1402
1403
1413 public void checkPasswordExpired(User user)
1414 throws PortalException, SystemException {
1415
1416 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1417 return;
1418 }
1419
1420 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1421
1422
1423
1424 if (isPasswordExpired(user)) {
1425 int graceLoginCount = user.getGraceLoginCount();
1426
1427 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
1428 user.setGraceLoginCount(++graceLoginCount);
1429
1430 userPersistence.update(user, false);
1431 }
1432 else {
1433 user.setDigest(StringPool.BLANK);
1434
1435 userPersistence.update(user, false);
1436
1437 throw new PasswordExpiredException();
1438 }
1439 }
1440
1441
1442
1443 if (passwordPolicy.isChangeable() &&
1444 passwordPolicy.isChangeRequired()) {
1445
1446 if (user.getLastLoginDate() == null) {
1447 user.setPasswordReset(true);
1448
1449 userPersistence.update(user, false);
1450 }
1451 }
1452 }
1453
1454
1460 public void clearOrganizationUsers(long organizationId)
1461 throws SystemException {
1462
1463 organizationPersistence.clearUsers(organizationId);
1464
1465 PermissionCacheUtil.clearCache();
1466 }
1467
1468
1474 public void clearUserGroupUsers(long userGroupId) throws SystemException {
1475 userGroupPersistence.clearUsers(userGroupId);
1476
1477 PermissionCacheUtil.clearCache();
1478 }
1479
1480
1492 public void completeUserRegistration(
1493 User user, ServiceContext serviceContext)
1494 throws PortalException, SystemException {
1495
1496 boolean autoPassword = ParamUtil.getBoolean(
1497 serviceContext, "autoPassword");
1498
1499 String password = null;
1500
1501 if (autoPassword) {
1502 PasswordPolicy passwordPolicy =
1503 passwordPolicyLocalService.getPasswordPolicy(
1504 user.getCompanyId(), user.getOrganizationIds());
1505
1506 password = PwdToolkitUtil.generate(passwordPolicy);
1507
1508 user.setPassword(PwdEncryptor.encrypt(password));
1509 user.setPasswordEncrypted(true);
1510 user.setPasswordUnencrypted(password);
1511
1512 userPersistence.update(user, false);
1513
1514 }
1515
1516 if (user.hasCompanyMx()) {
1517 String mailPassword = password;
1518
1519 if (Validator.isNull(mailPassword)) {
1520 mailPassword = user.getPasswordUnencrypted();
1521 }
1522
1523 mailService.addUser(
1524 user.getCompanyId(), user.getUserId(), mailPassword,
1525 user.getFirstName(), user.getMiddleName(), user.getLastName(),
1526 user.getEmailAddress());
1527 }
1528
1529 boolean sendEmail = ParamUtil.getBoolean(serviceContext, "sendEmail");
1530
1531 if (sendEmail) {
1532 sendEmail(user, password, serviceContext);
1533 }
1534
1535 Company company = companyPersistence.findByPrimaryKey(
1536 user.getCompanyId());
1537
1538 if (company.isStrangersVerify() && (serviceContext.getPlid() > 0)) {
1539 sendEmailAddressVerification(
1540 user, user.getEmailAddress(), serviceContext);
1541 }
1542 }
1543
1544
1557 public KeyValuePair decryptUserId(
1558 long companyId, String name, String password)
1559 throws PortalException, SystemException {
1560
1561 Company company = companyPersistence.findByPrimaryKey(companyId);
1562
1563 try {
1564 name = Encryptor.decrypt(company.getKeyObj(), name);
1565 }
1566 catch (EncryptorException ee) {
1567 throw new SystemException(ee);
1568 }
1569
1570 long userId = GetterUtil.getLong(name);
1571
1572 User user = userPersistence.findByPrimaryKey(userId);
1573
1574 try {
1575 password = Encryptor.decrypt(company.getKeyObj(), password);
1576 }
1577 catch (EncryptorException ee) {
1578 throw new SystemException(ee);
1579 }
1580
1581 String encPassword = PwdEncryptor.encrypt(password);
1582
1583 if (user.getPassword().equals(encPassword)) {
1584 if (isPasswordExpired(user)) {
1585 user.setPasswordReset(true);
1586
1587 userPersistence.update(user, false);
1588 }
1589
1590 return new KeyValuePair(name, password);
1591 }
1592 else {
1593 throw new PrincipalException();
1594 }
1595 }
1596
1597
1605 public void deletePortrait(long userId)
1606 throws PortalException, SystemException {
1607
1608 User user = userPersistence.findByPrimaryKey(userId);
1609
1610 long portraitId = user.getPortraitId();
1611
1612 if (portraitId > 0) {
1613 user.setPortraitId(0);
1614
1615 userPersistence.update(user, false);
1616
1617 imageLocalService.deleteImage(portraitId);
1618 }
1619 }
1620
1621
1630 public void deleteRoleUser(long roleId, long userId)
1631 throws PortalException, SystemException {
1632
1633 rolePersistence.removeUser(roleId, userId);
1634
1635 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1636
1637 indexer.reindex(userId);
1638
1639 PermissionCacheUtil.clearCache();
1640 }
1641
1642
1649 @Override
1650 public User deleteUser(long userId)
1651 throws PortalException, SystemException {
1652
1653 User user = userPersistence.findByPrimaryKey(userId);
1654
1655 return deleteUser(user);
1656 }
1657
1658
1665 @Override
1666 public User deleteUser(User user) throws PortalException, SystemException {
1667 if (!PropsValues.USERS_DELETE) {
1668 throw new RequiredUserException();
1669 }
1670
1671
1672
1673 browserTrackerLocalService.deleteUserBrowserTracker(user.getUserId());
1674
1675
1676
1677 Group group = user.getGroup();
1678
1679 if (group != null) {
1680 groupLocalService.deleteGroup(group);
1681 }
1682
1683
1684
1685 imageLocalService.deleteImage(user.getPortraitId());
1686
1687
1688
1689 passwordPolicyRelLocalService.deletePasswordPolicyRel(
1690 User.class.getName(), user.getUserId());
1691
1692
1693
1694 passwordTrackerLocalService.deletePasswordTrackers(user.getUserId());
1695
1696
1697
1698 subscriptionLocalService.deleteSubscriptions(user.getUserId());
1699
1700
1701
1702 userIdMapperLocalService.deleteUserIdMappers(user.getUserId());
1703
1704
1705
1706 announcementsDeliveryLocalService.deleteDeliveries(user.getUserId());
1707
1708
1709
1710 assetEntryLocalService.deleteEntry(
1711 User.class.getName(), user.getUserId());
1712
1713
1714
1715 blogsStatsUserLocalService.deleteStatsUserByUserId(user.getUserId());
1716
1717
1718
1719 dlFileRankLocalService.deleteFileRanksByUserId(user.getUserId());
1720
1721
1722
1723 expandoValueLocalService.deleteValues(
1724 User.class.getName(), user.getUserId());
1725
1726
1727
1728 mbBanLocalService.deleteBansByBanUserId(user.getUserId());
1729 mbStatsUserLocalService.deleteStatsUsersByUserId(user.getUserId());
1730 mbThreadFlagLocalService.deleteThreadFlagsByUserId(user.getUserId());
1731
1732
1733
1734 membershipRequestLocalService.deleteMembershipRequestsByUserId(
1735 user.getUserId());
1736
1737
1738
1739 shoppingCartLocalService.deleteUserCarts(user.getUserId());
1740
1741
1742
1743 socialActivityLocalService.deleteUserActivities(user.getUserId());
1744 socialRequestLocalService.deleteReceiverUserRequests(user.getUserId());
1745 socialRequestLocalService.deleteUserRequests(user.getUserId());
1746
1747
1748
1749 mailService.deleteUser(user.getCompanyId(), user.getUserId());
1750
1751
1752
1753 try {
1754 contactLocalService.deleteContact(user.getContactId());
1755 }
1756 catch (NoSuchContactException nsce) {
1757 }
1758
1759
1760
1761 resourceLocalService.deleteResource(
1762 user.getCompanyId(), User.class.getName(),
1763 ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
1764
1765
1766
1767 userGroupRoleLocalService.deleteUserGroupRolesByUserId(
1768 user.getUserId());
1769
1770
1771
1772 userPersistence.remove(user);
1773
1774
1775
1776 PermissionCacheUtil.clearCache();
1777
1778
1779
1780 workflowInstanceLinkLocalService.deleteWorkflowInstanceLinks(
1781 user.getCompanyId(), 0, User.class.getName(), user.getUserId());
1782
1783 return user;
1784 }
1785
1786
1794 public void deleteUserGroupUser(long userGroupId, long userId)
1795 throws PortalException, SystemException {
1796
1797 userGroupPersistence.removeUser(userGroupId, userId);
1798
1799 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1800
1801 indexer.reindex(userId);
1802
1803 PermissionCacheUtil.clearCache();
1804 }
1805
1806
1815 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1816 public String encryptUserId(String name)
1817 throws PortalException, SystemException {
1818
1819 long userId = GetterUtil.getLong(name);
1820
1821 User user = userPersistence.findByPrimaryKey(userId);
1822
1823 Company company = companyPersistence.findByPrimaryKey(
1824 user.getCompanyId());
1825
1826 try {
1827 return Encryptor.encrypt(company.getKeyObj(), name);
1828 }
1829 catch (EncryptorException ee) {
1830 throw new SystemException(ee);
1831 }
1832 }
1833
1834
1843 public User fetchUserByEmailAddress(long companyId, String emailAddress)
1844 throws SystemException {
1845
1846 return userPersistence.fetchByC_EA(companyId, emailAddress);
1847 }
1848
1849
1857 public User fetchUserById(long userId) throws SystemException {
1858 return userPersistence.fetchByPrimaryKey(userId);
1859 }
1860
1861
1870 public User fetchUserByScreenName(long companyId, String screenName)
1871 throws SystemException {
1872
1873 screenName = getScreenName(screenName);
1874
1875 return userPersistence.fetchByC_SN(companyId, screenName);
1876 }
1877
1878
1897 public List<User> getCompanyUsers(long companyId, int start, int end)
1898 throws SystemException {
1899
1900 return userPersistence.findByCompanyId(companyId, start, end);
1901 }
1902
1903
1910 public int getCompanyUsersCount(long companyId) throws SystemException {
1911 return userPersistence.countByCompanyId(companyId);
1912 }
1913
1914
1923 @Skip
1924 public User getDefaultUser(long companyId)
1925 throws PortalException, SystemException {
1926
1927 User userModel = _defaultUsers.get(companyId);
1928
1929 if (userModel == null) {
1930 userModel = userLocalService.loadGetDefaultUser(companyId);
1931
1932 _defaultUsers.put(companyId, userModel);
1933 }
1934
1935 return userModel;
1936 }
1937
1938
1947 @Skip
1948 public long getDefaultUserId(long companyId)
1949 throws PortalException, SystemException {
1950
1951 User user = getDefaultUser(companyId);
1952
1953 return user.getUserId();
1954 }
1955
1956
1963 public long[] getGroupUserIds(long groupId) throws SystemException {
1964 return getUserIds(getGroupUsers(groupId));
1965 }
1966
1967
1974 public List<User> getGroupUsers(long groupId) throws SystemException {
1975 return groupPersistence.getUsers(groupId);
1976 }
1977
1978
1985 public int getGroupUsersCount(long groupId) throws SystemException {
1986 return groupPersistence.getUsersSize(groupId);
1987 }
1988
1989
1999 public int getGroupUsersCount(long groupId, int status)
2000 throws PortalException, SystemException {
2001
2002 Group group = groupPersistence.findByPrimaryKey(groupId);
2003
2004 LinkedHashMap<String, Object> params =
2005 new LinkedHashMap<String, Object>();
2006
2007 params.put("usersGroups", new Long(groupId));
2008
2009 return searchCount(group.getCompanyId(), null, status, params);
2010 }
2011
2012
2020 public List<User> getNoAnnouncementsDeliveries(String type)
2021 throws SystemException {
2022
2023 return userFinder.findByNoAnnouncementsDeliveries(type);
2024 }
2025
2026
2032 public List<User> getNoContacts() throws SystemException {
2033 return userFinder.findByNoContacts();
2034 }
2035
2036
2043 public List<User> getNoGroups() throws SystemException {
2044 return userFinder.findByNoGroups();
2045 }
2046
2047
2054 public long[] getOrganizationUserIds(long organizationId)
2055 throws SystemException {
2056
2057 return getUserIds(getOrganizationUsers(organizationId));
2058 }
2059
2060
2067 public List<User> getOrganizationUsers(long organizationId)
2068 throws SystemException {
2069
2070 return organizationPersistence.getUsers(organizationId);
2071 }
2072
2073
2080 public int getOrganizationUsersCount(long organizationId)
2081 throws SystemException {
2082
2083 return organizationPersistence.getUsersSize(organizationId);
2084 }
2085
2086
2097 public int getOrganizationUsersCount(long organizationId, int status)
2098 throws PortalException, SystemException {
2099
2100 Organization organization = organizationPersistence.findByPrimaryKey(
2101 organizationId);
2102
2103 LinkedHashMap<String, Object> params =
2104 new LinkedHashMap<String, Object>();
2105
2106 params.put("usersOrgs", new Long(organizationId));
2107
2108 return searchCount(organization.getCompanyId(), null, status, params);
2109 }
2110
2111
2118 public long[] getRoleUserIds(long roleId) throws SystemException {
2119 return getUserIds(getRoleUsers(roleId));
2120 }
2121
2122
2129 public List<User> getRoleUsers(long roleId) throws SystemException {
2130 return rolePersistence.getUsers(roleId);
2131 }
2132
2133
2152 public List<User> getRoleUsers(long roleId, int start, int end)
2153 throws SystemException {
2154
2155 return rolePersistence.getUsers(roleId, start, end);
2156 }
2157
2158
2165 public int getRoleUsersCount(long roleId) throws SystemException {
2166 return rolePersistence.getUsersSize(roleId);
2167 }
2168
2169
2179 public int getRoleUsersCount(long roleId, int status)
2180 throws PortalException, SystemException {
2181
2182 Role role = rolePersistence.findByPrimaryKey(roleId);
2183
2184 LinkedHashMap<String, Object> params =
2185 new LinkedHashMap<String, Object>();
2186
2187 params.put("usersRoles", new Long(roleId));
2188
2189 return searchCount(role.getCompanyId(), null, status, params);
2190 }
2191
2192
2219 public List<User> getSocialUsers(
2220 long userId, int type, int start, int end, OrderByComparator obc)
2221 throws PortalException, SystemException {
2222
2223 User user = userPersistence.findByPrimaryKey(userId);
2224
2225 LinkedHashMap<String, Object> params =
2226 new LinkedHashMap<String, Object>();
2227
2228 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2229
2230 return search(
2231 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2232 params, start, end, obc);
2233 }
2234
2235
2258 public List<User> getSocialUsers(
2259 long userId, int start, int end, OrderByComparator obc)
2260 throws PortalException, SystemException {
2261
2262 User user = userPersistence.findByPrimaryKey(userId);
2263
2264 LinkedHashMap<String, Object> params =
2265 new LinkedHashMap<String, Object>();
2266
2267 params.put("socialRelation", new Long[] {userId});
2268
2269 return search(
2270 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2271 params, start, end, obc);
2272 }
2273
2274
2302 public List<User> getSocialUsers(
2303 long userId1, long userId2, int type, int start, int end,
2304 OrderByComparator obc)
2305 throws PortalException, SystemException {
2306
2307 User user1 = userPersistence.findByPrimaryKey(userId1);
2308
2309 LinkedHashMap<String, Object> params =
2310 new LinkedHashMap<String, Object>();
2311
2312 params.put(
2313 "socialMutualRelationType",
2314 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2315
2316 return search(
2317 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2318 params, start, end, obc);
2319 }
2320
2321
2346 public List<User> getSocialUsers(
2347 long userId1, long userId2, int start, int end,
2348 OrderByComparator obc)
2349 throws PortalException, SystemException {
2350
2351 User user1 = userPersistence.findByPrimaryKey(userId1);
2352
2353 LinkedHashMap<String, Object> params =
2354 new LinkedHashMap<String, Object>();
2355
2356 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2357
2358 return search(
2359 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2360 params, start, end, obc);
2361 }
2362
2363
2371 public int getSocialUsersCount(long userId)
2372 throws PortalException, SystemException {
2373
2374 User user = userPersistence.findByPrimaryKey(userId);
2375
2376 LinkedHashMap<String, Object> params =
2377 new LinkedHashMap<String, Object>();
2378
2379 params.put("socialRelation", new Long[] {userId});
2380
2381 return searchCount(
2382 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2383 params);
2384 }
2385
2386
2399 public int getSocialUsersCount(long userId, int type)
2400 throws PortalException, SystemException {
2401
2402 User user = userPersistence.findByPrimaryKey(userId);
2403
2404 LinkedHashMap<String, Object> params =
2405 new LinkedHashMap<String, Object>();
2406
2407 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2408
2409 return searchCount(
2410 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2411 params);
2412 }
2413
2414
2424 public int getSocialUsersCount(long userId1, long userId2)
2425 throws PortalException, SystemException {
2426
2427 User user1 = userPersistence.findByPrimaryKey(userId1);
2428
2429 LinkedHashMap<String, Object> params =
2430 new LinkedHashMap<String, Object>();
2431
2432 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2433
2434 return searchCount(
2435 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2436 params);
2437 }
2438
2439
2453 public int getSocialUsersCount(long userId1, long userId2, int type)
2454 throws PortalException, SystemException {
2455
2456 User user1 = userPersistence.findByPrimaryKey(userId1);
2457
2458 LinkedHashMap<String, Object> params =
2459 new LinkedHashMap<String, Object>();
2460
2461 params.put(
2462 "socialMutualRelationType",
2463 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2464
2465 return searchCount(
2466 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2467 params);
2468 }
2469
2470
2478 public User getUserByContactId(long contactId)
2479 throws PortalException, SystemException {
2480
2481 return userPersistence.findByContactId(contactId);
2482 }
2483
2484
2494 public User getUserByEmailAddress(long companyId, String emailAddress)
2495 throws PortalException, SystemException {
2496
2497 emailAddress = emailAddress.trim().toLowerCase();
2498
2499 return userPersistence.findByC_EA(companyId, emailAddress);
2500 }
2501
2502
2511 public User getUserByFacebookId(long companyId, long facebookId)
2512 throws PortalException, SystemException {
2513
2514 return userPersistence.findByC_FID(companyId, facebookId);
2515 }
2516
2517
2525 public User getUserById(long userId)
2526 throws PortalException, SystemException {
2527
2528 return userPersistence.findByPrimaryKey(userId);
2529 }
2530
2531
2541 public User getUserById(long companyId, long userId)
2542 throws PortalException, SystemException {
2543
2544 return userPersistence.findByC_U(companyId, userId);
2545 }
2546
2547
2556 public User getUserByOpenId(long companyId, String openId)
2557 throws PortalException, SystemException {
2558
2559 return userPersistence.findByC_O(companyId, openId);
2560 }
2561
2562
2570 public User getUserByPortraitId(long portraitId)
2571 throws PortalException, SystemException {
2572
2573 return userPersistence.findByPortraitId(portraitId);
2574 }
2575
2576
2585 public User getUserByScreenName(long companyId, String screenName)
2586 throws PortalException, SystemException {
2587
2588 screenName = getScreenName(screenName);
2589
2590 return userPersistence.findByC_SN(companyId, screenName);
2591 }
2592
2593
2602 public User getUserByUuid(String uuid)
2603 throws PortalException, SystemException {
2604
2605 List<User> users = userPersistence.findByUuid(uuid);
2606
2607 if (users.isEmpty()) {
2608 throw new NoSuchUserException();
2609 }
2610 else {
2611 return users.get(0);
2612 }
2613 }
2614
2615
2622 public List<User> getUserGroupUsers(long userGroupId)
2623 throws SystemException {
2624
2625 return userGroupPersistence.getUsers(userGroupId);
2626 }
2627
2628
2635 public int getUserGroupUsersCount(long userGroupId) throws SystemException {
2636 return userGroupPersistence.getUsersSize(userGroupId);
2637 }
2638
2639
2649 public int getUserGroupUsersCount(long userGroupId, int status)
2650 throws PortalException, SystemException {
2651
2652 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
2653 userGroupId);
2654
2655 LinkedHashMap<String, Object> params =
2656 new LinkedHashMap<String, Object>();
2657
2658 params.put("usersUserGroups", new Long(userGroupId));
2659
2660 return searchCount(userGroup.getCompanyId(), null, status, params);
2661 }
2662
2663
2673 public long getUserIdByEmailAddress(long companyId, String emailAddress)
2674 throws PortalException, SystemException {
2675
2676 emailAddress = emailAddress.trim().toLowerCase();
2677
2678 User user = userPersistence.findByC_EA(companyId, emailAddress);
2679
2680 return user.getUserId();
2681 }
2682
2683
2692 public long getUserIdByScreenName(long companyId, String screenName)
2693 throws PortalException, SystemException {
2694
2695 screenName = getScreenName(screenName);
2696
2697 User user = userPersistence.findByC_SN(companyId, screenName);
2698
2699 return user.getUserId();
2700 }
2701
2702
2711 public boolean hasGroupUser(long groupId, long userId)
2712 throws SystemException {
2713
2714 return groupPersistence.containsUser(groupId, userId);
2715 }
2716
2717
2726 public boolean hasOrganizationUser(long organizationId, long userId)
2727 throws SystemException {
2728
2729 return organizationPersistence.containsUser(organizationId, userId);
2730 }
2731
2732
2742 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
2743 throws SystemException {
2744
2745 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
2746 passwordPolicyId, User.class.getName(), userId);
2747 }
2748
2749
2758 public boolean hasRoleUser(long roleId, long userId)
2759 throws SystemException {
2760
2761 return rolePersistence.containsUser(roleId, userId);
2762 }
2763
2764
2779 public boolean hasRoleUser(
2780 long companyId, String name, long userId, boolean inherited)
2781 throws PortalException, SystemException {
2782
2783 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
2784 }
2785
2786
2795 public boolean hasTeamUser(long teamId, long userId)
2796 throws SystemException {
2797
2798 return teamPersistence.containsUser(teamId, userId);
2799 }
2800
2801
2810 public boolean hasUserGroupUser(long userGroupId, long userId)
2811 throws SystemException {
2812
2813 return userGroupPersistence.containsUser(userGroupId, userId);
2814 }
2815
2816
2826 public boolean isPasswordExpired(User user)
2827 throws PortalException, SystemException {
2828
2829 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2830
2831 if (passwordPolicy.getExpireable()) {
2832 Date now = new Date();
2833
2834 if (user.getPasswordModifiedDate() == null) {
2835 user.setPasswordModifiedDate(now);
2836
2837 userLocalService.updateUser(user, false);
2838 }
2839
2840 long passwordStartTime = user.getPasswordModifiedDate().getTime();
2841 long elapsedTime = now.getTime() - passwordStartTime;
2842
2843 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
2844 return true;
2845 }
2846 else {
2847 return false;
2848 }
2849 }
2850
2851 return false;
2852 }
2853
2854
2864 public boolean isPasswordExpiringSoon(User user)
2865 throws PortalException, SystemException {
2866
2867 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2868
2869 if (passwordPolicy.isExpireable()) {
2870 Date now = new Date();
2871
2872 if (user.getPasswordModifiedDate() == null) {
2873 user.setPasswordModifiedDate(now);
2874
2875 userLocalService.updateUser(user, false);
2876 }
2877
2878 long timeModified = user.getPasswordModifiedDate().getTime();
2879 long passwordExpiresOn =
2880 (passwordPolicy.getMaxAge() * 1000) + timeModified;
2881
2882 long timeStartWarning =
2883 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
2884
2885 if (now.getTime() > timeStartWarning) {
2886 return true;
2887 }
2888 else {
2889 return false;
2890 }
2891 }
2892
2893 return false;
2894 }
2895
2896 public User loadGetDefaultUser(long companyId)
2897 throws PortalException, SystemException {
2898
2899 return userPersistence.findByC_DU(companyId, true);
2900 }
2901
2902
2934 public List<User> search(
2935 long companyId, String keywords, int status,
2936 LinkedHashMap<String, Object> params, int start, int end,
2937 OrderByComparator obc)
2938 throws SystemException {
2939
2940 return userFinder.findByKeywords(
2941 companyId, keywords, status, params, start, end, obc);
2942 }
2943
2944
2975 public Hits search(
2976 long companyId, String keywords, int status,
2977 LinkedHashMap<String, Object> params, int start, int end, Sort sort)
2978 throws SystemException {
2979
2980 String firstName = null;
2981 String middleName = null;
2982 String lastName = null;
2983 String fullName = null;
2984 String screenName = null;
2985 String emailAddress = null;
2986 String street = null;
2987 String city = null;
2988 String zip = null;
2989 String region = null;
2990 String country = null;
2991 boolean andOperator = false;
2992
2993 if (Validator.isNotNull(keywords)) {
2994 firstName = keywords;
2995 middleName = keywords;
2996 lastName = keywords;
2997 fullName = keywords;
2998 screenName = keywords;
2999 emailAddress = keywords;
3000 street = keywords;
3001 city = keywords;
3002 zip = keywords;
3003 region = keywords;
3004 country = keywords;
3005 }
3006 else {
3007 andOperator = true;
3008 }
3009
3010 if (params != null) {
3011 params.put("keywords", keywords);
3012 }
3013
3014 return search(
3015 companyId, firstName, middleName, lastName, fullName, screenName,
3016 emailAddress, street, city, zip, region, country, status, params,
3017 andOperator, start, end, sort);
3018 }
3019
3020
3060 public List<User> search(
3061 long companyId, String firstName, String middleName,
3062 String lastName, String screenName, String emailAddress, int status,
3063 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3064 int end, OrderByComparator obc)
3065 throws SystemException {
3066
3067 return userFinder.findByC_FN_MN_LN_SN_EA_S(
3068 companyId, firstName, middleName, lastName, screenName,
3069 emailAddress, status, params, andSearch, start, end, obc);
3070 }
3071
3072
3111 public Hits search(
3112 long companyId, String firstName, String middleName,
3113 String lastName, String screenName, String emailAddress, int status,
3114 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3115 int end, Sort sort)
3116 throws SystemException {
3117
3118 return search(
3119 companyId, firstName, middleName, lastName, null, screenName,
3120 emailAddress, null, null, null, null, null, status, params,
3121 andSearch, start, end, sort);
3122 }
3123
3124
3138 public int searchCount(
3139 long companyId, String keywords, int status,
3140 LinkedHashMap<String, Object> params)
3141 throws SystemException {
3142
3143 return userFinder.countByKeywords(companyId, keywords, status, params);
3144 }
3145
3146
3168 public int searchCount(
3169 long companyId, String firstName, String middleName,
3170 String lastName, String screenName, String emailAddress, int status,
3171 LinkedHashMap<String, Object> params, boolean andSearch)
3172 throws SystemException {
3173
3174 return userFinder.countByC_FN_MN_LN_SN_EA_S(
3175 companyId, firstName, middleName, lastName, screenName,
3176 emailAddress, status, params, andSearch);
3177 }
3178
3179
3190 public void sendEmailAddressVerification(
3191 User user, String emailAddress, ServiceContext serviceContext)
3192 throws PortalException, SystemException {
3193
3194 if (user.isEmailAddressVerified() &&
3195 emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
3196
3197 return;
3198 }
3199
3200 Ticket ticket = ticketLocalService.addTicket(
3201 user.getCompanyId(), User.class.getName(), user.getUserId(),
3202 TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3203 serviceContext);
3204
3205 String verifyEmailAddressURL =
3206 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3207 "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3208
3209 Layout layout = layoutLocalService.getLayout(serviceContext.getPlid());
3210
3211 Group group = layout.getGroup();
3212
3213 if (!layout.isPrivateLayout() && !group.isUser()) {
3214 verifyEmailAddressURL += "&p_l_id=" + serviceContext.getPlid();
3215 }
3216
3217 String fromName = PrefsPropsUtil.getString(
3218 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3219 String fromAddress = PrefsPropsUtil.getString(
3220 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3221
3222 String toName = user.getFullName();
3223 String toAddress = emailAddress;
3224
3225 String subject = PrefsPropsUtil.getContent(
3226 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3227
3228 String body = PrefsPropsUtil.getContent(
3229 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3230
3231 SubscriptionSender subscriptionSender = new SubscriptionSender();
3232
3233 subscriptionSender.setBody(body);
3234 subscriptionSender.setCompanyId(user.getCompanyId());
3235 subscriptionSender.setContextAttributes(
3236 "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3237 "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3238 "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3239 "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_ID$]",
3240 user.getUserId(), "[$USER_SCREENNAME$]", user.getScreenName());
3241 subscriptionSender.setFrom(fromAddress, fromName);
3242 subscriptionSender.setHtmlFormat(true);
3243 subscriptionSender.setMailId("user", user.getUserId());
3244 subscriptionSender.setServiceContext(serviceContext);
3245 subscriptionSender.setSubject(subject);
3246 subscriptionSender.setUserId(user.getUserId());
3247
3248 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3249
3250 subscriptionSender.flushNotificationsAsync();
3251 }
3252
3253
3272 public void sendPassword(
3273 long companyId, String emailAddress, String fromName,
3274 String fromAddress, String subject, String body,
3275 ServiceContext serviceContext)
3276 throws PortalException, SystemException {
3277
3278 Company company = companyPersistence.findByPrimaryKey(companyId);
3279
3280 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3281 return;
3282 }
3283
3284 emailAddress = emailAddress.trim().toLowerCase();
3285
3286 if (Validator.isNull(emailAddress)) {
3287 throw new UserEmailAddressException();
3288 }
3289
3290 User user = userPersistence.findByC_EA(companyId, emailAddress);
3291
3292 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3293
3294 String newPassword = StringPool.BLANK;
3295 String passwordResetURL = StringPool.BLANK;
3296
3297 if (company.isSendPasswordResetLink()) {
3298 Date expirationDate = null;
3299
3300 if (passwordPolicy.getResetTicketMaxAge() > 0) {
3301 expirationDate = new Date(
3302 System.currentTimeMillis() +
3303 (passwordPolicy.getResetTicketMaxAge() * 1000));
3304 }
3305
3306 Ticket ticket = ticketLocalService.addTicket(
3307 companyId, User.class.getName(), user.getUserId(),
3308 TicketConstants.TYPE_PASSWORD, null, expirationDate,
3309 serviceContext);
3310
3311 passwordResetURL =
3312 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3313 "/portal/update_password?p_l_id="+
3314 serviceContext.getPlid() +
3315 "&ticketKey=" + ticket.getKey();
3316 }
3317 else {
3318 if (!PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
3319 PwdEncryptor.TYPE_NONE)) {
3320
3321 newPassword = PwdToolkitUtil.generate(passwordPolicy);
3322
3323 boolean passwordReset = false;
3324
3325 if (passwordPolicy.getChangeable() &&
3326 passwordPolicy.getChangeRequired()) {
3327
3328 passwordReset = true;
3329 }
3330
3331 user.setPassword(PwdEncryptor.encrypt(newPassword));
3332 user.setPasswordUnencrypted(newPassword);
3333 user.setPasswordEncrypted(true);
3334 user.setPasswordReset(passwordReset);
3335 user.setPasswordModified(true);
3336 user.setPasswordModifiedDate(new Date());
3337
3338 userPersistence.update(user, false);
3339
3340 user.setPasswordModified(false);
3341 }
3342 else {
3343 newPassword = user.getPassword();
3344 }
3345 }
3346
3347 if (Validator.isNull(fromName)) {
3348 fromName = PrefsPropsUtil.getString(
3349 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3350 }
3351
3352 if (Validator.isNull(fromAddress)) {
3353 fromAddress = PrefsPropsUtil.getString(
3354 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3355 }
3356
3357 String toName = user.getFullName();
3358 String toAddress = user.getEmailAddress();
3359
3360 if (Validator.isNull(subject)) {
3361 if (company.isSendPasswordResetLink()) {
3362 subject = PrefsPropsUtil.getContent(
3363 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
3364 }
3365 else {
3366 subject = PrefsPropsUtil.getContent(
3367 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
3368 }
3369 }
3370
3371 if (Validator.isNull(body)) {
3372 if (company.isSendPasswordResetLink()) {
3373 body = PrefsPropsUtil.getContent(
3374 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
3375 }
3376 else {
3377 body = PrefsPropsUtil.getContent(
3378 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
3379 }
3380 }
3381
3382 SubscriptionSender subscriptionSender = new SubscriptionSender();
3383
3384 subscriptionSender.setBody(body);
3385 subscriptionSender.setCompanyId(companyId);
3386 subscriptionSender.setContextAttributes(
3387 "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
3388 serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
3389 serviceContext.getRemoteHost(), "[$USER_ID$]", user.getUserId(),
3390 "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
3391 user.getScreenName());
3392 subscriptionSender.setFrom(fromAddress, fromName);
3393 subscriptionSender.setHtmlFormat(true);
3394 subscriptionSender.setMailId("user", user.getUserId());
3395 subscriptionSender.setServiceContext(serviceContext);
3396 subscriptionSender.setSubject(subject);
3397 subscriptionSender.setUserId(user.getUserId());
3398
3399 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3400
3401 subscriptionSender.flushNotificationsAsync();
3402 }
3403
3404
3413 public void setRoleUsers(long roleId, long[] userIds)
3414 throws PortalException, SystemException {
3415
3416 rolePersistence.setUsers(roleId, userIds);
3417
3418 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3419
3420 indexer.reindex(userIds);
3421
3422 PermissionCacheUtil.clearCache();
3423 }
3424
3425
3434 @SuppressWarnings("deprecation")
3435 public void setUserGroupUsers(long userGroupId, long[] userIds)
3436 throws PortalException, SystemException {
3437
3438 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3439 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3440 }
3441
3442 userGroupPersistence.setUsers(userGroupId, userIds);
3443
3444 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3445
3446 indexer.reindex(userIds);
3447
3448 PermissionCacheUtil.clearCache();
3449 }
3450
3451
3459 public void unsetGroupTeamsUsers(long groupId, long[] userIds)
3460 throws PortalException, SystemException {
3461
3462 List<Team> teams = teamPersistence.findByGroupId(groupId);
3463
3464 for (Team team : teams) {
3465 unsetTeamUsers(team.getTeamId(), userIds);
3466 }
3467
3468 PermissionCacheUtil.clearCache();
3469 }
3470
3471
3479 public void unsetGroupUsers(
3480 long groupId, long[] userIds, ServiceContext serviceContext)
3481 throws PortalException, SystemException {
3482
3483 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
3484
3485 userLocalService.unsetGroupTeamsUsers(groupId, userIds);
3486
3487 groupPersistence.removeUsers(groupId, userIds);
3488
3489 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3490
3491 indexer.reindex(userIds);
3492
3493 PermissionCacheUtil.clearCache();
3494 }
3495
3496
3504 public void unsetOrganizationUsers(long organizationId, long[] userIds)
3505 throws PortalException, SystemException {
3506
3507 Organization organization = organizationPersistence.findByPrimaryKey(
3508 organizationId);
3509
3510 Group group = organization.getGroup();
3511
3512 long groupId = group.getGroupId();
3513
3514 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
3515
3516 organizationPersistence.removeUsers(organizationId, userIds);
3517
3518 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3519
3520 indexer.reindex(userIds);
3521
3522 PermissionCacheUtil.clearCache();
3523 }
3524
3525
3532 public void unsetPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
3533 throws SystemException {
3534
3535 passwordPolicyRelLocalService.deletePasswordPolicyRels(
3536 passwordPolicyId, User.class.getName(), userIds);
3537 }
3538
3539
3547 public void unsetRoleUsers(long roleId, List<User> users)
3548 throws PortalException, SystemException {
3549
3550 Role role = rolePersistence.findByPrimaryKey(roleId);
3551
3552 if (role.getName().equals(RoleConstants.USER)) {
3553 return;
3554 }
3555
3556 rolePersistence.removeUsers(roleId, users);
3557
3558 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3559
3560 indexer.reindex(users);
3561
3562 PermissionCacheUtil.clearCache();
3563 }
3564
3565
3573 public void unsetRoleUsers(long roleId, long[] userIds)
3574 throws PortalException, SystemException {
3575
3576 Role role = rolePersistence.findByPrimaryKey(roleId);
3577
3578 if (role.getName().equals(RoleConstants.USER)) {
3579 return;
3580 }
3581
3582 rolePersistence.removeUsers(roleId, userIds);
3583
3584 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3585
3586 indexer.reindex(userIds);
3587
3588 PermissionCacheUtil.clearCache();
3589 }
3590
3591
3599 public void unsetTeamUsers(long teamId, long[] userIds)
3600 throws PortalException, SystemException {
3601
3602 teamPersistence.removeUsers(teamId, userIds);
3603
3604 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3605
3606 indexer.reindex(userIds);
3607
3608 PermissionCacheUtil.clearCache();
3609 }
3610
3611
3619 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
3620 throws PortalException, SystemException {
3621
3622 userGroupPersistence.removeUsers(userGroupId, userIds);
3623
3624 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3625
3626 indexer.reindex(userIds);
3627
3628 PermissionCacheUtil.clearCache();
3629 }
3630
3631
3641 public User updateAgreedToTermsOfUse(
3642 long userId, boolean agreedToTermsOfUse)
3643 throws PortalException, SystemException {
3644
3645 User user = userPersistence.findByPrimaryKey(userId);
3646
3647 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
3648
3649 userPersistence.update(user, false);
3650
3651 return user;
3652 }
3653
3654
3665 public void updateAsset(
3666 long userId, User user, long[] assetCategoryIds,
3667 String[] assetTagNames)
3668 throws PortalException, SystemException {
3669
3670 User owner = userPersistence.findByPrimaryKey(userId);
3671
3672 Company company = companyPersistence.findByPrimaryKey(
3673 owner.getCompanyId());
3674
3675 Group companyGroup = company.getGroup();
3676
3677 assetEntryLocalService.updateEntry(
3678 userId, companyGroup.getGroupId(), User.class.getName(),
3679 user.getUserId(), user.getUuid(), 0, assetCategoryIds,
3680 assetTagNames, false, null, null, null, null, null,
3681 user.getFullName(), null, null, null, null, 0, 0, null, false);
3682 }
3683
3684
3693 public User updateCreateDate(long userId, Date createDate)
3694 throws PortalException, SystemException {
3695
3696 User user = userPersistence.findByPrimaryKey(userId);
3697
3698 user.setCreateDate(createDate);
3699
3700 userPersistence.update(user, false);
3701
3702 return user;
3703 }
3704
3705
3716 public User updateEmailAddress(
3717 long userId, String password, String emailAddress1,
3718 String emailAddress2)
3719 throws PortalException, SystemException {
3720
3721 emailAddress1 = emailAddress1.trim().toLowerCase();
3722 emailAddress2 = emailAddress2.trim().toLowerCase();
3723
3724 User user = userPersistence.findByPrimaryKey(userId);
3725
3726 validateEmailAddress(user, emailAddress1, emailAddress2);
3727
3728 setEmailAddress(
3729 user, password, user.getFirstName(), user.getMiddleName(),
3730 user.getLastName(), emailAddress1);
3731
3732 userPersistence.update(user, false);
3733
3734 return user;
3735 }
3736
3737
3748 public User updateEmailAddress(
3749 long userId, String password, String emailAddress1,
3750 String emailAddress2, ServiceContext serviceContext)
3751 throws PortalException, SystemException {
3752
3753 emailAddress1 = emailAddress1.trim().toLowerCase();
3754 emailAddress2 = emailAddress2.trim().toLowerCase();
3755
3756 User user = userPersistence.findByPrimaryKey(userId);
3757
3758 validateEmailAddress(user, emailAddress1, emailAddress2);
3759
3760 Company company = companyPersistence.findByPrimaryKey(
3761 user.getCompanyId());
3762
3763 if (!company.isStrangersVerify()) {
3764 setEmailAddress(
3765 user, password, user.getFirstName(), user.getMiddleName(),
3766 user.getLastName(), emailAddress1);
3767
3768 userPersistence.update(user, false);
3769 }
3770 else {
3771 sendEmailAddressVerification(user, emailAddress1, serviceContext);
3772 }
3773
3774 return user;
3775 }
3776
3777
3786 public User updateEmailAddressVerified(
3787 long userId, boolean emailAddressVerified)
3788 throws PortalException, SystemException {
3789
3790 User user = userPersistence.findByPrimaryKey(userId);
3791
3792 user.setEmailAddressVerified(emailAddressVerified);
3793
3794 userPersistence.update(user, false);
3795
3796 return user;
3797 }
3798
3799
3808 public User updateFacebookId(long userId, long facebookId)
3809 throws PortalException, SystemException {
3810
3811 User user = userPersistence.findByPrimaryKey(userId);
3812
3813 user.setFacebookId(facebookId);
3814
3815 userPersistence.update(user, false);
3816
3817 return user;
3818 }
3819
3820
3828 public void updateGroups(
3829 long userId, long[] newGroupIds, ServiceContext serviceContext)
3830 throws PortalException, SystemException {
3831
3832 updateGroups(
3833 userId, newGroupIds, serviceContext,
3834 serviceContext.isIndexingEnabled());
3835 }
3836
3837
3876 public User updateIncompleteUser(
3877 long creatorUserId, long companyId, boolean autoPassword,
3878 String password1, String password2, boolean autoScreenName,
3879 String screenName, String emailAddress, long facebookId,
3880 String openId, Locale locale, String firstName, String middleName,
3881 String lastName, int prefixId, int suffixId, boolean male,
3882 int birthdayMonth, int birthdayDay, int birthdayYear,
3883 String jobTitle, boolean updateUserInformation, boolean sendEmail,
3884 ServiceContext serviceContext)
3885 throws PortalException, SystemException {
3886
3887 User user = getUserByEmailAddress(companyId, emailAddress);
3888
3889 if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
3890 throw new PortalException("Invalid user status");
3891 }
3892
3893 User defaultUser = getDefaultUser(companyId);
3894
3895 if (updateUserInformation) {
3896 autoScreenName = false;
3897
3898 if (PrefsPropsUtil.getBoolean(
3899 companyId,
3900 PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
3901
3902 autoScreenName = true;
3903 }
3904
3905 validate(
3906 companyId, user.getUserId(), autoPassword, password1, password2,
3907 autoScreenName, screenName, emailAddress, firstName, middleName,
3908 lastName, null);
3909
3910 if (!autoPassword) {
3911 if (Validator.isNull(password1) ||
3912 Validator.isNull(password2)) {
3913 throw new UserPasswordException(
3914 UserPasswordException.PASSWORD_INVALID);
3915 }
3916 }
3917
3918 if (autoScreenName) {
3919 ScreenNameGenerator screenNameGenerator =
3920 ScreenNameGeneratorFactory.getInstance();
3921
3922 try {
3923 screenName = screenNameGenerator.generate(
3924 companyId, user.getUserId(), emailAddress);
3925 }
3926 catch (Exception e) {
3927 throw new SystemException(e);
3928 }
3929 }
3930
3931 FullNameGenerator fullNameGenerator =
3932 FullNameGeneratorFactory.getInstance();
3933
3934 String fullName = fullNameGenerator.getFullName(
3935 firstName, middleName, lastName);
3936
3937 String greeting = LanguageUtil.format(
3938 locale, "welcome-x", " " + fullName, false);
3939
3940 if (Validator.isNotNull(password1)) {
3941 user.setPassword(PwdEncryptor.encrypt(password1));
3942 user.setPasswordUnencrypted(password1);
3943 }
3944
3945 user.setPasswordEncrypted(true);
3946
3947 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
3948
3949 if (passwordPolicy.isChangeable() &&
3950 passwordPolicy.isChangeRequired()) {
3951
3952 user.setPasswordReset(true);
3953 }
3954 else {
3955 user.setPasswordReset(false);
3956 }
3957
3958 user.setScreenName(screenName);
3959 user.setFacebookId(facebookId);
3960 user.setOpenId(openId);
3961 user.setLanguageId(locale.toString());
3962 user.setTimeZoneId(defaultUser.getTimeZoneId());
3963 user.setGreeting(greeting);
3964 user.setFirstName(firstName);
3965 user.setMiddleName(middleName);
3966 user.setLastName(lastName);
3967 user.setJobTitle(jobTitle);
3968 user.setExpandoBridgeAttributes(serviceContext);
3969
3970 Date birthday = PortalUtil.getDate(
3971 birthdayMonth, birthdayDay, birthdayYear,
3972 ContactBirthdayException.class);
3973
3974 Contact contact = user.getContact();
3975
3976 contact.setFirstName(firstName);
3977 contact.setMiddleName(middleName);
3978 contact.setLastName(lastName);
3979 contact.setPrefixId(prefixId);
3980 contact.setSuffixId(suffixId);
3981 contact.setMale(male);
3982 contact.setBirthday(birthday);
3983 contact.setJobTitle(jobTitle);
3984
3985 contactPersistence.update(contact, false, serviceContext);
3986
3987
3988
3989 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3990 User.class);
3991
3992 indexer.reindex(user);
3993 }
3994
3995 user.setStatus(WorkflowConstants.STATUS_DRAFT);
3996
3997 userPersistence.update(user, false, serviceContext);
3998
3999
4000
4001 long workflowUserId = creatorUserId;
4002
4003 if (workflowUserId == user.getUserId()) {
4004 workflowUserId = defaultUser.getUserId();
4005 }
4006
4007 ServiceContext workflowServiceContext = serviceContext;
4008
4009 if (workflowServiceContext == null) {
4010 workflowServiceContext = new ServiceContext();
4011 }
4012
4013 workflowServiceContext.setAttribute("autoPassword", autoPassword);
4014 workflowServiceContext.setAttribute("sendEmail", sendEmail);
4015
4016 WorkflowHandlerRegistryUtil.startWorkflowInstance(
4017 companyId, workflowUserId, User.class.getName(), user.getUserId(),
4018 user, workflowServiceContext);
4019
4020 return getUserByEmailAddress(companyId, emailAddress);
4021 }
4022
4023
4033 public User updateJobTitle(long userId, String jobTitle)
4034 throws PortalException, SystemException {
4035
4036 User user = userPersistence.findByPrimaryKey(userId);
4037
4038 user.setJobTitle(jobTitle);
4039
4040 userPersistence.update(user, false);
4041
4042 Contact contact = contactPersistence.findByPrimaryKey(
4043 user.getContactId());
4044
4045 contact.setJobTitle(jobTitle);
4046
4047 contactPersistence.update(contact, false);
4048
4049 return user;
4050 }
4051
4052
4061 public User updateLastLogin(long userId, String loginIP)
4062 throws PortalException, SystemException {
4063
4064 User user = userPersistence.findByPrimaryKey(userId);
4065
4066 Date lastLoginDate = user.getLoginDate();
4067
4068 if (lastLoginDate == null) {
4069 lastLoginDate = new Date();
4070 }
4071
4072 user.setLoginDate(new Date());
4073 user.setLoginIP(loginIP);
4074 user.setLastLoginDate(lastLoginDate);
4075 user.setLastLoginIP(user.getLoginIP());
4076 user.setLastFailedLoginDate(null);
4077 user.setFailedLoginAttempts(0);
4078
4079 userPersistence.update(user, false);
4080
4081 return user;
4082 }
4083
4084
4093 public User updateLockout(User user, boolean lockout)
4094 throws PortalException, SystemException {
4095
4096 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
4097
4098 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
4099 return user;
4100 }
4101
4102 Date lockoutDate = null;
4103
4104 if (lockout) {
4105 lockoutDate = new Date();
4106 }
4107
4108 user.setLockout(lockout);
4109 user.setLockoutDate(lockoutDate);
4110
4111 if (!lockout) {
4112 user.setLastFailedLoginDate(lockoutDate);
4113 user.setFailedLoginAttempts(0);
4114 }
4115
4116 userPersistence.update(user, false);
4117
4118 return user;
4119 }
4120
4121
4132 public User updateLockoutByEmailAddress(
4133 long companyId, String emailAddress, boolean lockout)
4134 throws PortalException, SystemException {
4135
4136 User user = getUserByEmailAddress(companyId, emailAddress);
4137
4138 return updateLockout(user, lockout);
4139 }
4140
4141
4150 public User updateLockoutById(long userId, boolean lockout)
4151 throws PortalException, SystemException {
4152
4153 User user = userPersistence.findByPrimaryKey(userId);
4154
4155 return updateLockout(user, lockout);
4156 }
4157
4158
4168 public User updateLockoutByScreenName(
4169 long companyId, String screenName, boolean lockout)
4170 throws PortalException, SystemException {
4171
4172 User user = getUserByScreenName(companyId, screenName);
4173
4174 return updateLockout(user, lockout);
4175 }
4176
4177
4186 public User updateModifiedDate(long userId, Date modifiedDate)
4187 throws PortalException, SystemException {
4188
4189 User user = userPersistence.findByPrimaryKey(userId);
4190
4191 user.setModifiedDate(modifiedDate);
4192
4193 userPersistence.update(user, false);
4194
4195 return user;
4196 }
4197
4198
4207 public User updateOpenId(long userId, String openId)
4208 throws PortalException, SystemException {
4209
4210 openId = openId.trim();
4211
4212 User user = userPersistence.findByPrimaryKey(userId);
4213
4214 user.setOpenId(openId);
4215
4216 userPersistence.update(user, false);
4217
4218 return user;
4219 }
4220
4221
4230 public void updateOrganizations(
4231 long userId, long[] newOrganizationIds,
4232 ServiceContext serviceContext)
4233 throws PortalException, SystemException {
4234
4235 updateOrganizations(
4236 userId, newOrganizationIds, serviceContext.isIndexingEnabled());
4237 }
4238
4239
4251 public User updatePassword(
4252 long userId, String password1, String password2,
4253 boolean passwordReset)
4254 throws PortalException, SystemException {
4255
4256 return updatePassword(
4257 userId, password1, password2, passwordReset, false);
4258 }
4259
4260
4275 public User updatePassword(
4276 long userId, String password1, String password2,
4277 boolean passwordReset, boolean silentUpdate)
4278 throws PortalException, SystemException {
4279
4280 User user = userPersistence.findByPrimaryKey(userId);
4281
4282 if (!silentUpdate) {
4283 validatePassword(user.getCompanyId(), userId, password1, password2);
4284 }
4285
4286 String oldEncPwd = user.getPassword();
4287
4288 if (!user.isPasswordEncrypted()) {
4289 oldEncPwd = PwdEncryptor.encrypt(user.getPassword());
4290 }
4291
4292 String newEncPwd = PwdEncryptor.encrypt(password1);
4293
4294 if (user.hasCompanyMx()) {
4295 mailService.updatePassword(user.getCompanyId(), userId, password1);
4296 }
4297
4298 user.setPassword(newEncPwd);
4299 user.setPasswordUnencrypted(password1);
4300 user.setPasswordEncrypted(true);
4301 user.setPasswordReset(passwordReset);
4302 user.setPasswordModifiedDate(new Date());
4303 user.setDigest(StringPool.BLANK);
4304 user.setGraceLoginCount(0);
4305
4306 if (!silentUpdate) {
4307 user.setPasswordModified(true);
4308 }
4309
4310 try {
4311 userPersistence.update(user, false);
4312 }
4313 catch (ModelListenerException mle) {
4314 String msg = GetterUtil.getString(mle.getCause().getMessage());
4315
4316 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
4317 String passwordHistory = PrefsPropsUtil.getString(
4318 user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
4319
4320 if (msg.indexOf(passwordHistory) != -1) {
4321 throw new UserPasswordException(
4322 UserPasswordException.PASSWORD_ALREADY_USED);
4323 }
4324 }
4325
4326 throw new UserPasswordException(
4327 UserPasswordException.PASSWORD_INVALID);
4328 }
4329
4330 if (!silentUpdate) {
4331 user.setPasswordModified(false);
4332
4333 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
4334 }
4335
4336 return user;
4337 }
4338
4339
4353 public User updatePasswordManually(
4354 long userId, String password, boolean passwordEncrypted,
4355 boolean passwordReset, Date passwordModifiedDate)
4356 throws PortalException, SystemException {
4357
4358
4359
4360 User user = userPersistence.findByPrimaryKey(userId);
4361
4362 user.setPassword(password);
4363 user.setPasswordEncrypted(passwordEncrypted);
4364 user.setPasswordReset(passwordReset);
4365 user.setPasswordModifiedDate(passwordModifiedDate);
4366 user.setDigest(StringPool.BLANK);
4367
4368 userPersistence.update(user, false);
4369
4370 return user;
4371 }
4372
4373
4384 public User updatePasswordReset(long userId, boolean passwordReset)
4385 throws PortalException, SystemException {
4386
4387 User user = userPersistence.findByPrimaryKey(userId);
4388
4389 user.setPasswordReset(passwordReset);
4390
4391 userPersistence.update(user, false);
4392
4393 return user;
4394 }
4395
4396
4406 public User updatePortrait(long userId, byte[] bytes)
4407 throws PortalException, SystemException {
4408
4409 User user = userPersistence.findByPrimaryKey(userId);
4410
4411 long imageMaxSize = PrefsPropsUtil.getLong(
4412 PropsKeys.USERS_IMAGE_MAX_SIZE);
4413
4414 if ((imageMaxSize > 0) &&
4415 ((bytes == null) || (bytes.length > imageMaxSize))) {
4416
4417 throw new UserPortraitSizeException();
4418 }
4419
4420 long portraitId = user.getPortraitId();
4421
4422 if (portraitId <= 0) {
4423 portraitId = counterLocalService.increment();
4424
4425 user.setPortraitId(portraitId);
4426 }
4427
4428 try {
4429 ImageBag imageBag = ImageToolUtil.read(bytes);
4430
4431 RenderedImage renderedImage = imageBag.getRenderedImage();
4432
4433 if (renderedImage == null) {
4434 throw new UserPortraitTypeException();
4435 }
4436
4437 renderedImage = ImageToolUtil.scale(
4438 renderedImage, PropsValues.USERS_IMAGE_MAX_HEIGHT,
4439 PropsValues.USERS_IMAGE_MAX_WIDTH);
4440
4441 String contentType = imageBag.getType();
4442
4443 imageLocalService.updateImage(
4444 portraitId,
4445 ImageToolUtil.getBytes(renderedImage, contentType));
4446 }
4447 catch (IOException ioe) {
4448 throw new ImageSizeException(ioe);
4449 }
4450
4451 userPersistence.update(user, false);
4452
4453 return user;
4454 }
4455
4456
4467 public User updateReminderQuery(long userId, String question, String answer)
4468 throws PortalException, SystemException {
4469
4470 validateReminderQuery(question, answer) ;
4471
4472 User user = userPersistence.findByPrimaryKey(userId);
4473
4474 user.setReminderQueryQuestion(question);
4475 user.setReminderQueryAnswer(answer);
4476
4477 userPersistence.update(user, false);
4478
4479 return user;
4480 }
4481
4482
4492 public User updateScreenName(long userId, String screenName)
4493 throws PortalException, SystemException {
4494
4495
4496
4497 User user = userPersistence.findByPrimaryKey(userId);
4498
4499 screenName = getScreenName(screenName);
4500
4501 validateScreenName(user.getCompanyId(), userId, screenName);
4502
4503 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
4504 user.setDigest(StringPool.BLANK);
4505 }
4506
4507 user.setScreenName(screenName);
4508
4509 userPersistence.update(user, false);
4510
4511
4512
4513 Group group = groupLocalService.getUserGroup(
4514 user.getCompanyId(), userId);
4515
4516 group.setFriendlyURL(StringPool.SLASH + screenName);
4517
4518 groupPersistence.update(group, false);
4519
4520 return user;
4521 }
4522
4523
4532 public User updateStatus(long userId, int status)
4533 throws PortalException, SystemException {
4534
4535 User user = userPersistence.findByPrimaryKey(userId);
4536
4537 user.setStatus(status);
4538
4539 userPersistence.update(user, false);
4540
4541 reindex(user);
4542
4543 return user;
4544 }
4545
4546
4602 @SuppressWarnings("deprecation")
4603 public User updateUser(
4604 long userId, String oldPassword, String newPassword1,
4605 String newPassword2, boolean passwordReset,
4606 String reminderQueryQuestion, String reminderQueryAnswer,
4607 String screenName, String emailAddress, long facebookId,
4608 String openId, String languageId, String timeZoneId,
4609 String greeting, String comments, String firstName,
4610 String middleName, String lastName, int prefixId, int suffixId,
4611 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
4612 String smsSn, String aimSn, String facebookSn, String icqSn,
4613 String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
4614 String twitterSn, String ymSn, String jobTitle, long[] groupIds,
4615 long[] organizationIds, long[] roleIds,
4616 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
4617 ServiceContext serviceContext)
4618 throws PortalException, SystemException {
4619
4620
4621
4622 User user = userPersistence.findByPrimaryKey(userId);
4623 Company company = companyPersistence.findByPrimaryKey(
4624 user.getCompanyId());
4625 String password = oldPassword;
4626 screenName = getScreenName(screenName);
4627 emailAddress = emailAddress.trim().toLowerCase();
4628 openId = openId.trim();
4629 String oldFullName = user.getFullName();
4630 aimSn = aimSn.trim().toLowerCase();
4631 facebookSn = facebookSn.trim().toLowerCase();
4632 icqSn = icqSn.trim().toLowerCase();
4633 jabberSn = jabberSn.trim().toLowerCase();
4634 msnSn = msnSn.trim().toLowerCase();
4635 mySpaceSn = mySpaceSn.trim().toLowerCase();
4636 skypeSn = skypeSn.trim().toLowerCase();
4637 twitterSn = twitterSn.trim().toLowerCase();
4638 ymSn = ymSn.trim().toLowerCase();
4639 Date now = new Date();
4640
4641 EmailAddressGenerator emailAddressGenerator =
4642 EmailAddressGeneratorFactory.getInstance();
4643
4644 if (emailAddressGenerator.isGenerated(emailAddress)) {
4645 emailAddress = StringPool.BLANK;
4646 }
4647
4648 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
4649 Validator.isNull(emailAddress)) {
4650
4651 emailAddress = emailAddressGenerator.generate(
4652 user.getCompanyId(), userId);
4653 }
4654
4655 validate(
4656 userId, screenName, emailAddress, firstName, middleName, lastName,
4657 smsSn);
4658
4659 if (Validator.isNotNull(newPassword1) ||
4660 Validator.isNotNull(newPassword2)) {
4661
4662 user = updatePassword(
4663 userId, newPassword1, newPassword2, passwordReset);
4664
4665 password = newPassword1;
4666
4667 user.setDigest(StringPool.BLANK);
4668 }
4669
4670 user.setModifiedDate(now);
4671
4672 if (user.getContactId() <= 0) {
4673 user.setContactId(counterLocalService.increment());
4674 }
4675
4676 user.setPasswordReset(passwordReset);
4677
4678 if (Validator.isNotNull(reminderQueryQuestion) &&
4679 Validator.isNotNull(reminderQueryAnswer)) {
4680
4681 user.setReminderQueryQuestion(reminderQueryQuestion);
4682 user.setReminderQueryAnswer(reminderQueryAnswer);
4683 }
4684
4685 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
4686 user.setScreenName(screenName);
4687
4688 user.setDigest(StringPool.BLANK);
4689 }
4690
4691 boolean sendEmailAddressVerification = false;
4692
4693 if (!company.isStrangersVerify()) {
4694 setEmailAddress(
4695 user, password, firstName, middleName, lastName, emailAddress);
4696 }
4697 else {
4698 sendEmailAddressVerification = true;
4699 }
4700
4701 if (serviceContext != null) {
4702 String uuid = serviceContext.getUuid();
4703
4704 if (Validator.isNotNull(uuid)) {
4705 user.setUuid(uuid);
4706 }
4707 }
4708
4709 user.setFacebookId(facebookId);
4710 user.setOpenId(openId);
4711 user.setLanguageId(languageId);
4712 user.setTimeZoneId(timeZoneId);
4713 user.setGreeting(greeting);
4714 user.setComments(comments);
4715 user.setFirstName(firstName);
4716 user.setMiddleName(middleName);
4717 user.setLastName(lastName);
4718 user.setJobTitle(jobTitle);
4719 user.setExpandoBridgeAttributes(serviceContext);
4720
4721 userPersistence.update(user, false, serviceContext);
4722
4723
4724
4725 Date birthday = PortalUtil.getDate(
4726 birthdayMonth, birthdayDay, birthdayYear,
4727 ContactBirthdayException.class);
4728
4729 long contactId = user.getContactId();
4730
4731 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
4732
4733 if (contact == null) {
4734 contact = contactPersistence.create(contactId);
4735
4736 contact.setCompanyId(user.getCompanyId());
4737 contact.setUserName(StringPool.BLANK);
4738 contact.setCreateDate(now);
4739 contact.setAccountId(company.getAccountId());
4740 contact.setParentContactId(
4741 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
4742 }
4743
4744 contact.setModifiedDate(now);
4745 contact.setFirstName(firstName);
4746 contact.setMiddleName(middleName);
4747 contact.setLastName(lastName);
4748 contact.setPrefixId(prefixId);
4749 contact.setSuffixId(suffixId);
4750 contact.setMale(male);
4751 contact.setBirthday(birthday);
4752 contact.setSmsSn(smsSn);
4753 contact.setAimSn(aimSn);
4754 contact.setFacebookSn(facebookSn);
4755 contact.setIcqSn(icqSn);
4756 contact.setJabberSn(jabberSn);
4757 contact.setMsnSn(msnSn);
4758 contact.setMySpaceSn(mySpaceSn);
4759 contact.setSkypeSn(skypeSn);
4760 contact.setTwitterSn(twitterSn);
4761 contact.setYmSn(ymSn);
4762 contact.setJobTitle(jobTitle);
4763
4764 contactPersistence.update(contact, false, serviceContext);
4765
4766
4767
4768 Group group = groupLocalService.getUserGroup(
4769 user.getCompanyId(), userId);
4770
4771 group.setFriendlyURL(StringPool.SLASH + screenName);
4772
4773 groupPersistence.update(group, false);
4774
4775
4776
4777 updateGroups(userId, groupIds, serviceContext, false);
4778 updateOrganizations(userId, organizationIds, false);
4779
4780
4781
4782 if (roleIds != null) {
4783 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
4784
4785 userPersistence.setRoles(userId, roleIds);
4786 }
4787
4788
4789
4790 updateUserGroupRoles(user, groupIds, organizationIds, userGroupRoles);
4791
4792
4793
4794 if (userGroupIds != null) {
4795 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
4796 userGroupLocalService.copyUserGroupLayouts(
4797 userGroupIds, userId);
4798 }
4799
4800 userPersistence.setUserGroups(userId, userGroupIds);
4801 }
4802
4803
4804
4805 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
4806
4807
4808
4809 if (serviceContext != null) {
4810 updateAsset(
4811 userId, user, serviceContext.getAssetCategoryIds(),
4812 serviceContext.getAssetTagNames());
4813 }
4814
4815
4816
4817 if (GetterUtil.getBoolean(
4818 PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
4819 !oldFullName.equals(user.getFullName())) {
4820
4821 mbMessageLocalService.updateUserName(userId, user.getFullName());
4822 }
4823
4824
4825
4826 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
4827 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4828 User.class);
4829
4830 indexer.reindex(user);
4831 }
4832
4833
4834
4835 if ((serviceContext != null) && sendEmailAddressVerification) {
4836 sendEmailAddressVerification(user, emailAddress, serviceContext);
4837 }
4838
4839
4840
4841 PermissionCacheUtil.clearCache();
4842
4843 return user;
4844 }
4845
4846
4855 public void verifyEmailAddress(String ticketKey)
4856 throws PortalException, SystemException {
4857
4858 Ticket ticket = ticketLocalService.getTicket(ticketKey);
4859
4860 if (ticket.isExpired() ||
4861 (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
4862
4863 throw new NoSuchTicketException();
4864 }
4865
4866 User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
4867
4868 String emailAddress = ticket.getExtraInfo();
4869
4870 emailAddress = emailAddress.toLowerCase().trim();
4871
4872 if (!emailAddress.equals(user.getEmailAddress())) {
4873 if (userPersistence.fetchByC_EA(
4874 user.getCompanyId(), emailAddress) != null) {
4875
4876 throw new DuplicateUserEmailAddressException();
4877 }
4878
4879 setEmailAddress(
4880 user, StringPool.BLANK, user.getFirstName(),
4881 user.getMiddleName(), user.getLastName(), emailAddress);
4882 }
4883
4884 user.setEmailAddressVerified(true);
4885
4886 userPersistence.update(user, false);
4887
4888 ticketLocalService.deleteTicket(ticket);
4889 }
4890
4891
4937 protected int authenticate(
4938 long companyId, String login, String password, String authType,
4939 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
4940 Map<String, Object> resultsMap)
4941 throws PortalException, SystemException {
4942
4943 if (PropsValues.AUTH_LOGIN_DISABLED) {
4944 return Authenticator.FAILURE;
4945 }
4946
4947 login = login.trim().toLowerCase();
4948
4949 long userId = GetterUtil.getLong(login);
4950
4951
4952
4953 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
4954 if (Validator.isNull(login)) {
4955 throw new UserEmailAddressException();
4956 }
4957 }
4958 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
4959 if (Validator.isNull(login)) {
4960 throw new UserScreenNameException();
4961 }
4962 }
4963 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
4964 if (Validator.isNull(login)) {
4965 throw new UserIdException();
4966 }
4967 }
4968
4969 if (Validator.isNull(password)) {
4970 throw new UserPasswordException(
4971 UserPasswordException.PASSWORD_INVALID);
4972 }
4973
4974 int authResult = Authenticator.FAILURE;
4975
4976
4977
4978 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
4979 authResult = AuthPipeline.authenticateByEmailAddress(
4980 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
4981 headerMap, parameterMap);
4982 }
4983 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
4984 authResult = AuthPipeline.authenticateByScreenName(
4985 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
4986 headerMap, parameterMap);
4987 }
4988 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
4989 authResult = AuthPipeline.authenticateByUserId(
4990 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
4991 headerMap, parameterMap);
4992 }
4993
4994
4995
4996 User user = null;
4997
4998 try {
4999 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5000 user = userPersistence.findByC_EA(companyId, login);
5001 }
5002 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5003 user = userPersistence.findByC_SN(companyId, login);
5004 }
5005 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5006 user = userPersistence.findByC_U(
5007 companyId, GetterUtil.getLong(login));
5008 }
5009 }
5010 catch (NoSuchUserException nsue) {
5011 return Authenticator.DNE;
5012 }
5013
5014 if (user.isDefaultUser()) {
5015 if (_log.isInfoEnabled()) {
5016 _log.info("Authentication is disabled for the default user");
5017 }
5018
5019 return Authenticator.DNE;
5020 }
5021 else if (!user.isActive()) {
5022 if (_log.isInfoEnabled()) {
5023 _log.info(
5024 "Authentication is disabled for inactive user " +
5025 user.getUserId());
5026 }
5027
5028 return Authenticator.FAILURE;
5029 }
5030
5031 if (!user.isPasswordEncrypted()) {
5032 user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
5033 user.setPasswordEncrypted(true);
5034
5035 userPersistence.update(user, false);
5036 }
5037
5038
5039
5040
5041 checkLockout(user);
5042
5043 checkPasswordExpired(user);
5044
5045
5046
5047 if ((authResult == Authenticator.SUCCESS) &&
5048 PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5049
5050 boolean authenticated = PwdAuthenticator.authenticate(
5051 login, password, user.getPassword());
5052
5053 if (authenticated) {
5054 authResult = Authenticator.SUCCESS;
5055 }
5056 else {
5057 authResult = Authenticator.FAILURE;
5058 }
5059 }
5060
5061
5062
5063 if (authResult == Authenticator.SUCCESS) {
5064 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5065 authResult = AuthPipeline.authenticateByEmailAddress(
5066 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5067 headerMap, parameterMap);
5068 }
5069 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5070 authResult = AuthPipeline.authenticateByScreenName(
5071 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5072 headerMap, parameterMap);
5073 }
5074 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5075 authResult = AuthPipeline.authenticateByUserId(
5076 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5077 headerMap, parameterMap);
5078 }
5079 }
5080
5081 if (authResult == Authenticator.SUCCESS) {
5082 if (resultsMap != null) {
5083 resultsMap.put("userId", user.getUserId());
5084 }
5085
5086
5087
5088 boolean updateDigest = true;
5089
5090 if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5091 if (Validator.isNotNull(user.getDigest())) {
5092 updateDigest = false;
5093 }
5094 }
5095
5096 if (updateDigest) {
5097 String digest = user.getDigest(password);
5098
5099 user.setDigest(digest);
5100
5101 userPersistence.update(user, false);
5102 }
5103 }
5104
5105
5106
5107 if (authResult == Authenticator.FAILURE) {
5108 try {
5109 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5110 AuthPipeline.onFailureByEmailAddress(
5111 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5112 parameterMap);
5113 }
5114 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5115 AuthPipeline.onFailureByScreenName(
5116 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5117 parameterMap);
5118 }
5119 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5120 AuthPipeline.onFailureByUserId(
5121 PropsKeys.AUTH_FAILURE, companyId, userId, headerMap,
5122 parameterMap);
5123 }
5124
5125 try {
5126 user = userPersistence.findByPrimaryKey(user.getUserId());
5127 }
5128 catch (NoSuchUserException nsue) {
5129 return Authenticator.DNE;
5130 }
5131
5132
5133
5134 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5135 user.getCompanyId())) {
5136
5137 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5138
5139 int failedLoginAttempts = user.getFailedLoginAttempts();
5140 int maxFailures = passwordPolicy.getMaxFailure();
5141
5142 if ((failedLoginAttempts >= maxFailures) &&
5143 (maxFailures != 0)) {
5144
5145 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5146 AuthPipeline.onMaxFailuresByEmailAddress(
5147 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5148 headerMap, parameterMap);
5149 }
5150 else if (authType.equals(
5151 CompanyConstants.AUTH_TYPE_SN)) {
5152
5153 AuthPipeline.onMaxFailuresByScreenName(
5154 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5155 headerMap, parameterMap);
5156 }
5157 else if (authType.equals(
5158 CompanyConstants.AUTH_TYPE_ID)) {
5159
5160 AuthPipeline.onMaxFailuresByUserId(
5161 PropsKeys.AUTH_MAX_FAILURES, companyId, userId,
5162 headerMap, parameterMap);
5163 }
5164 }
5165 }
5166 }
5167 catch (Exception e) {
5168 _log.error(e, e);
5169 }
5170 }
5171
5172 return authResult;
5173 }
5174
5175 protected String getScreenName(String screenName) {
5176 return StringUtil.lowerCase(StringUtil.trim(screenName));
5177 }
5178
5179 protected long[] getUserIds(List<User> users) {
5180 long[] userIds = new long[users.size()];
5181
5182 for (int i = 0; i < users.size(); i++) {
5183 User user = users.get(i);
5184
5185 userIds[i] = user.getUserId();
5186 }
5187
5188 return userIds;
5189 }
5190
5191 protected void reindex(final User user) {
5192 final Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5193 User.class);
5194
5195 Callable<Void> callable = new Callable<Void>() {
5196
5197 public Void call() throws Exception {
5198 indexer.reindex(user);
5199
5200 return null;
5201 }
5202
5203 };
5204
5205 TransactionCommitCallbackUtil.registerCallback(callable);
5206 }
5207
5208 protected Hits search(
5209 long companyId, String firstName, String middleName,
5210 String lastName, String fullName, String screenName,
5211 String emailAddress, String street, String city, String zip,
5212 String region, String country, int status,
5213 LinkedHashMap<String, Object> params, boolean andSearch, int start,
5214 int end, Sort sort)
5215 throws SystemException {
5216
5217 try {
5218 SearchContext searchContext = new SearchContext();
5219
5220 searchContext.setAndSearch(andSearch);
5221
5222 Map<String, Serializable> attributes =
5223 new HashMap<String, Serializable>();
5224
5225 attributes.put("city", city);
5226 attributes.put("country", country);
5227 attributes.put("emailAddress", emailAddress);
5228 attributes.put("firstName", firstName);
5229 attributes.put("fullName", fullName);
5230 attributes.put("lastName", lastName);
5231 attributes.put("middleName", middleName);
5232 attributes.put("params", params);
5233 attributes.put("region", region);
5234 attributes.put("screenName", screenName);
5235 attributes.put("street", street);
5236 attributes.put("status", status);
5237 attributes.put("zip", zip);
5238
5239 searchContext.setAttributes(attributes);
5240
5241 searchContext.setCompanyId(companyId);
5242 searchContext.setEnd(end);
5243
5244 if (params != null) {
5245 String keywords = (String)params.remove("keywords");
5246
5247 if (Validator.isNotNull(keywords)) {
5248 searchContext.setKeywords(keywords);
5249 }
5250 }
5251
5252 QueryConfig queryConfig = new QueryConfig();
5253
5254 queryConfig.setHighlightEnabled(false);
5255 queryConfig.setScoreEnabled(false);
5256
5257 searchContext.setQueryConfig(queryConfig);
5258
5259 searchContext.setSorts(new Sort[] {sort});
5260 searchContext.setStart(start);
5261
5262 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5263 User.class);
5264
5265 return indexer.search(searchContext);
5266 }
5267 catch (Exception e) {
5268 throw new SystemException(e);
5269 }
5270 }
5271
5272 protected void sendEmail(
5273 User user, String password, ServiceContext serviceContext)
5274 throws SystemException {
5275
5276 if (!PrefsPropsUtil.getBoolean(
5277 user.getCompanyId(),
5278 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
5279
5280 return;
5281 }
5282
5283 String fromName = PrefsPropsUtil.getString(
5284 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
5285 String fromAddress = PrefsPropsUtil.getString(
5286 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
5287
5288 String toName = user.getFullName();
5289 String toAddress = user.getEmailAddress();
5290
5291 String subject = PrefsPropsUtil.getContent(
5292 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
5293
5294 String body = null;
5295
5296 if (Validator.isNotNull(password)) {
5297 body = PrefsPropsUtil.getContent(
5298 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
5299 }
5300 else {
5301 body = PrefsPropsUtil.getContent(
5302 user.getCompanyId(),
5303 PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
5304 }
5305
5306 SubscriptionSender subscriptionSender = new SubscriptionSender();
5307
5308 subscriptionSender.setBody(body);
5309 subscriptionSender.setCompanyId(user.getCompanyId());
5310 subscriptionSender.setContextAttributes(
5311 "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
5312 "[$USER_SCREENNAME$]", user.getScreenName());
5313 subscriptionSender.setFrom(fromAddress, fromName);
5314 subscriptionSender.setHtmlFormat(true);
5315 subscriptionSender.setMailId("user", user.getUserId());
5316 subscriptionSender.setServiceContext(serviceContext);
5317 subscriptionSender.setSubject(subject);
5318 subscriptionSender.setUserId(user.getUserId());
5319
5320 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
5321
5322 subscriptionSender.flushNotificationsAsync();
5323 }
5324
5325 protected void setEmailAddress(
5326 User user, String password, String firstName, String middleName,
5327 String lastName, String emailAddress)
5328 throws PortalException, SystemException {
5329
5330 if (emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
5331 return;
5332 }
5333
5334 long userId = user.getUserId();
5335
5336
5337
5338 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
5339 Validator.isNotNull(password)) {
5340
5341 mailService.addUser(
5342 user.getCompanyId(), userId, password, firstName, middleName,
5343 lastName, emailAddress);
5344 }
5345
5346
5347
5348 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
5349 mailService.updateEmailAddress(
5350 user.getCompanyId(), userId, emailAddress);
5351 }
5352
5353
5354
5355 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
5356 mailService.deleteEmailAddress(user.getCompanyId(), userId);
5357 }
5358
5359 user.setEmailAddress(emailAddress);
5360 user.setDigest(StringPool.BLANK);
5361 }
5362
5363 protected void updateGroups(
5364 long userId, long[] newGroupIds, ServiceContext serviceContext,
5365 boolean indexingEnabled)
5366 throws PortalException, SystemException {
5367
5368 if (newGroupIds == null) {
5369 return;
5370 }
5371
5372 List<Group> oldGroups = userPersistence.getGroups(userId);
5373
5374 List<Long> oldGroupIds = new ArrayList<Long>(oldGroups.size());
5375
5376 for (Group oldGroup : oldGroups) {
5377 long oldGroupId = oldGroup.getGroupId();
5378
5379 oldGroupIds.add(oldGroupId);
5380
5381 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
5382 unsetGroupUsers(
5383 oldGroupId, new long[] {userId}, serviceContext);
5384 }
5385 }
5386
5387 for (long newGroupId : newGroupIds) {
5388 if (!oldGroupIds.contains(newGroupId)) {
5389 addGroupUsers(newGroupId, new long[] {userId});
5390 }
5391 }
5392
5393 if (indexingEnabled) {
5394 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5395 User.class);
5396
5397 indexer.reindex(new long[] {userId});
5398 }
5399
5400 PermissionCacheUtil.clearCache();
5401 }
5402
5403 protected void updateOrganizations(
5404 long userId, long[] newOrganizationIds, boolean indexingEnabled)
5405 throws PortalException, SystemException {
5406
5407 if (newOrganizationIds == null) {
5408 return;
5409 }
5410
5411 List<Organization> oldOrganizations = userPersistence.getOrganizations(
5412 userId);
5413
5414 List<Long> oldOrganizationIds = new ArrayList<Long>(
5415 oldOrganizations.size());
5416
5417 for (Organization oldOrganization : oldOrganizations) {
5418 long oldOrganizationId = oldOrganization.getOrganizationId();
5419
5420 oldOrganizationIds.add(oldOrganizationId);
5421
5422 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
5423 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
5424 }
5425 }
5426
5427 for (long newOrganizationId : newOrganizationIds) {
5428 if (!oldOrganizationIds.contains(newOrganizationId)) {
5429 addOrganizationUsers(newOrganizationId, new long[] {userId});
5430 }
5431 }
5432
5433 if (indexingEnabled) {
5434 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5435 User.class);
5436
5437 indexer.reindex(new long[] {userId});
5438 }
5439
5440 PermissionCacheUtil.clearCache();
5441 }
5442
5443 protected void updateUserGroupRoles(
5444 User user, long[] groupIds, long[] organizationIds,
5445 List<UserGroupRole> userGroupRoles)
5446 throws PortalException, SystemException {
5447
5448 if (userGroupRoles == null) {
5449 return;
5450 }
5451
5452 List<UserGroupRole> previousUserGroupRoles =
5453 userGroupRolePersistence.findByUserId(user.getUserId());
5454
5455 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
5456 if (userGroupRoles.contains(userGroupRole)) {
5457 userGroupRoles.remove(userGroupRole);
5458 }
5459 else {
5460 userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
5461 }
5462 }
5463
5464 long[] validGroupIds = null;
5465
5466 if (groupIds != null) {
5467 validGroupIds = ArrayUtil.clone(groupIds);
5468 }
5469 else {
5470 validGroupIds = user.getGroupIds();
5471 }
5472
5473 if (organizationIds == null) {
5474 organizationIds = user.getOrganizationIds();
5475 }
5476
5477 long[] organizationGroupIds = new long[organizationIds.length];
5478
5479 for (int i = 0; i < organizationIds.length; i++) {
5480 long organizationId = organizationIds[i];
5481
5482 Organization organization =
5483 organizationPersistence.findByPrimaryKey(organizationId);
5484
5485 Group organizationGroup = organization.getGroup();
5486
5487 organizationGroupIds[i] = organizationGroup.getGroupId();
5488 }
5489
5490 validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
5491
5492 Arrays.sort(validGroupIds);
5493
5494 for (UserGroupRole userGroupRole : userGroupRoles) {
5495 if (Arrays.binarySearch(
5496 validGroupIds, userGroupRole.getGroupId()) >= 0) {
5497
5498 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
5499 }
5500 }
5501 }
5502
5503 protected void validate(
5504 long companyId, long userId, boolean autoPassword, String password1,
5505 String password2, boolean autoScreenName, String screenName,
5506 String emailAddress, String firstName, String middleName,
5507 String lastName, long[] organizationIds)
5508 throws PortalException, SystemException {
5509
5510 Company company = companyPersistence.findByPrimaryKey(companyId);
5511
5512 if (company.isSystem()) {
5513 return;
5514 }
5515
5516 if ((company.getMaxUsers() > 0) &&
5517 (company.getMaxUsers() <=
5518 searchCount(
5519 companyId, null, WorkflowConstants.STATUS_APPROVED,
5520 null))) {
5521
5522 throw new CompanyMaxUsersException();
5523 }
5524
5525 if (!autoScreenName) {
5526 validateScreenName(companyId, userId, screenName);
5527 }
5528
5529 if (!autoPassword) {
5530 PasswordPolicy passwordPolicy =
5531 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
5532
5533 PwdToolkitUtil.validate(
5534 companyId, 0, password1, password2, passwordPolicy);
5535 }
5536
5537 validateEmailAddress(companyId, emailAddress);
5538
5539 if (Validator.isNotNull(emailAddress)) {
5540 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
5541
5542 if ((user != null) && (user.getUserId() != userId)) {
5543 throw new DuplicateUserEmailAddressException();
5544 }
5545 }
5546
5547 validateFullName(companyId, firstName, middleName, lastName);
5548
5549 if (organizationIds != null) {
5550 for (long organizationId : organizationIds) {
5551 Organization organization =
5552 organizationPersistence.fetchByPrimaryKey(organizationId);
5553
5554 if (organization == null) {
5555 throw new NoSuchOrganizationException();
5556 }
5557 }
5558 }
5559 }
5560
5561 protected void validate(
5562 long userId, String screenName, String emailAddress,
5563 String firstName, String middleName, String lastName, String smsSn)
5564 throws PortalException, SystemException {
5565
5566 User user = userPersistence.findByPrimaryKey(userId);
5567
5568 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
5569 validateScreenName(user.getCompanyId(), userId, screenName);
5570 }
5571
5572 validateEmailAddress(user.getCompanyId(), emailAddress);
5573
5574 if (!user.isDefaultUser()) {
5575 if (Validator.isNotNull(emailAddress) &&
5576 !user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
5577
5578 if (userPersistence.fetchByC_EA(
5579 user.getCompanyId(), emailAddress) != null) {
5580
5581 throw new DuplicateUserEmailAddressException();
5582 }
5583 }
5584
5585 validateFullName(
5586 user.getCompanyId(), firstName, middleName, lastName);
5587 }
5588
5589 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
5590 throw new UserSmsException();
5591 }
5592 }
5593
5594 protected void validateEmailAddress(long companyId, String emailAddress)
5595 throws PortalException, SystemException {
5596
5597 if (Validator.isNull(emailAddress) &&
5598 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
5599
5600 return;
5601 }
5602
5603 EmailAddressValidator emailAddressValidator =
5604 EmailAddressValidatorFactory.getInstance();
5605
5606 if (!emailAddressValidator.validate(companyId, emailAddress)) {
5607 throw new UserEmailAddressException();
5608 }
5609
5610 String pop3User = PrefsPropsUtil.getString(
5611 PropsKeys.MAIL_SESSION_MAIL_POP3_USER,
5612 PropsValues.MAIL_SESSION_MAIL_POP3_USER);
5613
5614 if (emailAddress.equalsIgnoreCase(pop3User)) {
5615 throw new ReservedUserEmailAddressException();
5616 }
5617
5618 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
5619 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
5620 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
5621
5622 for (String reservedEmailAddress : reservedEmailAddresses) {
5623 if (emailAddress.equalsIgnoreCase(reservedEmailAddress)) {
5624 throw new ReservedUserEmailAddressException();
5625 }
5626 }
5627 }
5628
5629 protected void validateEmailAddress(
5630 User user, String emailAddress1, String emailAddress2)
5631 throws PortalException, SystemException {
5632
5633 if (!emailAddress1.equals(emailAddress2)) {
5634 throw new UserEmailAddressException();
5635 }
5636
5637 validateEmailAddress(user.getCompanyId(), emailAddress1);
5638 validateEmailAddress(user.getCompanyId(), emailAddress2);
5639
5640 if (!emailAddress1.equalsIgnoreCase(user.getEmailAddress())) {
5641 if (userPersistence.fetchByC_EA(
5642 user.getCompanyId(), emailAddress1) != null) {
5643
5644 throw new DuplicateUserEmailAddressException();
5645 }
5646 }
5647 }
5648
5649 protected void validateFullName(
5650 long companyId, String firstName, String middleName,
5651 String lastName)
5652 throws PortalException, SystemException {
5653
5654 if (Validator.isNull(firstName)) {
5655 throw new ContactFirstNameException();
5656 }
5657 else if (Validator.isNull(lastName) &&
5658 PrefsPropsUtil.getBoolean(
5659 companyId, PropsKeys.USERS_LAST_NAME_REQUIRED,
5660 PropsValues.USERS_LAST_NAME_REQUIRED)) {
5661
5662 throw new ContactLastNameException();
5663 }
5664
5665 FullNameValidator fullNameValidator =
5666 FullNameValidatorFactory.getInstance();
5667
5668 if (!fullNameValidator.validate(
5669 companyId, firstName, middleName, lastName)) {
5670
5671 throw new ContactFullNameException();
5672 }
5673 }
5674
5675 protected void validatePassword(
5676 long companyId, long userId, String password1, String password2)
5677 throws PortalException, SystemException {
5678
5679 if (Validator.isNull(password1) || Validator.isNull(password2)) {
5680 throw new UserPasswordException(
5681 UserPasswordException.PASSWORD_INVALID);
5682 }
5683
5684 if (!password1.equals(password2)) {
5685 throw new UserPasswordException(
5686 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
5687 }
5688
5689 PasswordPolicy passwordPolicy =
5690 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
5691
5692 PwdToolkitUtil.validate(
5693 companyId, userId, password1, password2, passwordPolicy);
5694 }
5695
5696 protected void validateReminderQuery(String question, String answer)
5697 throws PortalException {
5698
5699 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
5700 return;
5701 }
5702
5703 if (Validator.isNull(question)) {
5704 throw new UserReminderQueryException("Question cannot be null");
5705 }
5706
5707 if (Validator.isNull(answer)) {
5708 throw new UserReminderQueryException("Answer cannot be null");
5709 }
5710 }
5711
5712 protected void validateScreenName(
5713 long companyId, long userId, String screenName)
5714 throws PortalException, SystemException {
5715
5716 if (Validator.isNull(screenName)) {
5717 throw new UserScreenNameException();
5718 }
5719
5720 ScreenNameValidator screenNameValidator =
5721 ScreenNameValidatorFactory.getInstance();
5722
5723 if (!screenNameValidator.validate(companyId, screenName)) {
5724 throw new UserScreenNameException();
5725 }
5726
5727 if (Validator.isNumber(screenName)) {
5728 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
5729 throw new UserScreenNameException();
5730 }
5731
5732 if (!screenName.equals(String.valueOf(userId))) {
5733 Group group = groupPersistence.fetchByPrimaryKey(
5734 GetterUtil.getLong(screenName));
5735
5736 if (group != null) {
5737 throw new UserScreenNameException();
5738 }
5739 }
5740 }
5741
5742 for (char c : screenName.toCharArray()) {
5743 if (!Validator.isChar(c) && !Validator.isDigit(c) &&
5744 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
5745 (c != CharPool.UNDERLINE)) {
5746
5747 throw new UserScreenNameException();
5748 }
5749 }
5750
5751 String[] anonymousNames = BaseServiceImpl.ANONYMOUS_NAMES;
5752
5753 for (String anonymousName : anonymousNames) {
5754 if (screenName.equalsIgnoreCase(anonymousName)) {
5755 throw new UserScreenNameException();
5756 }
5757 }
5758
5759 User user = userPersistence.fetchByC_SN(companyId, screenName);
5760
5761 if ((user != null) && (user.getUserId() != userId)) {
5762 throw new DuplicateUserScreenNameException();
5763 }
5764
5765 String friendlyURL = StringPool.SLASH + screenName;
5766
5767 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
5768
5769 if ((group != null) && (group.getClassPK() != userId)) {
5770 throw new GroupFriendlyURLException(
5771 GroupFriendlyURLException.DUPLICATE);
5772 }
5773
5774 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
5775
5776 if (exceptionType != -1) {
5777 throw new UserScreenNameException(
5778 new GroupFriendlyURLException(exceptionType));
5779 }
5780
5781 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
5782 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
5783 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
5784
5785 for (String reservedScreenName : reservedScreenNames) {
5786 if (screenName.equalsIgnoreCase(reservedScreenName)) {
5787 throw new ReservedUserScreenNameException();
5788 }
5789 }
5790 }
5791
5792 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
5793
5794 private static Map<Long, User> _defaultUsers =
5795 new ConcurrentHashMap<Long, User>();
5796
5797 }