001
014
015 package com.liferay.portal.service.impl;
016
017 import com.liferay.portal.CompanyMaxUsersException;
018 import com.liferay.portal.ContactBirthdayException;
019 import com.liferay.portal.ContactFirstNameException;
020 import com.liferay.portal.ContactFullNameException;
021 import com.liferay.portal.ContactLastNameException;
022 import com.liferay.portal.DuplicateOpenIdException;
023 import com.liferay.portal.DuplicateUserEmailAddressException;
024 import com.liferay.portal.DuplicateUserScreenNameException;
025 import com.liferay.portal.GroupFriendlyURLException;
026 import com.liferay.portal.ModelListenerException;
027 import com.liferay.portal.NoSuchContactException;
028 import com.liferay.portal.NoSuchGroupException;
029 import com.liferay.portal.NoSuchImageException;
030 import com.liferay.portal.NoSuchOrganizationException;
031 import com.liferay.portal.NoSuchRoleException;
032 import com.liferay.portal.NoSuchTicketException;
033 import com.liferay.portal.NoSuchUserException;
034 import com.liferay.portal.NoSuchUserGroupException;
035 import com.liferay.portal.PasswordExpiredException;
036 import com.liferay.portal.RequiredUserException;
037 import com.liferay.portal.ReservedUserEmailAddressException;
038 import com.liferay.portal.ReservedUserScreenNameException;
039 import com.liferay.portal.UserEmailAddressException;
040 import com.liferay.portal.UserIdException;
041 import com.liferay.portal.UserLockoutException;
042 import com.liferay.portal.UserPasswordException;
043 import com.liferay.portal.UserPortraitSizeException;
044 import com.liferay.portal.UserPortraitTypeException;
045 import com.liferay.portal.UserReminderQueryException;
046 import com.liferay.portal.UserScreenNameException;
047 import com.liferay.portal.UserSmsException;
048 import com.liferay.portal.kernel.dao.shard.ShardCallable;
049 import com.liferay.portal.kernel.exception.PortalException;
050 import com.liferay.portal.kernel.exception.SystemException;
051 import com.liferay.portal.kernel.image.ImageBag;
052 import com.liferay.portal.kernel.image.ImageToolUtil;
053 import com.liferay.portal.kernel.language.LanguageUtil;
054 import com.liferay.portal.kernel.log.Log;
055 import com.liferay.portal.kernel.log.LogFactoryUtil;
056 import com.liferay.portal.kernel.search.Hits;
057 import com.liferay.portal.kernel.search.Indexer;
058 import com.liferay.portal.kernel.search.IndexerRegistryUtil;
059 import com.liferay.portal.kernel.search.QueryConfig;
060 import com.liferay.portal.kernel.search.SearchContext;
061 import com.liferay.portal.kernel.search.Sort;
062 import com.liferay.portal.kernel.spring.aop.Skip;
063 import com.liferay.portal.kernel.transaction.Propagation;
064 import com.liferay.portal.kernel.transaction.TransactionCommitCallbackRegistryUtil;
065 import com.liferay.portal.kernel.transaction.Transactional;
066 import com.liferay.portal.kernel.util.ArrayUtil;
067 import com.liferay.portal.kernel.util.CharPool;
068 import com.liferay.portal.kernel.util.Digester;
069 import com.liferay.portal.kernel.util.DigesterUtil;
070 import com.liferay.portal.kernel.util.GetterUtil;
071 import com.liferay.portal.kernel.util.KeyValuePair;
072 import com.liferay.portal.kernel.util.LocaleUtil;
073 import com.liferay.portal.kernel.util.OrderByComparator;
074 import com.liferay.portal.kernel.util.ParamUtil;
075 import com.liferay.portal.kernel.util.PropsKeys;
076 import com.liferay.portal.kernel.util.StringBundler;
077 import com.liferay.portal.kernel.util.StringPool;
078 import com.liferay.portal.kernel.util.StringUtil;
079 import com.liferay.portal.kernel.util.Validator;
080 import com.liferay.portal.kernel.workflow.WorkflowConstants;
081 import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil;
082 import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
083 import com.liferay.portal.model.Account;
084 import com.liferay.portal.model.Company;
085 import com.liferay.portal.model.CompanyConstants;
086 import com.liferay.portal.model.Contact;
087 import com.liferay.portal.model.ContactConstants;
088 import com.liferay.portal.model.Group;
089 import com.liferay.portal.model.GroupConstants;
090 import com.liferay.portal.model.Layout;
091 import com.liferay.portal.model.Organization;
092 import com.liferay.portal.model.PasswordPolicy;
093 import com.liferay.portal.model.ResourceConstants;
094 import com.liferay.portal.model.Role;
095 import com.liferay.portal.model.RoleConstants;
096 import com.liferay.portal.model.Team;
097 import com.liferay.portal.model.Ticket;
098 import com.liferay.portal.model.TicketConstants;
099 import com.liferay.portal.model.User;
100 import com.liferay.portal.model.UserGroup;
101 import com.liferay.portal.model.UserGroupRole;
102 import com.liferay.portal.model.impl.LayoutImpl;
103 import com.liferay.portal.security.auth.AuthPipeline;
104 import com.liferay.portal.security.auth.Authenticator;
105 import com.liferay.portal.security.auth.EmailAddressGenerator;
106 import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
107 import com.liferay.portal.security.auth.EmailAddressValidator;
108 import com.liferay.portal.security.auth.EmailAddressValidatorFactory;
109 import com.liferay.portal.security.auth.FullNameGenerator;
110 import com.liferay.portal.security.auth.FullNameGeneratorFactory;
111 import com.liferay.portal.security.auth.FullNameValidator;
112 import com.liferay.portal.security.auth.FullNameValidatorFactory;
113 import com.liferay.portal.security.auth.PrincipalException;
114 import com.liferay.portal.security.auth.ScreenNameGenerator;
115 import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
116 import com.liferay.portal.security.auth.ScreenNameValidator;
117 import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
118 import com.liferay.portal.security.ldap.LDAPSettingsUtil;
119 import com.liferay.portal.security.permission.PermissionCacheUtil;
120 import com.liferay.portal.security.pwd.PwdAuthenticator;
121 import com.liferay.portal.security.pwd.PwdEncryptor;
122 import com.liferay.portal.security.pwd.PwdToolkitUtil;
123 import com.liferay.portal.security.pwd.RegExpToolkit;
124 import com.liferay.portal.service.BaseServiceImpl;
125 import com.liferay.portal.service.ServiceContext;
126 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
127 import com.liferay.portal.util.PortalUtil;
128 import com.liferay.portal.util.PrefsPropsUtil;
129 import com.liferay.portal.util.PropsValues;
130 import com.liferay.portal.util.SubscriptionSender;
131 import com.liferay.portlet.documentlibrary.ImageSizeException;
132 import com.liferay.portlet.messageboards.model.MBMessage;
133 import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
134 import com.liferay.util.Encryptor;
135 import com.liferay.util.EncryptorException;
136
137 import java.awt.image.RenderedImage;
138
139 import java.io.IOException;
140 import java.io.Serializable;
141
142 import java.util.Arrays;
143 import java.util.Calendar;
144 import java.util.Date;
145 import java.util.HashMap;
146 import java.util.HashSet;
147 import java.util.LinkedHashMap;
148 import java.util.List;
149 import java.util.Locale;
150 import java.util.Map;
151 import java.util.Set;
152 import java.util.concurrent.Callable;
153 import java.util.concurrent.ConcurrentHashMap;
154
155
166 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
167
168 @Override
169 public User addDefaultAdminUser(
170 long companyId, String screenName, String emailAddress,
171 Locale locale, String firstName, String middleName, String lastName)
172 throws PortalException, SystemException {
173
174 long creatorUserId = 0;
175 boolean autoPassword = false;
176 String password1 = PropsValues.DEFAULT_ADMIN_PASSWORD;
177 String password2 = password1;
178 boolean autoScreenName = false;
179
180 screenName = getScreenName(screenName);
181
182 for (int i = 1;; i++) {
183 User screenNameUser = userPersistence.fetchByC_SN(
184 companyId, screenName);
185
186 if (screenNameUser == null) {
187 break;
188 }
189
190 screenName = screenName + i;
191 }
192
193 long facebookId = 0;
194 String openId = StringPool.BLANK;
195 int prefixId = 0;
196 int suffixId = 0;
197 boolean male = true;
198 int birthdayMonth = Calendar.JANUARY;
199 int birthdayDay = 1;
200 int birthdayYear = 1970;
201 String jobTitle = StringPool.BLANK;
202
203 Group guestGroup = groupLocalService.getGroup(
204 companyId, GroupConstants.GUEST);
205
206 long[] groupIds = {guestGroup.getGroupId()};
207
208 long[] organizationIds = null;
209
210 Role adminRole = roleLocalService.getRole(
211 companyId, RoleConstants.ADMINISTRATOR);
212
213 Role powerUserRole = roleLocalService.getRole(
214 companyId, RoleConstants.POWER_USER);
215
216 long[] roleIds = {adminRole.getRoleId(), powerUserRole.getRoleId()};
217
218 long[] userGroupIds = null;
219 boolean sendEmail = false;
220 ServiceContext serviceContext = new ServiceContext();
221
222 User defaultAdminUser = addUser(
223 creatorUserId, companyId, autoPassword, password1, password2,
224 autoScreenName, screenName, emailAddress, facebookId, openId,
225 locale, firstName, middleName, lastName, prefixId, suffixId, male,
226 birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
227 organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
228
229 updateEmailAddressVerified(defaultAdminUser.getUserId(), true);
230
231 updateLastLogin(
232 defaultAdminUser.getUserId(), defaultAdminUser.getLoginIP());
233
234 updatePasswordReset(defaultAdminUser.getUserId(), false);
235
236 return defaultAdminUser;
237 }
238
239
249 @Override
250 public void addDefaultGroups(long userId)
251 throws PortalException, SystemException {
252
253 User user = userPersistence.findByPrimaryKey(userId);
254
255 Set<Long> groupIdsSet = new HashSet<Long>();
256
257 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
258 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
259 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
260
261 for (String defaultGroupName : defaultGroupNames) {
262 Company company = companyPersistence.findByPrimaryKey(
263 user.getCompanyId());
264
265 Account account = company.getAccount();
266
267 if (defaultGroupName.equalsIgnoreCase(account.getName())) {
268 defaultGroupName = GroupConstants.GUEST;
269 }
270
271 try {
272 Group group = groupPersistence.findByC_N(
273 user.getCompanyId(), defaultGroupName);
274
275 if (!userPersistence.containsGroup(
276 userId, group.getGroupId())) {
277
278 groupIdsSet.add(group.getGroupId());
279 }
280 }
281 catch (NoSuchGroupException nsge) {
282 }
283 }
284
285 String[] defaultOrganizationGroupNames = PrefsPropsUtil.getStringArray(
286 user.getCompanyId(),
287 PropsKeys.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES,
288 StringPool.NEW_LINE,
289 PropsValues.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES);
290
291 for (String defaultOrganizationGroupName :
292 defaultOrganizationGroupNames) {
293
294 defaultOrganizationGroupName +=
295 GroupLocalServiceImpl.ORGANIZATION_NAME_SUFFIX;
296
297 try {
298 Group group = groupPersistence.findByC_N(
299 user.getCompanyId(), defaultOrganizationGroupName);
300
301 if (!userPersistence.containsGroup(
302 userId, group.getGroupId())) {
303
304 groupIdsSet.add(group.getGroupId());
305 }
306 }
307 catch (NoSuchGroupException nsge) {
308 }
309 }
310
311 long[] groupIds = ArrayUtil.toArray(
312 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
313
314 groupLocalService.addUserGroups(userId, groupIds);
315 }
316
317
327 @Override
328 public void addDefaultRoles(long userId)
329 throws PortalException, SystemException {
330
331 User user = userPersistence.findByPrimaryKey(userId);
332
333 Set<Long> roleIdSet = new HashSet<Long>();
334
335 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
336 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
337 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
338
339 for (String defaultRoleName : defaultRoleNames) {
340 try {
341 Role role = rolePersistence.findByC_N(
342 user.getCompanyId(), defaultRoleName);
343
344 if (!userPersistence.containsRole(userId, role.getRoleId())) {
345 roleIdSet.add(role.getRoleId());
346 }
347 }
348 catch (NoSuchRoleException nsre) {
349 }
350 }
351
352 long[] roleIds = ArrayUtil.toArray(
353 roleIdSet.toArray(new Long[roleIdSet.size()]));
354
355 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
356
357 userPersistence.addRoles(userId, roleIds);
358 }
359
360
370 @Override
371 @SuppressWarnings("deprecation")
372 public void addDefaultUserGroups(long userId)
373 throws PortalException, SystemException {
374
375 User user = userPersistence.findByPrimaryKey(userId);
376
377 Set<Long> userGroupIdSet = new HashSet<Long>();
378
379 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
380 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
381 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
382
383 for (String defaultUserGroupName : defaultUserGroupNames) {
384 try {
385 UserGroup userGroup = userGroupPersistence.findByC_N(
386 user.getCompanyId(), defaultUserGroupName);
387
388 if (!userPersistence.containsUserGroup(
389 userId, userGroup.getUserGroupId())) {
390
391 userGroupIdSet.add(userGroup.getUserGroupId());
392 }
393 }
394 catch (NoSuchUserGroupException nsuge) {
395 }
396 }
397
398 long[] userGroupIds = ArrayUtil.toArray(
399 userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
400
401 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
402 for (long userGroupId : userGroupIds) {
403 userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
404 }
405 }
406
407 userPersistence.addUserGroups(userId, userGroupIds);
408 }
409
410
419 @Override
420 public void addGroupUsers(long groupId, long[] userIds)
421 throws PortalException, SystemException {
422
423 groupPersistence.addUsers(groupId, userIds);
424
425 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
426
427 indexer.reindex(userIds);
428
429 PermissionCacheUtil.clearCache();
430 }
431
432
441 @Override
442 public void addOrganizationUsers(long organizationId, long[] userIds)
443 throws PortalException, SystemException {
444
445 organizationPersistence.addUsers(organizationId, userIds);
446
447 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
448
449 indexer.reindex(userIds);
450
451 PermissionCacheUtil.clearCache();
452 }
453
454
462 @Override
463 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
464 throws SystemException {
465
466 passwordPolicyRelLocalService.addPasswordPolicyRels(
467 passwordPolicyId, User.class.getName(), userIds);
468 }
469
470
479 @Override
480 public void addRoleUsers(long roleId, long[] userIds)
481 throws PortalException, SystemException {
482
483 rolePersistence.addUsers(roleId, userIds);
484
485 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
486
487 indexer.reindex(userIds);
488
489 PermissionCacheUtil.clearCache();
490 }
491
492
501 @Override
502 public void addTeamUsers(long teamId, long[] userIds)
503 throws PortalException, SystemException {
504
505 teamPersistence.addUsers(teamId, userIds);
506
507 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
508
509 indexer.reindex(userIds);
510
511 PermissionCacheUtil.clearCache();
512 }
513
514
562 @Override
563 public User addUser(
564 long creatorUserId, long companyId, boolean autoPassword,
565 String password1, String password2, boolean autoScreenName,
566 String screenName, String emailAddress, long facebookId,
567 String openId, Locale locale, String firstName, String middleName,
568 String lastName, int prefixId, int suffixId, boolean male,
569 int birthdayMonth, int birthdayDay, int birthdayYear,
570 String jobTitle, long[] groupIds, long[] organizationIds,
571 long[] roleIds, long[] userGroupIds, boolean sendEmail,
572 ServiceContext serviceContext)
573 throws PortalException, SystemException {
574
575 boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
576
577 try {
578 WorkflowThreadLocal.setEnabled(false);
579
580 if (serviceContext == null) {
581 serviceContext = new ServiceContext();
582 }
583
584 if (serviceContext.getWorkflowAction() !=
585 WorkflowConstants.ACTION_PUBLISH) {
586
587 serviceContext.setWorkflowAction(
588 WorkflowConstants.ACTION_PUBLISH);
589 }
590
591 return addUserWithWorkflow(
592 creatorUserId, companyId, autoPassword, password1, password2,
593 autoScreenName, screenName, emailAddress, facebookId, openId,
594 locale, firstName, middleName, lastName, prefixId, suffixId,
595 male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
596 groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
597 serviceContext);
598 }
599 finally {
600 WorkflowThreadLocal.setEnabled(workflowEnabled);
601 }
602 }
603
604
613 @Override
614 @SuppressWarnings("deprecation")
615 public void addUserGroupUsers(long userGroupId, long[] userIds)
616 throws PortalException, SystemException {
617
618 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
619 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
620 }
621
622 userGroupPersistence.addUsers(userGroupId, userIds);
623
624 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
625
626 indexer.reindex(userIds);
627
628 PermissionCacheUtil.clearCache();
629 }
630
631
679 @Override
680 @SuppressWarnings("deprecation")
681 public User addUserWithWorkflow(
682 long creatorUserId, long companyId, boolean autoPassword,
683 String password1, String password2, boolean autoScreenName,
684 String screenName, String emailAddress, long facebookId,
685 String openId, Locale locale, String firstName, String middleName,
686 String lastName, int prefixId, int suffixId, boolean male,
687 int birthdayMonth, int birthdayDay, int birthdayYear,
688 String jobTitle, long[] groupIds, long[] organizationIds,
689 long[] roleIds, long[] userGroupIds, boolean sendEmail,
690 ServiceContext serviceContext)
691 throws PortalException, SystemException {
692
693
694
695 Company company = companyPersistence.findByPrimaryKey(companyId);
696 screenName = getScreenName(screenName);
697 openId = StringUtil.trim(openId);
698 Date now = new Date();
699
700 if (PrefsPropsUtil.getBoolean(
701 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
702
703 autoScreenName = true;
704 }
705
706 long userId = counterLocalService.increment();
707
708 EmailAddressGenerator emailAddressGenerator =
709 EmailAddressGeneratorFactory.getInstance();
710
711 if ((emailAddress == null) ||
712 emailAddressGenerator.isGenerated(emailAddress)) {
713
714 emailAddress = StringPool.BLANK;
715 }
716 else {
717 emailAddress = emailAddress.trim().toLowerCase();
718 }
719
720 if (!PrefsPropsUtil.getBoolean(
721 companyId, PropsKeys.USERS_EMAIL_ADDRESS_REQUIRED) &&
722 Validator.isNull(emailAddress)) {
723
724 emailAddress = emailAddressGenerator.generate(companyId, userId);
725 }
726
727 validate(
728 companyId, userId, autoPassword, password1, password2,
729 autoScreenName, screenName, emailAddress, openId, firstName,
730 middleName, lastName, organizationIds);
731
732 if (!autoPassword) {
733 if (Validator.isNull(password1) || Validator.isNull(password2)) {
734 throw new UserPasswordException(
735 UserPasswordException.PASSWORD_INVALID);
736 }
737 }
738
739 if (autoScreenName) {
740 ScreenNameGenerator screenNameGenerator =
741 ScreenNameGeneratorFactory.getInstance();
742
743 try {
744 screenName = screenNameGenerator.generate(
745 companyId, userId, emailAddress);
746 }
747 catch (Exception e) {
748 throw new SystemException(e);
749 }
750 }
751
752 User defaultUser = getDefaultUser(companyId);
753
754 FullNameGenerator fullNameGenerator =
755 FullNameGeneratorFactory.getInstance();
756
757 String fullName = fullNameGenerator.getFullName(
758 firstName, middleName, lastName);
759
760 String greeting = LanguageUtil.format(
761 locale, "welcome-x", " " + fullName, false);
762
763 User user = userPersistence.create(userId);
764
765 if (serviceContext != null) {
766 String uuid = serviceContext.getUuid();
767
768 if (Validator.isNotNull(uuid)) {
769 user.setUuid(uuid);
770 }
771 }
772
773 user.setCompanyId(companyId);
774 user.setCreateDate(now);
775 user.setModifiedDate(now);
776 user.setDefaultUser(false);
777 user.setContactId(counterLocalService.increment());
778
779 if (Validator.isNotNull(password1)) {
780 user.setPassword(PwdEncryptor.encrypt(password1));
781 user.setPasswordUnencrypted(password1);
782 }
783
784 user.setPasswordEncrypted(true);
785
786 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
787
788 boolean passwordReset = false;
789
790 if (passwordPolicy != null) {
791 if (passwordPolicy.isChangeable() &&
792 passwordPolicy.isChangeRequired()) {
793
794 passwordReset = true;
795 }
796
797 addPasswordPolicyUsers(
798 passwordPolicy.getPasswordPolicyId(), new long[] {userId});
799 }
800
801 user.setPasswordReset(passwordReset);
802
803 user.setDigest(StringPool.BLANK);
804 user.setScreenName(screenName);
805 user.setEmailAddress(emailAddress);
806 user.setFacebookId(facebookId);
807 user.setOpenId(openId);
808 user.setLanguageId(LocaleUtil.toLanguageId(locale));
809 user.setTimeZoneId(defaultUser.getTimeZoneId());
810 user.setGreeting(greeting);
811 user.setFirstName(firstName);
812 user.setMiddleName(middleName);
813 user.setLastName(lastName);
814 user.setJobTitle(jobTitle);
815 user.setStatus(WorkflowConstants.STATUS_DRAFT);
816 user.setExpandoBridgeAttributes(serviceContext);
817
818 userPersistence.update(user, false, serviceContext);
819
820
821
822 String creatorUserName = StringPool.BLANK;
823
824 if (creatorUserId <= 0) {
825 creatorUserId = user.getUserId();
826
827
828
829
830
831 }
832 else {
833 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
834
835 creatorUserName = creatorUser.getFullName();
836 }
837
838 resourceLocalService.addResources(
839 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
840 false, false, false);
841
842
843
844 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
845
846 Contact contact = contactPersistence.create(user.getContactId());
847
848 contact.setCompanyId(user.getCompanyId());
849 contact.setUserId(creatorUserId);
850 contact.setUserName(creatorUserName);
851 contact.setCreateDate(now);
852 contact.setModifiedDate(now);
853 contact.setAccountId(company.getAccountId());
854 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
855 contact.setFirstName(firstName);
856 contact.setMiddleName(middleName);
857 contact.setLastName(lastName);
858 contact.setPrefixId(prefixId);
859 contact.setSuffixId(suffixId);
860 contact.setMale(male);
861 contact.setBirthday(birthday);
862 contact.setJobTitle(jobTitle);
863
864 contactPersistence.update(contact, false, serviceContext);
865
866
867
868 groupLocalService.addGroup(
869 user.getUserId(), User.class.getName(), user.getUserId(), null,
870 null, 0, StringPool.SLASH + screenName, false, true, null);
871
872
873
874 if (groupIds != null) {
875 groupLocalService.addUserGroups(userId, groupIds);
876 }
877
878 addDefaultGroups(userId);
879
880
881
882 updateOrganizations(userId, organizationIds, false);
883
884
885
886 if (roleIds != null) {
887 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
888
889 userPersistence.setRoles(userId, roleIds);
890 }
891
892 addDefaultRoles(userId);
893
894
895
896 if (userGroupIds != null) {
897 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
898 for (long userGroupId : userGroupIds) {
899 userGroupLocalService.copyUserGroupLayouts(
900 userGroupId, new long[] {userId});
901 }
902 }
903
904 userPersistence.setUserGroups(userId, userGroupIds);
905 }
906
907 addDefaultUserGroups(userId);
908
909
910
911 if (serviceContext != null) {
912 updateAsset(
913 creatorUserId, user, serviceContext.getAssetCategoryIds(),
914 serviceContext.getAssetTagNames());
915 }
916
917
918
919 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
920 reindex(user);
921 }
922
923
924
925 long workflowUserId = creatorUserId;
926
927 if (workflowUserId == userId) {
928 workflowUserId = defaultUser.getUserId();
929 }
930
931 ServiceContext workflowServiceContext = serviceContext;
932
933 if (workflowServiceContext == null) {
934 workflowServiceContext = new ServiceContext();
935 }
936
937 workflowServiceContext.setAttribute("autoPassword", autoPassword);
938 workflowServiceContext.setAttribute("sendEmail", sendEmail);
939
940 startWorkflowInstance(
941 companyId, workflowUserId, userId, user, workflowServiceContext);
942
943 if (serviceContext != null) {
944 String passwordUnencrypted = (String)serviceContext.getAttribute(
945 "passwordUnencrypted");
946
947 if (Validator.isNotNull(passwordUnencrypted)) {
948 user.setPasswordUnencrypted(passwordUnencrypted);
949 }
950 }
951
952 return user;
953 }
954
955
979 @Override
980 public int authenticateByEmailAddress(
981 long companyId, String emailAddress, String password,
982 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
983 Map<String, Object> resultsMap)
984 throws PortalException, SystemException {
985
986 return authenticate(
987 companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
988 headerMap, parameterMap, resultsMap);
989 }
990
991
1015 @Override
1016 public int authenticateByScreenName(
1017 long companyId, String screenName, String password,
1018 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1019 Map<String, Object> resultsMap)
1020 throws PortalException, SystemException {
1021
1022 return authenticate(
1023 companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
1024 headerMap, parameterMap, resultsMap);
1025 }
1026
1027
1051 @Override
1052 public int authenticateByUserId(
1053 long companyId, long userId, String password,
1054 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1055 Map<String, Object> resultsMap)
1056 throws PortalException, SystemException {
1057
1058 return authenticate(
1059 companyId, String.valueOf(userId), password,
1060 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap, resultsMap);
1061 }
1062
1063
1103 @Override
1104 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1105 public long authenticateForBasic(
1106 long companyId, String authType, String login, String password)
1107 throws PortalException, SystemException {
1108
1109 if (PropsValues.AUTH_LOGIN_DISABLED) {
1110 return 0;
1111 }
1112
1113 try {
1114 User user = null;
1115
1116 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1117 user = getUserByEmailAddress(companyId, login);
1118 }
1119 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1120 user = getUserByScreenName(companyId, login);
1121 }
1122 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1123 user = getUserById(companyId, GetterUtil.getLong(login));
1124 }
1125
1126 if (user.isDefaultUser()) {
1127 if (_log.isInfoEnabled()) {
1128 _log.info(
1129 "Basic authentication is disabled for the default " +
1130 "user");
1131 }
1132
1133 return 0;
1134 }
1135 else if (!user.isActive()) {
1136 if (_log.isInfoEnabled()) {
1137 _log.info(
1138 "Basic authentication is disabled for inactive user " +
1139 user.getUserId());
1140 }
1141
1142 return 0;
1143 }
1144
1145 if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
1146 return user.getUserId();
1147 }
1148
1149 String userPassword = user.getPassword();
1150
1151 if (!user.isPasswordEncrypted()) {
1152 userPassword = PwdEncryptor.encrypt(userPassword);
1153 }
1154
1155 String encPassword = PwdEncryptor.encrypt(password);
1156
1157 if (userPassword.equals(password) ||
1158 userPassword.equals(encPassword)) {
1159
1160 return user.getUserId();
1161 }
1162 }
1163 catch (NoSuchUserException nsue) {
1164 }
1165
1166 return 0;
1167 }
1168
1169
1187 @Override
1188 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1189 public long authenticateForDigest(
1190 long companyId, String username, String realm, String nonce,
1191 String method, String uri, String response)
1192 throws PortalException, SystemException {
1193
1194 if (PropsValues.AUTH_LOGIN_DISABLED) {
1195 return 0;
1196 }
1197
1198
1199
1200 User user = null;
1201
1202 try {
1203 user = getUserByEmailAddress(companyId, username);
1204 }
1205 catch (NoSuchUserException nsue) {
1206 try {
1207 user = getUserByScreenName(companyId, username);
1208 }
1209 catch (NoSuchUserException nsue2) {
1210 try {
1211 user = getUserById(GetterUtil.getLong(username));
1212 }
1213 catch (NoSuchUserException nsue3) {
1214 return 0;
1215 }
1216 }
1217 }
1218
1219 if (user.isDefaultUser()) {
1220 if (_log.isInfoEnabled()) {
1221 _log.info(
1222 "Digest authentication is disabled for the default user");
1223 }
1224
1225 return 0;
1226 }
1227 else if (!user.isActive()) {
1228 if (_log.isInfoEnabled()) {
1229 _log.info(
1230 "Digest authentication is disabled for inactive user " +
1231 user.getUserId());
1232 }
1233
1234 return 0;
1235 }
1236
1237
1238
1239 String digest = user.getDigest();
1240
1241 if (Validator.isNull(digest)) {
1242 _log.error(
1243 "User must first login through the portal " + user.getUserId());
1244
1245 return 0;
1246 }
1247
1248 String[] digestArray = StringUtil.split(user.getDigest());
1249
1250 for (String ha1 : digestArray) {
1251 String ha2 = DigesterUtil.digestHex(Digester.MD5, method, uri);
1252
1253 String curResponse = DigesterUtil.digestHex(
1254 Digester.MD5, ha1, nonce, ha2);
1255
1256 if (response.equals(curResponse)) {
1257 return user.getUserId();
1258 }
1259 }
1260
1261 return 0;
1262 }
1263
1264
1273 @Override
1274 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1275 public boolean authenticateForJAAS(long userId, String encPassword) {
1276 if (PropsValues.AUTH_LOGIN_DISABLED) {
1277 return false;
1278 }
1279
1280 try {
1281 User user = userPersistence.findByPrimaryKey(userId);
1282
1283 if (user.isDefaultUser()) {
1284 if (_log.isInfoEnabled()) {
1285 _log.info(
1286 "JAAS authentication is disabled for the default user");
1287 }
1288
1289 return false;
1290 }
1291 else if (!user.isActive()) {
1292 if (_log.isInfoEnabled()) {
1293 _log.info(
1294 "JAAS authentication is disabled for inactive user " +
1295 userId);
1296 }
1297
1298 return false;
1299 }
1300
1301 String password = user.getPassword();
1302
1303 if (user.isPasswordEncrypted()) {
1304 if (password.equals(encPassword)) {
1305 return true;
1306 }
1307
1308 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1309 encPassword = PwdEncryptor.encrypt(encPassword, password);
1310
1311 if (password.equals(encPassword)) {
1312 return true;
1313 }
1314 }
1315 }
1316 else {
1317 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1318 if (password.equals(encPassword)) {
1319 return true;
1320 }
1321 }
1322
1323 password = PwdEncryptor.encrypt(password);
1324
1325 if (password.equals(encPassword)) {
1326 return true;
1327 }
1328 }
1329 }
1330 catch (Exception e) {
1331 _log.error(e);
1332 }
1333
1334 return false;
1335 }
1336
1337
1345 @Override
1346 public void checkLockout(User user)
1347 throws PortalException, SystemException {
1348
1349 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1350 return;
1351 }
1352
1353 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1354
1355 if (passwordPolicy.isLockout()) {
1356
1357
1358
1359 Date now = new Date();
1360 int failedLoginAttempts = user.getFailedLoginAttempts();
1361
1362 if (failedLoginAttempts > 0) {
1363 long failedLoginTime = user.getLastFailedLoginDate().getTime();
1364 long elapsedTime = now.getTime() - failedLoginTime;
1365 long requiredElapsedTime =
1366 passwordPolicy.getResetFailureCount() * 1000;
1367
1368 if ((requiredElapsedTime != 0) &&
1369 (elapsedTime > requiredElapsedTime)) {
1370
1371 user.setLastFailedLoginDate(null);
1372 user.setFailedLoginAttempts(0);
1373
1374 userPersistence.update(user, false);
1375 }
1376 }
1377
1378
1379
1380 if (user.isLockout()) {
1381 long lockoutTime = user.getLockoutDate().getTime();
1382 long elapsedTime = now.getTime() - lockoutTime;
1383 long requiredElapsedTime =
1384 passwordPolicy.getLockoutDuration() * 1000;
1385
1386 if ((requiredElapsedTime != 0) &&
1387 (elapsedTime > requiredElapsedTime)) {
1388
1389 user.setLockout(false);
1390 user.setLockoutDate(null);
1391
1392 userPersistence.update(user, false);
1393 }
1394 }
1395
1396 if (user.isLockout()) {
1397 throw new UserLockoutException();
1398 }
1399 }
1400 }
1401
1402
1409 @Override
1410 public void checkLoginFailure(User user) throws SystemException {
1411 Date now = new Date();
1412
1413 int failedLoginAttempts = user.getFailedLoginAttempts();
1414
1415 user.setLastFailedLoginDate(now);
1416 user.setFailedLoginAttempts(++failedLoginAttempts);
1417
1418 userPersistence.update(user, false);
1419 }
1420
1421
1431 @Override
1432 public void checkLoginFailureByEmailAddress(
1433 long companyId, String emailAddress)
1434 throws PortalException, SystemException {
1435
1436 User user = getUserByEmailAddress(companyId, emailAddress);
1437
1438 checkLoginFailure(user);
1439 }
1440
1441
1449 @Override
1450 public void checkLoginFailureById(long userId)
1451 throws PortalException, SystemException {
1452
1453 User user = userPersistence.findByPrimaryKey(userId);
1454
1455 checkLoginFailure(user);
1456 }
1457
1458
1467 @Override
1468 public void checkLoginFailureByScreenName(long companyId, String screenName)
1469 throws PortalException, SystemException {
1470
1471 User user = getUserByScreenName(companyId, screenName);
1472
1473 checkLoginFailure(user);
1474 }
1475
1476
1486 @Override
1487 public void checkPasswordExpired(User user)
1488 throws PortalException, SystemException {
1489
1490 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1491 return;
1492 }
1493
1494 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1495
1496
1497
1498 if (isPasswordExpired(user)) {
1499 int graceLoginCount = user.getGraceLoginCount();
1500
1501 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
1502 user.setGraceLoginCount(++graceLoginCount);
1503
1504 userPersistence.update(user, false);
1505 }
1506 else {
1507 user.setDigest(StringPool.BLANK);
1508
1509 userPersistence.update(user, false);
1510
1511 throw new PasswordExpiredException();
1512 }
1513 }
1514
1515
1516
1517 if (passwordPolicy.isChangeable() &&
1518 passwordPolicy.isChangeRequired()) {
1519
1520 if (user.getLastLoginDate() == null) {
1521 user.setPasswordReset(true);
1522
1523 userPersistence.update(user, false);
1524 }
1525 }
1526 }
1527
1528
1534 @Override
1535 public void clearOrganizationUsers(long organizationId)
1536 throws SystemException {
1537
1538 organizationPersistence.clearUsers(organizationId);
1539
1540 PermissionCacheUtil.clearCache();
1541 }
1542
1543
1549 @Override
1550 public void clearUserGroupUsers(long userGroupId) throws SystemException {
1551 userGroupPersistence.clearUsers(userGroupId);
1552
1553 PermissionCacheUtil.clearCache();
1554 }
1555
1556
1568 @Override
1569 public void completeUserRegistration(
1570 User user, ServiceContext serviceContext)
1571 throws PortalException, SystemException {
1572
1573 boolean autoPassword = ParamUtil.getBoolean(
1574 serviceContext, "autoPassword");
1575
1576 String password = null;
1577
1578 if (autoPassword) {
1579 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1580 if (_log.isWarnEnabled()) {
1581 StringBundler sb = new StringBundler(4);
1582
1583 sb.append("When LDAP password policy is enabled, it is ");
1584 sb.append("possible that portal generated passwords will ");
1585 sb.append("not match the LDAP policy. Using ");
1586 sb.append("RegExpToolkit to generate new password.");
1587
1588 _log.warn(sb.toString());
1589 }
1590
1591 RegExpToolkit regExpToolkit = new RegExpToolkit();
1592
1593 password = regExpToolkit.generate(null);
1594 }
1595 else {
1596 PasswordPolicy passwordPolicy =
1597 passwordPolicyLocalService.getPasswordPolicy(
1598 user.getCompanyId(), user.getOrganizationIds());
1599
1600 password = PwdToolkitUtil.generate(passwordPolicy);
1601 }
1602
1603 user.setPassword(PwdEncryptor.encrypt(password));
1604 user.setPasswordUnencrypted(password);
1605 user.setPasswordEncrypted(true);
1606 user.setPasswordModified(true);
1607 user.setPasswordModifiedDate(new Date());
1608
1609 userPersistence.update(user, false);
1610
1611 user.setPasswordModified(false);
1612 }
1613
1614 if (user.hasCompanyMx()) {
1615 String mailPassword = password;
1616
1617 if (Validator.isNull(mailPassword)) {
1618 mailPassword = user.getPasswordUnencrypted();
1619 }
1620
1621 mailService.addUser(
1622 user.getCompanyId(), user.getUserId(), mailPassword,
1623 user.getFirstName(), user.getMiddleName(), user.getLastName(),
1624 user.getEmailAddress());
1625 }
1626
1627 boolean sendEmail = ParamUtil.getBoolean(serviceContext, "sendEmail");
1628
1629 if (sendEmail) {
1630 sendEmail(user, password, serviceContext);
1631 }
1632
1633 Company company = companyPersistence.findByPrimaryKey(
1634 user.getCompanyId());
1635
1636 if (company.isStrangersVerify() && (serviceContext.getPlid() > 0)) {
1637 sendEmailAddressVerification(
1638 user, user.getEmailAddress(), serviceContext);
1639 }
1640 }
1641
1642
1655 @Override
1656 public KeyValuePair decryptUserId(
1657 long companyId, String name, String password)
1658 throws PortalException, SystemException {
1659
1660 Company company = companyPersistence.findByPrimaryKey(companyId);
1661
1662 try {
1663 name = Encryptor.decrypt(company.getKeyObj(), name);
1664 }
1665 catch (EncryptorException ee) {
1666 throw new SystemException(ee);
1667 }
1668
1669 long userId = GetterUtil.getLong(name);
1670
1671 User user = userPersistence.findByPrimaryKey(userId);
1672
1673 try {
1674 password = Encryptor.decrypt(company.getKeyObj(), password);
1675 }
1676 catch (EncryptorException ee) {
1677 throw new SystemException(ee);
1678 }
1679
1680 String encPassword = PwdEncryptor.encrypt(password);
1681
1682 if (user.getPassword().equals(encPassword)) {
1683 if (isPasswordExpired(user)) {
1684 user.setPasswordReset(true);
1685
1686 userPersistence.update(user, false);
1687 }
1688
1689 return new KeyValuePair(name, password);
1690 }
1691 else {
1692 throw new PrincipalException();
1693 }
1694 }
1695
1696
1704 @Override
1705 public void deletePortrait(long userId)
1706 throws PortalException, SystemException {
1707
1708 User user = userPersistence.findByPrimaryKey(userId);
1709
1710 long portraitId = user.getPortraitId();
1711
1712 if (portraitId > 0) {
1713 user.setPortraitId(0);
1714
1715 userPersistence.update(user, false);
1716
1717 imageLocalService.deleteImage(portraitId);
1718 }
1719 }
1720
1721
1730 @Override
1731 public void deleteRoleUser(long roleId, long userId)
1732 throws PortalException, SystemException {
1733
1734 rolePersistence.removeUser(roleId, userId);
1735
1736 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1737
1738 indexer.reindex(userId);
1739
1740 PermissionCacheUtil.clearCache();
1741 }
1742
1743
1751 @Override
1752 public User deleteUser(long userId)
1753 throws PortalException, SystemException {
1754
1755 User user = userPersistence.findByPrimaryKey(userId);
1756
1757 return deleteUser(user);
1758 }
1759
1760
1768 @Override
1769 public User deleteUser(User user) throws PortalException, SystemException {
1770 if (!PropsValues.USERS_DELETE) {
1771 throw new RequiredUserException();
1772 }
1773
1774
1775
1776 browserTrackerLocalService.deleteUserBrowserTracker(user.getUserId());
1777
1778
1779
1780 Group group = user.getGroup();
1781
1782 if (group != null) {
1783 groupLocalService.deleteGroup(group);
1784 }
1785
1786
1787
1788 try {
1789 imageLocalService.deleteImage(user.getPortraitId());
1790 }
1791 catch (NoSuchImageException nsie) {
1792 if (_log.isWarnEnabled()) {
1793 _log.warn("Unable to delete image " + user.getPortraitId());
1794 }
1795 }
1796
1797
1798
1799 passwordPolicyRelLocalService.deletePasswordPolicyRel(
1800 User.class.getName(), user.getUserId());
1801
1802
1803
1804 passwordTrackerLocalService.deletePasswordTrackers(user.getUserId());
1805
1806
1807
1808 subscriptionLocalService.deleteSubscriptions(user.getUserId());
1809
1810
1811
1812 userIdMapperLocalService.deleteUserIdMappers(user.getUserId());
1813
1814
1815
1816 announcementsDeliveryLocalService.deleteDeliveries(user.getUserId());
1817
1818
1819
1820 assetEntryLocalService.deleteEntry(
1821 User.class.getName(), user.getUserId());
1822
1823
1824
1825 blogsStatsUserLocalService.deleteStatsUserByUserId(user.getUserId());
1826
1827
1828
1829 dlFileRankLocalService.deleteFileRanksByUserId(user.getUserId());
1830
1831
1832
1833 expandoValueLocalService.deleteValues(
1834 User.class.getName(), user.getUserId());
1835
1836
1837
1838 mbBanLocalService.deleteBansByBanUserId(user.getUserId());
1839 mbStatsUserLocalService.deleteStatsUsersByUserId(user.getUserId());
1840 mbThreadFlagLocalService.deleteThreadFlagsByUserId(user.getUserId());
1841
1842
1843
1844 membershipRequestLocalService.deleteMembershipRequestsByUserId(
1845 user.getUserId());
1846
1847
1848
1849 shoppingCartLocalService.deleteUserCarts(user.getUserId());
1850
1851
1852
1853 socialActivityLocalService.deleteUserActivities(user.getUserId());
1854 socialRequestLocalService.deleteReceiverUserRequests(user.getUserId());
1855 socialRequestLocalService.deleteUserRequests(user.getUserId());
1856
1857
1858
1859 mailService.deleteUser(user.getCompanyId(), user.getUserId());
1860
1861
1862
1863 try {
1864 contactLocalService.deleteContact(user.getContactId());
1865 }
1866 catch (NoSuchContactException nsce) {
1867 }
1868
1869
1870
1871 resourceLocalService.deleteResource(
1872 user.getCompanyId(), User.class.getName(),
1873 ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
1874
1875
1876
1877 userGroupRoleLocalService.deleteUserGroupRolesByUserId(
1878 user.getUserId());
1879
1880
1881
1882 userPersistence.remove(user);
1883
1884
1885
1886 PermissionCacheUtil.clearCache();
1887
1888
1889
1890 workflowInstanceLinkLocalService.deleteWorkflowInstanceLinks(
1891 user.getCompanyId(), 0, User.class.getName(), user.getUserId());
1892
1893 return user;
1894 }
1895
1896
1904 @Override
1905 public void deleteUserGroupUser(long userGroupId, long userId)
1906 throws PortalException, SystemException {
1907
1908 userGroupPersistence.removeUser(userGroupId, userId);
1909
1910 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1911
1912 indexer.reindex(userId);
1913
1914 PermissionCacheUtil.clearCache();
1915 }
1916
1917
1926 @Override
1927 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1928 public String encryptUserId(String name)
1929 throws PortalException, SystemException {
1930
1931 long userId = GetterUtil.getLong(name);
1932
1933 User user = userPersistence.findByPrimaryKey(userId);
1934
1935 Company company = companyPersistence.findByPrimaryKey(
1936 user.getCompanyId());
1937
1938 try {
1939 return Encryptor.encrypt(company.getKeyObj(), name);
1940 }
1941 catch (EncryptorException ee) {
1942 throw new SystemException(ee);
1943 }
1944 }
1945
1946
1955 @Override
1956 public User fetchUserByEmailAddress(long companyId, String emailAddress)
1957 throws SystemException {
1958
1959 return userPersistence.fetchByC_EA(companyId, emailAddress);
1960 }
1961
1962
1970 @Override
1971 public User fetchUserById(long userId) throws SystemException {
1972 return userPersistence.fetchByPrimaryKey(userId);
1973 }
1974
1975
1984 @Override
1985 public User fetchUserByScreenName(long companyId, String screenName)
1986 throws SystemException {
1987
1988 screenName = getScreenName(screenName);
1989
1990 return userPersistence.fetchByC_SN(companyId, screenName);
1991 }
1992
1993
2012 @Override
2013 public List<User> getCompanyUsers(long companyId, int start, int end)
2014 throws SystemException {
2015
2016 return userPersistence.findByCompanyId(companyId, start, end);
2017 }
2018
2019
2026 @Override
2027 public int getCompanyUsersCount(long companyId) throws SystemException {
2028 return userPersistence.countByCompanyId(companyId);
2029 }
2030
2031
2040 @Override
2041 @Skip
2042 public User getDefaultUser(long companyId)
2043 throws PortalException, SystemException {
2044
2045 User userModel = _defaultUsers.get(companyId);
2046
2047 if (userModel == null) {
2048 userModel = userLocalService.loadGetDefaultUser(companyId);
2049
2050 _defaultUsers.put(companyId, userModel);
2051 }
2052
2053 return userModel;
2054 }
2055
2056
2065 @Override
2066 @Skip
2067 public long getDefaultUserId(long companyId)
2068 throws PortalException, SystemException {
2069
2070 User user = getDefaultUser(companyId);
2071
2072 return user.getUserId();
2073 }
2074
2075
2082 @Override
2083 public long[] getGroupUserIds(long groupId) throws SystemException {
2084 return getUserIds(getGroupUsers(groupId));
2085 }
2086
2087
2094 @Override
2095 public List<User> getGroupUsers(long groupId) throws SystemException {
2096 return groupPersistence.getUsers(groupId);
2097 }
2098
2099
2106 @Override
2107 public int getGroupUsersCount(long groupId) throws SystemException {
2108 return groupPersistence.getUsersSize(groupId);
2109 }
2110
2111
2121 @Override
2122 public int getGroupUsersCount(long groupId, int status)
2123 throws PortalException, SystemException {
2124
2125 Group group = groupPersistence.findByPrimaryKey(groupId);
2126
2127 LinkedHashMap<String, Object> params =
2128 new LinkedHashMap<String, Object>();
2129
2130 params.put("usersGroups", new Long(groupId));
2131
2132 return searchCount(group.getCompanyId(), null, status, params);
2133 }
2134
2135
2143 @Override
2144 public List<User> getNoAnnouncementsDeliveries(String type)
2145 throws SystemException {
2146
2147 return userFinder.findByNoAnnouncementsDeliveries(type);
2148 }
2149
2150
2156 @Override
2157 public List<User> getNoContacts() throws SystemException {
2158 return userFinder.findByNoContacts();
2159 }
2160
2161
2168 @Override
2169 public List<User> getNoGroups() throws SystemException {
2170 return userFinder.findByNoGroups();
2171 }
2172
2173
2180 @Override
2181 public long[] getOrganizationUserIds(long organizationId)
2182 throws SystemException {
2183
2184 return getUserIds(getOrganizationUsers(organizationId));
2185 }
2186
2187
2194 @Override
2195 public List<User> getOrganizationUsers(long organizationId)
2196 throws SystemException {
2197
2198 return organizationPersistence.getUsers(organizationId);
2199 }
2200
2201
2208 @Override
2209 public int getOrganizationUsersCount(long organizationId)
2210 throws SystemException {
2211
2212 return organizationPersistence.getUsersSize(organizationId);
2213 }
2214
2215
2226 @Override
2227 public int getOrganizationUsersCount(long organizationId, int status)
2228 throws PortalException, SystemException {
2229
2230 Organization organization = organizationPersistence.findByPrimaryKey(
2231 organizationId);
2232
2233 LinkedHashMap<String, Object> params =
2234 new LinkedHashMap<String, Object>();
2235
2236 params.put("usersOrgs", new Long(organizationId));
2237
2238 return searchCount(organization.getCompanyId(), null, status, params);
2239 }
2240
2241
2248 @Override
2249 public long[] getRoleUserIds(long roleId) throws SystemException {
2250 return getUserIds(getRoleUsers(roleId));
2251 }
2252
2253
2260 @Override
2261 public List<User> getRoleUsers(long roleId) throws SystemException {
2262 return rolePersistence.getUsers(roleId);
2263 }
2264
2265
2284 @Override
2285 public List<User> getRoleUsers(long roleId, int start, int end)
2286 throws SystemException {
2287
2288 return rolePersistence.getUsers(roleId, start, end);
2289 }
2290
2291
2298 @Override
2299 public int getRoleUsersCount(long roleId) throws SystemException {
2300 return rolePersistence.getUsersSize(roleId);
2301 }
2302
2303
2313 @Override
2314 public int getRoleUsersCount(long roleId, int status)
2315 throws PortalException, SystemException {
2316
2317 Role role = rolePersistence.findByPrimaryKey(roleId);
2318
2319 LinkedHashMap<String, Object> params =
2320 new LinkedHashMap<String, Object>();
2321
2322 params.put("usersRoles", new Long(roleId));
2323
2324 return searchCount(role.getCompanyId(), null, status, params);
2325 }
2326
2327
2354 @Override
2355 public List<User> getSocialUsers(
2356 long userId, int type, int start, int end, OrderByComparator obc)
2357 throws PortalException, SystemException {
2358
2359 User user = userPersistence.findByPrimaryKey(userId);
2360
2361 LinkedHashMap<String, Object> params =
2362 new LinkedHashMap<String, Object>();
2363
2364 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2365
2366 return search(
2367 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2368 params, start, end, obc);
2369 }
2370
2371
2394 @Override
2395 public List<User> getSocialUsers(
2396 long userId, int start, int end, OrderByComparator obc)
2397 throws PortalException, SystemException {
2398
2399 User user = userPersistence.findByPrimaryKey(userId);
2400
2401 LinkedHashMap<String, Object> params =
2402 new LinkedHashMap<String, Object>();
2403
2404 params.put("socialRelation", new Long[] {userId});
2405
2406 return search(
2407 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2408 params, start, end, obc);
2409 }
2410
2411
2439 @Override
2440 public List<User> getSocialUsers(
2441 long userId1, long userId2, int type, int start, int end,
2442 OrderByComparator obc)
2443 throws PortalException, SystemException {
2444
2445 User user1 = userPersistence.findByPrimaryKey(userId1);
2446
2447 LinkedHashMap<String, Object> params =
2448 new LinkedHashMap<String, Object>();
2449
2450 params.put(
2451 "socialMutualRelationType",
2452 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2453
2454 return search(
2455 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2456 params, start, end, obc);
2457 }
2458
2459
2484 @Override
2485 public List<User> getSocialUsers(
2486 long userId1, long userId2, int start, int end,
2487 OrderByComparator obc)
2488 throws PortalException, SystemException {
2489
2490 User user1 = userPersistence.findByPrimaryKey(userId1);
2491
2492 LinkedHashMap<String, Object> params =
2493 new LinkedHashMap<String, Object>();
2494
2495 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2496
2497 return search(
2498 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2499 params, start, end, obc);
2500 }
2501
2502
2510 @Override
2511 public int getSocialUsersCount(long userId)
2512 throws PortalException, SystemException {
2513
2514 User user = userPersistence.findByPrimaryKey(userId);
2515
2516 LinkedHashMap<String, Object> params =
2517 new LinkedHashMap<String, Object>();
2518
2519 params.put("socialRelation", new Long[] {userId});
2520
2521 return searchCount(
2522 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2523 params);
2524 }
2525
2526
2539 @Override
2540 public int getSocialUsersCount(long userId, int type)
2541 throws PortalException, SystemException {
2542
2543 User user = userPersistence.findByPrimaryKey(userId);
2544
2545 LinkedHashMap<String, Object> params =
2546 new LinkedHashMap<String, Object>();
2547
2548 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2549
2550 return searchCount(
2551 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2552 params);
2553 }
2554
2555
2565 @Override
2566 public int getSocialUsersCount(long userId1, long userId2)
2567 throws PortalException, SystemException {
2568
2569 User user1 = userPersistence.findByPrimaryKey(userId1);
2570
2571 LinkedHashMap<String, Object> params =
2572 new LinkedHashMap<String, Object>();
2573
2574 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2575
2576 return searchCount(
2577 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2578 params);
2579 }
2580
2581
2595 @Override
2596 public int getSocialUsersCount(long userId1, long userId2, int type)
2597 throws PortalException, SystemException {
2598
2599 User user1 = userPersistence.findByPrimaryKey(userId1);
2600
2601 LinkedHashMap<String, Object> params =
2602 new LinkedHashMap<String, Object>();
2603
2604 params.put(
2605 "socialMutualRelationType",
2606 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2607
2608 return searchCount(
2609 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2610 params);
2611 }
2612
2613
2621 @Override
2622 public User getUserByContactId(long contactId)
2623 throws PortalException, SystemException {
2624
2625 return userPersistence.findByContactId(contactId);
2626 }
2627
2628
2638 @Override
2639 public User getUserByEmailAddress(long companyId, String emailAddress)
2640 throws PortalException, SystemException {
2641
2642 emailAddress = emailAddress.trim().toLowerCase();
2643
2644 return userPersistence.findByC_EA(companyId, emailAddress);
2645 }
2646
2647
2656 @Override
2657 public User getUserByFacebookId(long companyId, long facebookId)
2658 throws PortalException, SystemException {
2659
2660 return userPersistence.findByC_FID(companyId, facebookId);
2661 }
2662
2663
2671 @Override
2672 public User getUserById(long userId)
2673 throws PortalException, SystemException {
2674
2675 return userPersistence.findByPrimaryKey(userId);
2676 }
2677
2678
2688 @Override
2689 public User getUserById(long companyId, long userId)
2690 throws PortalException, SystemException {
2691
2692 return userPersistence.findByC_U(companyId, userId);
2693 }
2694
2695
2704 @Override
2705 public User getUserByOpenId(long companyId, String openId)
2706 throws PortalException, SystemException {
2707
2708 return userPersistence.findByC_O(companyId, openId);
2709 }
2710
2711
2719 @Override
2720 public User getUserByPortraitId(long portraitId)
2721 throws PortalException, SystemException {
2722
2723 return userPersistence.findByPortraitId(portraitId);
2724 }
2725
2726
2735 @Override
2736 public User getUserByScreenName(long companyId, String screenName)
2737 throws PortalException, SystemException {
2738
2739 screenName = getScreenName(screenName);
2740
2741 return userPersistence.findByC_SN(companyId, screenName);
2742 }
2743
2744
2753 @Override
2754 public User getUserByUuid(String uuid)
2755 throws PortalException, SystemException {
2756
2757 List<User> users = userPersistence.findByUuid(uuid);
2758
2759 if (users.isEmpty()) {
2760 throw new NoSuchUserException();
2761 }
2762 else {
2763 return users.get(0);
2764 }
2765 }
2766
2767
2774 @Override
2775 public List<User> getUserGroupUsers(long userGroupId)
2776 throws SystemException {
2777
2778 return userGroupPersistence.getUsers(userGroupId);
2779 }
2780
2781
2788 @Override
2789 public int getUserGroupUsersCount(long userGroupId) throws SystemException {
2790 return userGroupPersistence.getUsersSize(userGroupId);
2791 }
2792
2793
2803 @Override
2804 public int getUserGroupUsersCount(long userGroupId, int status)
2805 throws PortalException, SystemException {
2806
2807 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
2808 userGroupId);
2809
2810 LinkedHashMap<String, Object> params =
2811 new LinkedHashMap<String, Object>();
2812
2813 params.put("usersUserGroups", new Long(userGroupId));
2814
2815 return searchCount(userGroup.getCompanyId(), null, status, params);
2816 }
2817
2818
2828 @Override
2829 public long getUserIdByEmailAddress(long companyId, String emailAddress)
2830 throws PortalException, SystemException {
2831
2832 emailAddress = emailAddress.trim().toLowerCase();
2833
2834 User user = userPersistence.findByC_EA(companyId, emailAddress);
2835
2836 return user.getUserId();
2837 }
2838
2839
2848 @Override
2849 public long getUserIdByScreenName(long companyId, String screenName)
2850 throws PortalException, SystemException {
2851
2852 screenName = getScreenName(screenName);
2853
2854 User user = userPersistence.findByC_SN(companyId, screenName);
2855
2856 return user.getUserId();
2857 }
2858
2859
2868 @Override
2869 public boolean hasGroupUser(long groupId, long userId)
2870 throws SystemException {
2871
2872 return groupPersistence.containsUser(groupId, userId);
2873 }
2874
2875
2884 @Override
2885 public boolean hasOrganizationUser(long organizationId, long userId)
2886 throws SystemException {
2887
2888 return organizationPersistence.containsUser(organizationId, userId);
2889 }
2890
2891
2901 @Override
2902 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
2903 throws SystemException {
2904
2905 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
2906 passwordPolicyId, User.class.getName(), userId);
2907 }
2908
2909
2918 @Override
2919 public boolean hasRoleUser(long roleId, long userId)
2920 throws SystemException {
2921
2922 return rolePersistence.containsUser(roleId, userId);
2923 }
2924
2925
2940 @Override
2941 public boolean hasRoleUser(
2942 long companyId, String name, long userId, boolean inherited)
2943 throws PortalException, SystemException {
2944
2945 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
2946 }
2947
2948
2957 @Override
2958 public boolean hasTeamUser(long teamId, long userId)
2959 throws SystemException {
2960
2961 return teamPersistence.containsUser(teamId, userId);
2962 }
2963
2964
2973 @Override
2974 public boolean hasUserGroupUser(long userGroupId, long userId)
2975 throws SystemException {
2976
2977 return userGroupPersistence.containsUser(userGroupId, userId);
2978 }
2979
2980
2990 @Override
2991 public boolean isPasswordExpired(User user)
2992 throws PortalException, SystemException {
2993
2994 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2995
2996 if ((passwordPolicy != null) && passwordPolicy.getExpireable()) {
2997 Date now = new Date();
2998
2999 if (user.getPasswordModifiedDate() == null) {
3000 user.setPasswordModifiedDate(now);
3001
3002 userLocalService.updateUser(user, false);
3003 }
3004
3005 long passwordStartTime = user.getPasswordModifiedDate().getTime();
3006 long elapsedTime = now.getTime() - passwordStartTime;
3007
3008 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
3009 return true;
3010 }
3011 else {
3012 return false;
3013 }
3014 }
3015
3016 return false;
3017 }
3018
3019
3029 @Override
3030 public boolean isPasswordExpiringSoon(User user)
3031 throws PortalException, SystemException {
3032
3033 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3034
3035 if ((passwordPolicy != null) && passwordPolicy.isExpireable()) {
3036 Date now = new Date();
3037
3038 if (user.getPasswordModifiedDate() == null) {
3039 user.setPasswordModifiedDate(now);
3040
3041 userLocalService.updateUser(user, false);
3042 }
3043
3044 long timeModified = user.getPasswordModifiedDate().getTime();
3045 long passwordExpiresOn =
3046 (passwordPolicy.getMaxAge() * 1000) + timeModified;
3047
3048 long timeStartWarning =
3049 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
3050
3051 if (now.getTime() > timeStartWarning) {
3052 return true;
3053 }
3054 else {
3055 return false;
3056 }
3057 }
3058
3059 return false;
3060 }
3061
3062 @Override
3063 public User loadGetDefaultUser(long companyId)
3064 throws PortalException, SystemException {
3065
3066 return userPersistence.findByC_DU(companyId, true);
3067 }
3068
3069
3101 @Override
3102 public List<User> search(
3103 long companyId, String keywords, int status,
3104 LinkedHashMap<String, Object> params, int start, int end,
3105 OrderByComparator obc)
3106 throws SystemException {
3107
3108 return userFinder.findByKeywords(
3109 companyId, keywords, status, params, start, end, obc);
3110 }
3111
3112
3143 @Override
3144 public Hits search(
3145 long companyId, String keywords, int status,
3146 LinkedHashMap<String, Object> params, int start, int end, Sort sort)
3147 throws SystemException {
3148
3149 String firstName = null;
3150 String middleName = null;
3151 String lastName = null;
3152 String fullName = null;
3153 String screenName = null;
3154 String emailAddress = null;
3155 String street = null;
3156 String city = null;
3157 String zip = null;
3158 String region = null;
3159 String country = null;
3160 boolean andOperator = false;
3161
3162 if (Validator.isNotNull(keywords)) {
3163 firstName = keywords;
3164 middleName = keywords;
3165 lastName = keywords;
3166 fullName = keywords;
3167 screenName = keywords;
3168 emailAddress = keywords;
3169 street = keywords;
3170 city = keywords;
3171 zip = keywords;
3172 region = keywords;
3173 country = keywords;
3174 }
3175 else {
3176 andOperator = true;
3177 }
3178
3179 if (params != null) {
3180 params.put("keywords", keywords);
3181 }
3182
3183 return search(
3184 companyId, firstName, middleName, lastName, fullName, screenName,
3185 emailAddress, street, city, zip, region, country, status, params,
3186 andOperator, start, end, sort);
3187 }
3188
3189
3229 @Override
3230 public List<User> search(
3231 long companyId, String firstName, String middleName,
3232 String lastName, String screenName, String emailAddress, int status,
3233 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3234 int end, OrderByComparator obc)
3235 throws SystemException {
3236
3237 return userFinder.findByC_FN_MN_LN_SN_EA_S(
3238 companyId, firstName, middleName, lastName, screenName,
3239 emailAddress, status, params, andSearch, start, end, obc);
3240 }
3241
3242
3281 @Override
3282 public Hits search(
3283 long companyId, String firstName, String middleName,
3284 String lastName, String screenName, String emailAddress, int status,
3285 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3286 int end, Sort sort)
3287 throws SystemException {
3288
3289 return search(
3290 companyId, firstName, middleName, lastName, null, screenName,
3291 emailAddress, null, null, null, null, null, status, params,
3292 andSearch, start, end, sort);
3293 }
3294
3295
3309 @Override
3310 public int searchCount(
3311 long companyId, String keywords, int status,
3312 LinkedHashMap<String, Object> params)
3313 throws SystemException {
3314
3315 return userFinder.countByKeywords(companyId, keywords, status, params);
3316 }
3317
3318
3340 @Override
3341 public int searchCount(
3342 long companyId, String firstName, String middleName,
3343 String lastName, String screenName, String emailAddress, int status,
3344 LinkedHashMap<String, Object> params, boolean andSearch)
3345 throws SystemException {
3346
3347 return userFinder.countByC_FN_MN_LN_SN_EA_S(
3348 companyId, firstName, middleName, lastName, screenName,
3349 emailAddress, status, params, andSearch);
3350 }
3351
3352
3363 @Override
3364 public void sendEmailAddressVerification(
3365 User user, String emailAddress, ServiceContext serviceContext)
3366 throws PortalException, SystemException {
3367
3368 if (user.isEmailAddressVerified() &&
3369 emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
3370
3371 return;
3372 }
3373
3374 Ticket ticket = ticketLocalService.addTicket(
3375 user.getCompanyId(), User.class.getName(), user.getUserId(),
3376 TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3377 serviceContext);
3378
3379 String verifyEmailAddressURL =
3380 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3381 "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3382
3383 Layout layout = layoutLocalService.getLayout(serviceContext.getPlid());
3384
3385 Group group = layout.getGroup();
3386
3387 if (!layout.isPrivateLayout() && !group.isUser()) {
3388 verifyEmailAddressURL += "&p_l_id=" + serviceContext.getPlid();
3389 }
3390
3391 String fromName = PrefsPropsUtil.getString(
3392 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3393 String fromAddress = PrefsPropsUtil.getString(
3394 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3395
3396 String toName = user.getFullName();
3397 String toAddress = emailAddress;
3398
3399 String subject = PrefsPropsUtil.getContent(
3400 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3401
3402 String body = PrefsPropsUtil.getContent(
3403 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3404
3405 SubscriptionSender subscriptionSender = new SubscriptionSender();
3406
3407 subscriptionSender.setBody(body);
3408 subscriptionSender.setCompanyId(user.getCompanyId());
3409 subscriptionSender.setContextAttributes(
3410 "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3411 "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3412 "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3413 "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_ID$]",
3414 user.getUserId(), "[$USER_SCREENNAME$]", user.getScreenName());
3415 subscriptionSender.setFrom(fromAddress, fromName);
3416 subscriptionSender.setHtmlFormat(true);
3417 subscriptionSender.setMailId("user", user.getUserId());
3418 subscriptionSender.setServiceContext(serviceContext);
3419 subscriptionSender.setSubject(subject);
3420 subscriptionSender.setUserId(user.getUserId());
3421
3422 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3423
3424 subscriptionSender.flushNotificationsAsync();
3425 }
3426
3427
3446 @Override
3447 public void sendPassword(
3448 long companyId, String emailAddress, String fromName,
3449 String fromAddress, String subject, String body,
3450 ServiceContext serviceContext)
3451 throws PortalException, SystemException {
3452
3453 Company company = companyPersistence.findByPrimaryKey(companyId);
3454
3455 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3456 return;
3457 }
3458
3459 emailAddress = emailAddress.trim().toLowerCase();
3460
3461 if (Validator.isNull(emailAddress)) {
3462 throw new UserEmailAddressException();
3463 }
3464
3465 User user = userPersistence.findByC_EA(companyId, emailAddress);
3466
3467 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3468
3469 String newPassword = StringPool.BLANK;
3470 String passwordResetURL = StringPool.BLANK;
3471
3472 if (company.isSendPasswordResetLink()) {
3473 Date expirationDate = null;
3474
3475 if ((passwordPolicy != null) &&
3476 (passwordPolicy.getResetTicketMaxAge() > 0)) {
3477
3478 expirationDate = new Date(
3479 System.currentTimeMillis() +
3480 (passwordPolicy.getResetTicketMaxAge() * 1000));
3481 }
3482
3483 Ticket ticket = ticketLocalService.addTicket(
3484 companyId, User.class.getName(), user.getUserId(),
3485 TicketConstants.TYPE_PASSWORD, null, expirationDate,
3486 serviceContext);
3487
3488 passwordResetURL =
3489 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3490 "/portal/update_password?p_l_id="+
3491 serviceContext.getPlid() +
3492 "&ticketKey=" + ticket.getKey();
3493 }
3494 else {
3495 if (!PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
3496 PwdEncryptor.TYPE_NONE)) {
3497
3498 if (LDAPSettingsUtil.isPasswordPolicyEnabled(
3499 user.getCompanyId())) {
3500
3501 if (_log.isWarnEnabled()) {
3502 StringBundler sb = new StringBundler(5);
3503
3504 sb.append("When LDAP password policy is enabled, ");
3505 sb.append("it is possible that portal generated ");
3506 sb.append("passwords will not match the LDAP policy.");
3507 sb.append("Using RegExpToolkit to generate new ");
3508 sb.append("password.");
3509
3510 _log.warn(sb.toString());
3511 }
3512
3513 RegExpToolkit regExpToolkit = new RegExpToolkit();
3514
3515 newPassword = regExpToolkit.generate(null);
3516 }
3517 else {
3518 newPassword = PwdToolkitUtil.generate(passwordPolicy);
3519 }
3520
3521 boolean passwordReset = false;
3522
3523 if (passwordPolicy.getChangeable() &&
3524 passwordPolicy.getChangeRequired()) {
3525
3526 passwordReset = true;
3527 }
3528
3529 user.setPassword(PwdEncryptor.encrypt(newPassword));
3530 user.setPasswordUnencrypted(newPassword);
3531 user.setPasswordEncrypted(true);
3532 user.setPasswordReset(passwordReset);
3533 user.setPasswordModified(true);
3534 user.setPasswordModifiedDate(new Date());
3535
3536 userPersistence.update(user, false);
3537
3538 user.setPasswordModified(false);
3539 }
3540 else {
3541 newPassword = user.getPassword();
3542 }
3543 }
3544
3545 if (Validator.isNull(fromName)) {
3546 fromName = PrefsPropsUtil.getString(
3547 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3548 }
3549
3550 if (Validator.isNull(fromAddress)) {
3551 fromAddress = PrefsPropsUtil.getString(
3552 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3553 }
3554
3555 String toName = user.getFullName();
3556 String toAddress = user.getEmailAddress();
3557
3558 if (Validator.isNull(subject)) {
3559 if (company.isSendPasswordResetLink()) {
3560 subject = PrefsPropsUtil.getContent(
3561 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
3562 }
3563 else {
3564 subject = PrefsPropsUtil.getContent(
3565 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
3566 }
3567 }
3568
3569 if (Validator.isNull(body)) {
3570 if (company.isSendPasswordResetLink()) {
3571 body = PrefsPropsUtil.getContent(
3572 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
3573 }
3574 else {
3575 body = PrefsPropsUtil.getContent(
3576 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
3577 }
3578 }
3579
3580 SubscriptionSender subscriptionSender = new SubscriptionSender();
3581
3582 subscriptionSender.setBody(body);
3583 subscriptionSender.setCompanyId(companyId);
3584 subscriptionSender.setContextAttributes(
3585 "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
3586 serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
3587 serviceContext.getRemoteHost(), "[$USER_ID$]", user.getUserId(),
3588 "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
3589 user.getScreenName());
3590 subscriptionSender.setFrom(fromAddress, fromName);
3591 subscriptionSender.setHtmlFormat(true);
3592 subscriptionSender.setMailId("user", user.getUserId());
3593 subscriptionSender.setServiceContext(serviceContext);
3594 subscriptionSender.setSubject(subject);
3595 subscriptionSender.setUserId(user.getUserId());
3596
3597 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3598
3599 subscriptionSender.flushNotificationsAsync();
3600 }
3601
3602
3611 @Override
3612 public void setRoleUsers(long roleId, long[] userIds)
3613 throws PortalException, SystemException {
3614
3615 rolePersistence.setUsers(roleId, userIds);
3616
3617 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3618
3619 indexer.reindex(userIds);
3620
3621 PermissionCacheUtil.clearCache();
3622 }
3623
3624
3633 @Override
3634 @SuppressWarnings("deprecation")
3635 public void setUserGroupUsers(long userGroupId, long[] userIds)
3636 throws PortalException, SystemException {
3637
3638 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3639 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3640 }
3641
3642 userGroupPersistence.setUsers(userGroupId, userIds);
3643
3644 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3645
3646 indexer.reindex(userIds);
3647
3648 PermissionCacheUtil.clearCache();
3649 }
3650
3651
3659 @Override
3660 public void unsetGroupTeamsUsers(long groupId, long[] userIds)
3661 throws PortalException, SystemException {
3662
3663 List<Team> teams = teamPersistence.findByGroupId(groupId);
3664
3665 for (Team team : teams) {
3666 unsetTeamUsers(team.getTeamId(), userIds);
3667 }
3668
3669 PermissionCacheUtil.clearCache();
3670 }
3671
3672
3682 @Override
3683 public void unsetGroupUsers(
3684 long groupId, long[] userIds, ServiceContext serviceContext)
3685 throws PortalException, SystemException {
3686
3687 userGroupRoleLocalService.deleteUserGroupRoles(
3688 userIds, groupId, RoleConstants.TYPE_SITE);
3689
3690 userLocalService.unsetGroupTeamsUsers(groupId, userIds);
3691
3692 groupPersistence.removeUsers(groupId, userIds);
3693
3694 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3695
3696 indexer.reindex(userIds);
3697
3698 PermissionCacheUtil.clearCache();
3699 }
3700
3701
3709 @Override
3710 public void unsetOrganizationUsers(long organizationId, long[] userIds)
3711 throws PortalException, SystemException {
3712
3713 Organization organization = organizationPersistence.findByPrimaryKey(
3714 organizationId);
3715
3716 Group group = organization.getGroup();
3717
3718 userGroupRoleLocalService.deleteUserGroupRoles(
3719 userIds, group.getGroupId(), RoleConstants.TYPE_ORGANIZATION);
3720
3721 organizationPersistence.removeUsers(organizationId, userIds);
3722
3723 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3724
3725 indexer.reindex(userIds);
3726
3727 PermissionCacheUtil.clearCache();
3728 }
3729
3730
3737 @Override
3738 public void unsetPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
3739 throws SystemException {
3740
3741 passwordPolicyRelLocalService.deletePasswordPolicyRels(
3742 passwordPolicyId, User.class.getName(), userIds);
3743 }
3744
3745
3753 @Override
3754 public void unsetRoleUsers(long roleId, List<User> users)
3755 throws PortalException, SystemException {
3756
3757 Role role = rolePersistence.findByPrimaryKey(roleId);
3758
3759 String roleName = role.getName();
3760
3761 if ((roleName.equals(RoleConstants.ADMINISTRATOR) &&
3762 (getRoleUsersCount(role.getRoleId()) <= 1)) ||
3763 roleName.equals(RoleConstants.USER)) {
3764
3765 return;
3766 }
3767
3768 rolePersistence.removeUsers(roleId, users);
3769
3770 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3771
3772 indexer.reindex(users);
3773
3774 PermissionCacheUtil.clearCache();
3775 }
3776
3777
3785 @Override
3786 public void unsetRoleUsers(long roleId, long[] userIds)
3787 throws PortalException, SystemException {
3788
3789 Role role = rolePersistence.findByPrimaryKey(roleId);
3790
3791 String roleName = role.getName();
3792
3793 if (roleName.equals(RoleConstants.USER) ||
3794 (roleName.equals(RoleConstants.ADMINISTRATOR) &&
3795 getRoleUsersCount(role.getRoleId()) <= 1)) {
3796
3797 return;
3798 }
3799
3800 rolePersistence.removeUsers(roleId, userIds);
3801
3802 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3803
3804 indexer.reindex(userIds);
3805
3806 PermissionCacheUtil.clearCache();
3807 }
3808
3809
3817 @Override
3818 public void unsetTeamUsers(long teamId, long[] userIds)
3819 throws PortalException, SystemException {
3820
3821 teamPersistence.removeUsers(teamId, userIds);
3822
3823 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3824
3825 indexer.reindex(userIds);
3826
3827 PermissionCacheUtil.clearCache();
3828 }
3829
3830
3838 @Override
3839 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
3840 throws PortalException, SystemException {
3841
3842 userGroupPersistence.removeUsers(userGroupId, userIds);
3843
3844 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3845
3846 indexer.reindex(userIds);
3847
3848 PermissionCacheUtil.clearCache();
3849 }
3850
3851
3861 @Override
3862 public User updateAgreedToTermsOfUse(
3863 long userId, boolean agreedToTermsOfUse)
3864 throws PortalException, SystemException {
3865
3866 User user = userPersistence.findByPrimaryKey(userId);
3867
3868 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
3869
3870 userPersistence.update(user, false);
3871
3872 return user;
3873 }
3874
3875
3886 @Override
3887 public void updateAsset(
3888 long userId, User user, long[] assetCategoryIds,
3889 String[] assetTagNames)
3890 throws PortalException, SystemException {
3891
3892 User owner = userPersistence.findByPrimaryKey(userId);
3893
3894 Company company = companyPersistence.findByPrimaryKey(
3895 owner.getCompanyId());
3896
3897 Group companyGroup = company.getGroup();
3898
3899 assetEntryLocalService.updateEntry(
3900 userId, companyGroup.getGroupId(), user.getCreateDate(),
3901 user.getModifiedDate(), User.class.getName(), user.getUserId(),
3902 user.getUuid(), 0, assetCategoryIds, assetTagNames, false, null,
3903 null, null, null, null, user.getFullName(), null, null, null, null,
3904 0, 0, null, false);
3905 }
3906
3907
3916 @Override
3917 public User updateCreateDate(long userId, Date createDate)
3918 throws PortalException, SystemException {
3919
3920 User user = userPersistence.findByPrimaryKey(userId);
3921
3922 user.setCreateDate(createDate);
3923
3924 userPersistence.update(user, false);
3925
3926 return user;
3927 }
3928
3929
3940 @Override
3941 public User updateEmailAddress(
3942 long userId, String password, String emailAddress1,
3943 String emailAddress2)
3944 throws PortalException, SystemException {
3945
3946 emailAddress1 = emailAddress1.trim().toLowerCase();
3947 emailAddress2 = emailAddress2.trim().toLowerCase();
3948
3949 User user = userPersistence.findByPrimaryKey(userId);
3950
3951 validateEmailAddress(user, emailAddress1, emailAddress2);
3952
3953 setEmailAddress(
3954 user, password, user.getFirstName(), user.getMiddleName(),
3955 user.getLastName(), emailAddress1);
3956
3957 userPersistence.update(user, false);
3958
3959 return user;
3960 }
3961
3962
3976 @Override
3977 public User updateEmailAddress(
3978 long userId, String password, String emailAddress1,
3979 String emailAddress2, ServiceContext serviceContext)
3980 throws PortalException, SystemException {
3981
3982 emailAddress1 = emailAddress1.trim().toLowerCase();
3983 emailAddress2 = emailAddress2.trim().toLowerCase();
3984
3985 User user = userPersistence.findByPrimaryKey(userId);
3986
3987 validateEmailAddress(user, emailAddress1, emailAddress2);
3988
3989 Company company = companyPersistence.findByPrimaryKey(
3990 user.getCompanyId());
3991
3992 if (!company.isStrangersVerify()) {
3993 setEmailAddress(
3994 user, password, user.getFirstName(), user.getMiddleName(),
3995 user.getLastName(), emailAddress1);
3996
3997 userPersistence.update(user, false);
3998 }
3999 else {
4000 sendEmailAddressVerification(user, emailAddress1, serviceContext);
4001 }
4002
4003 return user;
4004 }
4005
4006
4015 @Override
4016 public User updateEmailAddressVerified(
4017 long userId, boolean emailAddressVerified)
4018 throws PortalException, SystemException {
4019
4020 User user = userPersistence.findByPrimaryKey(userId);
4021
4022 user.setEmailAddressVerified(emailAddressVerified);
4023
4024 userPersistence.update(user, false);
4025
4026 return user;
4027 }
4028
4029
4038 @Override
4039 public User updateFacebookId(long userId, long facebookId)
4040 throws PortalException, SystemException {
4041
4042 User user = userPersistence.findByPrimaryKey(userId);
4043
4044 user.setFacebookId(facebookId);
4045
4046 userPersistence.update(user, false);
4047
4048 return user;
4049 }
4050
4051
4061 @Override
4062 public void updateGroups(
4063 long userId, long[] newGroupIds, ServiceContext serviceContext)
4064 throws PortalException, SystemException {
4065
4066 updateGroups(
4067 userId, newGroupIds, serviceContext,
4068 serviceContext.isIndexingEnabled());
4069 }
4070
4071
4110 @Override
4111 public User updateIncompleteUser(
4112 long creatorUserId, long companyId, boolean autoPassword,
4113 String password1, String password2, boolean autoScreenName,
4114 String screenName, String emailAddress, long facebookId,
4115 String openId, Locale locale, String firstName, String middleName,
4116 String lastName, int prefixId, int suffixId, boolean male,
4117 int birthdayMonth, int birthdayDay, int birthdayYear,
4118 String jobTitle, boolean updateUserInformation, boolean sendEmail,
4119 ServiceContext serviceContext)
4120 throws PortalException, SystemException {
4121
4122 User user = getUserByEmailAddress(companyId, emailAddress);
4123
4124 if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
4125 throw new PortalException("Invalid user status");
4126 }
4127
4128 User defaultUser = getDefaultUser(companyId);
4129
4130 if (updateUserInformation) {
4131 autoScreenName = false;
4132
4133 if (PrefsPropsUtil.getBoolean(
4134 companyId,
4135 PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
4136
4137 autoScreenName = true;
4138 }
4139
4140 validate(
4141 companyId, user.getUserId(), autoPassword, password1, password2,
4142 autoScreenName, screenName, emailAddress, openId, firstName,
4143 middleName, lastName, null);
4144
4145 if (!autoPassword) {
4146 if (Validator.isNull(password1) ||
4147 Validator.isNull(password2)) {
4148 throw new UserPasswordException(
4149 UserPasswordException.PASSWORD_INVALID);
4150 }
4151 }
4152
4153 if (autoScreenName) {
4154 ScreenNameGenerator screenNameGenerator =
4155 ScreenNameGeneratorFactory.getInstance();
4156
4157 try {
4158 screenName = screenNameGenerator.generate(
4159 companyId, user.getUserId(), emailAddress);
4160 }
4161 catch (Exception e) {
4162 throw new SystemException(e);
4163 }
4164 }
4165
4166 FullNameGenerator fullNameGenerator =
4167 FullNameGeneratorFactory.getInstance();
4168
4169 String fullName = fullNameGenerator.getFullName(
4170 firstName, middleName, lastName);
4171
4172 String greeting = LanguageUtil.format(
4173 locale, "welcome-x", " " + fullName, false);
4174
4175 if (Validator.isNotNull(password1)) {
4176 user.setPassword(PwdEncryptor.encrypt(password1));
4177 user.setPasswordUnencrypted(password1);
4178 }
4179
4180 user.setPasswordEncrypted(true);
4181
4182 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
4183
4184 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
4185 passwordPolicy.isChangeRequired()) {
4186
4187 user.setPasswordReset(true);
4188 }
4189 else {
4190 user.setPasswordReset(false);
4191 }
4192
4193 user.setScreenName(screenName);
4194 user.setFacebookId(facebookId);
4195 user.setOpenId(openId);
4196 user.setLanguageId(locale.toString());
4197 user.setTimeZoneId(defaultUser.getTimeZoneId());
4198 user.setGreeting(greeting);
4199 user.setFirstName(firstName);
4200 user.setMiddleName(middleName);
4201 user.setLastName(lastName);
4202 user.setJobTitle(jobTitle);
4203 user.setExpandoBridgeAttributes(serviceContext);
4204
4205 Date birthday = getBirthday(
4206 birthdayMonth, birthdayDay, birthdayYear);
4207
4208 Contact contact = user.getContact();
4209
4210 contact.setFirstName(firstName);
4211 contact.setMiddleName(middleName);
4212 contact.setLastName(lastName);
4213 contact.setPrefixId(prefixId);
4214 contact.setSuffixId(suffixId);
4215 contact.setMale(male);
4216 contact.setBirthday(birthday);
4217 contact.setJobTitle(jobTitle);
4218
4219 contactPersistence.update(contact, false, serviceContext);
4220
4221
4222
4223 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4224 User.class);
4225
4226 indexer.reindex(user);
4227 }
4228
4229 user.setStatus(WorkflowConstants.STATUS_DRAFT);
4230
4231 userPersistence.update(user, false, serviceContext);
4232
4233
4234
4235 long workflowUserId = creatorUserId;
4236
4237 if (workflowUserId == user.getUserId()) {
4238 workflowUserId = defaultUser.getUserId();
4239 }
4240
4241 ServiceContext workflowServiceContext = serviceContext;
4242
4243 if (workflowServiceContext == null) {
4244 workflowServiceContext = new ServiceContext();
4245 }
4246
4247 workflowServiceContext.setAttribute("autoPassword", autoPassword);
4248 workflowServiceContext.setAttribute("sendEmail", sendEmail);
4249
4250 WorkflowHandlerRegistryUtil.startWorkflowInstance(
4251 companyId, workflowUserId, User.class.getName(), user.getUserId(),
4252 user, workflowServiceContext);
4253
4254 return getUserByEmailAddress(companyId, emailAddress);
4255 }
4256
4257
4267 @Override
4268 public User updateJobTitle(long userId, String jobTitle)
4269 throws PortalException, SystemException {
4270
4271 User user = userPersistence.findByPrimaryKey(userId);
4272
4273 user.setJobTitle(jobTitle);
4274
4275 userPersistence.update(user, false);
4276
4277 Contact contact = contactPersistence.findByPrimaryKey(
4278 user.getContactId());
4279
4280 contact.setJobTitle(jobTitle);
4281
4282 contactPersistence.update(contact, false);
4283
4284 return user;
4285 }
4286
4287
4296 @Override
4297 public User updateLastLogin(long userId, String loginIP)
4298 throws PortalException, SystemException {
4299
4300 User user = userPersistence.findByPrimaryKey(userId);
4301
4302 Date lastLoginDate = user.getLoginDate();
4303
4304 if (lastLoginDate == null) {
4305 lastLoginDate = new Date();
4306 }
4307
4308 user.setLoginDate(new Date());
4309 user.setLoginIP(loginIP);
4310 user.setLastLoginDate(lastLoginDate);
4311 user.setLastLoginIP(user.getLoginIP());
4312 user.setLastFailedLoginDate(null);
4313 user.setFailedLoginAttempts(0);
4314
4315 userPersistence.update(user, false);
4316
4317 return user;
4318 }
4319
4320
4329 @Override
4330 public User updateLockout(User user, boolean lockout)
4331 throws PortalException, SystemException {
4332
4333 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
4334
4335 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
4336 return user;
4337 }
4338
4339 Date lockoutDate = null;
4340
4341 if (lockout) {
4342 lockoutDate = new Date();
4343 }
4344
4345 user.setLockout(lockout);
4346 user.setLockoutDate(lockoutDate);
4347
4348 if (!lockout) {
4349 user.setLastFailedLoginDate(lockoutDate);
4350 user.setFailedLoginAttempts(0);
4351 }
4352
4353 userPersistence.update(user, false);
4354
4355 return user;
4356 }
4357
4358
4369 @Override
4370 public User updateLockoutByEmailAddress(
4371 long companyId, String emailAddress, boolean lockout)
4372 throws PortalException, SystemException {
4373
4374 User user = getUserByEmailAddress(companyId, emailAddress);
4375
4376 return updateLockout(user, lockout);
4377 }
4378
4379
4388 @Override
4389 public User updateLockoutById(long userId, boolean lockout)
4390 throws PortalException, SystemException {
4391
4392 User user = userPersistence.findByPrimaryKey(userId);
4393
4394 return updateLockout(user, lockout);
4395 }
4396
4397
4407 @Override
4408 public User updateLockoutByScreenName(
4409 long companyId, String screenName, boolean lockout)
4410 throws PortalException, SystemException {
4411
4412 User user = getUserByScreenName(companyId, screenName);
4413
4414 return updateLockout(user, lockout);
4415 }
4416
4417
4426 @Override
4427 public User updateModifiedDate(long userId, Date modifiedDate)
4428 throws PortalException, SystemException {
4429
4430 User user = userPersistence.findByPrimaryKey(userId);
4431
4432 user.setModifiedDate(modifiedDate);
4433
4434 userPersistence.update(user, false);
4435
4436 return user;
4437 }
4438
4439
4448 @Override
4449 public User updateOpenId(long userId, String openId)
4450 throws PortalException, SystemException {
4451
4452 openId = openId.trim();
4453
4454 User user = userPersistence.findByPrimaryKey(userId);
4455
4456 user.setOpenId(openId);
4457
4458 userPersistence.update(user, false);
4459
4460 return user;
4461 }
4462
4463
4474 @Override
4475 public void updateOrganizations(
4476 long userId, long[] newOrganizationIds,
4477 ServiceContext serviceContext)
4478 throws PortalException, SystemException {
4479
4480 updateOrganizations(
4481 userId, newOrganizationIds, serviceContext.isIndexingEnabled());
4482 }
4483
4484
4496 @Override
4497 public User updatePassword(
4498 long userId, String password1, String password2,
4499 boolean passwordReset)
4500 throws PortalException, SystemException {
4501
4502 return updatePassword(
4503 userId, password1, password2, passwordReset, false);
4504 }
4505
4506
4521 @Override
4522 public User updatePassword(
4523 long userId, String password1, String password2,
4524 boolean passwordReset, boolean silentUpdate)
4525 throws PortalException, SystemException {
4526
4527 User user = userPersistence.findByPrimaryKey(userId);
4528
4529 if (!silentUpdate) {
4530 validatePassword(user.getCompanyId(), userId, password1, password2);
4531 }
4532
4533 String oldEncPwd = user.getPassword();
4534
4535 if (!user.isPasswordEncrypted()) {
4536 oldEncPwd = PwdEncryptor.encrypt(user.getPassword());
4537 }
4538
4539 String newEncPwd = PwdEncryptor.encrypt(password1);
4540
4541 if (user.hasCompanyMx()) {
4542 mailService.updatePassword(user.getCompanyId(), userId, password1);
4543 }
4544
4545 user.setPassword(newEncPwd);
4546 user.setPasswordUnencrypted(password1);
4547 user.setPasswordEncrypted(true);
4548 user.setPasswordReset(passwordReset);
4549 user.setPasswordModifiedDate(new Date());
4550 user.setDigest(StringPool.BLANK);
4551 user.setGraceLoginCount(0);
4552
4553 if (!silentUpdate) {
4554 user.setPasswordModified(true);
4555 }
4556
4557 try {
4558 userPersistence.update(user, false);
4559 }
4560 catch (ModelListenerException mle) {
4561 String msg = GetterUtil.getString(mle.getCause().getMessage());
4562
4563 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
4564 String passwordHistory = PrefsPropsUtil.getString(
4565 user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
4566
4567 if (msg.contains(passwordHistory)) {
4568 throw new UserPasswordException(
4569 UserPasswordException.PASSWORD_ALREADY_USED);
4570 }
4571 }
4572
4573 throw new UserPasswordException(
4574 UserPasswordException.PASSWORD_INVALID);
4575 }
4576
4577 if (!silentUpdate) {
4578 user.setPasswordModified(false);
4579
4580 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
4581 }
4582
4583 return user;
4584 }
4585
4586
4600 @Override
4601 public User updatePasswordManually(
4602 long userId, String password, boolean passwordEncrypted,
4603 boolean passwordReset, Date passwordModifiedDate)
4604 throws PortalException, SystemException {
4605
4606
4607
4608 User user = userPersistence.findByPrimaryKey(userId);
4609
4610 user.setPassword(password);
4611 user.setPasswordEncrypted(passwordEncrypted);
4612 user.setPasswordReset(passwordReset);
4613 user.setPasswordModifiedDate(passwordModifiedDate);
4614 user.setDigest(StringPool.BLANK);
4615
4616 userPersistence.update(user, false);
4617
4618 return user;
4619 }
4620
4621
4632 @Override
4633 public User updatePasswordReset(long userId, boolean passwordReset)
4634 throws PortalException, SystemException {
4635
4636 User user = userPersistence.findByPrimaryKey(userId);
4637
4638 user.setPasswordReset(passwordReset);
4639
4640 userPersistence.update(user, false);
4641
4642 return user;
4643 }
4644
4645
4655 @Override
4656 public User updatePortrait(long userId, byte[] bytes)
4657 throws PortalException, SystemException {
4658
4659 User user = userPersistence.findByPrimaryKey(userId);
4660
4661 long imageMaxSize = PrefsPropsUtil.getLong(
4662 PropsKeys.USERS_IMAGE_MAX_SIZE);
4663
4664 if ((imageMaxSize > 0) &&
4665 ((bytes == null) || (bytes.length > imageMaxSize))) {
4666
4667 throw new UserPortraitSizeException();
4668 }
4669
4670 long portraitId = user.getPortraitId();
4671
4672 if (portraitId <= 0) {
4673 portraitId = counterLocalService.increment();
4674
4675 user.setPortraitId(portraitId);
4676 }
4677
4678 try {
4679 ImageBag imageBag = ImageToolUtil.read(bytes);
4680
4681 RenderedImage renderedImage = imageBag.getRenderedImage();
4682
4683 if (renderedImage == null) {
4684 throw new UserPortraitTypeException();
4685 }
4686
4687 renderedImage = ImageToolUtil.scale(
4688 renderedImage, PropsValues.USERS_IMAGE_MAX_HEIGHT,
4689 PropsValues.USERS_IMAGE_MAX_WIDTH);
4690
4691 String contentType = imageBag.getType();
4692
4693 imageLocalService.updateImage(
4694 portraitId,
4695 ImageToolUtil.getBytes(renderedImage, contentType));
4696 }
4697 catch (IOException ioe) {
4698 throw new ImageSizeException(ioe);
4699 }
4700
4701 userPersistence.update(user, false);
4702
4703 return user;
4704 }
4705
4706
4717 @Override
4718 public User updateReminderQuery(long userId, String question, String answer)
4719 throws PortalException, SystemException {
4720
4721 validateReminderQuery(question, answer);
4722
4723 User user = userPersistence.findByPrimaryKey(userId);
4724
4725 user.setReminderQueryQuestion(question);
4726 user.setReminderQueryAnswer(answer);
4727
4728 userPersistence.update(user, false);
4729
4730 return user;
4731 }
4732
4733
4743 @Override
4744 public User updateScreenName(long userId, String screenName)
4745 throws PortalException, SystemException {
4746
4747
4748
4749 User user = userPersistence.findByPrimaryKey(userId);
4750
4751 screenName = getScreenName(screenName);
4752
4753 validateScreenName(user.getCompanyId(), userId, screenName);
4754
4755 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
4756 user.setDigest(StringPool.BLANK);
4757 }
4758
4759 user.setScreenName(screenName);
4760
4761 userPersistence.update(user, false);
4762
4763
4764
4765 Group group = groupLocalService.getUserGroup(
4766 user.getCompanyId(), userId);
4767
4768 group.setFriendlyURL(StringPool.SLASH + screenName);
4769
4770 groupPersistence.update(group, false);
4771
4772 return user;
4773 }
4774
4775
4784 @Override
4785 public User updateStatus(long userId, int status)
4786 throws PortalException, SystemException {
4787
4788 User user = userPersistence.findByPrimaryKey(userId);
4789
4790 if ((status == WorkflowConstants.STATUS_APPROVED) &&
4791 (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {
4792
4793 validateCompanyMaxUsers(user.getCompanyId());
4794 }
4795
4796 user.setStatus(status);
4797
4798 userPersistence.update(user, false);
4799
4800 reindex(user);
4801
4802 return user;
4803 }
4804
4805
4861 @Override
4862 @SuppressWarnings("deprecation")
4863 public User updateUser(
4864 long userId, String oldPassword, String newPassword1,
4865 String newPassword2, boolean passwordReset,
4866 String reminderQueryQuestion, String reminderQueryAnswer,
4867 String screenName, String emailAddress, long facebookId,
4868 String openId, String languageId, String timeZoneId,
4869 String greeting, String comments, String firstName,
4870 String middleName, String lastName, int prefixId, int suffixId,
4871 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
4872 String smsSn, String aimSn, String facebookSn, String icqSn,
4873 String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
4874 String twitterSn, String ymSn, String jobTitle, long[] groupIds,
4875 long[] organizationIds, long[] roleIds,
4876 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
4877 ServiceContext serviceContext)
4878 throws PortalException, SystemException {
4879
4880
4881
4882 User user = userPersistence.findByPrimaryKey(userId);
4883 Company company = companyPersistence.findByPrimaryKey(
4884 user.getCompanyId());
4885 String password = oldPassword;
4886 screenName = getScreenName(screenName);
4887 emailAddress = emailAddress.trim().toLowerCase();
4888 openId = openId.trim();
4889 String oldFullName = user.getFullName();
4890 aimSn = aimSn.trim().toLowerCase();
4891 facebookSn = facebookSn.trim().toLowerCase();
4892 icqSn = icqSn.trim().toLowerCase();
4893 jabberSn = jabberSn.trim().toLowerCase();
4894 msnSn = msnSn.trim().toLowerCase();
4895 mySpaceSn = mySpaceSn.trim().toLowerCase();
4896 skypeSn = skypeSn.trim().toLowerCase();
4897 twitterSn = twitterSn.trim().toLowerCase();
4898 ymSn = ymSn.trim().toLowerCase();
4899 Date now = new Date();
4900
4901 EmailAddressGenerator emailAddressGenerator =
4902 EmailAddressGeneratorFactory.getInstance();
4903
4904 if (emailAddressGenerator.isGenerated(emailAddress)) {
4905 emailAddress = StringPool.BLANK;
4906 }
4907
4908 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
4909 Validator.isNull(emailAddress)) {
4910
4911 emailAddress = emailAddressGenerator.generate(
4912 user.getCompanyId(), userId);
4913 }
4914
4915 validate(
4916 userId, screenName, emailAddress, openId, firstName, middleName,
4917 lastName, smsSn);
4918
4919 if (Validator.isNotNull(newPassword1) ||
4920 Validator.isNotNull(newPassword2)) {
4921
4922 user = updatePassword(
4923 userId, newPassword1, newPassword2, passwordReset);
4924
4925 password = newPassword1;
4926
4927 user.setDigest(StringPool.BLANK);
4928 }
4929
4930 user.setModifiedDate(now);
4931
4932 if (user.getContactId() <= 0) {
4933 user.setContactId(counterLocalService.increment());
4934 }
4935
4936 user.setPasswordReset(passwordReset);
4937
4938 if (Validator.isNotNull(reminderQueryQuestion) &&
4939 Validator.isNotNull(reminderQueryAnswer)) {
4940
4941 user.setReminderQueryQuestion(reminderQueryQuestion);
4942 user.setReminderQueryAnswer(reminderQueryAnswer);
4943 }
4944
4945 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
4946 user.setScreenName(screenName);
4947
4948 user.setDigest(StringPool.BLANK);
4949 }
4950
4951 boolean sendEmailAddressVerification = false;
4952
4953 if (!company.isStrangersVerify()) {
4954 setEmailAddress(
4955 user, password, firstName, middleName, lastName, emailAddress);
4956 }
4957 else {
4958 sendEmailAddressVerification = true;
4959 }
4960
4961 if (serviceContext != null) {
4962 String uuid = serviceContext.getUuid();
4963
4964 if (Validator.isNotNull(uuid)) {
4965 user.setUuid(uuid);
4966 }
4967 }
4968
4969 user.setFacebookId(facebookId);
4970 user.setOpenId(openId);
4971 user.setLanguageId(languageId);
4972 user.setTimeZoneId(timeZoneId);
4973 user.setGreeting(greeting);
4974 user.setComments(comments);
4975 user.setFirstName(firstName);
4976 user.setMiddleName(middleName);
4977 user.setLastName(lastName);
4978 user.setJobTitle(jobTitle);
4979 user.setExpandoBridgeAttributes(serviceContext);
4980
4981 userPersistence.update(user, false, serviceContext);
4982
4983
4984
4985 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
4986
4987 long contactId = user.getContactId();
4988
4989 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
4990
4991 if (contact == null) {
4992 contact = contactPersistence.create(contactId);
4993
4994 contact.setCompanyId(user.getCompanyId());
4995 contact.setUserName(StringPool.BLANK);
4996 contact.setCreateDate(now);
4997 contact.setAccountId(company.getAccountId());
4998 contact.setParentContactId(
4999 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
5000 }
5001
5002 contact.setModifiedDate(now);
5003 contact.setFirstName(firstName);
5004 contact.setMiddleName(middleName);
5005 contact.setLastName(lastName);
5006 contact.setPrefixId(prefixId);
5007 contact.setSuffixId(suffixId);
5008 contact.setMale(male);
5009 contact.setBirthday(birthday);
5010 contact.setSmsSn(smsSn);
5011 contact.setAimSn(aimSn);
5012 contact.setFacebookSn(facebookSn);
5013 contact.setIcqSn(icqSn);
5014 contact.setJabberSn(jabberSn);
5015 contact.setMsnSn(msnSn);
5016 contact.setMySpaceSn(mySpaceSn);
5017 contact.setSkypeSn(skypeSn);
5018 contact.setTwitterSn(twitterSn);
5019 contact.setYmSn(ymSn);
5020 contact.setJobTitle(jobTitle);
5021
5022 contactPersistence.update(contact, false, serviceContext);
5023
5024
5025
5026 Group group = groupLocalService.getUserGroup(
5027 user.getCompanyId(), userId);
5028
5029 group.setFriendlyURL(StringPool.SLASH + screenName);
5030
5031 groupPersistence.update(group, false);
5032
5033
5034
5035 updateGroups(userId, groupIds, serviceContext, false);
5036 updateOrganizations(userId, organizationIds, false);
5037
5038
5039
5040 if (roleIds != null) {
5041 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
5042
5043 userPersistence.setRoles(userId, roleIds);
5044 }
5045
5046
5047
5048 updateUserGroupRoles(user, groupIds, organizationIds, userGroupRoles);
5049
5050
5051
5052 if (userGroupIds != null) {
5053 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
5054 userGroupLocalService.copyUserGroupLayouts(
5055 userGroupIds, userId);
5056 }
5057
5058 userPersistence.setUserGroups(userId, userGroupIds);
5059 }
5060
5061
5062
5063 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
5064
5065
5066
5067 if (serviceContext != null) {
5068 updateAsset(
5069 userId, user, serviceContext.getAssetCategoryIds(),
5070 serviceContext.getAssetTagNames());
5071 }
5072
5073
5074
5075 if (GetterUtil.getBoolean(
5076 PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
5077 !oldFullName.equals(user.getFullName())) {
5078
5079 mbMessageLocalService.updateUserName(userId, user.getFullName());
5080 }
5081
5082
5083
5084 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
5085 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5086 User.class);
5087
5088 indexer.reindex(user);
5089 }
5090
5091
5092
5093 if ((serviceContext != null) && sendEmailAddressVerification) {
5094 sendEmailAddressVerification(user, emailAddress, serviceContext);
5095 }
5096
5097
5098
5099 PermissionCacheUtil.clearCache();
5100
5101 return user;
5102 }
5103
5104
5113 @Override
5114 public void verifyEmailAddress(String ticketKey)
5115 throws PortalException, SystemException {
5116
5117 Ticket ticket = ticketLocalService.getTicket(ticketKey);
5118
5119 if (ticket.isExpired() ||
5120 (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
5121
5122 throw new NoSuchTicketException();
5123 }
5124
5125 User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
5126
5127 String emailAddress = ticket.getExtraInfo();
5128
5129 emailAddress = emailAddress.toLowerCase().trim();
5130
5131 if (!emailAddress.equals(user.getEmailAddress())) {
5132 if (userPersistence.fetchByC_EA(
5133 user.getCompanyId(), emailAddress) != null) {
5134
5135 throw new DuplicateUserEmailAddressException();
5136 }
5137
5138 setEmailAddress(
5139 user, StringPool.BLANK, user.getFirstName(),
5140 user.getMiddleName(), user.getLastName(), emailAddress);
5141 }
5142
5143 user.setEmailAddressVerified(true);
5144
5145 userPersistence.update(user, false);
5146
5147 ticketLocalService.deleteTicket(ticket);
5148 }
5149
5150
5196 protected int authenticate(
5197 long companyId, String login, String password, String authType,
5198 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
5199 Map<String, Object> resultsMap)
5200 throws PortalException, SystemException {
5201
5202 if (PropsValues.AUTH_LOGIN_DISABLED) {
5203 return Authenticator.FAILURE;
5204 }
5205
5206 login = login.trim().toLowerCase();
5207
5208 long userId = GetterUtil.getLong(login);
5209
5210
5211
5212 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5213 if (Validator.isNull(login)) {
5214 throw new UserEmailAddressException();
5215 }
5216 }
5217 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5218 if (Validator.isNull(login)) {
5219 throw new UserScreenNameException();
5220 }
5221 }
5222 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5223 if (Validator.isNull(login)) {
5224 throw new UserIdException();
5225 }
5226 }
5227
5228 if (Validator.isNull(password)) {
5229 throw new UserPasswordException(
5230 UserPasswordException.PASSWORD_INVALID);
5231 }
5232
5233 int authResult = Authenticator.FAILURE;
5234
5235
5236
5237 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5238 authResult = AuthPipeline.authenticateByEmailAddress(
5239 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5240 headerMap, parameterMap);
5241 }
5242 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5243 authResult = AuthPipeline.authenticateByScreenName(
5244 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5245 headerMap, parameterMap);
5246 }
5247 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5248 authResult = AuthPipeline.authenticateByUserId(
5249 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
5250 headerMap, parameterMap);
5251 }
5252
5253
5254
5255 User user = null;
5256
5257 try {
5258 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5259 user = userPersistence.findByC_EA(companyId, login);
5260 }
5261 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5262 user = userPersistence.findByC_SN(companyId, login);
5263 }
5264 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5265 user = userPersistence.findByC_U(
5266 companyId, GetterUtil.getLong(login));
5267 }
5268 }
5269 catch (NoSuchUserException nsue) {
5270 return Authenticator.DNE;
5271 }
5272
5273 if (user.isDefaultUser()) {
5274 if (_log.isInfoEnabled()) {
5275 _log.info("Authentication is disabled for the default user");
5276 }
5277
5278 return Authenticator.DNE;
5279 }
5280 else if (!user.isActive()) {
5281 if (_log.isInfoEnabled()) {
5282 _log.info(
5283 "Authentication is disabled for inactive user " +
5284 user.getUserId());
5285 }
5286
5287 return Authenticator.FAILURE;
5288 }
5289
5290 if (!user.isPasswordEncrypted()) {
5291 user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
5292 user.setPasswordEncrypted(true);
5293
5294 userPersistence.update(user, false);
5295 }
5296
5297
5298
5299
5300 checkLockout(user);
5301
5302 checkPasswordExpired(user);
5303
5304
5305
5306 boolean skipLiferayCheck = false;
5307
5308 if (authResult == Authenticator.SKIP_LIFERAY_CHECK) {
5309 authResult = Authenticator.SUCCESS;
5310
5311 skipLiferayCheck = true;
5312 }
5313 else if ((authResult == Authenticator.SUCCESS) &&
5314 PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5315
5316 boolean authenticated = PwdAuthenticator.authenticate(
5317 login, password, user.getPassword());
5318
5319 if (authenticated) {
5320 authResult = Authenticator.SUCCESS;
5321 }
5322 else {
5323 authResult = Authenticator.FAILURE;
5324 }
5325 }
5326
5327
5328
5329 if (authResult == Authenticator.SUCCESS) {
5330 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5331 authResult = AuthPipeline.authenticateByEmailAddress(
5332 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5333 headerMap, parameterMap);
5334 }
5335 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5336 authResult = AuthPipeline.authenticateByScreenName(
5337 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5338 headerMap, parameterMap);
5339 }
5340 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5341 authResult = AuthPipeline.authenticateByUserId(
5342 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5343 headerMap, parameterMap);
5344 }
5345 }
5346
5347 if (authResult == Authenticator.SUCCESS) {
5348 if (resultsMap != null) {
5349 resultsMap.put("userId", user.getUserId());
5350 }
5351
5352
5353
5354 if (skipLiferayCheck ||
5355 !PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK ||
5356 Validator.isNull(user.getDigest())) {
5357
5358 String digest = user.getDigest(password);
5359
5360 user.setDigest(digest);
5361
5362 userPersistence.update(user, false);
5363 }
5364 }
5365
5366
5367
5368 if (authResult == Authenticator.FAILURE) {
5369 try {
5370 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5371 AuthPipeline.onFailureByEmailAddress(
5372 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5373 parameterMap);
5374 }
5375 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5376 AuthPipeline.onFailureByScreenName(
5377 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5378 parameterMap);
5379 }
5380 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5381 AuthPipeline.onFailureByUserId(
5382 PropsKeys.AUTH_FAILURE, companyId, userId, headerMap,
5383 parameterMap);
5384 }
5385
5386 try {
5387 user = userPersistence.findByPrimaryKey(user.getUserId());
5388 }
5389 catch (NoSuchUserException nsue) {
5390 return Authenticator.DNE;
5391 }
5392
5393
5394
5395 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5396 user.getCompanyId())) {
5397
5398 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5399
5400 int failedLoginAttempts = user.getFailedLoginAttempts();
5401 int maxFailures = passwordPolicy.getMaxFailure();
5402
5403 if ((failedLoginAttempts >= maxFailures) &&
5404 (maxFailures != 0)) {
5405
5406 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5407 AuthPipeline.onMaxFailuresByEmailAddress(
5408 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5409 headerMap, parameterMap);
5410 }
5411 else if (authType.equals(
5412 CompanyConstants.AUTH_TYPE_SN)) {
5413
5414 AuthPipeline.onMaxFailuresByScreenName(
5415 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5416 headerMap, parameterMap);
5417 }
5418 else if (authType.equals(
5419 CompanyConstants.AUTH_TYPE_ID)) {
5420
5421 AuthPipeline.onMaxFailuresByUserId(
5422 PropsKeys.AUTH_MAX_FAILURES, companyId, userId,
5423 headerMap, parameterMap);
5424 }
5425 }
5426 }
5427 }
5428 catch (Exception e) {
5429 _log.error(e, e);
5430 }
5431 }
5432
5433 return authResult;
5434 }
5435
5436 protected Date getBirthday(
5437 int birthdayMonth, int birthdayDay, int birthdayYear)
5438 throws PortalException {
5439
5440 Date birthday = PortalUtil.getDate(
5441 birthdayMonth, birthdayDay, birthdayYear,
5442 ContactBirthdayException.class);
5443
5444 Date now = new Date();
5445
5446 if (birthday.after(now)) {
5447 throw new ContactBirthdayException();
5448 }
5449
5450 return birthday;
5451 }
5452
5453 protected String getScreenName(String screenName) {
5454 return StringUtil.lowerCase(StringUtil.trim(screenName));
5455 }
5456
5457 protected long[] getUserIds(List<User> users) {
5458 long[] userIds = new long[users.size()];
5459
5460 for (int i = 0; i < users.size(); i++) {
5461 User user = users.get(i);
5462
5463 userIds[i] = user.getUserId();
5464 }
5465
5466 return userIds;
5467 }
5468
5469 protected void reindex(final User user) {
5470 final Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5471 User.class);
5472
5473 Callable<Void> callable = new ShardCallable<Void>(
5474 user.getCompanyId()) {
5475
5476 @Override
5477 protected Void doCall() throws Exception {
5478 indexer.reindex(user);
5479
5480 return null;
5481 }
5482
5483 };
5484
5485 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
5486 }
5487
5488 protected Hits search(
5489 long companyId, String firstName, String middleName,
5490 String lastName, String fullName, String screenName,
5491 String emailAddress, String street, String city, String zip,
5492 String region, String country, int status,
5493 LinkedHashMap<String, Object> params, boolean andSearch, int start,
5494 int end, Sort sort)
5495 throws SystemException {
5496
5497 try {
5498 SearchContext searchContext = new SearchContext();
5499
5500 searchContext.setAndSearch(andSearch);
5501
5502 Map<String, Serializable> attributes =
5503 new HashMap<String, Serializable>();
5504
5505 attributes.put("city", city);
5506 attributes.put("country", country);
5507 attributes.put("emailAddress", emailAddress);
5508 attributes.put("firstName", firstName);
5509 attributes.put("fullName", fullName);
5510 attributes.put("lastName", lastName);
5511 attributes.put("middleName", middleName);
5512 attributes.put("params", params);
5513 attributes.put("region", region);
5514 attributes.put("screenName", screenName);
5515 attributes.put("street", street);
5516 attributes.put("status", status);
5517 attributes.put("zip", zip);
5518
5519 searchContext.setAttributes(attributes);
5520
5521 searchContext.setCompanyId(companyId);
5522 searchContext.setEnd(end);
5523
5524 if (params != null) {
5525 String keywords = (String)params.remove("keywords");
5526
5527 if (Validator.isNotNull(keywords)) {
5528 searchContext.setKeywords(keywords);
5529 }
5530 }
5531
5532 QueryConfig queryConfig = new QueryConfig();
5533
5534 queryConfig.setHighlightEnabled(false);
5535 queryConfig.setScoreEnabled(false);
5536
5537 searchContext.setQueryConfig(queryConfig);
5538
5539 if (sort != null) {
5540 searchContext.setSorts(new Sort[] {sort});
5541 }
5542
5543 searchContext.setStart(start);
5544
5545 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5546 User.class);
5547
5548 return indexer.search(searchContext);
5549 }
5550 catch (Exception e) {
5551 throw new SystemException(e);
5552 }
5553 }
5554
5555 protected void sendEmail(
5556 User user, String password, ServiceContext serviceContext)
5557 throws SystemException {
5558
5559 if (!PrefsPropsUtil.getBoolean(
5560 user.getCompanyId(),
5561 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
5562
5563 return;
5564 }
5565
5566 String fromName = PrefsPropsUtil.getString(
5567 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
5568 String fromAddress = PrefsPropsUtil.getString(
5569 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
5570
5571 String toName = user.getFullName();
5572 String toAddress = user.getEmailAddress();
5573
5574 String subject = PrefsPropsUtil.getContent(
5575 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
5576
5577 String body = null;
5578
5579 if (Validator.isNotNull(password)) {
5580 body = PrefsPropsUtil.getContent(
5581 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
5582 }
5583 else {
5584 body = PrefsPropsUtil.getContent(
5585 user.getCompanyId(),
5586 PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
5587 }
5588
5589 SubscriptionSender subscriptionSender = new SubscriptionSender();
5590
5591 subscriptionSender.setBody(body);
5592 subscriptionSender.setCompanyId(user.getCompanyId());
5593 subscriptionSender.setContextAttributes(
5594 "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
5595 "[$USER_SCREENNAME$]", user.getScreenName());
5596 subscriptionSender.setFrom(fromAddress, fromName);
5597 subscriptionSender.setHtmlFormat(true);
5598 subscriptionSender.setMailId("user", user.getUserId());
5599 subscriptionSender.setServiceContext(serviceContext);
5600 subscriptionSender.setSubject(subject);
5601 subscriptionSender.setUserId(user.getUserId());
5602
5603 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
5604
5605 subscriptionSender.flushNotificationsAsync();
5606 }
5607
5608 protected void setEmailAddress(
5609 User user, String password, String firstName, String middleName,
5610 String lastName, String emailAddress)
5611 throws PortalException, SystemException {
5612
5613 if (emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
5614 return;
5615 }
5616
5617 long userId = user.getUserId();
5618
5619
5620
5621 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
5622 Validator.isNotNull(password)) {
5623
5624 mailService.addUser(
5625 user.getCompanyId(), userId, password, firstName, middleName,
5626 lastName, emailAddress);
5627 }
5628
5629
5630
5631 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
5632 mailService.updateEmailAddress(
5633 user.getCompanyId(), userId, emailAddress);
5634 }
5635
5636
5637
5638 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
5639 mailService.deleteEmailAddress(user.getCompanyId(), userId);
5640 }
5641
5642 user.setEmailAddress(emailAddress);
5643 user.setDigest(StringPool.BLANK);
5644 }
5645
5646 protected void startWorkflowInstance(
5647 final long companyId, final long workflowUserId, final long userId,
5648 final User user, final ServiceContext workflowServiceContext) {
5649
5650 Callable<Void> callable = new ShardCallable<Void>(companyId) {
5651
5652 @Override
5653 protected Void doCall() throws Exception {
5654 WorkflowHandlerRegistryUtil.startWorkflowInstance(
5655 companyId, workflowUserId, User.class.getName(), userId,
5656 user, workflowServiceContext);
5657
5658 return null;
5659 }
5660
5661 };
5662
5663 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
5664 }
5665
5666 protected void updateGroups(
5667 long userId, long[] newGroupIds, ServiceContext serviceContext,
5668 boolean indexingEnabled)
5669 throws PortalException, SystemException {
5670
5671 if (newGroupIds == null) {
5672 return;
5673 }
5674
5675 List<Group> oldGroups = userPersistence.getGroups(userId);
5676
5677 Set<Long> oldGroupIds = new HashSet<Long>(oldGroups.size());
5678
5679 for (Group oldGroup : oldGroups) {
5680 long oldGroupId = oldGroup.getGroupId();
5681
5682 oldGroupIds.add(oldGroupId);
5683
5684 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
5685 unsetGroupUsers(
5686 oldGroupId, new long[] {userId}, serviceContext);
5687 }
5688 }
5689
5690 for (long newGroupId : newGroupIds) {
5691 if (!oldGroupIds.contains(newGroupId)) {
5692 addGroupUsers(newGroupId, new long[] {userId});
5693 }
5694 }
5695
5696 if (indexingEnabled) {
5697 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5698 User.class);
5699
5700 indexer.reindex(new long[] {userId});
5701 }
5702
5703 PermissionCacheUtil.clearCache();
5704 }
5705
5706 protected void updateOrganizations(
5707 long userId, long[] newOrganizationIds, boolean indexingEnabled)
5708 throws PortalException, SystemException {
5709
5710 if (newOrganizationIds == null) {
5711 return;
5712 }
5713
5714 List<Organization> oldOrganizations = userPersistence.getOrganizations(
5715 userId);
5716
5717 Set<Long> oldOrganizationIds = new HashSet<Long>(
5718 oldOrganizations.size());
5719
5720 for (Organization oldOrganization : oldOrganizations) {
5721 long oldOrganizationId = oldOrganization.getOrganizationId();
5722
5723 oldOrganizationIds.add(oldOrganizationId);
5724
5725 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
5726 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
5727 }
5728 }
5729
5730 for (long newOrganizationId : newOrganizationIds) {
5731 if (!oldOrganizationIds.contains(newOrganizationId)) {
5732 addOrganizationUsers(newOrganizationId, new long[] {userId});
5733 }
5734 }
5735
5736 if (indexingEnabled) {
5737 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5738 User.class);
5739
5740 indexer.reindex(new long[] {userId});
5741 }
5742
5743 PermissionCacheUtil.clearCache();
5744 }
5745
5746 protected void updateUserGroupRoles(
5747 User user, long[] groupIds, long[] organizationIds,
5748 List<UserGroupRole> userGroupRoles)
5749 throws PortalException, SystemException {
5750
5751 if (userGroupRoles == null) {
5752 return;
5753 }
5754
5755 List<UserGroupRole> previousUserGroupRoles =
5756 userGroupRolePersistence.findByUserId(user.getUserId());
5757
5758 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
5759 if (userGroupRoles.contains(userGroupRole)) {
5760 userGroupRoles.remove(userGroupRole);
5761 }
5762 else {
5763 userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
5764 }
5765 }
5766
5767 long[] validGroupIds = null;
5768
5769 if (groupIds != null) {
5770 validGroupIds = ArrayUtil.clone(groupIds);
5771 }
5772 else {
5773 validGroupIds = user.getGroupIds();
5774 }
5775
5776 if (organizationIds == null) {
5777 organizationIds = user.getOrganizationIds();
5778 }
5779
5780 long[] organizationGroupIds = new long[organizationIds.length];
5781
5782 for (int i = 0; i < organizationIds.length; i++) {
5783 long organizationId = organizationIds[i];
5784
5785 Organization organization =
5786 organizationPersistence.findByPrimaryKey(organizationId);
5787
5788 Group organizationGroup = organization.getGroup();
5789
5790 organizationGroupIds[i] = organizationGroup.getGroupId();
5791 }
5792
5793 validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
5794
5795 Arrays.sort(validGroupIds);
5796
5797 for (UserGroupRole userGroupRole : userGroupRoles) {
5798 if (Arrays.binarySearch(
5799 validGroupIds, userGroupRole.getGroupId()) >= 0) {
5800
5801 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
5802 }
5803 }
5804 }
5805
5806 protected void validate(
5807 long companyId, long userId, boolean autoPassword, String password1,
5808 String password2, boolean autoScreenName, String screenName,
5809 String emailAddress, String openId, String firstName,
5810 String middleName, String lastName, long[] organizationIds)
5811 throws PortalException, SystemException {
5812
5813 validateCompanyMaxUsers(companyId);
5814
5815 if (!autoScreenName) {
5816 validateScreenName(companyId, userId, screenName);
5817 }
5818
5819 if (!autoPassword) {
5820 PasswordPolicy passwordPolicy =
5821 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
5822
5823 PwdToolkitUtil.validate(
5824 companyId, 0, password1, password2, passwordPolicy);
5825 }
5826
5827 validateEmailAddress(companyId, emailAddress);
5828
5829 if (Validator.isNotNull(emailAddress)) {
5830 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
5831
5832 if ((user != null) && (user.getUserId() != userId)) {
5833 throw new DuplicateUserEmailAddressException();
5834 }
5835 }
5836
5837 validateOpenId(companyId, userId, openId);
5838
5839 validateFullName(companyId, firstName, middleName, lastName);
5840
5841 if (organizationIds != null) {
5842 for (long organizationId : organizationIds) {
5843 Organization organization =
5844 organizationPersistence.fetchByPrimaryKey(organizationId);
5845
5846 if (organization == null) {
5847 throw new NoSuchOrganizationException();
5848 }
5849 }
5850 }
5851 }
5852
5853 protected void validate(
5854 long userId, String screenName, String emailAddress, String openId,
5855 String firstName, String middleName, String lastName, String smsSn)
5856 throws PortalException, SystemException {
5857
5858 User user = userPersistence.findByPrimaryKey(userId);
5859
5860 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
5861 validateScreenName(user.getCompanyId(), userId, screenName);
5862 }
5863
5864 validateEmailAddress(user.getCompanyId(), emailAddress);
5865
5866 validateOpenId(user.getCompanyId(), userId, openId);
5867
5868 if (!user.isDefaultUser()) {
5869 if (Validator.isNotNull(emailAddress) &&
5870 !user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
5871
5872 if (userPersistence.fetchByC_EA(
5873 user.getCompanyId(), emailAddress) != null) {
5874
5875 throw new DuplicateUserEmailAddressException();
5876 }
5877 }
5878
5879 validateFullName(
5880 user.getCompanyId(), firstName, middleName, lastName);
5881 }
5882
5883 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
5884 throw new UserSmsException();
5885 }
5886 }
5887
5888 protected void validateCompanyMaxUsers(long companyId)
5889 throws PortalException, SystemException {
5890
5891 Company company = companyPersistence.findByPrimaryKey(companyId);
5892
5893 if (company.isSystem() || (company.getMaxUsers() == 0)) {
5894 return;
5895 }
5896
5897 int userCount = searchCount(
5898 companyId, null, WorkflowConstants.STATUS_APPROVED, null);
5899
5900 if (userCount >= company.getMaxUsers()) {
5901 throw new CompanyMaxUsersException();
5902 }
5903 }
5904
5905 protected void validateEmailAddress(long companyId, String emailAddress)
5906 throws PortalException, SystemException {
5907
5908 if (Validator.isNull(emailAddress) &&
5909 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
5910
5911 return;
5912 }
5913
5914 EmailAddressValidator emailAddressValidator =
5915 EmailAddressValidatorFactory.getInstance();
5916
5917 if (!emailAddressValidator.validate(companyId, emailAddress)) {
5918 throw new UserEmailAddressException();
5919 }
5920
5921 String pop3User = PrefsPropsUtil.getString(
5922 PropsKeys.MAIL_SESSION_MAIL_POP3_USER,
5923 PropsValues.MAIL_SESSION_MAIL_POP3_USER);
5924
5925 if (emailAddress.equalsIgnoreCase(pop3User)) {
5926 throw new ReservedUserEmailAddressException();
5927 }
5928
5929 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
5930 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
5931 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
5932
5933 for (String reservedEmailAddress : reservedEmailAddresses) {
5934 if (emailAddress.equalsIgnoreCase(reservedEmailAddress)) {
5935 throw new ReservedUserEmailAddressException();
5936 }
5937 }
5938 }
5939
5940 protected void validateEmailAddress(
5941 User user, String emailAddress1, String emailAddress2)
5942 throws PortalException, SystemException {
5943
5944 if (!emailAddress1.equals(emailAddress2)) {
5945 throw new UserEmailAddressException();
5946 }
5947
5948 validateEmailAddress(user.getCompanyId(), emailAddress1);
5949 validateEmailAddress(user.getCompanyId(), emailAddress2);
5950
5951 if (!emailAddress1.equalsIgnoreCase(user.getEmailAddress())) {
5952 if (userPersistence.fetchByC_EA(
5953 user.getCompanyId(), emailAddress1) != null) {
5954
5955 throw new DuplicateUserEmailAddressException();
5956 }
5957 }
5958 }
5959
5960 protected void validateFullName(
5961 long companyId, String firstName, String middleName,
5962 String lastName)
5963 throws PortalException, SystemException {
5964
5965 if (Validator.isNull(firstName)) {
5966 throw new ContactFirstNameException();
5967 }
5968 else if (Validator.isNull(lastName) &&
5969 PrefsPropsUtil.getBoolean(
5970 companyId, PropsKeys.USERS_LAST_NAME_REQUIRED,
5971 PropsValues.USERS_LAST_NAME_REQUIRED)) {
5972
5973 throw new ContactLastNameException();
5974 }
5975
5976 FullNameValidator fullNameValidator =
5977 FullNameValidatorFactory.getInstance();
5978
5979 if (!fullNameValidator.validate(
5980 companyId, firstName, middleName, lastName)) {
5981
5982 throw new ContactFullNameException();
5983 }
5984 }
5985
5986 protected void validateOpenId(long companyId, long userId, String openId)
5987 throws PortalException, SystemException {
5988
5989 if (Validator.isNull(openId)) {
5990 return;
5991 }
5992
5993 User user = userPersistence.fetchByC_O(companyId, openId);
5994
5995 if ((user != null) && (user.getUserId() != userId)) {
5996 throw new DuplicateOpenIdException();
5997 }
5998 }
5999
6000 protected void validatePassword(
6001 long companyId, long userId, String password1, String password2)
6002 throws PortalException, SystemException {
6003
6004 if (Validator.isNull(password1) || Validator.isNull(password2)) {
6005 throw new UserPasswordException(
6006 UserPasswordException.PASSWORD_INVALID);
6007 }
6008
6009 if (!password1.equals(password2)) {
6010 throw new UserPasswordException(
6011 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
6012 }
6013
6014 PasswordPolicy passwordPolicy =
6015 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
6016
6017 PwdToolkitUtil.validate(
6018 companyId, userId, password1, password2, passwordPolicy);
6019 }
6020
6021 protected void validateReminderQuery(String question, String answer)
6022 throws PortalException {
6023
6024 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
6025 return;
6026 }
6027
6028 if (Validator.isNull(question)) {
6029 throw new UserReminderQueryException("Question cannot be null");
6030 }
6031
6032 if (Validator.isNull(answer)) {
6033 throw new UserReminderQueryException("Answer cannot be null");
6034 }
6035 }
6036
6037 protected void validateScreenName(
6038 long companyId, long userId, String screenName)
6039 throws PortalException, SystemException {
6040
6041 if (Validator.isNull(screenName)) {
6042 throw new UserScreenNameException();
6043 }
6044
6045 ScreenNameValidator screenNameValidator =
6046 ScreenNameValidatorFactory.getInstance();
6047
6048 if (!screenNameValidator.validate(companyId, screenName)) {
6049 throw new UserScreenNameException();
6050 }
6051
6052 if (Validator.isNumber(screenName)) {
6053 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
6054 throw new UserScreenNameException();
6055 }
6056
6057 if (!screenName.equals(String.valueOf(userId))) {
6058 Group group = groupPersistence.fetchByPrimaryKey(
6059 GetterUtil.getLong(screenName));
6060
6061 if (group != null) {
6062 throw new UserScreenNameException();
6063 }
6064 }
6065 }
6066
6067 for (char c : screenName.toCharArray()) {
6068 if (!Validator.isChar(c) && !Validator.isDigit(c) &&
6069 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
6070 (c != CharPool.UNDERLINE)) {
6071
6072 throw new UserScreenNameException();
6073 }
6074 }
6075
6076 String[] anonymousNames = BaseServiceImpl.ANONYMOUS_NAMES;
6077
6078 for (String anonymousName : anonymousNames) {
6079 if (screenName.equalsIgnoreCase(anonymousName)) {
6080 throw new UserScreenNameException();
6081 }
6082 }
6083
6084 User user = userPersistence.fetchByC_SN(companyId, screenName);
6085
6086 if ((user != null) && (user.getUserId() != userId)) {
6087 throw new DuplicateUserScreenNameException();
6088 }
6089
6090 String friendlyURL = StringPool.SLASH + screenName;
6091
6092 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
6093
6094 if ((group != null) && (group.getClassPK() != userId)) {
6095 throw new GroupFriendlyURLException(
6096 GroupFriendlyURLException.DUPLICATE);
6097 }
6098
6099 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
6100
6101 if (exceptionType != -1) {
6102 throw new UserScreenNameException(
6103 new GroupFriendlyURLException(exceptionType));
6104 }
6105
6106 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
6107 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
6108 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
6109
6110 for (String reservedScreenName : reservedScreenNames) {
6111 if (screenName.equalsIgnoreCase(reservedScreenName)) {
6112 throw new ReservedUserScreenNameException();
6113 }
6114 }
6115 }
6116
6117 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
6118
6119 private Map<Long, User> _defaultUsers = new ConcurrentHashMap<Long, User>();
6120
6121 }