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.concurrent.PortalCallable;
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.UnicodeProperties;
080 import com.liferay.portal.kernel.util.Validator;
081 import com.liferay.portal.kernel.workflow.WorkflowConstants;
082 import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil;
083 import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
084 import com.liferay.portal.model.Account;
085 import com.liferay.portal.model.Company;
086 import com.liferay.portal.model.CompanyConstants;
087 import com.liferay.portal.model.Contact;
088 import com.liferay.portal.model.ContactConstants;
089 import com.liferay.portal.model.Group;
090 import com.liferay.portal.model.GroupConstants;
091 import com.liferay.portal.model.Layout;
092 import com.liferay.portal.model.Organization;
093 import com.liferay.portal.model.PasswordPolicy;
094 import com.liferay.portal.model.ResourceConstants;
095 import com.liferay.portal.model.Role;
096 import com.liferay.portal.model.RoleConstants;
097 import com.liferay.portal.model.Team;
098 import com.liferay.portal.model.Ticket;
099 import com.liferay.portal.model.TicketConstants;
100 import com.liferay.portal.model.User;
101 import com.liferay.portal.model.UserGroup;
102 import com.liferay.portal.model.UserGroupRole;
103 import com.liferay.portal.model.impl.LayoutImpl;
104 import com.liferay.portal.security.auth.AuthPipeline;
105 import com.liferay.portal.security.auth.Authenticator;
106 import com.liferay.portal.security.auth.EmailAddressGenerator;
107 import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
108 import com.liferay.portal.security.auth.EmailAddressValidator;
109 import com.liferay.portal.security.auth.EmailAddressValidatorFactory;
110 import com.liferay.portal.security.auth.FullNameGenerator;
111 import com.liferay.portal.security.auth.FullNameGeneratorFactory;
112 import com.liferay.portal.security.auth.FullNameValidator;
113 import com.liferay.portal.security.auth.FullNameValidatorFactory;
114 import com.liferay.portal.security.auth.PrincipalException;
115 import com.liferay.portal.security.auth.ScreenNameGenerator;
116 import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
117 import com.liferay.portal.security.auth.ScreenNameValidator;
118 import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
119 import com.liferay.portal.security.ldap.LDAPSettingsUtil;
120 import com.liferay.portal.security.permission.PermissionCacheUtil;
121 import com.liferay.portal.security.pwd.PasswordEncryptorUtil;
122 import com.liferay.portal.security.pwd.PwdAuthenticator;
123 import com.liferay.portal.security.pwd.PwdToolkitUtil;
124 import com.liferay.portal.security.pwd.RegExpToolkit;
125 import com.liferay.portal.service.BaseServiceImpl;
126 import com.liferay.portal.service.ServiceContext;
127 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
128 import com.liferay.portal.util.PortalUtil;
129 import com.liferay.portal.util.PrefsPropsUtil;
130 import com.liferay.portal.util.PropsValues;
131 import com.liferay.portal.util.SubscriptionSender;
132 import com.liferay.portlet.documentlibrary.ImageSizeException;
133 import com.liferay.portlet.messageboards.model.MBMessage;
134 import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
135 import com.liferay.util.Encryptor;
136 import com.liferay.util.EncryptorException;
137 import com.liferay.util.PwdGenerator;
138
139 import java.awt.image.RenderedImage;
140
141 import java.io.IOException;
142 import java.io.Serializable;
143
144 import java.util.ArrayList;
145 import java.util.Arrays;
146 import java.util.Calendar;
147 import java.util.Date;
148 import java.util.HashMap;
149 import java.util.HashSet;
150 import java.util.LinkedHashMap;
151 import java.util.List;
152 import java.util.Locale;
153 import java.util.Map;
154 import java.util.Set;
155 import java.util.concurrent.Callable;
156 import java.util.concurrent.ConcurrentHashMap;
157
158
170 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
171
172
186 public User addDefaultAdminUser(
187 long companyId, String screenName, String emailAddress,
188 Locale locale, String firstName, String middleName, String lastName)
189 throws PortalException, SystemException {
190
191 long creatorUserId = 0;
192 boolean autoPassword = false;
193 String password1 = PropsValues.DEFAULT_ADMIN_PASSWORD;
194 String password2 = password1;
195 boolean autoScreenName = false;
196
197 screenName = getScreenName(screenName);
198
199 for (int i = 1;; i++) {
200 User screenNameUser = userPersistence.fetchByC_SN(
201 companyId, screenName);
202
203 if (screenNameUser == null) {
204 break;
205 }
206
207 screenName = screenName + i;
208 }
209
210 long facebookId = 0;
211 String openId = StringPool.BLANK;
212 int prefixId = 0;
213 int suffixId = 0;
214 boolean male = true;
215 int birthdayMonth = Calendar.JANUARY;
216 int birthdayDay = 1;
217 int birthdayYear = 1970;
218 String jobTitle = StringPool.BLANK;
219
220 Group guestGroup = groupLocalService.getGroup(
221 companyId, GroupConstants.GUEST);
222
223 long[] groupIds = {guestGroup.getGroupId()};
224
225 long[] organizationIds = null;
226
227 Role adminRole = roleLocalService.getRole(
228 companyId, RoleConstants.ADMINISTRATOR);
229
230 Role powerUserRole = roleLocalService.getRole(
231 companyId, RoleConstants.POWER_USER);
232
233 long[] roleIds = {adminRole.getRoleId(), powerUserRole.getRoleId()};
234
235 long[] userGroupIds = null;
236 boolean sendEmail = false;
237 ServiceContext serviceContext = new ServiceContext();
238
239 User defaultAdminUser = addUser(
240 creatorUserId, companyId, autoPassword, password1, password2,
241 autoScreenName, screenName, emailAddress, facebookId, openId,
242 locale, firstName, middleName, lastName, prefixId, suffixId, male,
243 birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
244 organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
245
246 updateEmailAddressVerified(defaultAdminUser.getUserId(), true);
247
248 updateLastLogin(
249 defaultAdminUser.getUserId(), defaultAdminUser.getLoginIP());
250
251 updatePasswordReset(defaultAdminUser.getUserId(), false);
252
253 return defaultAdminUser;
254 }
255
256
266 public void addDefaultGroups(long userId)
267 throws PortalException, SystemException {
268
269 User user = userPersistence.findByPrimaryKey(userId);
270
271 Set<Long> groupIdsSet = new HashSet<Long>();
272
273 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
274 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
275 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
276
277 for (String defaultGroupName : defaultGroupNames) {
278 Company company = companyPersistence.findByPrimaryKey(
279 user.getCompanyId());
280
281 Account account = company.getAccount();
282
283 if (defaultGroupName.equalsIgnoreCase(account.getName())) {
284 defaultGroupName = GroupConstants.GUEST;
285 }
286
287 try {
288 Group group = groupPersistence.findByC_N(
289 user.getCompanyId(), defaultGroupName);
290
291 if (!userPersistence.containsGroup(
292 userId, group.getGroupId())) {
293
294 groupIdsSet.add(group.getGroupId());
295 }
296 }
297 catch (NoSuchGroupException nsge) {
298 }
299 }
300
301 String[] defaultOrganizationGroupNames = PrefsPropsUtil.getStringArray(
302 user.getCompanyId(),
303 PropsKeys.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES,
304 StringPool.NEW_LINE,
305 PropsValues.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES);
306
307 for (String defaultOrganizationGroupName :
308 defaultOrganizationGroupNames) {
309
310 defaultOrganizationGroupName +=
311 GroupLocalServiceImpl.ORGANIZATION_NAME_SUFFIX;
312
313 try {
314 Group group = groupPersistence.findByC_N(
315 user.getCompanyId(), defaultOrganizationGroupName);
316
317 if (!userPersistence.containsGroup(
318 userId, group.getGroupId())) {
319
320 groupIdsSet.add(group.getGroupId());
321 }
322 }
323 catch (NoSuchGroupException nsge) {
324 }
325 }
326
327 long[] groupIds = ArrayUtil.toArray(
328 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
329
330 groupLocalService.addUserGroups(userId, groupIds);
331 }
332
333
343 public void addDefaultRoles(long userId)
344 throws PortalException, SystemException {
345
346 User user = userPersistence.findByPrimaryKey(userId);
347
348 Set<Long> roleIdSet = new HashSet<Long>();
349
350 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
351 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
352 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
353
354 for (String defaultRoleName : defaultRoleNames) {
355 try {
356 Role role = rolePersistence.findByC_N(
357 user.getCompanyId(), defaultRoleName);
358
359 if (!userPersistence.containsRole(userId, role.getRoleId())) {
360 roleIdSet.add(role.getRoleId());
361 }
362 }
363 catch (NoSuchRoleException nsre) {
364 }
365 }
366
367 long[] roleIds = ArrayUtil.toArray(
368 roleIdSet.toArray(new Long[roleIdSet.size()]));
369
370 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
371
372 userPersistence.addRoles(userId, roleIds);
373 }
374
375
385 @SuppressWarnings("deprecation")
386 public void addDefaultUserGroups(long userId)
387 throws PortalException, SystemException {
388
389 User user = userPersistence.findByPrimaryKey(userId);
390
391 Set<Long> userGroupIdSet = new HashSet<Long>();
392
393 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
394 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
395 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
396
397 for (String defaultUserGroupName : defaultUserGroupNames) {
398 try {
399 UserGroup userGroup = userGroupPersistence.findByC_N(
400 user.getCompanyId(), defaultUserGroupName);
401
402 if (!userPersistence.containsUserGroup(
403 userId, userGroup.getUserGroupId())) {
404
405 userGroupIdSet.add(userGroup.getUserGroupId());
406 }
407 }
408 catch (NoSuchUserGroupException nsuge) {
409 }
410 }
411
412 long[] userGroupIds = ArrayUtil.toArray(
413 userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
414
415 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
416 for (long userGroupId : userGroupIds) {
417 userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
418 }
419 }
420
421 userPersistence.addUserGroups(userId, userGroupIds);
422 }
423
424
433 @Override
434 public void addGroupUsers(long groupId, long[] userIds)
435 throws PortalException, SystemException {
436
437 groupPersistence.addUsers(groupId, userIds);
438
439 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
440
441 indexer.reindex(userIds);
442
443 PermissionCacheUtil.clearCache();
444
445 addDefaultRolesAndTeams(groupId, userIds);
446 }
447
448
457 @Override
458 public void addOrganizationUsers(long organizationId, long[] userIds)
459 throws PortalException, SystemException {
460
461 organizationPersistence.addUsers(organizationId, userIds);
462
463 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
464
465 indexer.reindex(userIds);
466
467 PermissionCacheUtil.clearCache();
468 }
469
470
478 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
479 throws SystemException {
480
481 passwordPolicyRelLocalService.addPasswordPolicyRels(
482 passwordPolicyId, User.class.getName(), userIds);
483 }
484
485
494 @Override
495 public void addRoleUsers(long roleId, long[] userIds)
496 throws PortalException, SystemException {
497
498 rolePersistence.addUsers(roleId, userIds);
499
500 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
501
502 indexer.reindex(userIds);
503
504 PermissionCacheUtil.clearCache();
505 }
506
507
516 @Override
517 public void addTeamUsers(long teamId, long[] userIds)
518 throws PortalException, SystemException {
519
520 teamPersistence.addUsers(teamId, userIds);
521
522 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
523
524 indexer.reindex(userIds);
525
526 PermissionCacheUtil.clearCache();
527 }
528
529
577 public User addUser(
578 long creatorUserId, long companyId, boolean autoPassword,
579 String password1, String password2, boolean autoScreenName,
580 String screenName, String emailAddress, long facebookId,
581 String openId, Locale locale, String firstName, String middleName,
582 String lastName, int prefixId, int suffixId, boolean male,
583 int birthdayMonth, int birthdayDay, int birthdayYear,
584 String jobTitle, long[] groupIds, long[] organizationIds,
585 long[] roleIds, long[] userGroupIds, boolean sendEmail,
586 ServiceContext serviceContext)
587 throws PortalException, SystemException {
588
589 boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
590
591 try {
592 WorkflowThreadLocal.setEnabled(false);
593
594 return addUserWithWorkflow(
595 creatorUserId, companyId, autoPassword, password1, password2,
596 autoScreenName, screenName, emailAddress, facebookId, openId,
597 locale, firstName, middleName, lastName, prefixId, suffixId,
598 male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
599 groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
600 serviceContext);
601 }
602 finally {
603 WorkflowThreadLocal.setEnabled(workflowEnabled);
604 }
605 }
606
607
616 @Override
617 @SuppressWarnings("deprecation")
618 public void addUserGroupUsers(long userGroupId, long[] userIds)
619 throws PortalException, SystemException {
620
621 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
622 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
623 }
624
625 userGroupPersistence.addUsers(userGroupId, userIds);
626
627 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
628
629 indexer.reindex(userIds);
630
631 PermissionCacheUtil.clearCache();
632 }
633
634
682 @SuppressWarnings("deprecation")
683 public User addUserWithWorkflow(
684 long creatorUserId, long companyId, boolean autoPassword,
685 String password1, String password2, boolean autoScreenName,
686 String screenName, String emailAddress, long facebookId,
687 String openId, Locale locale, String firstName, String middleName,
688 String lastName, int prefixId, int suffixId, boolean male,
689 int birthdayMonth, int birthdayDay, int birthdayYear,
690 String jobTitle, long[] groupIds, long[] organizationIds,
691 long[] roleIds, long[] userGroupIds, boolean sendEmail,
692 ServiceContext serviceContext)
693 throws PortalException, SystemException {
694
695
696
697 Company company = companyPersistence.findByPrimaryKey(companyId);
698 screenName = getScreenName(screenName);
699 openId = StringUtil.trim(openId);
700 Date now = new Date();
701
702 if (PrefsPropsUtil.getBoolean(
703 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
704
705 autoScreenName = true;
706 }
707
708
709
710 long userId = counterLocalService.increment();
711
712 EmailAddressGenerator emailAddressGenerator =
713 EmailAddressGeneratorFactory.getInstance();
714
715 if ((emailAddress == null) ||
716 emailAddressGenerator.isGenerated(emailAddress)) {
717
718 emailAddress = StringPool.BLANK;
719 }
720 else {
721 emailAddress = emailAddress.trim().toLowerCase();
722 }
723
724 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
725 Validator.isNull(emailAddress)) {
726
727 emailAddress = emailAddressGenerator.generate(companyId, userId);
728 }
729
730 validate(
731 companyId, userId, autoPassword, password1, password2,
732 autoScreenName, screenName, emailAddress, openId, firstName,
733 middleName, lastName, organizationIds);
734
735 if (!autoPassword) {
736 if (Validator.isNull(password1) || Validator.isNull(password2)) {
737 throw new UserPasswordException(
738 UserPasswordException.PASSWORD_INVALID);
739 }
740 }
741
742 if (autoScreenName) {
743 ScreenNameGenerator screenNameGenerator =
744 ScreenNameGeneratorFactory.getInstance();
745
746 try {
747 screenName = screenNameGenerator.generate(
748 companyId, userId, emailAddress);
749 }
750 catch (Exception e) {
751 throw new SystemException(e);
752 }
753 }
754
755 User defaultUser = getDefaultUser(companyId);
756
757 FullNameGenerator fullNameGenerator =
758 FullNameGeneratorFactory.getInstance();
759
760 String fullName = fullNameGenerator.getFullName(
761 firstName, middleName, lastName);
762
763 String greeting = LanguageUtil.format(
764 locale, "welcome-x", " " + fullName, false);
765
766 User user = userPersistence.create(userId);
767
768 if (serviceContext != null) {
769 String uuid = serviceContext.getUuid();
770
771 if (Validator.isNotNull(uuid)) {
772 user.setUuid(uuid);
773 }
774 }
775
776 user.setCompanyId(companyId);
777 user.setCreateDate(now);
778 user.setModifiedDate(now);
779 user.setDefaultUser(false);
780 user.setContactId(counterLocalService.increment());
781
782 if (Validator.isNotNull(password1)) {
783 user.setPassword(PasswordEncryptorUtil.encrypt(password1));
784 user.setPasswordUnencrypted(password1);
785 }
786
787 user.setPasswordEncrypted(true);
788
789 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
790
791 boolean passwordReset = false;
792
793 if (passwordPolicy != null) {
794 if (passwordPolicy.isChangeable() &&
795 passwordPolicy.isChangeRequired()) {
796
797 passwordReset = true;
798 }
799
800 addPasswordPolicyUsers(
801 passwordPolicy.getPasswordPolicyId(), new long[] {userId});
802 }
803
804 user.setPasswordReset(passwordReset);
805
806 user.setDigest(StringPool.BLANK);
807 user.setScreenName(screenName);
808 user.setEmailAddress(emailAddress);
809 user.setFacebookId(facebookId);
810
811 Long ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
812
813 if (ldapServerId != null) {
814 user.setLdapServerId(ldapServerId);
815 }
816 else {
817 user.setLdapServerId(-1);
818 }
819
820 user.setOpenId(openId);
821 user.setLanguageId(LocaleUtil.toLanguageId(locale));
822 user.setTimeZoneId(defaultUser.getTimeZoneId());
823 user.setGreeting(greeting);
824 user.setFirstName(firstName);
825 user.setMiddleName(middleName);
826 user.setLastName(lastName);
827 user.setJobTitle(jobTitle);
828 user.setStatus(WorkflowConstants.STATUS_DRAFT);
829 user.setExpandoBridgeAttributes(serviceContext);
830
831 userPersistence.update(user, serviceContext);
832
833
834
835 String creatorUserName = StringPool.BLANK;
836
837 if (creatorUserId <= 0) {
838 creatorUserId = user.getUserId();
839
840
841
842
843
844 }
845 else {
846 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
847
848 creatorUserName = creatorUser.getFullName();
849 }
850
851 resourceLocalService.addResources(
852 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
853 false, false, false);
854
855
856
857 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
858
859 Contact contact = contactPersistence.create(user.getContactId());
860
861 contact.setCompanyId(user.getCompanyId());
862 contact.setUserId(creatorUserId);
863 contact.setUserName(creatorUserName);
864 contact.setCreateDate(now);
865 contact.setModifiedDate(now);
866 contact.setClassName(User.class.getName());
867 contact.setClassPK(user.getUserId());
868 contact.setAccountId(company.getAccountId());
869 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
870 contact.setEmailAddress(user.getEmailAddress());
871 contact.setFirstName(firstName);
872 contact.setMiddleName(middleName);
873 contact.setLastName(lastName);
874 contact.setPrefixId(prefixId);
875 contact.setSuffixId(suffixId);
876 contact.setMale(male);
877 contact.setBirthday(birthday);
878 contact.setJobTitle(jobTitle);
879
880 contactPersistence.update(contact, serviceContext);
881
882
883
884 groupLocalService.addGroup(
885 user.getUserId(), GroupConstants.DEFAULT_PARENT_GROUP_ID,
886 User.class.getName(), user.getUserId(), null, null, 0,
887 StringPool.SLASH + screenName, false, true, null);
888
889
890
891 if (groupIds != null) {
892 groupLocalService.addUserGroups(userId, groupIds);
893 }
894
895 addDefaultGroups(userId);
896
897
898
899 updateOrganizations(userId, organizationIds, false);
900
901
902
903 if (roleIds != null) {
904 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
905
906 userPersistence.setRoles(userId, roleIds);
907 }
908
909 addDefaultRoles(userId);
910
911
912
913 if (userGroupIds != null) {
914 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
915 for (long userGroupId : userGroupIds) {
916 userGroupLocalService.copyUserGroupLayouts(
917 userGroupId, new long[] {userId});
918 }
919 }
920
921 userPersistence.setUserGroups(userId, userGroupIds);
922 }
923
924 addDefaultUserGroups(userId);
925
926
927
928 if (serviceContext != null) {
929 updateAsset(
930 creatorUserId, user, serviceContext.getAssetCategoryIds(),
931 serviceContext.getAssetTagNames());
932 }
933
934
935
936 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
937 reindex(user);
938 }
939
940
941
942 long workflowUserId = creatorUserId;
943
944 if (workflowUserId == userId) {
945 workflowUserId = defaultUser.getUserId();
946 }
947
948 ServiceContext workflowServiceContext = serviceContext;
949
950 if (workflowServiceContext == null) {
951 workflowServiceContext = new ServiceContext();
952 }
953
954 workflowServiceContext.setAttribute("autoPassword", autoPassword);
955 workflowServiceContext.setAttribute("sendEmail", sendEmail);
956
957 startWorkflowInstance(
958 companyId, workflowUserId, userId, user, workflowServiceContext);
959
960 if (serviceContext != null) {
961 String passwordUnencrypted = (String)serviceContext.getAttribute(
962 "passwordUnencrypted");
963
964 if (Validator.isNotNull(passwordUnencrypted)) {
965 user.setPasswordUnencrypted(passwordUnencrypted);
966 }
967 }
968
969 return user;
970 }
971
972
996 public int authenticateByEmailAddress(
997 long companyId, String emailAddress, String password,
998 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
999 Map<String, Object> resultsMap)
1000 throws PortalException, SystemException {
1001
1002 return authenticate(
1003 companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
1004 headerMap, parameterMap, resultsMap);
1005 }
1006
1007
1031 public int authenticateByScreenName(
1032 long companyId, String screenName, String password,
1033 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1034 Map<String, Object> resultsMap)
1035 throws PortalException, SystemException {
1036
1037 return authenticate(
1038 companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
1039 headerMap, parameterMap, resultsMap);
1040 }
1041
1042
1066 public int authenticateByUserId(
1067 long companyId, long userId, String password,
1068 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1069 Map<String, Object> resultsMap)
1070 throws PortalException, SystemException {
1071
1072 return authenticate(
1073 companyId, String.valueOf(userId), password,
1074 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap, resultsMap);
1075 }
1076
1077
1117 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1118 public long authenticateForBasic(
1119 long companyId, String authType, String login, String password)
1120 throws PortalException, SystemException {
1121
1122 if (PropsValues.AUTH_LOGIN_DISABLED) {
1123 return 0;
1124 }
1125
1126 try {
1127 User user = null;
1128
1129 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1130 user = getUserByEmailAddress(companyId, login);
1131 }
1132 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1133 user = getUserByScreenName(companyId, login);
1134 }
1135 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1136 user = getUserById(companyId, GetterUtil.getLong(login));
1137 }
1138
1139 if (user.isDefaultUser()) {
1140 if (_log.isInfoEnabled()) {
1141 _log.info(
1142 "Basic authentication is disabled for the default " +
1143 "user");
1144 }
1145
1146 return 0;
1147 }
1148 else if (!user.isActive()) {
1149 if (_log.isInfoEnabled()) {
1150 _log.info(
1151 "Basic authentication is disabled for inactive user " +
1152 user.getUserId());
1153 }
1154
1155 return 0;
1156 }
1157
1158 if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
1159 return user.getUserId();
1160 }
1161
1162 String userPassword = user.getPassword();
1163
1164 if (!user.isPasswordEncrypted()) {
1165 userPassword = PasswordEncryptorUtil.encrypt(userPassword);
1166 }
1167
1168 String encPassword = PasswordEncryptorUtil.encrypt(
1169 password, userPassword);
1170
1171 if (userPassword.equals(password) ||
1172 userPassword.equals(encPassword)) {
1173
1174 return user.getUserId();
1175 }
1176 }
1177 catch (NoSuchUserException nsue) {
1178 }
1179
1180 return 0;
1181 }
1182
1183
1201 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1202 public long authenticateForDigest(
1203 long companyId, String username, String realm, String nonce,
1204 String method, String uri, String response)
1205 throws PortalException, SystemException {
1206
1207 if (PropsValues.AUTH_LOGIN_DISABLED) {
1208 return 0;
1209 }
1210
1211
1212
1213 User user = null;
1214
1215 try {
1216 user = getUserByEmailAddress(companyId, username);
1217 }
1218 catch (NoSuchUserException nsue) {
1219 }
1220
1221 if (user == null) {
1222 try {
1223 user = getUserByScreenName(companyId, username);
1224 }
1225 catch (NoSuchUserException nsue) {
1226 }
1227 }
1228
1229 if (user == null) {
1230 try {
1231 user = getUserById(GetterUtil.getLong(username));
1232 }
1233 catch (NoSuchUserException nsue) {
1234 return 0;
1235 }
1236 }
1237
1238 if (user.isDefaultUser()) {
1239 if (_log.isInfoEnabled()) {
1240 _log.info(
1241 "Digest authentication is disabled for the default user");
1242 }
1243
1244 return 0;
1245 }
1246 else if (!user.isActive()) {
1247 if (_log.isInfoEnabled()) {
1248 _log.info(
1249 "Digest authentication is disabled for inactive user " +
1250 user.getUserId());
1251 }
1252
1253 return 0;
1254 }
1255
1256
1257
1258 String digest = user.getDigest();
1259
1260 if (Validator.isNull(digest)) {
1261 _log.error(
1262 "User must first login through the portal " + user.getUserId());
1263
1264 return 0;
1265 }
1266
1267 String[] digestArray = StringUtil.split(user.getDigest());
1268
1269 for (String ha1 : digestArray) {
1270 String ha2 = DigesterUtil.digestHex(Digester.MD5, method, uri);
1271
1272 String curResponse = DigesterUtil.digestHex(
1273 Digester.MD5, ha1, nonce, ha2);
1274
1275 if (response.equals(curResponse)) {
1276 return user.getUserId();
1277 }
1278 }
1279
1280 return 0;
1281 }
1282
1283
1292 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1293 public boolean authenticateForJAAS(long userId, String encPassword) {
1294 if (PropsValues.AUTH_LOGIN_DISABLED) {
1295 return false;
1296 }
1297
1298 try {
1299 User user = userPersistence.findByPrimaryKey(userId);
1300
1301 if (user.isDefaultUser()) {
1302 if (_log.isInfoEnabled()) {
1303 _log.info(
1304 "JAAS authentication is disabled for the default user");
1305 }
1306
1307 return false;
1308 }
1309 else if (!user.isActive()) {
1310 if (_log.isInfoEnabled()) {
1311 _log.info(
1312 "JAAS authentication is disabled for inactive user " +
1313 userId);
1314 }
1315
1316 return false;
1317 }
1318
1319 String userPassword = user.getPassword();
1320
1321 if (user.isPasswordEncrypted()) {
1322 if (userPassword.equals(encPassword)) {
1323 return true;
1324 }
1325
1326 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1327 encPassword = PasswordEncryptorUtil.encrypt(
1328 encPassword, userPassword);
1329
1330 if (userPassword.equals(encPassword)) {
1331 return true;
1332 }
1333 }
1334 }
1335 else {
1336 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1337 if (userPassword.equals(encPassword)) {
1338 return true;
1339 }
1340 }
1341
1342 userPassword = PasswordEncryptorUtil.encrypt(
1343 userPassword, encPassword);
1344
1345 if (userPassword.equals(encPassword)) {
1346 return true;
1347 }
1348 }
1349 }
1350 catch (Exception e) {
1351 _log.error(e);
1352 }
1353
1354 return false;
1355 }
1356
1357
1365 public void checkLockout(User user)
1366 throws PortalException, SystemException {
1367
1368 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1369 return;
1370 }
1371
1372 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1373
1374 if (passwordPolicy.isLockout()) {
1375
1376
1377
1378 Date now = new Date();
1379 int failedLoginAttempts = user.getFailedLoginAttempts();
1380
1381 if (failedLoginAttempts > 0) {
1382 long failedLoginTime = user.getLastFailedLoginDate().getTime();
1383 long elapsedTime = now.getTime() - failedLoginTime;
1384 long requiredElapsedTime =
1385 passwordPolicy.getResetFailureCount() * 1000;
1386
1387 if ((requiredElapsedTime != 0) &&
1388 (elapsedTime > requiredElapsedTime)) {
1389
1390 user.setLastFailedLoginDate(null);
1391 user.setFailedLoginAttempts(0);
1392
1393 userPersistence.update(user);
1394 }
1395 }
1396
1397
1398
1399 if (user.isLockout()) {
1400 long lockoutTime = user.getLockoutDate().getTime();
1401 long elapsedTime = now.getTime() - lockoutTime;
1402 long requiredElapsedTime =
1403 passwordPolicy.getLockoutDuration() * 1000;
1404
1405 if ((requiredElapsedTime != 0) &&
1406 (elapsedTime > requiredElapsedTime)) {
1407
1408 user.setLockout(false);
1409 user.setLockoutDate(null);
1410
1411 userPersistence.update(user);
1412 }
1413 }
1414
1415 if (user.isLockout()) {
1416 throw new UserLockoutException();
1417 }
1418 }
1419 }
1420
1421
1428 public void checkLoginFailure(User user) throws SystemException {
1429 Date now = new Date();
1430
1431 int failedLoginAttempts = user.getFailedLoginAttempts();
1432
1433 user.setLastFailedLoginDate(now);
1434 user.setFailedLoginAttempts(++failedLoginAttempts);
1435
1436 userPersistence.update(user);
1437 }
1438
1439
1449 public void checkLoginFailureByEmailAddress(
1450 long companyId, String emailAddress)
1451 throws PortalException, SystemException {
1452
1453 User user = getUserByEmailAddress(companyId, emailAddress);
1454
1455 checkLoginFailure(user);
1456 }
1457
1458
1466 public void checkLoginFailureById(long userId)
1467 throws PortalException, SystemException {
1468
1469 User user = userPersistence.findByPrimaryKey(userId);
1470
1471 checkLoginFailure(user);
1472 }
1473
1474
1483 public void checkLoginFailureByScreenName(long companyId, String screenName)
1484 throws PortalException, SystemException {
1485
1486 User user = getUserByScreenName(companyId, screenName);
1487
1488 checkLoginFailure(user);
1489 }
1490
1491
1501 public void checkPasswordExpired(User user)
1502 throws PortalException, SystemException {
1503
1504 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1505 return;
1506 }
1507
1508 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1509
1510
1511
1512 if (isPasswordExpired(user)) {
1513 int graceLoginCount = user.getGraceLoginCount();
1514
1515 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
1516 user.setGraceLoginCount(++graceLoginCount);
1517
1518 userPersistence.update(user);
1519 }
1520 else {
1521 user.setDigest(StringPool.BLANK);
1522
1523 userPersistence.update(user);
1524
1525 throw new PasswordExpiredException();
1526 }
1527 }
1528
1529
1530
1531 if (passwordPolicy.isChangeable() &&
1532 passwordPolicy.isChangeRequired()) {
1533
1534 if (user.getLastLoginDate() == null) {
1535 user.setPasswordReset(true);
1536
1537 userPersistence.update(user);
1538 }
1539 }
1540 }
1541
1542
1548 @Override
1549 public void clearOrganizationUsers(long organizationId)
1550 throws SystemException {
1551
1552 organizationPersistence.clearUsers(organizationId);
1553
1554 PermissionCacheUtil.clearCache();
1555 }
1556
1557
1563 @Override
1564 public void clearUserGroupUsers(long userGroupId) throws SystemException {
1565 userGroupPersistence.clearUsers(userGroupId);
1566
1567 PermissionCacheUtil.clearCache();
1568 }
1569
1570
1583 public void completeUserRegistration(
1584 User user, ServiceContext serviceContext)
1585 throws PortalException, SystemException {
1586
1587 boolean autoPassword = ParamUtil.getBoolean(
1588 serviceContext, "autoPassword");
1589
1590 String password = null;
1591
1592 if (autoPassword) {
1593 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1594 if (_log.isWarnEnabled()) {
1595 StringBundler sb = new StringBundler(4);
1596
1597 sb.append("When LDAP password policy is enabled, it is ");
1598 sb.append("possible that portal generated passwords will ");
1599 sb.append("not match the LDAP policy. Using ");
1600 sb.append("RegExpToolkit to generate new password.");
1601
1602 _log.warn(sb.toString());
1603 }
1604
1605 RegExpToolkit regExpToolkit = new RegExpToolkit();
1606
1607 password = regExpToolkit.generate(null);
1608 }
1609 else {
1610 PasswordPolicy passwordPolicy =
1611 passwordPolicyLocalService.getPasswordPolicy(
1612 user.getCompanyId(), user.getOrganizationIds());
1613
1614 password = PwdToolkitUtil.generate(passwordPolicy);
1615 }
1616
1617 user.setPassword(PasswordEncryptorUtil.encrypt(password));
1618 user.setPasswordEncrypted(true);
1619 user.setPasswordUnencrypted(password);
1620
1621 userPersistence.update(user);
1622 }
1623
1624 if (user.hasCompanyMx()) {
1625 String mailPassword = password;
1626
1627 if (Validator.isNull(mailPassword)) {
1628 mailPassword = user.getPasswordUnencrypted();
1629 }
1630
1631 mailService.addUser(
1632 user.getCompanyId(), user.getUserId(), mailPassword,
1633 user.getFirstName(), user.getMiddleName(), user.getLastName(),
1634 user.getEmailAddress());
1635 }
1636
1637 boolean sendEmail = ParamUtil.getBoolean(serviceContext, "sendEmail");
1638
1639 if (sendEmail) {
1640 sendEmail(user, password, serviceContext);
1641 }
1642
1643 Company company = companyPersistence.findByPrimaryKey(
1644 user.getCompanyId());
1645
1646 if (company.isStrangersVerify() && (serviceContext.getPlid() > 0)) {
1647 sendEmailAddressVerification(
1648 user, user.getEmailAddress(), serviceContext);
1649 }
1650 }
1651
1652
1665 public KeyValuePair decryptUserId(
1666 long companyId, String name, String password)
1667 throws PortalException, SystemException {
1668
1669 Company company = companyPersistence.findByPrimaryKey(companyId);
1670
1671 try {
1672 name = Encryptor.decrypt(company.getKeyObj(), name);
1673 }
1674 catch (EncryptorException ee) {
1675 throw new SystemException(ee);
1676 }
1677
1678 long userId = GetterUtil.getLong(name);
1679
1680 User user = userPersistence.findByPrimaryKey(userId);
1681
1682 try {
1683 password = Encryptor.decrypt(company.getKeyObj(), password);
1684 }
1685 catch (EncryptorException ee) {
1686 throw new SystemException(ee);
1687 }
1688
1689 String userPassword = user.getPassword();
1690 String encPassword = PasswordEncryptorUtil.encrypt(
1691 password, userPassword);
1692
1693 if (userPassword.equals(encPassword)) {
1694 if (isPasswordExpired(user)) {
1695 user.setPasswordReset(true);
1696
1697 userPersistence.update(user);
1698 }
1699
1700 return new KeyValuePair(name, password);
1701 }
1702 else {
1703 throw new PrincipalException();
1704 }
1705 }
1706
1707
1715 public void deletePortrait(long userId)
1716 throws PortalException, SystemException {
1717
1718 User user = userPersistence.findByPrimaryKey(userId);
1719
1720 long portraitId = user.getPortraitId();
1721
1722 if (portraitId > 0) {
1723 user.setPortraitId(0);
1724
1725 userPersistence.update(user);
1726
1727 imageLocalService.deleteImage(portraitId);
1728 }
1729 }
1730
1731
1740 @Override
1741 public void deleteRoleUser(long roleId, long userId)
1742 throws PortalException, SystemException {
1743
1744 rolePersistence.removeUser(roleId, userId);
1745
1746 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1747
1748 indexer.reindex(userId);
1749
1750 PermissionCacheUtil.clearCache();
1751 }
1752
1753
1761 @Override
1762 public User deleteUser(long userId)
1763 throws PortalException, SystemException {
1764
1765 User user = userPersistence.findByPrimaryKey(userId);
1766
1767 return deleteUser(user);
1768 }
1769
1770
1778 @Override
1779 public User deleteUser(User user) throws PortalException, SystemException {
1780 if (!PropsValues.USERS_DELETE) {
1781 throw new RequiredUserException();
1782 }
1783
1784
1785
1786 browserTrackerLocalService.deleteUserBrowserTracker(user.getUserId());
1787
1788
1789
1790 Group group = user.getGroup();
1791
1792 if (group != null) {
1793 groupLocalService.deleteGroup(group);
1794 }
1795
1796
1797
1798 try {
1799 imageLocalService.deleteImage(user.getPortraitId());
1800 }
1801 catch (NoSuchImageException e) {
1802 if (_log.isWarnEnabled()) {
1803 _log.warn("Unable to delete image " + user.getPortraitId());
1804 }
1805 }
1806
1807
1808
1809 passwordPolicyRelLocalService.deletePasswordPolicyRel(
1810 User.class.getName(), user.getUserId());
1811
1812
1813
1814 passwordTrackerLocalService.deletePasswordTrackers(user.getUserId());
1815
1816
1817
1818 subscriptionLocalService.deleteSubscriptions(user.getUserId());
1819
1820
1821
1822 userIdMapperLocalService.deleteUserIdMappers(user.getUserId());
1823
1824
1825
1826 announcementsDeliveryLocalService.deleteDeliveries(user.getUserId());
1827
1828
1829
1830 assetEntryLocalService.deleteEntry(
1831 User.class.getName(), user.getUserId());
1832
1833
1834
1835 blogsStatsUserLocalService.deleteStatsUserByUserId(user.getUserId());
1836
1837
1838
1839 dlFileRankLocalService.deleteFileRanksByUserId(user.getUserId());
1840
1841
1842
1843 expandoValueLocalService.deleteValues(
1844 User.class.getName(), user.getUserId());
1845
1846
1847
1848 mbBanLocalService.deleteBansByBanUserId(user.getUserId());
1849 mbStatsUserLocalService.deleteStatsUsersByUserId(user.getUserId());
1850 mbThreadFlagLocalService.deleteThreadFlagsByUserId(user.getUserId());
1851
1852
1853
1854 membershipRequestLocalService.deleteMembershipRequestsByUserId(
1855 user.getUserId());
1856
1857
1858
1859 shoppingCartLocalService.deleteUserCarts(user.getUserId());
1860
1861
1862
1863 socialActivityLocalService.deleteUserActivities(user.getUserId());
1864 socialRequestLocalService.deleteReceiverUserRequests(user.getUserId());
1865 socialRequestLocalService.deleteUserRequests(user.getUserId());
1866
1867
1868
1869 mailService.deleteUser(user.getCompanyId(), user.getUserId());
1870
1871
1872
1873 try {
1874 contactLocalService.deleteContact(user.getContactId());
1875 }
1876 catch (NoSuchContactException nsce) {
1877 }
1878
1879
1880
1881 resourceLocalService.deleteResource(
1882 user.getCompanyId(), User.class.getName(),
1883 ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
1884
1885
1886
1887 userGroupRoleLocalService.deleteUserGroupRolesByUserId(
1888 user.getUserId());
1889
1890
1891
1892 userPersistence.remove(user);
1893
1894
1895
1896 PermissionCacheUtil.clearCache();
1897
1898
1899
1900 workflowInstanceLinkLocalService.deleteWorkflowInstanceLinks(
1901 user.getCompanyId(), 0, User.class.getName(), user.getUserId());
1902
1903 return user;
1904 }
1905
1906
1914 @Override
1915 public void deleteUserGroupUser(long userGroupId, long userId)
1916 throws PortalException, SystemException {
1917
1918 userGroupPersistence.removeUser(userGroupId, userId);
1919
1920 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1921
1922 indexer.reindex(userId);
1923
1924 PermissionCacheUtil.clearCache();
1925 }
1926
1927
1936 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1937 public String encryptUserId(String name)
1938 throws PortalException, SystemException {
1939
1940 long userId = GetterUtil.getLong(name);
1941
1942 User user = userPersistence.findByPrimaryKey(userId);
1943
1944 Company company = companyPersistence.findByPrimaryKey(
1945 user.getCompanyId());
1946
1947 try {
1948 return Encryptor.encrypt(company.getKeyObj(), name);
1949 }
1950 catch (EncryptorException ee) {
1951 throw new SystemException(ee);
1952 }
1953 }
1954
1955
1964 public User fetchUserByEmailAddress(long companyId, String emailAddress)
1965 throws SystemException {
1966
1967 return userPersistence.fetchByC_EA(companyId, emailAddress);
1968 }
1969
1970
1978 public User fetchUserById(long userId) throws SystemException {
1979 return userPersistence.fetchByPrimaryKey(userId);
1980 }
1981
1982
1991 public User fetchUserByScreenName(long companyId, String screenName)
1992 throws SystemException {
1993
1994 screenName = getScreenName(screenName);
1995
1996 return userPersistence.fetchByC_SN(companyId, screenName);
1997 }
1998
1999
2018 public List<User> getCompanyUsers(long companyId, int start, int end)
2019 throws SystemException {
2020
2021 return userPersistence.findByCompanyId(companyId, start, end);
2022 }
2023
2024
2031 public int getCompanyUsersCount(long companyId) throws SystemException {
2032 return userPersistence.countByCompanyId(companyId);
2033 }
2034
2035
2044 @Skip
2045 public User getDefaultUser(long companyId)
2046 throws PortalException, SystemException {
2047
2048 User userModel = _defaultUsers.get(companyId);
2049
2050 if (userModel == null) {
2051 userModel = userLocalService.loadGetDefaultUser(companyId);
2052
2053 _defaultUsers.put(companyId, userModel);
2054 }
2055
2056 return userModel;
2057 }
2058
2059
2068 @Skip
2069 public long getDefaultUserId(long companyId)
2070 throws PortalException, SystemException {
2071
2072 User user = getDefaultUser(companyId);
2073
2074 return user.getUserId();
2075 }
2076
2077
2084 public long[] getGroupUserIds(long groupId) throws SystemException {
2085 return getUserIds(getGroupUsers(groupId));
2086 }
2087
2088
2098 public int getGroupUsersCount(long groupId, int status)
2099 throws PortalException, SystemException {
2100
2101 Group group = groupPersistence.findByPrimaryKey(groupId);
2102
2103 LinkedHashMap<String, Object> params =
2104 new LinkedHashMap<String, Object>();
2105
2106 params.put("usersGroups", new Long(groupId));
2107
2108 return searchCount(group.getCompanyId(), null, status, params);
2109 }
2110
2111
2119 public List<User> getNoAnnouncementsDeliveries(String type)
2120 throws SystemException {
2121
2122 return userFinder.findByNoAnnouncementsDeliveries(type);
2123 }
2124
2125
2131 public List<User> getNoContacts() throws SystemException {
2132 return userFinder.findByNoContacts();
2133 }
2134
2135
2142 public List<User> getNoGroups() throws SystemException {
2143 return userFinder.findByNoGroups();
2144 }
2145
2146
2153 public long[] getOrganizationUserIds(long organizationId)
2154 throws SystemException {
2155
2156 return getUserIds(getOrganizationUsers(organizationId));
2157 }
2158
2159
2170 public int getOrganizationUsersCount(long organizationId, int status)
2171 throws PortalException, SystemException {
2172
2173 Organization organization = organizationPersistence.findByPrimaryKey(
2174 organizationId);
2175
2176 LinkedHashMap<String, Object> params =
2177 new LinkedHashMap<String, Object>();
2178
2179 params.put("usersOrgs", new Long(organizationId));
2180
2181 return searchCount(organization.getCompanyId(), null, status, params);
2182 }
2183
2184
2191 public long[] getRoleUserIds(long roleId) throws SystemException {
2192 return getUserIds(getRoleUsers(roleId));
2193 }
2194
2195
2205 public int getRoleUsersCount(long roleId, int status)
2206 throws PortalException, SystemException {
2207
2208 Role role = rolePersistence.findByPrimaryKey(roleId);
2209
2210 LinkedHashMap<String, Object> params =
2211 new LinkedHashMap<String, Object>();
2212
2213 params.put("usersRoles", new Long(roleId));
2214
2215 return searchCount(role.getCompanyId(), null, status, params);
2216 }
2217
2218
2245 public List<User> getSocialUsers(
2246 long userId, int type, int start, int end, OrderByComparator obc)
2247 throws PortalException, SystemException {
2248
2249 User user = userPersistence.findByPrimaryKey(userId);
2250
2251 LinkedHashMap<String, Object> params =
2252 new LinkedHashMap<String, Object>();
2253
2254 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2255
2256 return search(
2257 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2258 params, start, end, obc);
2259 }
2260
2261
2284 public List<User> getSocialUsers(
2285 long userId, int start, int end, OrderByComparator obc)
2286 throws PortalException, SystemException {
2287
2288 User user = userPersistence.findByPrimaryKey(userId);
2289
2290 LinkedHashMap<String, Object> params =
2291 new LinkedHashMap<String, Object>();
2292
2293 params.put("socialRelation", new Long[] {userId});
2294
2295 return search(
2296 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2297 params, start, end, obc);
2298 }
2299
2300
2328 public List<User> getSocialUsers(
2329 long userId1, long userId2, int type, int start, int end,
2330 OrderByComparator obc)
2331 throws PortalException, SystemException {
2332
2333 User user1 = userPersistence.findByPrimaryKey(userId1);
2334
2335 LinkedHashMap<String, Object> params =
2336 new LinkedHashMap<String, Object>();
2337
2338 params.put(
2339 "socialMutualRelationType",
2340 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2341
2342 return search(
2343 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2344 params, start, end, obc);
2345 }
2346
2347
2372 public List<User> getSocialUsers(
2373 long userId1, long userId2, int start, int end,
2374 OrderByComparator obc)
2375 throws PortalException, SystemException {
2376
2377 User user1 = userPersistence.findByPrimaryKey(userId1);
2378
2379 LinkedHashMap<String, Object> params =
2380 new LinkedHashMap<String, Object>();
2381
2382 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2383
2384 return search(
2385 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2386 params, start, end, obc);
2387 }
2388
2389
2397 public int getSocialUsersCount(long userId)
2398 throws PortalException, SystemException {
2399
2400 User user = userPersistence.findByPrimaryKey(userId);
2401
2402 LinkedHashMap<String, Object> params =
2403 new LinkedHashMap<String, Object>();
2404
2405 params.put("socialRelation", new Long[] {userId});
2406
2407 return searchCount(
2408 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2409 params);
2410 }
2411
2412
2425 public int getSocialUsersCount(long userId, int type)
2426 throws PortalException, SystemException {
2427
2428 User user = userPersistence.findByPrimaryKey(userId);
2429
2430 LinkedHashMap<String, Object> params =
2431 new LinkedHashMap<String, Object>();
2432
2433 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2434
2435 return searchCount(
2436 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2437 params);
2438 }
2439
2440
2450 public int getSocialUsersCount(long userId1, long userId2)
2451 throws PortalException, SystemException {
2452
2453 User user1 = userPersistence.findByPrimaryKey(userId1);
2454
2455 LinkedHashMap<String, Object> params =
2456 new LinkedHashMap<String, Object>();
2457
2458 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2459
2460 return searchCount(
2461 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2462 params);
2463 }
2464
2465
2479 public int getSocialUsersCount(long userId1, long userId2, int type)
2480 throws PortalException, SystemException {
2481
2482 User user1 = userPersistence.findByPrimaryKey(userId1);
2483
2484 LinkedHashMap<String, Object> params =
2485 new LinkedHashMap<String, Object>();
2486
2487 params.put(
2488 "socialMutualRelationType",
2489 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2490
2491 return searchCount(
2492 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2493 params);
2494 }
2495
2496
2504 public User getUserByContactId(long contactId)
2505 throws PortalException, SystemException {
2506
2507 return userPersistence.findByContactId(contactId);
2508 }
2509
2510
2520 public User getUserByEmailAddress(long companyId, String emailAddress)
2521 throws PortalException, SystemException {
2522
2523 emailAddress = emailAddress.trim().toLowerCase();
2524
2525 return userPersistence.findByC_EA(companyId, emailAddress);
2526 }
2527
2528
2537 public User getUserByFacebookId(long companyId, long facebookId)
2538 throws PortalException, SystemException {
2539
2540 return userPersistence.findByC_FID(companyId, facebookId);
2541 }
2542
2543
2551 public User getUserById(long userId)
2552 throws PortalException, SystemException {
2553
2554 return userPersistence.findByPrimaryKey(userId);
2555 }
2556
2557
2567 public User getUserById(long companyId, long userId)
2568 throws PortalException, SystemException {
2569
2570 return userPersistence.findByC_U(companyId, userId);
2571 }
2572
2573
2582 public User getUserByOpenId(long companyId, String openId)
2583 throws PortalException, SystemException {
2584
2585 return userPersistence.findByC_O(companyId, openId);
2586 }
2587
2588
2596 public User getUserByPortraitId(long portraitId)
2597 throws PortalException, SystemException {
2598
2599 return userPersistence.findByPortraitId(portraitId);
2600 }
2601
2602
2611 public User getUserByScreenName(long companyId, String screenName)
2612 throws PortalException, SystemException {
2613
2614 screenName = getScreenName(screenName);
2615
2616 return userPersistence.findByC_SN(companyId, screenName);
2617 }
2618
2619
2629 public User getUserByUuid(String uuid)
2630 throws PortalException, SystemException {
2631
2632 List<User> users = userPersistence.findByUuid(uuid);
2633
2634 if (users.isEmpty()) {
2635 throw new NoSuchUserException();
2636 }
2637 else {
2638 return users.get(0);
2639 }
2640 }
2641
2642
2651 public User getUserByUuidAndCompanyId(String uuid, long companyId)
2652 throws PortalException, SystemException {
2653
2654 List<User> users = userPersistence.findByUuid_C(uuid, companyId);
2655
2656 if (users.isEmpty()) {
2657 throw new NoSuchUserException();
2658 }
2659 else {
2660 return users.get(0);
2661 }
2662 }
2663
2664
2674 public int getUserGroupUsersCount(long userGroupId, int status)
2675 throws PortalException, SystemException {
2676
2677 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
2678 userGroupId);
2679
2680 LinkedHashMap<String, Object> params =
2681 new LinkedHashMap<String, Object>();
2682
2683 params.put("usersUserGroups", new Long(userGroupId));
2684
2685 return searchCount(userGroup.getCompanyId(), null, status, params);
2686 }
2687
2688
2698 public long getUserIdByEmailAddress(long companyId, String emailAddress)
2699 throws PortalException, SystemException {
2700
2701 emailAddress = emailAddress.trim().toLowerCase();
2702
2703 User user = userPersistence.findByC_EA(companyId, emailAddress);
2704
2705 return user.getUserId();
2706 }
2707
2708
2717 public long getUserIdByScreenName(long companyId, String screenName)
2718 throws PortalException, SystemException {
2719
2720 screenName = getScreenName(screenName);
2721
2722 User user = userPersistence.findByC_SN(companyId, screenName);
2723
2724 return user.getUserId();
2725 }
2726
2727
2737 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
2738 throws SystemException {
2739
2740 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
2741 passwordPolicyId, User.class.getName(), userId);
2742 }
2743
2744
2759 public boolean hasRoleUser(
2760 long companyId, String name, long userId, boolean inherited)
2761 throws PortalException, SystemException {
2762
2763 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
2764 }
2765
2766
2776 public boolean isPasswordExpired(User user)
2777 throws PortalException, SystemException {
2778
2779 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2780
2781 if ((passwordPolicy != null) && passwordPolicy.getExpireable()) {
2782 Date now = new Date();
2783
2784 if (user.getPasswordModifiedDate() == null) {
2785 user.setPasswordModifiedDate(now);
2786
2787 userLocalService.updateUser(user);
2788 }
2789
2790 long passwordStartTime = user.getPasswordModifiedDate().getTime();
2791 long elapsedTime = now.getTime() - passwordStartTime;
2792
2793 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
2794 return true;
2795 }
2796 else {
2797 return false;
2798 }
2799 }
2800
2801 return false;
2802 }
2803
2804
2816 public boolean isPasswordExpiringSoon(User user)
2817 throws PortalException, SystemException {
2818
2819 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2820
2821 if ((passwordPolicy != null) && passwordPolicy.isExpireable() &&
2822 (passwordPolicy.getWarningTime() > 0)) {
2823
2824 Date now = new Date();
2825
2826 if (user.getPasswordModifiedDate() == null) {
2827 user.setPasswordModifiedDate(now);
2828
2829 userLocalService.updateUser(user);
2830 }
2831
2832 long timeModified = user.getPasswordModifiedDate().getTime();
2833 long passwordExpiresOn =
2834 (passwordPolicy.getMaxAge() * 1000) + timeModified;
2835
2836 long timeStartWarning =
2837 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
2838
2839 if (now.getTime() > timeStartWarning) {
2840 return true;
2841 }
2842 else {
2843 return false;
2844 }
2845 }
2846
2847 return false;
2848 }
2849
2850
2858 public User loadGetDefaultUser(long companyId)
2859 throws PortalException, SystemException {
2860
2861 return userPersistence.findByC_DU(companyId, true);
2862 }
2863
2864
2896 public List<User> search(
2897 long companyId, String keywords, int status,
2898 LinkedHashMap<String, Object> params, int start, int end,
2899 OrderByComparator obc)
2900 throws SystemException {
2901
2902 return userFinder.findByKeywords(
2903 companyId, keywords, status, params, start, end, obc);
2904 }
2905
2906
2937 public Hits search(
2938 long companyId, String keywords, int status,
2939 LinkedHashMap<String, Object> params, int start, int end, Sort sort)
2940 throws SystemException {
2941
2942 String firstName = null;
2943 String middleName = null;
2944 String lastName = null;
2945 String fullName = null;
2946 String screenName = null;
2947 String emailAddress = null;
2948 String street = null;
2949 String city = null;
2950 String zip = null;
2951 String region = null;
2952 String country = null;
2953 boolean andOperator = false;
2954
2955 if (Validator.isNotNull(keywords)) {
2956 firstName = keywords;
2957 middleName = keywords;
2958 lastName = keywords;
2959 fullName = keywords;
2960 screenName = keywords;
2961 emailAddress = keywords;
2962 street = keywords;
2963 city = keywords;
2964 zip = keywords;
2965 region = keywords;
2966 country = keywords;
2967 }
2968 else {
2969 andOperator = true;
2970 }
2971
2972 if (params != null) {
2973 params.put("keywords", keywords);
2974 }
2975
2976 return search(
2977 companyId, firstName, middleName, lastName, fullName, screenName,
2978 emailAddress, street, city, zip, region, country, status, params,
2979 andOperator, start, end, sort);
2980 }
2981
2982
3022 public List<User> search(
3023 long companyId, String firstName, String middleName,
3024 String lastName, String screenName, String emailAddress, int status,
3025 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3026 int end, OrderByComparator obc)
3027 throws SystemException {
3028
3029 return userFinder.findByC_FN_MN_LN_SN_EA_S(
3030 companyId, firstName, middleName, lastName, screenName,
3031 emailAddress, status, params, andSearch, start, end, obc);
3032 }
3033
3034
3073 public Hits search(
3074 long companyId, String firstName, String middleName,
3075 String lastName, String screenName, String emailAddress, int status,
3076 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3077 int end, Sort sort)
3078 throws SystemException {
3079
3080 return search(
3081 companyId, firstName, middleName, lastName, null, screenName,
3082 emailAddress, null, null, null, null, null, status, params,
3083 andSearch, start, end, sort);
3084 }
3085
3086
3100 public int searchCount(
3101 long companyId, String keywords, int status,
3102 LinkedHashMap<String, Object> params)
3103 throws SystemException {
3104
3105 return userFinder.countByKeywords(companyId, keywords, status, params);
3106 }
3107
3108
3130 public int searchCount(
3131 long companyId, String firstName, String middleName,
3132 String lastName, String screenName, String emailAddress, int status,
3133 LinkedHashMap<String, Object> params, boolean andSearch)
3134 throws SystemException {
3135
3136 return userFinder.countByC_FN_MN_LN_SN_EA_S(
3137 companyId, firstName, middleName, lastName, screenName,
3138 emailAddress, status, params, andSearch);
3139 }
3140
3141
3152 public void sendEmailAddressVerification(
3153 User user, String emailAddress, ServiceContext serviceContext)
3154 throws PortalException, SystemException {
3155
3156 if (user.isEmailAddressVerified() &&
3157 emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
3158
3159 return;
3160 }
3161
3162 Ticket ticket = ticketLocalService.addTicket(
3163 user.getCompanyId(), User.class.getName(), user.getUserId(),
3164 TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3165 serviceContext);
3166
3167 String verifyEmailAddressURL =
3168 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3169 "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3170
3171 Layout layout = layoutLocalService.getLayout(serviceContext.getPlid());
3172
3173 Group group = layout.getGroup();
3174
3175 if (!layout.isPrivateLayout() && !group.isUser()) {
3176 verifyEmailAddressURL += "&p_l_id=" + serviceContext.getPlid();
3177 }
3178
3179 String fromName = PrefsPropsUtil.getString(
3180 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3181 String fromAddress = PrefsPropsUtil.getString(
3182 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3183
3184 String toName = user.getFullName();
3185 String toAddress = emailAddress;
3186
3187 String subject = PrefsPropsUtil.getContent(
3188 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3189
3190 String body = PrefsPropsUtil.getContent(
3191 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3192
3193 SubscriptionSender subscriptionSender = new SubscriptionSender();
3194
3195 subscriptionSender.setBody(body);
3196 subscriptionSender.setCompanyId(user.getCompanyId());
3197 subscriptionSender.setContextAttributes(
3198 "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3199 "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3200 "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3201 "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_ID$]",
3202 user.getUserId(), "[$USER_SCREENNAME$]", user.getScreenName());
3203 subscriptionSender.setFrom(fromAddress, fromName);
3204 subscriptionSender.setHtmlFormat(true);
3205 subscriptionSender.setMailId("user", user.getUserId());
3206 subscriptionSender.setServiceContext(serviceContext);
3207 subscriptionSender.setSubject(subject);
3208 subscriptionSender.setUserId(user.getUserId());
3209
3210 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3211
3212 subscriptionSender.flushNotificationsAsync();
3213 }
3214
3215
3234 public void sendPassword(
3235 long companyId, String emailAddress, String fromName,
3236 String fromAddress, String subject, String body,
3237 ServiceContext serviceContext)
3238 throws PortalException, SystemException {
3239
3240 Company company = companyPersistence.findByPrimaryKey(companyId);
3241
3242 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3243 return;
3244 }
3245
3246 emailAddress = emailAddress.trim().toLowerCase();
3247
3248 if (Validator.isNull(emailAddress)) {
3249 throw new UserEmailAddressException();
3250 }
3251
3252 User user = userPersistence.findByC_EA(companyId, emailAddress);
3253
3254 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3255
3256 String newPassword = StringPool.BLANK;
3257 String passwordResetURL = StringPool.BLANK;
3258
3259 if (company.isSendPasswordResetLink()) {
3260 Date expirationDate = null;
3261
3262 if ((passwordPolicy != null) &&
3263 (passwordPolicy.getResetTicketMaxAge() > 0)) {
3264
3265 expirationDate = new Date(
3266 System.currentTimeMillis() +
3267 (passwordPolicy.getResetTicketMaxAge() * 1000));
3268 }
3269
3270 Ticket ticket = ticketLocalService.addTicket(
3271 companyId, User.class.getName(), user.getUserId(),
3272 TicketConstants.TYPE_PASSWORD, null, expirationDate,
3273 serviceContext);
3274
3275 passwordResetURL =
3276 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3277 "/portal/update_password?p_l_id="+
3278 serviceContext.getPlid() +
3279 "&ticketKey=" + ticket.getKey();
3280 }
3281 else {
3282 if (!PasswordEncryptorUtil.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
3283 PasswordEncryptorUtil.TYPE_NONE)) {
3284
3285 if (LDAPSettingsUtil.isPasswordPolicyEnabled(
3286 user.getCompanyId())) {
3287
3288 if (_log.isWarnEnabled()) {
3289 StringBundler sb = new StringBundler(5);
3290
3291 sb.append("When LDAP password policy is enabled, ");
3292 sb.append("it is possible that portal generated ");
3293 sb.append("passwords will not match the LDAP policy.");
3294 sb.append("Using RegExpToolkit to generate new ");
3295 sb.append("password.");
3296
3297 _log.warn(sb.toString());
3298 }
3299
3300 RegExpToolkit regExpToolkit = new RegExpToolkit();
3301
3302 newPassword = regExpToolkit.generate(null);
3303 }
3304 else {
3305 newPassword = PwdToolkitUtil.generate(passwordPolicy);
3306 }
3307
3308 boolean passwordReset = false;
3309
3310 if (passwordPolicy.getChangeable() &&
3311 passwordPolicy.getChangeRequired()) {
3312
3313 passwordReset = true;
3314 }
3315
3316 user.setPassword(PasswordEncryptorUtil.encrypt(newPassword));
3317 user.setPasswordUnencrypted(newPassword);
3318 user.setPasswordEncrypted(true);
3319 user.setPasswordReset(passwordReset);
3320 user.setPasswordModified(true);
3321 user.setPasswordModifiedDate(new Date());
3322
3323 userPersistence.update(user);
3324
3325 user.setPasswordModified(false);
3326 }
3327 else {
3328 newPassword = user.getPassword();
3329 }
3330 }
3331
3332 if (Validator.isNull(fromName)) {
3333 fromName = PrefsPropsUtil.getString(
3334 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3335 }
3336
3337 if (Validator.isNull(fromAddress)) {
3338 fromAddress = PrefsPropsUtil.getString(
3339 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3340 }
3341
3342 String toName = user.getFullName();
3343 String toAddress = user.getEmailAddress();
3344
3345 if (Validator.isNull(subject)) {
3346 if (company.isSendPasswordResetLink()) {
3347 subject = PrefsPropsUtil.getContent(
3348 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
3349 }
3350 else {
3351 subject = PrefsPropsUtil.getContent(
3352 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
3353 }
3354 }
3355
3356 if (Validator.isNull(body)) {
3357 if (company.isSendPasswordResetLink()) {
3358 body = PrefsPropsUtil.getContent(
3359 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
3360 }
3361 else {
3362 body = PrefsPropsUtil.getContent(
3363 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
3364 }
3365 }
3366
3367 SubscriptionSender subscriptionSender = new SubscriptionSender();
3368
3369 subscriptionSender.setBody(body);
3370 subscriptionSender.setCompanyId(companyId);
3371 subscriptionSender.setContextAttributes(
3372 "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
3373 serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
3374 serviceContext.getRemoteHost(), "[$USER_ID$]", user.getUserId(),
3375 "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
3376 user.getScreenName());
3377 subscriptionSender.setFrom(fromAddress, fromName);
3378 subscriptionSender.setHtmlFormat(true);
3379 subscriptionSender.setMailId("user", user.getUserId());
3380 subscriptionSender.setServiceContext(serviceContext);
3381 subscriptionSender.setSubject(subject);
3382 subscriptionSender.setUserId(user.getUserId());
3383
3384 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3385
3386 subscriptionSender.flushNotificationsAsync();
3387 }
3388
3389
3398 @Override
3399 public void setRoleUsers(long roleId, long[] userIds)
3400 throws PortalException, SystemException {
3401
3402 rolePersistence.setUsers(roleId, userIds);
3403
3404 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3405
3406 indexer.reindex(userIds);
3407
3408 PermissionCacheUtil.clearCache();
3409 }
3410
3411
3420 @Override
3421 @SuppressWarnings("deprecation")
3422 public void setUserGroupUsers(long userGroupId, long[] userIds)
3423 throws PortalException, SystemException {
3424
3425 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3426 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3427 }
3428
3429 userGroupPersistence.setUsers(userGroupId, userIds);
3430
3431 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3432
3433 indexer.reindex(userIds);
3434
3435 PermissionCacheUtil.clearCache();
3436 }
3437
3438
3446 public void unsetGroupTeamsUsers(long groupId, long[] userIds)
3447 throws PortalException, SystemException {
3448
3449 List<Team> teams = teamPersistence.findByGroupId(groupId);
3450
3451 for (Team team : teams) {
3452 unsetTeamUsers(team.getTeamId(), userIds);
3453 }
3454
3455 PermissionCacheUtil.clearCache();
3456 }
3457
3458
3468 public void unsetGroupUsers(
3469 long groupId, long[] userIds, ServiceContext serviceContext)
3470 throws PortalException, SystemException {
3471
3472 userGroupRoleLocalService.deleteUserGroupRoles(
3473 userIds, groupId, RoleConstants.TYPE_SITE);
3474
3475 userLocalService.unsetGroupTeamsUsers(groupId, userIds);
3476
3477 groupPersistence.removeUsers(groupId, userIds);
3478
3479 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3480
3481 indexer.reindex(userIds);
3482
3483 PermissionCacheUtil.clearCache();
3484 }
3485
3486
3494 public void unsetOrganizationUsers(long organizationId, long[] userIds)
3495 throws PortalException, SystemException {
3496
3497 Organization organization = organizationPersistence.findByPrimaryKey(
3498 organizationId);
3499
3500 Group group = organization.getGroup();
3501
3502 userGroupRoleLocalService.deleteUserGroupRoles(
3503 userIds, group.getGroupId(), RoleConstants.TYPE_ORGANIZATION);
3504
3505 organizationPersistence.removeUsers(organizationId, userIds);
3506
3507 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3508
3509 indexer.reindex(userIds);
3510
3511 PermissionCacheUtil.clearCache();
3512 }
3513
3514
3521 public void unsetPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
3522 throws SystemException {
3523
3524 passwordPolicyRelLocalService.deletePasswordPolicyRels(
3525 passwordPolicyId, User.class.getName(), userIds);
3526 }
3527
3528
3536 public void unsetRoleUsers(long roleId, List<User> users)
3537 throws PortalException, SystemException {
3538
3539 Role role = rolePersistence.findByPrimaryKey(roleId);
3540
3541 String roleName = role.getName();
3542
3543 if ((roleName.equals(RoleConstants.ADMINISTRATOR) &&
3544 (getRoleUsersCount(role.getRoleId()) <= 1)) ||
3545 roleName.equals(RoleConstants.USER)) {
3546
3547 return;
3548 }
3549
3550 rolePersistence.removeUsers(roleId, users);
3551
3552 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3553
3554 indexer.reindex(users);
3555
3556 PermissionCacheUtil.clearCache();
3557 }
3558
3559
3567 public void unsetRoleUsers(long roleId, long[] userIds)
3568 throws PortalException, SystemException {
3569
3570 Role role = rolePersistence.findByPrimaryKey(roleId);
3571
3572 String roleName = role.getName();
3573
3574 if (roleName.equals(RoleConstants.USER) ||
3575 (roleName.equals(RoleConstants.ADMINISTRATOR) &&
3576 getRoleUsersCount(role.getRoleId()) <= 1)) {
3577
3578 return;
3579 }
3580
3581 rolePersistence.removeUsers(roleId, userIds);
3582
3583 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3584
3585 indexer.reindex(userIds);
3586
3587 PermissionCacheUtil.clearCache();
3588 }
3589
3590
3598 public void unsetTeamUsers(long teamId, long[] userIds)
3599 throws PortalException, SystemException {
3600
3601 teamPersistence.removeUsers(teamId, userIds);
3602
3603 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3604
3605 indexer.reindex(userIds);
3606
3607 PermissionCacheUtil.clearCache();
3608 }
3609
3610
3618 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
3619 throws PortalException, SystemException {
3620
3621 userGroupPersistence.removeUsers(userGroupId, userIds);
3622
3623 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3624
3625 indexer.reindex(userIds);
3626
3627 PermissionCacheUtil.clearCache();
3628 }
3629
3630
3640 public User updateAgreedToTermsOfUse(
3641 long userId, boolean agreedToTermsOfUse)
3642 throws PortalException, SystemException {
3643
3644 User user = userPersistence.findByPrimaryKey(userId);
3645
3646 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
3647
3648 userPersistence.update(user);
3649
3650 return user;
3651 }
3652
3653
3664 public void updateAsset(
3665 long userId, User user, long[] assetCategoryIds,
3666 String[] assetTagNames)
3667 throws PortalException, SystemException {
3668
3669 User owner = userPersistence.findByPrimaryKey(userId);
3670
3671 Company company = companyPersistence.findByPrimaryKey(
3672 owner.getCompanyId());
3673
3674 Group companyGroup = company.getGroup();
3675
3676 assetEntryLocalService.updateEntry(
3677 userId, companyGroup.getGroupId(), user.getCreateDate(),
3678 user.getModifiedDate(), User.class.getName(), user.getUserId(),
3679 user.getUuid(), 0, assetCategoryIds, assetTagNames, false, null,
3680 null, null, null, user.getFullName(), null, null, null, null, 0, 0,
3681 null, false);
3682 }
3683
3684
3693 public User updateCreateDate(long userId, Date createDate)
3694 throws PortalException, SystemException {
3695
3696 User user = userPersistence.findByPrimaryKey(userId);
3697
3698 user.setCreateDate(createDate);
3699
3700 userPersistence.update(user);
3701
3702 return user;
3703 }
3704
3705
3716 public User updateEmailAddress(
3717 long userId, String password, String emailAddress1,
3718 String emailAddress2)
3719 throws PortalException, SystemException {
3720
3721 emailAddress1 = emailAddress1.trim().toLowerCase();
3722 emailAddress2 = emailAddress2.trim().toLowerCase();
3723
3724 User user = userPersistence.findByPrimaryKey(userId);
3725
3726 validateEmailAddress(user, emailAddress1, emailAddress2);
3727
3728 setEmailAddress(
3729 user, password, user.getFirstName(), user.getMiddleName(),
3730 user.getLastName(), emailAddress1);
3731
3732 userPersistence.update(user);
3733
3734 Contact contact = user.getContact();
3735
3736 contact.setEmailAddress(user.getEmailAddress());
3737
3738 contactPersistence.update(contact);
3739
3740 return user;
3741 }
3742
3743
3757 public User updateEmailAddress(
3758 long userId, String password, String emailAddress1,
3759 String emailAddress2, ServiceContext serviceContext)
3760 throws PortalException, SystemException {
3761
3762 emailAddress1 = emailAddress1.trim().toLowerCase();
3763 emailAddress2 = emailAddress2.trim().toLowerCase();
3764
3765 User user = userPersistence.findByPrimaryKey(userId);
3766
3767 validateEmailAddress(user, emailAddress1, emailAddress2);
3768
3769 Company company = companyPersistence.findByPrimaryKey(
3770 user.getCompanyId());
3771
3772 if (!company.isStrangersVerify()) {
3773 setEmailAddress(
3774 user, password, user.getFirstName(), user.getMiddleName(),
3775 user.getLastName(), emailAddress1);
3776
3777 userPersistence.update(user);
3778
3779 Contact contact = user.getContact();
3780
3781 contact.setEmailAddress(user.getEmailAddress());
3782
3783 contactPersistence.update(contact);
3784 }
3785 else {
3786 sendEmailAddressVerification(user, emailAddress1, serviceContext);
3787 }
3788
3789 return user;
3790 }
3791
3792
3801 public User updateEmailAddressVerified(
3802 long userId, boolean emailAddressVerified)
3803 throws PortalException, SystemException {
3804
3805 User user = userPersistence.findByPrimaryKey(userId);
3806
3807 user.setEmailAddressVerified(emailAddressVerified);
3808
3809 userPersistence.update(user);
3810
3811 return user;
3812 }
3813
3814
3823 public User updateFacebookId(long userId, long facebookId)
3824 throws PortalException, SystemException {
3825
3826 User user = userPersistence.findByPrimaryKey(userId);
3827
3828 user.setFacebookId(facebookId);
3829
3830 userPersistence.update(user);
3831
3832 return user;
3833 }
3834
3835
3845 public void updateGroups(
3846 long userId, long[] newGroupIds, ServiceContext serviceContext)
3847 throws PortalException, SystemException {
3848
3849 updateGroups(
3850 userId, newGroupIds, serviceContext,
3851 serviceContext.isIndexingEnabled());
3852 }
3853
3854
3893 public User updateIncompleteUser(
3894 long creatorUserId, long companyId, boolean autoPassword,
3895 String password1, String password2, boolean autoScreenName,
3896 String screenName, String emailAddress, long facebookId,
3897 String openId, Locale locale, String firstName, String middleName,
3898 String lastName, int prefixId, int suffixId, boolean male,
3899 int birthdayMonth, int birthdayDay, int birthdayYear,
3900 String jobTitle, boolean updateUserInformation, boolean sendEmail,
3901 ServiceContext serviceContext)
3902 throws PortalException, SystemException {
3903
3904 User user = getUserByEmailAddress(companyId, emailAddress);
3905
3906 if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
3907 throw new PortalException("Invalid user status");
3908 }
3909
3910 User defaultUser = getDefaultUser(companyId);
3911
3912 if (facebookId > 0) {
3913 autoPassword = false;
3914
3915 if ((password1 == null) || (password2 == null)) {
3916 password1 = PwdGenerator.getPassword();
3917 password2 = password1;
3918 }
3919
3920 sendEmail = false;
3921 }
3922
3923 if (updateUserInformation) {
3924 autoScreenName = false;
3925
3926 if (PrefsPropsUtil.getBoolean(
3927 companyId,
3928 PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
3929
3930 autoScreenName = true;
3931 }
3932
3933 validate(
3934 companyId, user.getUserId(), autoPassword, password1, password2,
3935 autoScreenName, screenName, emailAddress, openId, firstName,
3936 middleName, lastName, null);
3937
3938 if (!autoPassword) {
3939 if (Validator.isNull(password1) ||
3940 Validator.isNull(password2)) {
3941 throw new UserPasswordException(
3942 UserPasswordException.PASSWORD_INVALID);
3943 }
3944 }
3945
3946 if (autoScreenName) {
3947 ScreenNameGenerator screenNameGenerator =
3948 ScreenNameGeneratorFactory.getInstance();
3949
3950 try {
3951 screenName = screenNameGenerator.generate(
3952 companyId, user.getUserId(), emailAddress);
3953 }
3954 catch (Exception e) {
3955 throw new SystemException(e);
3956 }
3957 }
3958
3959 FullNameGenerator fullNameGenerator =
3960 FullNameGeneratorFactory.getInstance();
3961
3962 String fullName = fullNameGenerator.getFullName(
3963 firstName, middleName, lastName);
3964
3965 String greeting = LanguageUtil.format(
3966 locale, "welcome-x", " " + fullName, false);
3967
3968 if (Validator.isNotNull(password1)) {
3969 user.setPassword(PasswordEncryptorUtil.encrypt(password1));
3970 user.setPasswordUnencrypted(password1);
3971 }
3972
3973 user.setPasswordEncrypted(true);
3974
3975 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
3976
3977 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
3978 passwordPolicy.isChangeRequired()) {
3979
3980 user.setPasswordReset(true);
3981 }
3982 else {
3983 user.setPasswordReset(false);
3984 }
3985
3986 user.setScreenName(screenName);
3987 user.setFacebookId(facebookId);
3988 user.setOpenId(openId);
3989 user.setLanguageId(locale.toString());
3990 user.setTimeZoneId(defaultUser.getTimeZoneId());
3991 user.setGreeting(greeting);
3992 user.setFirstName(firstName);
3993 user.setMiddleName(middleName);
3994 user.setLastName(lastName);
3995 user.setJobTitle(jobTitle);
3996 user.setExpandoBridgeAttributes(serviceContext);
3997
3998 Date birthday = getBirthday(
3999 birthdayMonth, birthdayDay, birthdayYear);
4000
4001 Contact contact = user.getContact();
4002
4003 contact.setFirstName(firstName);
4004 contact.setMiddleName(middleName);
4005 contact.setLastName(lastName);
4006 contact.setPrefixId(prefixId);
4007 contact.setSuffixId(suffixId);
4008 contact.setMale(male);
4009 contact.setBirthday(birthday);
4010 contact.setJobTitle(jobTitle);
4011
4012 contactPersistence.update(contact, serviceContext);
4013
4014
4015
4016 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4017 User.class);
4018
4019 indexer.reindex(user);
4020 }
4021
4022 user.setStatus(WorkflowConstants.STATUS_DRAFT);
4023
4024 userPersistence.update(user, serviceContext);
4025
4026
4027
4028 long workflowUserId = creatorUserId;
4029
4030 if (workflowUserId == user.getUserId()) {
4031 workflowUserId = defaultUser.getUserId();
4032 }
4033
4034 ServiceContext workflowServiceContext = serviceContext;
4035
4036 if (workflowServiceContext == null) {
4037 workflowServiceContext = new ServiceContext();
4038 }
4039
4040 workflowServiceContext.setAttribute("autoPassword", autoPassword);
4041 workflowServiceContext.setAttribute("sendEmail", sendEmail);
4042
4043 WorkflowHandlerRegistryUtil.startWorkflowInstance(
4044 companyId, workflowUserId, User.class.getName(), user.getUserId(),
4045 user, workflowServiceContext);
4046
4047 return getUserByEmailAddress(companyId, emailAddress);
4048 }
4049
4050
4060 public User updateJobTitle(long userId, String jobTitle)
4061 throws PortalException, SystemException {
4062
4063 User user = userPersistence.findByPrimaryKey(userId);
4064
4065 user.setJobTitle(jobTitle);
4066
4067 userPersistence.update(user);
4068
4069 Contact contact = contactPersistence.findByPrimaryKey(
4070 user.getContactId());
4071
4072 contact.setJobTitle(jobTitle);
4073
4074 contactPersistence.update(contact);
4075
4076 return user;
4077 }
4078
4079
4088 public User updateLastLogin(long userId, String loginIP)
4089 throws PortalException, SystemException {
4090
4091 User user = userPersistence.findByPrimaryKey(userId);
4092
4093 Date lastLoginDate = user.getLoginDate();
4094
4095 if (lastLoginDate == null) {
4096 lastLoginDate = new Date();
4097 }
4098
4099 user.setLoginDate(new Date());
4100 user.setLoginIP(loginIP);
4101 user.setLastLoginDate(lastLoginDate);
4102 user.setLastLoginIP(user.getLoginIP());
4103 user.setLastFailedLoginDate(null);
4104 user.setFailedLoginAttempts(0);
4105
4106 userPersistence.update(user);
4107
4108 return user;
4109 }
4110
4111
4120 public User updateLockout(User user, boolean lockout)
4121 throws PortalException, SystemException {
4122
4123 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
4124
4125 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
4126 return user;
4127 }
4128
4129 Date lockoutDate = null;
4130
4131 if (lockout) {
4132 lockoutDate = new Date();
4133 }
4134
4135 user.setLockout(lockout);
4136 user.setLockoutDate(lockoutDate);
4137
4138 if (!lockout) {
4139 user.setLastFailedLoginDate(lockoutDate);
4140 user.setFailedLoginAttempts(0);
4141 }
4142
4143 userPersistence.update(user);
4144
4145 return user;
4146 }
4147
4148
4159 public User updateLockoutByEmailAddress(
4160 long companyId, String emailAddress, boolean lockout)
4161 throws PortalException, SystemException {
4162
4163 User user = getUserByEmailAddress(companyId, emailAddress);
4164
4165 return updateLockout(user, lockout);
4166 }
4167
4168
4177 public User updateLockoutById(long userId, boolean lockout)
4178 throws PortalException, SystemException {
4179
4180 User user = userPersistence.findByPrimaryKey(userId);
4181
4182 return updateLockout(user, lockout);
4183 }
4184
4185
4195 public User updateLockoutByScreenName(
4196 long companyId, String screenName, boolean lockout)
4197 throws PortalException, SystemException {
4198
4199 User user = getUserByScreenName(companyId, screenName);
4200
4201 return updateLockout(user, lockout);
4202 }
4203
4204
4213 public User updateModifiedDate(long userId, Date modifiedDate)
4214 throws PortalException, SystemException {
4215
4216 User user = userPersistence.findByPrimaryKey(userId);
4217
4218 user.setModifiedDate(modifiedDate);
4219
4220 userPersistence.update(user);
4221
4222 return user;
4223 }
4224
4225
4234 public User updateOpenId(long userId, String openId)
4235 throws PortalException, SystemException {
4236
4237 openId = openId.trim();
4238
4239 User user = userPersistence.findByPrimaryKey(userId);
4240
4241 user.setOpenId(openId);
4242
4243 userPersistence.update(user);
4244
4245 return user;
4246 }
4247
4248
4259 public void updateOrganizations(
4260 long userId, long[] newOrganizationIds,
4261 ServiceContext serviceContext)
4262 throws PortalException, SystemException {
4263
4264 updateOrganizations(
4265 userId, newOrganizationIds, serviceContext.isIndexingEnabled());
4266 }
4267
4268
4280 public User updatePassword(
4281 long userId, String password1, String password2,
4282 boolean passwordReset)
4283 throws PortalException, SystemException {
4284
4285 return updatePassword(
4286 userId, password1, password2, passwordReset, false);
4287 }
4288
4289
4304 public User updatePassword(
4305 long userId, String password1, String password2,
4306 boolean passwordReset, boolean silentUpdate)
4307 throws PortalException, SystemException {
4308
4309 User user = userPersistence.findByPrimaryKey(userId);
4310
4311 if (!silentUpdate) {
4312 validatePassword(user.getCompanyId(), userId, password1, password2);
4313 }
4314
4315 String oldEncPwd = user.getPassword();
4316
4317 if (!user.isPasswordEncrypted()) {
4318 oldEncPwd = PasswordEncryptorUtil.encrypt(user.getPassword());
4319 }
4320
4321 String newEncPwd = PasswordEncryptorUtil.encrypt(password1);
4322
4323 if (user.hasCompanyMx()) {
4324 mailService.updatePassword(user.getCompanyId(), userId, password1);
4325 }
4326
4327 user.setPassword(newEncPwd);
4328 user.setPasswordUnencrypted(password1);
4329 user.setPasswordEncrypted(true);
4330 user.setPasswordReset(passwordReset);
4331 user.setPasswordModifiedDate(new Date());
4332 user.setDigest(StringPool.BLANK);
4333 user.setGraceLoginCount(0);
4334
4335 if (!silentUpdate) {
4336 user.setPasswordModified(true);
4337 }
4338
4339 try {
4340 userPersistence.update(user);
4341 }
4342 catch (ModelListenerException mle) {
4343 String msg = GetterUtil.getString(mle.getCause().getMessage());
4344
4345 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
4346 String passwordHistory = PrefsPropsUtil.getString(
4347 user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
4348
4349 if (msg.contains(passwordHistory)) {
4350 throw new UserPasswordException(
4351 UserPasswordException.PASSWORD_ALREADY_USED);
4352 }
4353 }
4354
4355 throw new UserPasswordException(
4356 UserPasswordException.PASSWORD_INVALID);
4357 }
4358
4359 if (!silentUpdate) {
4360 user.setPasswordModified(false);
4361
4362 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
4363 }
4364
4365 return user;
4366 }
4367
4368
4382 public User updatePasswordManually(
4383 long userId, String password, boolean passwordEncrypted,
4384 boolean passwordReset, Date passwordModifiedDate)
4385 throws PortalException, SystemException {
4386
4387
4388
4389 User user = userPersistence.findByPrimaryKey(userId);
4390
4391 user.setPassword(password);
4392 user.setPasswordEncrypted(passwordEncrypted);
4393 user.setPasswordReset(passwordReset);
4394 user.setPasswordModifiedDate(passwordModifiedDate);
4395 user.setDigest(StringPool.BLANK);
4396
4397 userPersistence.update(user);
4398
4399 return user;
4400 }
4401
4402
4413 public User updatePasswordReset(long userId, boolean passwordReset)
4414 throws PortalException, SystemException {
4415
4416 User user = userPersistence.findByPrimaryKey(userId);
4417
4418 user.setPasswordReset(passwordReset);
4419
4420 userPersistence.update(user);
4421
4422 return user;
4423 }
4424
4425
4435 public User updatePortrait(long userId, byte[] bytes)
4436 throws PortalException, SystemException {
4437
4438 User user = userPersistence.findByPrimaryKey(userId);
4439
4440 long imageMaxSize = PrefsPropsUtil.getLong(
4441 PropsKeys.USERS_IMAGE_MAX_SIZE);
4442
4443 if ((imageMaxSize > 0) &&
4444 ((bytes == null) || (bytes.length > imageMaxSize))) {
4445
4446 throw new UserPortraitSizeException();
4447 }
4448
4449 long portraitId = user.getPortraitId();
4450
4451 if (portraitId <= 0) {
4452 portraitId = counterLocalService.increment();
4453
4454 user.setPortraitId(portraitId);
4455 }
4456
4457 try {
4458 ImageBag imageBag = ImageToolUtil.read(bytes);
4459
4460 RenderedImage renderedImage = imageBag.getRenderedImage();
4461
4462 if (renderedImage == null) {
4463 throw new UserPortraitTypeException();
4464 }
4465
4466 renderedImage = ImageToolUtil.scale(
4467 renderedImage, PropsValues.USERS_IMAGE_MAX_HEIGHT,
4468 PropsValues.USERS_IMAGE_MAX_WIDTH);
4469
4470 String contentType = imageBag.getType();
4471
4472 imageLocalService.updateImage(
4473 portraitId,
4474 ImageToolUtil.getBytes(renderedImage, contentType));
4475 }
4476 catch (IOException ioe) {
4477 throw new ImageSizeException(ioe);
4478 }
4479
4480 userPersistence.update(user);
4481
4482 return user;
4483 }
4484
4485
4496 public User updateReminderQuery(long userId, String question, String answer)
4497 throws PortalException, SystemException {
4498
4499 validateReminderQuery(question, answer);
4500
4501 User user = userPersistence.findByPrimaryKey(userId);
4502
4503 user.setReminderQueryQuestion(question);
4504 user.setReminderQueryAnswer(answer);
4505
4506 userPersistence.update(user);
4507
4508 return user;
4509 }
4510
4511
4521 public User updateScreenName(long userId, String screenName)
4522 throws PortalException, SystemException {
4523
4524
4525
4526 User user = userPersistence.findByPrimaryKey(userId);
4527
4528 screenName = getScreenName(screenName);
4529
4530 validateScreenName(user.getCompanyId(), userId, screenName);
4531
4532 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
4533 user.setDigest(StringPool.BLANK);
4534 }
4535
4536 user.setScreenName(screenName);
4537
4538 userPersistence.update(user);
4539
4540
4541
4542 Group group = groupLocalService.getUserGroup(
4543 user.getCompanyId(), userId);
4544
4545 group.setFriendlyURL(StringPool.SLASH + screenName);
4546
4547 groupPersistence.update(group);
4548
4549 return user;
4550 }
4551
4552
4561 public User updateStatus(long userId, int status)
4562 throws PortalException, SystemException {
4563
4564 User user = userPersistence.findByPrimaryKey(userId);
4565
4566 if ((status == WorkflowConstants.STATUS_APPROVED) &&
4567 (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {
4568
4569 validateCompanyMaxUsers(user.getCompanyId());
4570 }
4571
4572 user.setStatus(status);
4573
4574 userPersistence.update(user);
4575
4576 reindex(user);
4577
4578 return user;
4579 }
4580
4581
4637 @SuppressWarnings("deprecation")
4638 public User updateUser(
4639 long userId, String oldPassword, String newPassword1,
4640 String newPassword2, boolean passwordReset,
4641 String reminderQueryQuestion, String reminderQueryAnswer,
4642 String screenName, String emailAddress, long facebookId,
4643 String openId, String languageId, String timeZoneId,
4644 String greeting, String comments, String firstName,
4645 String middleName, String lastName, int prefixId, int suffixId,
4646 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
4647 String smsSn, String aimSn, String facebookSn, String icqSn,
4648 String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
4649 String twitterSn, String ymSn, String jobTitle, long[] groupIds,
4650 long[] organizationIds, long[] roleIds,
4651 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
4652 ServiceContext serviceContext)
4653 throws PortalException, SystemException {
4654
4655
4656
4657 User user = userPersistence.findByPrimaryKey(userId);
4658 Company company = companyPersistence.findByPrimaryKey(
4659 user.getCompanyId());
4660 String password = oldPassword;
4661 screenName = getScreenName(screenName);
4662 emailAddress = emailAddress.trim().toLowerCase();
4663 openId = openId.trim();
4664 String oldFullName = user.getFullName();
4665 aimSn = aimSn.trim().toLowerCase();
4666 facebookSn = facebookSn.trim().toLowerCase();
4667 icqSn = icqSn.trim().toLowerCase();
4668 jabberSn = jabberSn.trim().toLowerCase();
4669 msnSn = msnSn.trim().toLowerCase();
4670 mySpaceSn = mySpaceSn.trim().toLowerCase();
4671 skypeSn = skypeSn.trim().toLowerCase();
4672 twitterSn = twitterSn.trim().toLowerCase();
4673 ymSn = ymSn.trim().toLowerCase();
4674 Date now = new Date();
4675
4676 EmailAddressGenerator emailAddressGenerator =
4677 EmailAddressGeneratorFactory.getInstance();
4678
4679 if (emailAddressGenerator.isGenerated(emailAddress)) {
4680 emailAddress = StringPool.BLANK;
4681 }
4682
4683 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
4684 Validator.isNull(emailAddress)) {
4685
4686 emailAddress = emailAddressGenerator.generate(
4687 user.getCompanyId(), userId);
4688 }
4689
4690 validate(
4691 userId, screenName, emailAddress, openId, firstName, middleName,
4692 lastName, smsSn);
4693
4694 if (Validator.isNotNull(newPassword1) ||
4695 Validator.isNotNull(newPassword2)) {
4696
4697 user = updatePassword(
4698 userId, newPassword1, newPassword2, passwordReset);
4699
4700 password = newPassword1;
4701
4702 user.setDigest(StringPool.BLANK);
4703 }
4704
4705 user.setModifiedDate(now);
4706
4707 if (user.getContactId() <= 0) {
4708 user.setContactId(counterLocalService.increment());
4709 }
4710
4711 user.setPasswordReset(passwordReset);
4712
4713 if (Validator.isNotNull(reminderQueryQuestion) &&
4714 Validator.isNotNull(reminderQueryAnswer)) {
4715
4716 user.setReminderQueryQuestion(reminderQueryQuestion);
4717 user.setReminderQueryAnswer(reminderQueryAnswer);
4718 }
4719
4720 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
4721 user.setScreenName(screenName);
4722
4723 user.setDigest(StringPool.BLANK);
4724 }
4725
4726 boolean sendEmailAddressVerification = false;
4727
4728 if (!company.isStrangersVerify()) {
4729 setEmailAddress(
4730 user, password, firstName, middleName, lastName, emailAddress);
4731 }
4732 else {
4733 sendEmailAddressVerification = true;
4734 }
4735
4736 if (serviceContext != null) {
4737 String uuid = serviceContext.getUuid();
4738
4739 if (Validator.isNotNull(uuid)) {
4740 user.setUuid(uuid);
4741 }
4742 }
4743
4744 user.setFacebookId(facebookId);
4745
4746 Long ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
4747
4748 if (ldapServerId != null) {
4749 user.setLdapServerId(ldapServerId);
4750 }
4751
4752 user.setOpenId(openId);
4753 user.setLanguageId(languageId);
4754 user.setTimeZoneId(timeZoneId);
4755 user.setGreeting(greeting);
4756 user.setComments(comments);
4757 user.setFirstName(firstName);
4758 user.setMiddleName(middleName);
4759 user.setLastName(lastName);
4760 user.setJobTitle(jobTitle);
4761 user.setExpandoBridgeAttributes(serviceContext);
4762
4763 userPersistence.update(user, serviceContext);
4764
4765
4766
4767 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
4768
4769 long contactId = user.getContactId();
4770
4771 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
4772
4773 if (contact == null) {
4774 contact = contactPersistence.create(contactId);
4775
4776 contact.setCompanyId(user.getCompanyId());
4777 contact.setUserName(StringPool.BLANK);
4778 contact.setCreateDate(now);
4779 contact.setClassName(User.class.getName());
4780 contact.setClassPK(user.getUserId());
4781 contact.setAccountId(company.getAccountId());
4782 contact.setParentContactId(
4783 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
4784 }
4785
4786 contact.setModifiedDate(now);
4787 contact.setEmailAddress(user.getEmailAddress());
4788 contact.setFirstName(firstName);
4789 contact.setMiddleName(middleName);
4790 contact.setLastName(lastName);
4791 contact.setPrefixId(prefixId);
4792 contact.setSuffixId(suffixId);
4793 contact.setMale(male);
4794 contact.setBirthday(birthday);
4795 contact.setSmsSn(smsSn);
4796 contact.setAimSn(aimSn);
4797 contact.setFacebookSn(facebookSn);
4798 contact.setIcqSn(icqSn);
4799 contact.setJabberSn(jabberSn);
4800 contact.setMsnSn(msnSn);
4801 contact.setMySpaceSn(mySpaceSn);
4802 contact.setSkypeSn(skypeSn);
4803 contact.setTwitterSn(twitterSn);
4804 contact.setYmSn(ymSn);
4805 contact.setJobTitle(jobTitle);
4806
4807 contactPersistence.update(contact, serviceContext);
4808
4809
4810
4811 Group group = groupLocalService.getUserGroup(
4812 user.getCompanyId(), userId);
4813
4814 group.setFriendlyURL(StringPool.SLASH + screenName);
4815
4816 groupPersistence.update(group);
4817
4818
4819
4820 updateGroups(userId, groupIds, serviceContext, false);
4821 updateOrganizations(userId, organizationIds, false);
4822
4823
4824
4825 if (roleIds != null) {
4826 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
4827
4828 userPersistence.setRoles(userId, roleIds);
4829 }
4830
4831
4832
4833 updateUserGroupRoles(user, groupIds, organizationIds, userGroupRoles);
4834
4835
4836
4837 if (userGroupIds != null) {
4838 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
4839 userGroupLocalService.copyUserGroupLayouts(
4840 userGroupIds, userId);
4841 }
4842
4843 userPersistence.setUserGroups(userId, userGroupIds);
4844 }
4845
4846
4847
4848 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
4849
4850
4851
4852 if (serviceContext != null) {
4853 updateAsset(
4854 userId, user, serviceContext.getAssetCategoryIds(),
4855 serviceContext.getAssetTagNames());
4856 }
4857
4858
4859
4860 if (GetterUtil.getBoolean(
4861 PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
4862 !oldFullName.equals(user.getFullName())) {
4863
4864 mbMessageLocalService.updateUserName(userId, user.getFullName());
4865 }
4866
4867
4868
4869 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
4870 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4871 User.class);
4872
4873 indexer.reindex(user);
4874 }
4875
4876
4877
4878 if ((serviceContext != null) && sendEmailAddressVerification) {
4879 sendEmailAddressVerification(user, emailAddress, serviceContext);
4880 }
4881
4882
4883
4884 PermissionCacheUtil.clearCache();
4885
4886 return user;
4887 }
4888
4889
4898 public void verifyEmailAddress(String ticketKey)
4899 throws PortalException, SystemException {
4900
4901 Ticket ticket = ticketLocalService.getTicket(ticketKey);
4902
4903 if (ticket.isExpired() ||
4904 (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
4905
4906 throw new NoSuchTicketException();
4907 }
4908
4909 User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
4910
4911 String emailAddress = ticket.getExtraInfo();
4912
4913 emailAddress = emailAddress.toLowerCase().trim();
4914
4915 if (!emailAddress.equals(user.getEmailAddress())) {
4916 if (userPersistence.fetchByC_EA(
4917 user.getCompanyId(), emailAddress) != null) {
4918
4919 throw new DuplicateUserEmailAddressException();
4920 }
4921
4922 setEmailAddress(
4923 user, StringPool.BLANK, user.getFirstName(),
4924 user.getMiddleName(), user.getLastName(), emailAddress);
4925
4926 Contact contact = user.getContact();
4927
4928 contact.setEmailAddress(user.getEmailAddress());
4929
4930 contactPersistence.update(contact);
4931 }
4932
4933 user.setEmailAddressVerified(true);
4934
4935 userPersistence.update(user);
4936
4937 ticketLocalService.deleteTicket(ticket);
4938 }
4939
4940 protected void addDefaultRolesAndTeams(long groupId, long[] userIds)
4941 throws PortalException, SystemException {
4942
4943 List<Role> defaultSiteRoles = new ArrayList<Role>();
4944
4945 Group group = groupLocalService.getGroup(groupId);
4946
4947 UnicodeProperties typeSettingsProperties =
4948 group.getTypeSettingsProperties();
4949
4950 long[] defaultSiteRoleIds = StringUtil.split(
4951 typeSettingsProperties.getProperty("defaultSiteRoleIds"), 0L);
4952
4953 for (long defaultSiteRoleId : defaultSiteRoleIds) {
4954 Role defaultSiteRole = rolePersistence.fetchByPrimaryKey(
4955 defaultSiteRoleId);
4956
4957 if (defaultSiteRole == null) {
4958 if (_log.isWarnEnabled()) {
4959 _log.warn("Unable to find role " + defaultSiteRoleId);
4960 }
4961
4962 continue;
4963 }
4964
4965 defaultSiteRoles.add(defaultSiteRole);
4966 }
4967
4968 List<Team> defaultTeams = new ArrayList<Team>();
4969
4970 long[] defaultTeamIds = StringUtil.split(
4971 typeSettingsProperties.getProperty("defaultTeamIds"), 0L);
4972
4973 for (long defaultTeamId : defaultTeamIds) {
4974 Team defaultTeam = teamPersistence.findByPrimaryKey(defaultTeamId);
4975
4976 if (defaultTeam == null) {
4977 if (_log.isWarnEnabled()) {
4978 _log.warn("Unable to find team " + defaultTeamId);
4979 }
4980
4981 continue;
4982 }
4983
4984 defaultTeams.add(defaultTeam);
4985 }
4986
4987 for (long userId : userIds) {
4988 Set<Long> userRoleIdsSet = new HashSet<Long>();
4989
4990 for (Role role : defaultSiteRoles) {
4991 if (!userPersistence.containsRole(userId, role.getRoleId())) {
4992 userRoleIdsSet.add(role.getRoleId());
4993 }
4994 }
4995
4996 long[] userRoleIds = ArrayUtil.toArray(
4997 userRoleIdsSet.toArray(new Long[userRoleIdsSet.size()]));
4998
4999 userGroupRoleLocalService.addUserGroupRoles(
5000 userId, groupId, userRoleIds);
5001
5002 Set<Long> userTeamIdsSet = new HashSet<Long>();
5003
5004 for (Team team : defaultTeams) {
5005 if (!userPersistence.containsTeam(userId, team.getTeamId())) {
5006 userTeamIdsSet.add(team.getTeamId());
5007 }
5008 }
5009
5010 long[] userTeamIds = ArrayUtil.toArray(
5011 userTeamIdsSet.toArray(new Long[userTeamIdsSet.size()]));
5012
5013 userPersistence.addTeams(userId, userTeamIds);
5014 }
5015 }
5016
5017
5063 protected int authenticate(
5064 long companyId, String login, String password, String authType,
5065 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
5066 Map<String, Object> resultsMap)
5067 throws PortalException, SystemException {
5068
5069 if (PropsValues.AUTH_LOGIN_DISABLED) {
5070 return Authenticator.FAILURE;
5071 }
5072
5073 login = login.trim().toLowerCase();
5074
5075 long userId = GetterUtil.getLong(login);
5076
5077
5078
5079 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5080 if (Validator.isNull(login)) {
5081 throw new UserEmailAddressException();
5082 }
5083 }
5084 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5085 if (Validator.isNull(login)) {
5086 throw new UserScreenNameException();
5087 }
5088 }
5089 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5090 if (Validator.isNull(login)) {
5091 throw new UserIdException();
5092 }
5093 }
5094
5095 if (Validator.isNull(password)) {
5096 throw new UserPasswordException(
5097 UserPasswordException.PASSWORD_INVALID);
5098 }
5099
5100 int authResult = Authenticator.FAILURE;
5101
5102
5103
5104 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5105 authResult = AuthPipeline.authenticateByEmailAddress(
5106 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5107 headerMap, parameterMap);
5108 }
5109 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5110 authResult = AuthPipeline.authenticateByScreenName(
5111 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5112 headerMap, parameterMap);
5113 }
5114 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5115 authResult = AuthPipeline.authenticateByUserId(
5116 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
5117 headerMap, parameterMap);
5118 }
5119
5120
5121
5122 User user = null;
5123
5124 try {
5125 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5126 user = userPersistence.findByC_EA(companyId, login);
5127 }
5128 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5129 user = userPersistence.findByC_SN(companyId, login);
5130 }
5131 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5132 user = userPersistence.findByC_U(
5133 companyId, GetterUtil.getLong(login));
5134 }
5135 }
5136 catch (NoSuchUserException nsue) {
5137 return Authenticator.DNE;
5138 }
5139
5140 if (user.isDefaultUser()) {
5141 if (_log.isInfoEnabled()) {
5142 _log.info("Authentication is disabled for the default user");
5143 }
5144
5145 return Authenticator.DNE;
5146 }
5147 else if (!user.isActive()) {
5148 if (_log.isInfoEnabled()) {
5149 _log.info(
5150 "Authentication is disabled for inactive user " +
5151 user.getUserId());
5152 }
5153
5154 return Authenticator.FAILURE;
5155 }
5156
5157 if (!user.isPasswordEncrypted()) {
5158 user.setPassword(PasswordEncryptorUtil.encrypt(user.getPassword()));
5159 user.setPasswordEncrypted(true);
5160
5161 userPersistence.update(user);
5162 }
5163
5164
5165
5166
5167 checkLockout(user);
5168
5169 checkPasswordExpired(user);
5170
5171
5172
5173 if ((authResult == Authenticator.SUCCESS) &&
5174 PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5175
5176 boolean authenticated = PwdAuthenticator.authenticate(
5177 login, password, user.getPassword());
5178
5179 if (authenticated) {
5180 authResult = Authenticator.SUCCESS;
5181 }
5182 else {
5183 authResult = Authenticator.FAILURE;
5184 }
5185 }
5186
5187
5188
5189 if (authResult == Authenticator.SUCCESS) {
5190 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5191 authResult = AuthPipeline.authenticateByEmailAddress(
5192 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5193 headerMap, parameterMap);
5194 }
5195 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5196 authResult = AuthPipeline.authenticateByScreenName(
5197 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5198 headerMap, parameterMap);
5199 }
5200 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5201 authResult = AuthPipeline.authenticateByUserId(
5202 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5203 headerMap, parameterMap);
5204 }
5205 }
5206
5207 if (authResult == Authenticator.SUCCESS) {
5208 if (resultsMap != null) {
5209 resultsMap.put("userId", user.getUserId());
5210 }
5211
5212
5213
5214 boolean updateDigest = true;
5215
5216 if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5217 if (Validator.isNotNull(user.getDigest())) {
5218 updateDigest = false;
5219 }
5220 }
5221
5222 if (updateDigest) {
5223 String digest = user.getDigest(password);
5224
5225 user.setDigest(digest);
5226
5227 userPersistence.update(user);
5228 }
5229 }
5230
5231
5232
5233 if (authResult == Authenticator.FAILURE) {
5234 try {
5235 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5236 AuthPipeline.onFailureByEmailAddress(
5237 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5238 parameterMap);
5239 }
5240 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5241 AuthPipeline.onFailureByScreenName(
5242 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5243 parameterMap);
5244 }
5245 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5246 AuthPipeline.onFailureByUserId(
5247 PropsKeys.AUTH_FAILURE, companyId, userId, headerMap,
5248 parameterMap);
5249 }
5250
5251 try {
5252 user = userPersistence.findByPrimaryKey(user.getUserId());
5253 }
5254 catch (NoSuchUserException nsue) {
5255 return Authenticator.DNE;
5256 }
5257
5258
5259
5260 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5261 user.getCompanyId())) {
5262
5263 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5264
5265 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5266
5267 int failedLoginAttempts = user.getFailedLoginAttempts();
5268 int maxFailures = passwordPolicy.getMaxFailure();
5269
5270 if ((failedLoginAttempts >= maxFailures) &&
5271 (maxFailures != 0)) {
5272
5273 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5274 AuthPipeline.onMaxFailuresByEmailAddress(
5275 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5276 headerMap, parameterMap);
5277 }
5278 else if (authType.equals(
5279 CompanyConstants.AUTH_TYPE_SN)) {
5280
5281 AuthPipeline.onMaxFailuresByScreenName(
5282 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5283 headerMap, parameterMap);
5284 }
5285 else if (authType.equals(
5286 CompanyConstants.AUTH_TYPE_ID)) {
5287
5288 AuthPipeline.onMaxFailuresByUserId(
5289 PropsKeys.AUTH_MAX_FAILURES, companyId, userId,
5290 headerMap, parameterMap);
5291 }
5292 }
5293 }
5294 }
5295 catch (Exception e) {
5296 _log.error(e, e);
5297 }
5298 }
5299
5300
5301
5302 return authResult;
5303 }
5304
5305 protected Date getBirthday(
5306 int birthdayMonth, int birthdayDay, int birthdayYear)
5307 throws PortalException {
5308
5309 Date birthday = PortalUtil.getDate(
5310 birthdayMonth, birthdayDay, birthdayYear,
5311 ContactBirthdayException.class);
5312
5313 Date now = new Date();
5314
5315 if (birthday.after(now)) {
5316 throw new ContactBirthdayException();
5317 }
5318
5319 return birthday;
5320 }
5321
5322 protected String getScreenName(String screenName) {
5323 return StringUtil.lowerCase(StringUtil.trim(screenName));
5324 }
5325
5326 protected long[] getUserIds(List<User> users) {
5327 long[] userIds = new long[users.size()];
5328
5329 for (int i = 0; i < users.size(); i++) {
5330 User user = users.get(i);
5331
5332 userIds[i] = user.getUserId();
5333 }
5334
5335 return userIds;
5336 }
5337
5338 protected void reindex(final User user) {
5339 final Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5340 User.class);
5341
5342 Callable<Void> callable = new PortalCallable<Void>(
5343 user.getCompanyId()) {
5344
5345 @Override
5346 protected Void doCall() throws Exception {
5347 indexer.reindex(user);
5348
5349 return null;
5350 }
5351
5352 };
5353
5354 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
5355 }
5356
5357 protected Hits search(
5358 long companyId, String firstName, String middleName,
5359 String lastName, String fullName, String screenName,
5360 String emailAddress, String street, String city, String zip,
5361 String region, String country, int status,
5362 LinkedHashMap<String, Object> params, boolean andSearch, int start,
5363 int end, Sort sort)
5364 throws SystemException {
5365
5366 try {
5367 SearchContext searchContext = new SearchContext();
5368
5369 searchContext.setAndSearch(andSearch);
5370
5371 Map<String, Serializable> attributes =
5372 new HashMap<String, Serializable>();
5373
5374 attributes.put("city", city);
5375 attributes.put("country", country);
5376 attributes.put("emailAddress", emailAddress);
5377 attributes.put("firstName", firstName);
5378 attributes.put("fullName", fullName);
5379 attributes.put("lastName", lastName);
5380 attributes.put("middleName", middleName);
5381 attributes.put("params", params);
5382 attributes.put("region", region);
5383 attributes.put("screenName", screenName);
5384 attributes.put("street", street);
5385 attributes.put("status", status);
5386 attributes.put("zip", zip);
5387
5388 searchContext.setAttributes(attributes);
5389
5390 searchContext.setCompanyId(companyId);
5391 searchContext.setEnd(end);
5392
5393 if (params != null) {
5394 String keywords = (String)params.remove("keywords");
5395
5396 if (Validator.isNotNull(keywords)) {
5397 searchContext.setKeywords(keywords);
5398 }
5399 }
5400
5401 QueryConfig queryConfig = new QueryConfig();
5402
5403 queryConfig.setHighlightEnabled(false);
5404 queryConfig.setScoreEnabled(false);
5405
5406 searchContext.setQueryConfig(queryConfig);
5407
5408 if (sort != null) {
5409 searchContext.setSorts(new Sort[] {sort});
5410 }
5411
5412 searchContext.setStart(start);
5413
5414 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5415 User.class);
5416
5417 return indexer.search(searchContext);
5418 }
5419 catch (Exception e) {
5420 throw new SystemException(e);
5421 }
5422 }
5423
5424 protected void sendEmail(
5425 User user, String password, ServiceContext serviceContext)
5426 throws SystemException {
5427
5428 if (!PrefsPropsUtil.getBoolean(
5429 user.getCompanyId(),
5430 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
5431
5432 return;
5433 }
5434
5435 String fromName = PrefsPropsUtil.getString(
5436 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
5437 String fromAddress = PrefsPropsUtil.getString(
5438 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
5439
5440 String toName = user.getFullName();
5441 String toAddress = user.getEmailAddress();
5442
5443 String subject = PrefsPropsUtil.getContent(
5444 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
5445
5446 String body = null;
5447
5448 if (Validator.isNotNull(password)) {
5449 body = PrefsPropsUtil.getContent(
5450 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
5451 }
5452 else {
5453 body = PrefsPropsUtil.getContent(
5454 user.getCompanyId(),
5455 PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
5456 }
5457
5458 SubscriptionSender subscriptionSender = new SubscriptionSender();
5459
5460 subscriptionSender.setBody(body);
5461 subscriptionSender.setCompanyId(user.getCompanyId());
5462 subscriptionSender.setContextAttributes(
5463 "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
5464 "[$USER_SCREENNAME$]", user.getScreenName());
5465 subscriptionSender.setFrom(fromAddress, fromName);
5466 subscriptionSender.setHtmlFormat(true);
5467 subscriptionSender.setMailId("user", user.getUserId());
5468 subscriptionSender.setServiceContext(serviceContext);
5469 subscriptionSender.setSubject(subject);
5470 subscriptionSender.setUserId(user.getUserId());
5471
5472 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
5473
5474 subscriptionSender.flushNotificationsAsync();
5475 }
5476
5477 protected void setEmailAddress(
5478 User user, String password, String firstName, String middleName,
5479 String lastName, String emailAddress)
5480 throws PortalException, SystemException {
5481
5482 if (emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
5483 return;
5484 }
5485
5486 long userId = user.getUserId();
5487
5488
5489
5490 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
5491 Validator.isNotNull(password)) {
5492
5493 mailService.addUser(
5494 user.getCompanyId(), userId, password, firstName, middleName,
5495 lastName, emailAddress);
5496 }
5497
5498
5499
5500 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
5501 mailService.updateEmailAddress(
5502 user.getCompanyId(), userId, emailAddress);
5503 }
5504
5505
5506
5507 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
5508 mailService.deleteEmailAddress(user.getCompanyId(), userId);
5509 }
5510
5511 user.setEmailAddress(emailAddress);
5512 user.setDigest(StringPool.BLANK);
5513 }
5514
5515 protected void startWorkflowInstance(
5516 final long companyId, final long workflowUserId, final long userId,
5517 final User user, final ServiceContext workflowServiceContext) {
5518
5519 Callable<Void> callable = new PortalCallable<Void>(companyId) {
5520
5521 @Override
5522 protected Void doCall() throws Exception {
5523 WorkflowHandlerRegistryUtil.startWorkflowInstance(
5524 companyId, workflowUserId, User.class.getName(), userId,
5525 user, workflowServiceContext);
5526
5527 return null;
5528 }
5529
5530 };
5531
5532 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
5533 }
5534
5535 protected void updateGroups(
5536 long userId, long[] newGroupIds, ServiceContext serviceContext,
5537 boolean indexingEnabled)
5538 throws PortalException, SystemException {
5539
5540 if (newGroupIds == null) {
5541 return;
5542 }
5543
5544 List<Group> oldGroups = userPersistence.getGroups(userId);
5545
5546 Set<Long> oldGroupIds = new HashSet<Long>(oldGroups.size());
5547
5548 for (Group oldGroup : oldGroups) {
5549 long oldGroupId = oldGroup.getGroupId();
5550
5551 oldGroupIds.add(oldGroupId);
5552
5553 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
5554 unsetGroupUsers(
5555 oldGroupId, new long[] {userId}, serviceContext);
5556 }
5557 }
5558
5559 for (long newGroupId : newGroupIds) {
5560 if (!oldGroupIds.contains(newGroupId)) {
5561 addGroupUsers(newGroupId, new long[] {userId});
5562 }
5563 }
5564
5565 if (indexingEnabled) {
5566 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5567 User.class);
5568
5569 indexer.reindex(new long[] {userId});
5570 }
5571
5572 PermissionCacheUtil.clearCache();
5573 }
5574
5575 protected void updateOrganizations(
5576 long userId, long[] newOrganizationIds, boolean indexingEnabled)
5577 throws PortalException, SystemException {
5578
5579 if (newOrganizationIds == null) {
5580 return;
5581 }
5582
5583 List<Organization> oldOrganizations = userPersistence.getOrganizations(
5584 userId);
5585
5586 Set<Long> oldOrganizationIds = new HashSet<Long>(
5587 oldOrganizations.size());
5588
5589 for (Organization oldOrganization : oldOrganizations) {
5590 long oldOrganizationId = oldOrganization.getOrganizationId();
5591
5592 oldOrganizationIds.add(oldOrganizationId);
5593
5594 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
5595 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
5596 }
5597 }
5598
5599 for (long newOrganizationId : newOrganizationIds) {
5600 if (!oldOrganizationIds.contains(newOrganizationId)) {
5601 addOrganizationUsers(newOrganizationId, new long[] {userId});
5602 }
5603 }
5604
5605 if (indexingEnabled) {
5606 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5607 User.class);
5608
5609 indexer.reindex(new long[] {userId});
5610 }
5611
5612 PermissionCacheUtil.clearCache();
5613 }
5614
5615 protected void updateUserGroupRoles(
5616 User user, long[] groupIds, long[] organizationIds,
5617 List<UserGroupRole> userGroupRoles)
5618 throws PortalException, SystemException {
5619
5620 if (userGroupRoles == null) {
5621 return;
5622 }
5623
5624 List<UserGroupRole> previousUserGroupRoles =
5625 userGroupRolePersistence.findByUserId(user.getUserId());
5626
5627 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
5628 if (userGroupRoles.contains(userGroupRole)) {
5629 userGroupRoles.remove(userGroupRole);
5630 }
5631 else {
5632 userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
5633 }
5634 }
5635
5636 long[] validGroupIds = null;
5637
5638 if (groupIds != null) {
5639 validGroupIds = ArrayUtil.clone(groupIds);
5640 }
5641 else {
5642 validGroupIds = user.getGroupIds();
5643 }
5644
5645 if (organizationIds == null) {
5646 organizationIds = user.getOrganizationIds();
5647 }
5648
5649 long[] organizationGroupIds = new long[organizationIds.length];
5650
5651 for (int i = 0; i < organizationIds.length; i++) {
5652 long organizationId = organizationIds[i];
5653
5654 Organization organization =
5655 organizationPersistence.findByPrimaryKey(organizationId);
5656
5657 Group organizationGroup = organization.getGroup();
5658
5659 organizationGroupIds[i] = organizationGroup.getGroupId();
5660 }
5661
5662 validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
5663
5664 Arrays.sort(validGroupIds);
5665
5666 for (UserGroupRole userGroupRole : userGroupRoles) {
5667 if (Arrays.binarySearch(
5668 validGroupIds, userGroupRole.getGroupId()) >= 0) {
5669
5670 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
5671 }
5672 }
5673 }
5674
5675 protected void validate(
5676 long companyId, long userId, boolean autoPassword, String password1,
5677 String password2, boolean autoScreenName, String screenName,
5678 String emailAddress, String openId, String firstName,
5679 String middleName, String lastName, long[] organizationIds)
5680 throws PortalException, SystemException {
5681
5682 validateCompanyMaxUsers(companyId);
5683
5684 if (!autoScreenName) {
5685 validateScreenName(companyId, userId, screenName);
5686 }
5687
5688 if (!autoPassword) {
5689 PasswordPolicy passwordPolicy =
5690 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
5691
5692 PwdToolkitUtil.validate(
5693 companyId, 0, password1, password2, passwordPolicy);
5694 }
5695
5696 validateEmailAddress(companyId, emailAddress);
5697
5698 if (Validator.isNotNull(emailAddress)) {
5699 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
5700
5701 if ((user != null) && (user.getUserId() != userId)) {
5702 throw new DuplicateUserEmailAddressException();
5703 }
5704 }
5705
5706 validateOpenId(companyId, userId, openId);
5707
5708 validateFullName(companyId, firstName, middleName, lastName);
5709
5710 if (organizationIds != null) {
5711 for (long organizationId : organizationIds) {
5712 Organization organization =
5713 organizationPersistence.fetchByPrimaryKey(organizationId);
5714
5715 if (organization == null) {
5716 throw new NoSuchOrganizationException();
5717 }
5718 }
5719 }
5720 }
5721
5722 protected void validate(
5723 long userId, String screenName, String emailAddress, String openId,
5724 String firstName, String middleName, String lastName, String smsSn)
5725 throws PortalException, SystemException {
5726
5727 User user = userPersistence.findByPrimaryKey(userId);
5728
5729 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
5730 validateScreenName(user.getCompanyId(), userId, screenName);
5731 }
5732
5733 validateEmailAddress(user.getCompanyId(), emailAddress);
5734
5735 validateOpenId(user.getCompanyId(), userId, openId);
5736
5737 if (!user.isDefaultUser()) {
5738 if (Validator.isNotNull(emailAddress) &&
5739 !user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
5740
5741 if (userPersistence.fetchByC_EA(
5742 user.getCompanyId(), emailAddress) != null) {
5743
5744 throw new DuplicateUserEmailAddressException();
5745 }
5746 }
5747
5748 validateFullName(
5749 user.getCompanyId(), firstName, middleName, lastName);
5750 }
5751
5752 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
5753 throw new UserSmsException();
5754 }
5755 }
5756
5757 protected void validateCompanyMaxUsers(long companyId)
5758 throws PortalException, SystemException {
5759
5760 Company company = companyPersistence.findByPrimaryKey(companyId);
5761
5762 if (company.isSystem() || (company.getMaxUsers() == 0)) {
5763 return;
5764 }
5765
5766 int userCount = searchCount(
5767 companyId, null, WorkflowConstants.STATUS_APPROVED, null);
5768
5769 if (userCount > company.getMaxUsers()) {
5770 throw new CompanyMaxUsersException();
5771 }
5772 }
5773
5774 protected void validateEmailAddress(long companyId, String emailAddress)
5775 throws PortalException, SystemException {
5776
5777 if (Validator.isNull(emailAddress) &&
5778 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
5779
5780 return;
5781 }
5782
5783 EmailAddressValidator emailAddressValidator =
5784 EmailAddressValidatorFactory.getInstance();
5785
5786 if (!emailAddressValidator.validate(companyId, emailAddress)) {
5787 throw new UserEmailAddressException();
5788 }
5789
5790 String pop3User = PrefsPropsUtil.getString(
5791 PropsKeys.MAIL_SESSION_MAIL_POP3_USER,
5792 PropsValues.MAIL_SESSION_MAIL_POP3_USER);
5793
5794 if (emailAddress.equalsIgnoreCase(pop3User)) {
5795 throw new ReservedUserEmailAddressException();
5796 }
5797
5798 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
5799 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
5800 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
5801
5802 for (String reservedEmailAddress : reservedEmailAddresses) {
5803 if (emailAddress.equalsIgnoreCase(reservedEmailAddress)) {
5804 throw new ReservedUserEmailAddressException();
5805 }
5806 }
5807 }
5808
5809 protected void validateEmailAddress(
5810 User user, String emailAddress1, String emailAddress2)
5811 throws PortalException, SystemException {
5812
5813 if (!emailAddress1.equals(emailAddress2)) {
5814 throw new UserEmailAddressException();
5815 }
5816
5817 validateEmailAddress(user.getCompanyId(), emailAddress1);
5818 validateEmailAddress(user.getCompanyId(), emailAddress2);
5819
5820 if (!emailAddress1.equalsIgnoreCase(user.getEmailAddress())) {
5821 if (userPersistence.fetchByC_EA(
5822 user.getCompanyId(), emailAddress1) != null) {
5823
5824 throw new DuplicateUserEmailAddressException();
5825 }
5826 }
5827 }
5828
5829 protected void validateFullName(
5830 long companyId, String firstName, String middleName,
5831 String lastName)
5832 throws PortalException, SystemException {
5833
5834 if (Validator.isNull(firstName)) {
5835 throw new ContactFirstNameException();
5836 }
5837 else if (Validator.isNull(lastName) &&
5838 PrefsPropsUtil.getBoolean(
5839 companyId, PropsKeys.USERS_LAST_NAME_REQUIRED,
5840 PropsValues.USERS_LAST_NAME_REQUIRED)) {
5841
5842 throw new ContactLastNameException();
5843 }
5844
5845 FullNameValidator fullNameValidator =
5846 FullNameValidatorFactory.getInstance();
5847
5848 if (!fullNameValidator.validate(
5849 companyId, firstName, middleName, lastName)) {
5850
5851 throw new ContactFullNameException();
5852 }
5853 }
5854
5855 protected void validateOpenId(long companyId, long userId, String openId)
5856 throws PortalException, SystemException {
5857
5858 if (Validator.isNull(openId)) {
5859 return;
5860 }
5861
5862 User user = userPersistence.fetchByC_O(companyId, openId);
5863
5864 if ((user != null) && (user.getUserId() != userId)) {
5865 throw new DuplicateOpenIdException();
5866 }
5867 }
5868
5869 protected void validatePassword(
5870 long companyId, long userId, String password1, String password2)
5871 throws PortalException, SystemException {
5872
5873 if (Validator.isNull(password1) || Validator.isNull(password2)) {
5874 throw new UserPasswordException(
5875 UserPasswordException.PASSWORD_INVALID);
5876 }
5877
5878 if (!password1.equals(password2)) {
5879 throw new UserPasswordException(
5880 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
5881 }
5882
5883 PasswordPolicy passwordPolicy =
5884 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
5885
5886 PwdToolkitUtil.validate(
5887 companyId, userId, password1, password2, passwordPolicy);
5888 }
5889
5890 protected void validateReminderQuery(String question, String answer)
5891 throws PortalException {
5892
5893 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
5894 return;
5895 }
5896
5897 if (Validator.isNull(question)) {
5898 throw new UserReminderQueryException("Question cannot be null");
5899 }
5900
5901 if (Validator.isNull(answer)) {
5902 throw new UserReminderQueryException("Answer cannot be null");
5903 }
5904 }
5905
5906 protected void validateScreenName(
5907 long companyId, long userId, String screenName)
5908 throws PortalException, SystemException {
5909
5910 if (Validator.isNull(screenName)) {
5911 throw new UserScreenNameException();
5912 }
5913
5914 ScreenNameValidator screenNameValidator =
5915 ScreenNameValidatorFactory.getInstance();
5916
5917 if (!screenNameValidator.validate(companyId, screenName)) {
5918 throw new UserScreenNameException();
5919 }
5920
5921 if (Validator.isNumber(screenName)) {
5922 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
5923 throw new UserScreenNameException();
5924 }
5925
5926 if (!screenName.equals(String.valueOf(userId))) {
5927 Group group = groupPersistence.fetchByPrimaryKey(
5928 GetterUtil.getLong(screenName));
5929
5930 if (group != null) {
5931 throw new UserScreenNameException();
5932 }
5933 }
5934 }
5935
5936 for (char c : screenName.toCharArray()) {
5937 if (!Validator.isChar(c) && !Validator.isDigit(c) &&
5938 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
5939 (c != CharPool.UNDERLINE)) {
5940
5941 throw new UserScreenNameException();
5942 }
5943 }
5944
5945 String[] anonymousNames = BaseServiceImpl.ANONYMOUS_NAMES;
5946
5947 for (String anonymousName : anonymousNames) {
5948 if (screenName.equalsIgnoreCase(anonymousName)) {
5949 throw new UserScreenNameException();
5950 }
5951 }
5952
5953 User user = userPersistence.fetchByC_SN(companyId, screenName);
5954
5955 if ((user != null) && (user.getUserId() != userId)) {
5956 throw new DuplicateUserScreenNameException();
5957 }
5958
5959 String friendlyURL = StringPool.SLASH + screenName;
5960
5961 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
5962
5963 if ((group != null) && (group.getClassPK() != userId)) {
5964 throw new GroupFriendlyURLException(
5965 GroupFriendlyURLException.DUPLICATE);
5966 }
5967
5968 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
5969
5970 if (exceptionType != -1) {
5971 throw new UserScreenNameException(
5972 new GroupFriendlyURLException(exceptionType));
5973 }
5974
5975 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
5976 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
5977 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
5978
5979 for (String reservedScreenName : reservedScreenNames) {
5980 if (screenName.equalsIgnoreCase(reservedScreenName)) {
5981 throw new ReservedUserScreenNameException();
5982 }
5983 }
5984 }
5985
5986 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
5987
5988 private Map<Long, User> _defaultUsers = new ConcurrentHashMap<Long, User>();
5989
5990 }