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.NoSuchImageException;
028 import com.liferay.portal.NoSuchOrganizationException;
029 import com.liferay.portal.NoSuchRoleException;
030 import com.liferay.portal.NoSuchTicketException;
031 import com.liferay.portal.NoSuchUserException;
032 import com.liferay.portal.NoSuchUserGroupException;
033 import com.liferay.portal.PasswordExpiredException;
034 import com.liferay.portal.RequiredUserException;
035 import com.liferay.portal.ReservedUserEmailAddressException;
036 import com.liferay.portal.ReservedUserScreenNameException;
037 import com.liferay.portal.UserEmailAddressException;
038 import com.liferay.portal.UserIdException;
039 import com.liferay.portal.UserLockoutException;
040 import com.liferay.portal.UserPasswordException;
041 import com.liferay.portal.UserPortraitSizeException;
042 import com.liferay.portal.UserPortraitTypeException;
043 import com.liferay.portal.UserReminderQueryException;
044 import com.liferay.portal.UserScreenNameException;
045 import com.liferay.portal.UserSmsException;
046 import com.liferay.portal.kernel.dao.shard.ShardCallable;
047 import com.liferay.portal.kernel.exception.PortalException;
048 import com.liferay.portal.kernel.exception.SystemException;
049 import com.liferay.portal.kernel.image.ImageBag;
050 import com.liferay.portal.kernel.image.ImageToolUtil;
051 import com.liferay.portal.kernel.language.LanguageUtil;
052 import com.liferay.portal.kernel.log.Log;
053 import com.liferay.portal.kernel.log.LogFactoryUtil;
054 import com.liferay.portal.kernel.messaging.DestinationNames;
055 import com.liferay.portal.kernel.messaging.Message;
056 import com.liferay.portal.kernel.messaging.MessageBusUtil;
057 import com.liferay.portal.kernel.search.Hits;
058 import com.liferay.portal.kernel.search.Indexer;
059 import com.liferay.portal.kernel.search.IndexerRegistryUtil;
060 import com.liferay.portal.kernel.search.QueryConfig;
061 import com.liferay.portal.kernel.search.SearchContext;
062 import com.liferay.portal.kernel.search.Sort;
063 import com.liferay.portal.kernel.spring.aop.Skip;
064 import com.liferay.portal.kernel.transaction.Propagation;
065 import com.liferay.portal.kernel.transaction.TransactionCommitCallbackRegistryUtil;
066 import com.liferay.portal.kernel.transaction.Transactional;
067 import com.liferay.portal.kernel.util.ArrayUtil;
068 import com.liferay.portal.kernel.util.CharPool;
069 import com.liferay.portal.kernel.util.Digester;
070 import com.liferay.portal.kernel.util.DigesterUtil;
071 import com.liferay.portal.kernel.util.GetterUtil;
072 import com.liferay.portal.kernel.util.KeyValuePair;
073 import com.liferay.portal.kernel.util.LocaleUtil;
074 import com.liferay.portal.kernel.util.OrderByComparator;
075 import com.liferay.portal.kernel.util.ParamUtil;
076 import com.liferay.portal.kernel.util.PropsKeys;
077 import com.liferay.portal.kernel.util.StringBundler;
078 import com.liferay.portal.kernel.util.StringPool;
079 import com.liferay.portal.kernel.util.StringUtil;
080 import com.liferay.portal.kernel.util.UnicodeProperties;
081 import com.liferay.portal.kernel.util.Validator;
082 import com.liferay.portal.kernel.workflow.WorkflowConstants;
083 import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil;
084 import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
085 import com.liferay.portal.model.Account;
086 import com.liferay.portal.model.Company;
087 import com.liferay.portal.model.CompanyConstants;
088 import com.liferay.portal.model.Contact;
089 import com.liferay.portal.model.ContactConstants;
090 import com.liferay.portal.model.Group;
091 import com.liferay.portal.model.GroupConstants;
092 import com.liferay.portal.model.Layout;
093 import com.liferay.portal.model.Organization;
094 import com.liferay.portal.model.PasswordPolicy;
095 import com.liferay.portal.model.ResourceConstants;
096 import com.liferay.portal.model.Role;
097 import com.liferay.portal.model.RoleConstants;
098 import com.liferay.portal.model.Team;
099 import com.liferay.portal.model.Ticket;
100 import com.liferay.portal.model.TicketConstants;
101 import com.liferay.portal.model.User;
102 import com.liferay.portal.model.UserGroup;
103 import com.liferay.portal.model.UserGroupRole;
104 import com.liferay.portal.model.impl.LayoutImpl;
105 import com.liferay.portal.security.auth.AuthPipeline;
106 import com.liferay.portal.security.auth.Authenticator;
107 import com.liferay.portal.security.auth.EmailAddressGenerator;
108 import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
109 import com.liferay.portal.security.auth.EmailAddressValidator;
110 import com.liferay.portal.security.auth.EmailAddressValidatorFactory;
111 import com.liferay.portal.security.auth.FullNameGenerator;
112 import com.liferay.portal.security.auth.FullNameGeneratorFactory;
113 import com.liferay.portal.security.auth.FullNameValidator;
114 import com.liferay.portal.security.auth.FullNameValidatorFactory;
115 import com.liferay.portal.security.auth.PrincipalException;
116 import com.liferay.portal.security.auth.ScreenNameGenerator;
117 import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
118 import com.liferay.portal.security.auth.ScreenNameValidator;
119 import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
120 import com.liferay.portal.security.ldap.LDAPSettingsUtil;
121 import com.liferay.portal.security.permission.PermissionCacheUtil;
122 import com.liferay.portal.security.pwd.PasswordEncryptorUtil;
123 import com.liferay.portal.security.pwd.PwdAuthenticator;
124 import com.liferay.portal.security.pwd.PwdToolkitUtil;
125 import com.liferay.portal.security.pwd.RegExpToolkit;
126 import com.liferay.portal.service.BaseServiceImpl;
127 import com.liferay.portal.service.ServiceContext;
128 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
129 import com.liferay.portal.util.PortalUtil;
130 import com.liferay.portal.util.PrefsPropsUtil;
131 import com.liferay.portal.util.PropsValues;
132 import com.liferay.portal.util.SubscriptionSender;
133 import com.liferay.portlet.documentlibrary.ImageSizeException;
134 import com.liferay.portlet.messageboards.model.MBMessage;
135 import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
136 import com.liferay.util.Encryptor;
137 import com.liferay.util.EncryptorException;
138 import com.liferay.util.PwdGenerator;
139
140 import java.awt.image.RenderedImage;
141
142 import java.io.IOException;
143 import java.io.Serializable;
144
145 import java.util.ArrayList;
146 import java.util.Arrays;
147 import java.util.Calendar;
148 import java.util.Date;
149 import java.util.HashMap;
150 import java.util.HashSet;
151 import java.util.LinkedHashMap;
152 import java.util.List;
153 import java.util.Locale;
154 import java.util.Map;
155 import java.util.Set;
156 import java.util.concurrent.Callable;
157 import java.util.concurrent.ConcurrentHashMap;
158
159
171 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
172
173
187 @Override
188 public User addDefaultAdminUser(
189 long companyId, String screenName, String emailAddress,
190 Locale locale, String firstName, String middleName, String lastName)
191 throws PortalException, SystemException {
192
193 long creatorUserId = 0;
194 boolean autoPassword = false;
195 String password1 = PropsValues.DEFAULT_ADMIN_PASSWORD;
196 String password2 = password1;
197 boolean autoScreenName = false;
198
199 screenName = getLogin(screenName);
200
201 for (int i = 1;; i++) {
202 User screenNameUser = userPersistence.fetchByC_SN(
203 companyId, screenName);
204
205 if (screenNameUser == null) {
206 break;
207 }
208
209 screenName = screenName + i;
210 }
211
212 long facebookId = 0;
213 String openId = StringPool.BLANK;
214 int prefixId = 0;
215 int suffixId = 0;
216 boolean male = true;
217 int birthdayMonth = Calendar.JANUARY;
218 int birthdayDay = 1;
219 int birthdayYear = 1970;
220 String jobTitle = StringPool.BLANK;
221
222 Group guestGroup = groupLocalService.getGroup(
223 companyId, GroupConstants.GUEST);
224
225 long[] groupIds = {guestGroup.getGroupId()};
226
227 long[] organizationIds = null;
228
229 Role adminRole = roleLocalService.getRole(
230 companyId, RoleConstants.ADMINISTRATOR);
231
232 Role powerUserRole = roleLocalService.getRole(
233 companyId, RoleConstants.POWER_USER);
234
235 long[] roleIds = {adminRole.getRoleId(), powerUserRole.getRoleId()};
236
237 long[] userGroupIds = null;
238 boolean sendEmail = false;
239 ServiceContext serviceContext = new ServiceContext();
240
241 User defaultAdminUser = addUser(
242 creatorUserId, companyId, autoPassword, password1, password2,
243 autoScreenName, screenName, emailAddress, facebookId, openId,
244 locale, firstName, middleName, lastName, prefixId, suffixId, male,
245 birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
246 organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
247
248 updateEmailAddressVerified(defaultAdminUser.getUserId(), true);
249
250 updateLastLogin(
251 defaultAdminUser.getUserId(), defaultAdminUser.getLoginIP());
252
253 updatePasswordReset(defaultAdminUser.getUserId(), false);
254
255 return defaultAdminUser;
256 }
257
258
268 @Override
269 public void addDefaultGroups(long userId)
270 throws PortalException, SystemException {
271
272 User user = userPersistence.findByPrimaryKey(userId);
273
274 Set<Long> groupIdsSet = new HashSet<Long>();
275
276 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
277 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
278 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
279
280 for (String defaultGroupName : defaultGroupNames) {
281 Company company = companyPersistence.findByPrimaryKey(
282 user.getCompanyId());
283
284 Account account = company.getAccount();
285
286 if (StringUtil.equalsIgnoreCase(
287 defaultGroupName, account.getName())) {
288
289 defaultGroupName = GroupConstants.GUEST;
290 }
291
292 Group group = groupPersistence.fetchByC_N(
293 user.getCompanyId(), defaultGroupName);
294
295 if ((group != null) &&
296 !userPersistence.containsGroup(
297 userId, group.getGroupId())) {
298
299 groupIdsSet.add(group.getGroupId());
300 }
301 }
302
303 String[] defaultOrganizationGroupNames = PrefsPropsUtil.getStringArray(
304 user.getCompanyId(),
305 PropsKeys.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES,
306 StringPool.NEW_LINE,
307 PropsValues.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES);
308
309 for (String defaultOrganizationGroupName :
310 defaultOrganizationGroupNames) {
311
312 defaultOrganizationGroupName +=
313 GroupLocalServiceImpl.ORGANIZATION_NAME_SUFFIX;
314
315 Group group = groupPersistence.fetchByC_N(
316 user.getCompanyId(), defaultOrganizationGroupName);
317
318 if ((group != null) &&
319 !userPersistence.containsGroup(
320 userId, group.getGroupId())) {
321
322 groupIdsSet.add(group.getGroupId());
323 }
324 }
325
326 long[] groupIds = ArrayUtil.toArray(
327 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
328
329 groupLocalService.addUserGroups(userId, groupIds);
330 }
331
332
342 @Override
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 @Override
386 @SuppressWarnings("deprecation")
387 public void addDefaultUserGroups(long userId)
388 throws PortalException, SystemException {
389
390 User user = userPersistence.findByPrimaryKey(userId);
391
392 Set<Long> userGroupIdSet = new HashSet<Long>();
393
394 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
395 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
396 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
397
398 for (String defaultUserGroupName : defaultUserGroupNames) {
399 try {
400 UserGroup userGroup = userGroupPersistence.findByC_N(
401 user.getCompanyId(), defaultUserGroupName);
402
403 if (!userPersistence.containsUserGroup(
404 userId, userGroup.getUserGroupId())) {
405
406 userGroupIdSet.add(userGroup.getUserGroupId());
407 }
408 }
409 catch (NoSuchUserGroupException nsuge) {
410 }
411 }
412
413 long[] userGroupIds = ArrayUtil.toArray(
414 userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
415
416 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
417 for (long userGroupId : userGroupIds) {
418 userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
419 }
420 }
421
422 userPersistence.addUserGroups(userId, userGroupIds);
423 }
424
425
434 @Override
435 public void addGroupUsers(long groupId, long[] userIds)
436 throws PortalException, SystemException {
437
438 groupPersistence.addUsers(groupId, userIds);
439
440 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
441
442 indexer.reindex(userIds);
443
444 PermissionCacheUtil.clearCache();
445
446 addDefaultRolesAndTeams(groupId, userIds);
447 }
448
449
458 @Override
459 public void addOrganizationUsers(long organizationId, long[] userIds)
460 throws PortalException, SystemException {
461
462 organizationPersistence.addUsers(organizationId, userIds);
463
464 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
465
466 indexer.reindex(userIds);
467
468 PermissionCacheUtil.clearCache();
469 }
470
471
479 @Override
480 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
481 throws SystemException {
482
483 passwordPolicyRelLocalService.addPasswordPolicyRels(
484 passwordPolicyId, User.class.getName(), userIds);
485 }
486
487
496 @Override
497 public void addRoleUsers(long roleId, long[] userIds)
498 throws PortalException, SystemException {
499
500 rolePersistence.addUsers(roleId, userIds);
501
502 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
503
504 indexer.reindex(userIds);
505
506 PermissionCacheUtil.clearCache();
507 }
508
509
518 @Override
519 public void addTeamUsers(long teamId, long[] userIds)
520 throws PortalException, SystemException {
521
522 teamPersistence.addUsers(teamId, userIds);
523
524 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
525
526 indexer.reindex(userIds);
527
528 PermissionCacheUtil.clearCache();
529 }
530
531
579 @Override
580 public User addUser(
581 long creatorUserId, long companyId, boolean autoPassword,
582 String password1, String password2, boolean autoScreenName,
583 String screenName, String emailAddress, long facebookId,
584 String openId, Locale locale, String firstName, String middleName,
585 String lastName, int prefixId, int suffixId, boolean male,
586 int birthdayMonth, int birthdayDay, int birthdayYear,
587 String jobTitle, long[] groupIds, long[] organizationIds,
588 long[] roleIds, long[] userGroupIds, boolean sendEmail,
589 ServiceContext serviceContext)
590 throws PortalException, SystemException {
591
592 boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
593
594 try {
595 WorkflowThreadLocal.setEnabled(false);
596
597 if (serviceContext == null) {
598 serviceContext = new ServiceContext();
599 }
600
601 if (serviceContext.getWorkflowAction() !=
602 WorkflowConstants.ACTION_PUBLISH) {
603
604 serviceContext.setWorkflowAction(
605 WorkflowConstants.ACTION_PUBLISH);
606 }
607
608 return addUserWithWorkflow(
609 creatorUserId, companyId, autoPassword, password1, password2,
610 autoScreenName, screenName, emailAddress, facebookId, openId,
611 locale, firstName, middleName, lastName, prefixId, suffixId,
612 male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
613 groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
614 serviceContext);
615 }
616 finally {
617 WorkflowThreadLocal.setEnabled(workflowEnabled);
618 }
619 }
620
621
630 @Override
631 @SuppressWarnings("deprecation")
632 public void addUserGroupUsers(long userGroupId, long[] userIds)
633 throws PortalException, SystemException {
634
635 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
636 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
637 }
638
639 userGroupPersistence.addUsers(userGroupId, userIds);
640
641 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
642
643 indexer.reindex(userIds);
644
645 PermissionCacheUtil.clearCache();
646 }
647
648
696 @Override
697 @SuppressWarnings("deprecation")
698 public User addUserWithWorkflow(
699 long creatorUserId, long companyId, boolean autoPassword,
700 String password1, String password2, boolean autoScreenName,
701 String screenName, String emailAddress, long facebookId,
702 String openId, Locale locale, String firstName, String middleName,
703 String lastName, int prefixId, int suffixId, boolean male,
704 int birthdayMonth, int birthdayDay, int birthdayYear,
705 String jobTitle, long[] groupIds, long[] organizationIds,
706 long[] roleIds, long[] userGroupIds, boolean sendEmail,
707 ServiceContext serviceContext)
708 throws PortalException, SystemException {
709
710
711
712 Company company = companyPersistence.findByPrimaryKey(companyId);
713 screenName = getLogin(screenName);
714 openId = StringUtil.trim(openId);
715 Date now = new Date();
716
717 if (PrefsPropsUtil.getBoolean(
718 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
719
720 autoScreenName = true;
721 }
722
723
724
725 long userId = counterLocalService.increment();
726
727 EmailAddressGenerator emailAddressGenerator =
728 EmailAddressGeneratorFactory.getInstance();
729
730 if ((emailAddress == null) ||
731 emailAddressGenerator.isGenerated(emailAddress)) {
732
733 emailAddress = StringPool.BLANK;
734 }
735 else {
736 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
737 }
738
739 if (!PrefsPropsUtil.getBoolean(
740 companyId, PropsKeys.USERS_EMAIL_ADDRESS_REQUIRED) &&
741 Validator.isNull(emailAddress)) {
742
743 emailAddress = emailAddressGenerator.generate(companyId, userId);
744 }
745
746 validate(
747 companyId, userId, autoPassword, password1, password2,
748 autoScreenName, screenName, emailAddress, openId, firstName,
749 middleName, lastName, organizationIds);
750
751 if (!autoPassword) {
752 if (Validator.isNull(password1) || Validator.isNull(password2)) {
753 throw new UserPasswordException(
754 UserPasswordException.PASSWORD_INVALID);
755 }
756 }
757
758 if (autoScreenName) {
759 ScreenNameGenerator screenNameGenerator =
760 ScreenNameGeneratorFactory.getInstance();
761
762 try {
763 screenName = screenNameGenerator.generate(
764 companyId, userId, emailAddress);
765 }
766 catch (Exception e) {
767 throw new SystemException(e);
768 }
769 }
770
771 User defaultUser = getDefaultUser(companyId);
772
773 FullNameGenerator fullNameGenerator =
774 FullNameGeneratorFactory.getInstance();
775
776 String fullName = fullNameGenerator.getFullName(
777 firstName, middleName, lastName);
778
779 String greeting = LanguageUtil.format(
780 locale, "welcome-x", " " + fullName, false);
781
782 User user = userPersistence.create(userId);
783
784 if (serviceContext != null) {
785 String uuid = serviceContext.getUuid();
786
787 if (Validator.isNotNull(uuid)) {
788 user.setUuid(uuid);
789 }
790 }
791
792 user.setCompanyId(companyId);
793 user.setCreateDate(now);
794 user.setModifiedDate(now);
795 user.setDefaultUser(false);
796 user.setContactId(counterLocalService.increment());
797
798 if (Validator.isNotNull(password1)) {
799 user.setPassword(PasswordEncryptorUtil.encrypt(password1));
800 user.setPasswordUnencrypted(password1);
801 }
802
803 user.setPasswordEncrypted(true);
804
805 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
806
807 boolean passwordReset = false;
808
809 if (passwordPolicy != null) {
810 if (passwordPolicy.isChangeable() &&
811 passwordPolicy.isChangeRequired()) {
812
813 passwordReset = true;
814 }
815
816 addPasswordPolicyUsers(
817 passwordPolicy.getPasswordPolicyId(), new long[] {userId});
818 }
819
820 user.setPasswordReset(passwordReset);
821
822 user.setDigest(StringPool.BLANK);
823 user.setScreenName(screenName);
824 user.setEmailAddress(emailAddress);
825 user.setFacebookId(facebookId);
826
827 Long ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
828
829 if (ldapServerId != null) {
830 user.setLdapServerId(ldapServerId);
831 }
832 else {
833 user.setLdapServerId(-1);
834 }
835
836 user.setOpenId(openId);
837 user.setLanguageId(LocaleUtil.toLanguageId(locale));
838 user.setTimeZoneId(defaultUser.getTimeZoneId());
839 user.setGreeting(greeting);
840 user.setFirstName(firstName);
841 user.setMiddleName(middleName);
842 user.setLastName(lastName);
843 user.setJobTitle(jobTitle);
844 user.setStatus(WorkflowConstants.STATUS_DRAFT);
845 user.setExpandoBridgeAttributes(serviceContext);
846
847 userPersistence.update(user, serviceContext);
848
849
850
851 String creatorUserName = StringPool.BLANK;
852
853 if (creatorUserId <= 0) {
854 creatorUserId = user.getUserId();
855
856
857
858
859
860 }
861 else {
862 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
863
864 creatorUserName = creatorUser.getFullName();
865 }
866
867 resourceLocalService.addResources(
868 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
869 false, false, false);
870
871
872
873 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
874
875 Contact contact = contactPersistence.create(user.getContactId());
876
877 contact.setCompanyId(user.getCompanyId());
878 contact.setUserId(creatorUserId);
879 contact.setUserName(creatorUserName);
880 contact.setCreateDate(now);
881 contact.setModifiedDate(now);
882 contact.setClassName(User.class.getName());
883 contact.setClassPK(user.getUserId());
884 contact.setAccountId(company.getAccountId());
885 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
886 contact.setEmailAddress(user.getEmailAddress());
887 contact.setFirstName(firstName);
888 contact.setMiddleName(middleName);
889 contact.setLastName(lastName);
890 contact.setPrefixId(prefixId);
891 contact.setSuffixId(suffixId);
892 contact.setMale(male);
893 contact.setBirthday(birthday);
894 contact.setJobTitle(jobTitle);
895
896 contactPersistence.update(contact, serviceContext);
897
898
899
900 groupLocalService.addGroup(
901 user.getUserId(), GroupConstants.DEFAULT_PARENT_GROUP_ID,
902 User.class.getName(), user.getUserId(), null, null, 0,
903 StringPool.SLASH + screenName, false, true, null);
904
905
906
907 if (groupIds != null) {
908 List<Group> groups = new ArrayList<Group>();
909
910 for (long groupId : groupIds) {
911 Group group = groupLocalService.fetchGroup(groupId);
912
913 if (group != null) {
914 groups.add(group);
915 }
916 else {
917 if (_log.isWarnEnabled()) {
918 _log.warn("Group " + groupId + " does not exist");
919 }
920 }
921 }
922
923 groupLocalService.addUserGroups(userId, groups);
924 }
925
926 addDefaultGroups(userId);
927
928
929
930 updateOrganizations(userId, organizationIds, false);
931
932
933
934 if (roleIds != null) {
935 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
936
937 userPersistence.setRoles(userId, roleIds);
938 }
939
940 addDefaultRoles(userId);
941
942
943
944 if (userGroupIds != null) {
945 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
946 for (long userGroupId : userGroupIds) {
947 userGroupLocalService.copyUserGroupLayouts(
948 userGroupId, new long[] {userId});
949 }
950 }
951
952 userPersistence.setUserGroups(userId, userGroupIds);
953 }
954
955 addDefaultUserGroups(userId);
956
957
958
959 if (serviceContext != null) {
960 updateAsset(
961 creatorUserId, user, serviceContext.getAssetCategoryIds(),
962 serviceContext.getAssetTagNames());
963 }
964
965
966
967 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
968 reindex(user);
969 }
970
971
972
973 long workflowUserId = creatorUserId;
974
975 if (workflowUserId == userId) {
976 workflowUserId = defaultUser.getUserId();
977 }
978
979 ServiceContext workflowServiceContext = serviceContext;
980
981 if (workflowServiceContext == null) {
982 workflowServiceContext = new ServiceContext();
983 }
984
985 workflowServiceContext.setAttribute("autoPassword", autoPassword);
986 workflowServiceContext.setAttribute("sendEmail", sendEmail);
987
988 WorkflowHandlerRegistryUtil.startWorkflowInstance(
989 companyId, workflowUserId, User.class.getName(), userId, user,
990 workflowServiceContext);
991
992 if (serviceContext != null) {
993 String passwordUnencrypted = (String)serviceContext.getAttribute(
994 "passwordUnencrypted");
995
996 if (Validator.isNotNull(passwordUnencrypted)) {
997 user.setPasswordUnencrypted(passwordUnencrypted);
998 }
999 }
1000
1001 return user;
1002 }
1003
1004
1028 @Override
1029 public int authenticateByEmailAddress(
1030 long companyId, String emailAddress, String password,
1031 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1032 Map<String, Object> resultsMap)
1033 throws PortalException, SystemException {
1034
1035 return authenticate(
1036 companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
1037 headerMap, parameterMap, resultsMap);
1038 }
1039
1040
1064 @Override
1065 public int authenticateByScreenName(
1066 long companyId, String screenName, String password,
1067 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1068 Map<String, Object> resultsMap)
1069 throws PortalException, SystemException {
1070
1071 return authenticate(
1072 companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
1073 headerMap, parameterMap, resultsMap);
1074 }
1075
1076
1100 @Override
1101 public int authenticateByUserId(
1102 long companyId, long userId, String password,
1103 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1104 Map<String, Object> resultsMap)
1105 throws PortalException, SystemException {
1106
1107 return authenticate(
1108 companyId, String.valueOf(userId), password,
1109 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap, resultsMap);
1110 }
1111
1112
1152 @Override
1153 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1154 public long authenticateForBasic(
1155 long companyId, String authType, String login, String password)
1156 throws PortalException, SystemException {
1157
1158 if (PropsValues.AUTH_LOGIN_DISABLED) {
1159 return 0;
1160 }
1161
1162 User user = null;
1163
1164 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1165 user = fetchUserByEmailAddress(companyId, login);
1166 }
1167 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1168 user = fetchUserByScreenName(companyId, login);
1169 }
1170 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1171 user = userPersistence.fetchByPrimaryKey(GetterUtil.getLong(login));
1172 }
1173
1174 if (user == null) {
1175 return 0;
1176 }
1177
1178 if (user.isDefaultUser()) {
1179 if (_log.isInfoEnabled()) {
1180 _log.info(
1181 "Basic authentication is disabled for the default " +
1182 "user");
1183 }
1184
1185 return 0;
1186 }
1187 else if (!user.isActive()) {
1188 if (_log.isInfoEnabled()) {
1189 _log.info(
1190 "Basic authentication is disabled for inactive user " +
1191 user.getUserId());
1192 }
1193
1194 return 0;
1195 }
1196
1197 if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
1198 return user.getUserId();
1199 }
1200
1201 String userPassword = user.getPassword();
1202
1203 if (!user.isPasswordEncrypted()) {
1204 userPassword = PasswordEncryptorUtil.encrypt(userPassword);
1205 }
1206
1207 String encPassword = PasswordEncryptorUtil.encrypt(
1208 password, userPassword);
1209
1210 if (userPassword.equals(password) || userPassword.equals(encPassword)) {
1211 return user.getUserId();
1212 }
1213
1214 return 0;
1215 }
1216
1217
1235 @Override
1236 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1237 public long authenticateForDigest(
1238 long companyId, String username, String realm, String nonce,
1239 String method, String uri, String response)
1240 throws PortalException, SystemException {
1241
1242 if (PropsValues.AUTH_LOGIN_DISABLED) {
1243 return 0;
1244 }
1245
1246
1247
1248 User user = fetchUserByEmailAddress(companyId, username);
1249
1250 if (user == null) {
1251 user = fetchUserByScreenName(companyId, username);
1252 }
1253
1254 if (user == null) {
1255 user = userPersistence.fetchByPrimaryKey(
1256 GetterUtil.getLong(username));
1257 }
1258
1259 if (user == null) {
1260 return 0;
1261 }
1262
1263 if (user.isDefaultUser()) {
1264 if (_log.isInfoEnabled()) {
1265 _log.info(
1266 "Digest authentication is disabled for the default user");
1267 }
1268
1269 return 0;
1270 }
1271 else if (!user.isActive()) {
1272 if (_log.isInfoEnabled()) {
1273 _log.info(
1274 "Digest authentication is disabled for inactive user " +
1275 user.getUserId());
1276 }
1277
1278 return 0;
1279 }
1280
1281
1282
1283 String digest = user.getDigest();
1284
1285 if (Validator.isNull(digest)) {
1286 _log.error(
1287 "User must first login through the portal " + user.getUserId());
1288
1289 return 0;
1290 }
1291
1292 String[] digestArray = StringUtil.split(user.getDigest());
1293
1294 for (String ha1 : digestArray) {
1295 String ha2 = DigesterUtil.digestHex(Digester.MD5, method, uri);
1296
1297 String curResponse = DigesterUtil.digestHex(
1298 Digester.MD5, ha1, nonce, ha2);
1299
1300 if (response.equals(curResponse)) {
1301 return user.getUserId();
1302 }
1303 }
1304
1305 return 0;
1306 }
1307
1308
1317 @Override
1318 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1319 public boolean authenticateForJAAS(long userId, String encPassword) {
1320 if (PropsValues.AUTH_LOGIN_DISABLED) {
1321 return false;
1322 }
1323
1324 try {
1325 User user = userPersistence.findByPrimaryKey(userId);
1326
1327 if (user.isDefaultUser()) {
1328 if (_log.isInfoEnabled()) {
1329 _log.info(
1330 "JAAS authentication is disabled for the default user");
1331 }
1332
1333 return false;
1334 }
1335 else if (!user.isActive()) {
1336 if (_log.isInfoEnabled()) {
1337 _log.info(
1338 "JAAS authentication is disabled for inactive user " +
1339 userId);
1340 }
1341
1342 return false;
1343 }
1344
1345 String userPassword = user.getPassword();
1346
1347 if (user.isPasswordEncrypted()) {
1348 if (userPassword.equals(encPassword)) {
1349 return true;
1350 }
1351
1352 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1353 encPassword = PasswordEncryptorUtil.encrypt(
1354 encPassword, userPassword);
1355
1356 if (userPassword.equals(encPassword)) {
1357 return true;
1358 }
1359 }
1360 }
1361 else {
1362 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1363 if (userPassword.equals(encPassword)) {
1364 return true;
1365 }
1366 }
1367
1368 userPassword = PasswordEncryptorUtil.encrypt(
1369 userPassword, encPassword);
1370
1371 if (userPassword.equals(encPassword)) {
1372 return true;
1373 }
1374 }
1375 }
1376 catch (Exception e) {
1377 _log.error(e);
1378 }
1379
1380 return false;
1381 }
1382
1383
1391 @Override
1392 public void checkLockout(User user)
1393 throws PortalException, SystemException {
1394
1395 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1396 return;
1397 }
1398
1399 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1400
1401 if (!passwordPolicy.isLockout()) {
1402 return;
1403 }
1404
1405
1406
1407 Date now = new Date();
1408 int failedLoginAttempts = user.getFailedLoginAttempts();
1409
1410 if (failedLoginAttempts > 0) {
1411 long failedLoginTime = user.getLastFailedLoginDate().getTime();
1412 long elapsedTime = now.getTime() - failedLoginTime;
1413 long requiredElapsedTime =
1414 passwordPolicy.getResetFailureCount() * 1000;
1415
1416 if ((requiredElapsedTime != 0) &&
1417 (elapsedTime > requiredElapsedTime)) {
1418
1419 user.setLastFailedLoginDate(null);
1420 user.setFailedLoginAttempts(0);
1421
1422 userPersistence.update(user);
1423 }
1424 }
1425
1426
1427
1428 if (user.isLockout()) {
1429 long lockoutTime = user.getLockoutDate().getTime();
1430 long elapsedTime = now.getTime() - lockoutTime;
1431 long requiredElapsedTime =
1432 passwordPolicy.getLockoutDuration() * 1000;
1433
1434 if ((requiredElapsedTime != 0) &&
1435 (elapsedTime > requiredElapsedTime)) {
1436
1437 user.setLockout(false);
1438 user.setLockoutDate(null);
1439
1440 userPersistence.update(user);
1441 }
1442 }
1443
1444 if (user.isLockout()) {
1445 throw new UserLockoutException();
1446 }
1447 }
1448
1449
1456 @Override
1457 public void checkLoginFailure(User user) throws SystemException {
1458 Date now = new Date();
1459
1460 int failedLoginAttempts = user.getFailedLoginAttempts();
1461
1462 user.setLastFailedLoginDate(now);
1463 user.setFailedLoginAttempts(++failedLoginAttempts);
1464
1465 userPersistence.update(user);
1466 }
1467
1468
1478 @Override
1479 public void checkLoginFailureByEmailAddress(
1480 long companyId, String emailAddress)
1481 throws PortalException, SystemException {
1482
1483 User user = getUserByEmailAddress(companyId, emailAddress);
1484
1485 checkLoginFailure(user);
1486 }
1487
1488
1496 @Override
1497 public void checkLoginFailureById(long userId)
1498 throws PortalException, SystemException {
1499
1500 User user = userPersistence.findByPrimaryKey(userId);
1501
1502 checkLoginFailure(user);
1503 }
1504
1505
1514 @Override
1515 public void checkLoginFailureByScreenName(long companyId, String screenName)
1516 throws PortalException, SystemException {
1517
1518 User user = getUserByScreenName(companyId, screenName);
1519
1520 checkLoginFailure(user);
1521 }
1522
1523
1533 @Override
1534 public void checkPasswordExpired(User user)
1535 throws PortalException, SystemException {
1536
1537 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1538 return;
1539 }
1540
1541 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1542
1543
1544
1545 if (isPasswordExpired(user)) {
1546 int graceLoginCount = user.getGraceLoginCount();
1547
1548 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
1549 user.setGraceLoginCount(++graceLoginCount);
1550
1551 userPersistence.update(user);
1552 }
1553 else {
1554 user.setDigest(StringPool.BLANK);
1555
1556 userPersistence.update(user);
1557
1558 throw new PasswordExpiredException();
1559 }
1560 }
1561
1562
1563
1564 if (passwordPolicy.isChangeable() &&
1565 passwordPolicy.isChangeRequired()) {
1566
1567 if (user.getLastLoginDate() == null) {
1568 user.setPasswordReset(true);
1569
1570 userPersistence.update(user);
1571 }
1572 }
1573 }
1574
1575
1581 @Override
1582 public void clearOrganizationUsers(long organizationId)
1583 throws SystemException {
1584
1585 organizationPersistence.clearUsers(organizationId);
1586
1587 PermissionCacheUtil.clearCache();
1588 }
1589
1590
1596 @Override
1597 public void clearUserGroupUsers(long userGroupId) throws SystemException {
1598 userGroupPersistence.clearUsers(userGroupId);
1599
1600 PermissionCacheUtil.clearCache();
1601 }
1602
1603
1616 @Override
1617 public void completeUserRegistration(
1618 User user, ServiceContext serviceContext)
1619 throws PortalException, SystemException {
1620
1621 boolean autoPassword = ParamUtil.getBoolean(
1622 serviceContext, "autoPassword");
1623
1624 String password = null;
1625
1626 if (autoPassword) {
1627 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1628 if (_log.isWarnEnabled()) {
1629 StringBundler sb = new StringBundler(4);
1630
1631 sb.append("When LDAP password policy is enabled, it is ");
1632 sb.append("possible that portal generated passwords will ");
1633 sb.append("not match the LDAP policy. Using ");
1634 sb.append("RegExpToolkit to generate new password.");
1635
1636 _log.warn(sb.toString());
1637 }
1638
1639 RegExpToolkit regExpToolkit = new RegExpToolkit();
1640
1641 password = regExpToolkit.generate(null);
1642 }
1643 else {
1644 PasswordPolicy passwordPolicy =
1645 passwordPolicyLocalService.getPasswordPolicy(
1646 user.getCompanyId(), user.getOrganizationIds());
1647
1648 password = PwdToolkitUtil.generate(passwordPolicy);
1649 }
1650
1651 user.setPassword(PasswordEncryptorUtil.encrypt(password));
1652 user.setPasswordUnencrypted(password);
1653 user.setPasswordEncrypted(true);
1654 user.setPasswordModified(true);
1655 user.setPasswordModifiedDate(new Date());
1656
1657 userPersistence.update(user);
1658
1659 user.setPasswordModified(false);
1660 }
1661
1662 if (user.hasCompanyMx()) {
1663 String mailPassword = password;
1664
1665 if (Validator.isNull(mailPassword)) {
1666 mailPassword = user.getPasswordUnencrypted();
1667 }
1668
1669 mailService.addUser(
1670 user.getCompanyId(), user.getUserId(), mailPassword,
1671 user.getFirstName(), user.getMiddleName(), user.getLastName(),
1672 user.getEmailAddress());
1673 }
1674
1675 boolean sendEmail = ParamUtil.getBoolean(serviceContext, "sendEmail");
1676
1677 if (sendEmail) {
1678 sendEmail(user, password, serviceContext);
1679 }
1680
1681 Company company = companyPersistence.findByPrimaryKey(
1682 user.getCompanyId());
1683
1684 if (company.isStrangersVerify() && (serviceContext.getPlid() > 0)) {
1685 sendEmailAddressVerification(
1686 user, user.getEmailAddress(), serviceContext);
1687 }
1688 }
1689
1690
1703 @Override
1704 public KeyValuePair decryptUserId(
1705 long companyId, String name, String password)
1706 throws PortalException, SystemException {
1707
1708 Company company = companyPersistence.findByPrimaryKey(companyId);
1709
1710 try {
1711 name = Encryptor.decrypt(company.getKeyObj(), name);
1712 }
1713 catch (EncryptorException ee) {
1714 throw new SystemException(ee);
1715 }
1716
1717 long userId = GetterUtil.getLong(name);
1718
1719 User user = userPersistence.findByPrimaryKey(userId);
1720
1721 try {
1722 password = Encryptor.decrypt(company.getKeyObj(), password);
1723 }
1724 catch (EncryptorException ee) {
1725 throw new SystemException(ee);
1726 }
1727
1728 String userPassword = user.getPassword();
1729 String encPassword = PasswordEncryptorUtil.encrypt(
1730 password, userPassword);
1731
1732 if (userPassword.equals(encPassword)) {
1733 if (isPasswordExpired(user)) {
1734 user.setPasswordReset(true);
1735
1736 userPersistence.update(user);
1737 }
1738
1739 return new KeyValuePair(name, password);
1740 }
1741 else {
1742 throw new PrincipalException();
1743 }
1744 }
1745
1746
1754 @Override
1755 public void deletePortrait(long userId)
1756 throws PortalException, SystemException {
1757
1758 User user = userPersistence.findByPrimaryKey(userId);
1759
1760 long portraitId = user.getPortraitId();
1761
1762 if (portraitId > 0) {
1763 user.setPortraitId(0);
1764
1765 userPersistence.update(user);
1766
1767 imageLocalService.deleteImage(portraitId);
1768 }
1769 }
1770
1771
1780 @Override
1781 public void deleteRoleUser(long roleId, long userId)
1782 throws PortalException, SystemException {
1783
1784 rolePersistence.removeUser(roleId, userId);
1785
1786 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1787
1788 indexer.reindex(userId);
1789
1790 PermissionCacheUtil.clearCache();
1791 }
1792
1793
1801 @Override
1802 public User deleteUser(long userId)
1803 throws PortalException, SystemException {
1804
1805 User user = userPersistence.findByPrimaryKey(userId);
1806
1807 return deleteUser(user);
1808 }
1809
1810
1818 @Override
1819 public User deleteUser(User user) throws PortalException, SystemException {
1820 if (!PropsValues.USERS_DELETE) {
1821 throw new RequiredUserException();
1822 }
1823
1824
1825
1826 browserTrackerLocalService.deleteUserBrowserTracker(user.getUserId());
1827
1828
1829
1830 Group group = null;
1831
1832 if (!user.isDefaultUser()) {
1833 group = user.getGroup();
1834 }
1835
1836 if (group != null) {
1837 groupLocalService.deleteGroup(group);
1838 }
1839
1840
1841
1842 try {
1843 imageLocalService.deleteImage(user.getPortraitId());
1844 }
1845 catch (NoSuchImageException nsie) {
1846 if (_log.isWarnEnabled()) {
1847 _log.warn("Unable to delete image " + user.getPortraitId());
1848 }
1849 }
1850
1851
1852
1853 passwordPolicyRelLocalService.deletePasswordPolicyRel(
1854 User.class.getName(), user.getUserId());
1855
1856
1857
1858 passwordTrackerLocalService.deletePasswordTrackers(user.getUserId());
1859
1860
1861
1862 subscriptionLocalService.deleteSubscriptions(user.getUserId());
1863
1864
1865
1866 userIdMapperLocalService.deleteUserIdMappers(user.getUserId());
1867
1868
1869
1870 announcementsDeliveryLocalService.deleteDeliveries(user.getUserId());
1871
1872
1873
1874 assetEntryLocalService.deleteEntry(
1875 User.class.getName(), user.getUserId());
1876
1877
1878
1879 blogsStatsUserLocalService.deleteStatsUserByUserId(user.getUserId());
1880
1881
1882
1883 dlFileRankLocalService.deleteFileRanksByUserId(user.getUserId());
1884
1885
1886
1887 expandoRowLocalService.deleteRows(user.getUserId());
1888
1889
1890
1891 mbBanLocalService.deleteBansByBanUserId(user.getUserId());
1892 mbStatsUserLocalService.deleteStatsUsersByUserId(user.getUserId());
1893 mbThreadFlagLocalService.deleteThreadFlagsByUserId(user.getUserId());
1894
1895
1896
1897 membershipRequestLocalService.deleteMembershipRequestsByUserId(
1898 user.getUserId());
1899
1900
1901
1902 shoppingCartLocalService.deleteUserCarts(user.getUserId());
1903
1904
1905
1906 socialActivityLocalService.deleteUserActivities(user.getUserId());
1907 socialRequestLocalService.deleteReceiverUserRequests(user.getUserId());
1908 socialRequestLocalService.deleteUserRequests(user.getUserId());
1909
1910
1911
1912 mailService.deleteUser(user.getCompanyId(), user.getUserId());
1913
1914
1915
1916 Contact contact = contactLocalService.fetchContact(user.getContactId());
1917
1918 if (contact != null) {
1919 contactLocalService.deleteContact(contact);
1920 }
1921
1922
1923
1924 resourceLocalService.deleteResource(
1925 user.getCompanyId(), User.class.getName(),
1926 ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
1927
1928
1929
1930 userGroupRoleLocalService.deleteUserGroupRolesByUserId(
1931 user.getUserId());
1932
1933
1934
1935 userPersistence.remove(user);
1936
1937
1938
1939 PermissionCacheUtil.clearCache();
1940
1941
1942
1943 workflowInstanceLinkLocalService.deleteWorkflowInstanceLinks(
1944 user.getCompanyId(), 0, User.class.getName(), user.getUserId());
1945
1946 return user;
1947 }
1948
1949
1957 @Override
1958 public void deleteUserGroupUser(long userGroupId, long userId)
1959 throws PortalException, SystemException {
1960
1961 userGroupPersistence.removeUser(userGroupId, userId);
1962
1963 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1964
1965 indexer.reindex(userId);
1966
1967 PermissionCacheUtil.clearCache();
1968 }
1969
1970
1979 @Override
1980 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1981 public String encryptUserId(String name)
1982 throws PortalException, SystemException {
1983
1984 long userId = GetterUtil.getLong(name);
1985
1986 User user = userPersistence.findByPrimaryKey(userId);
1987
1988 Company company = companyPersistence.findByPrimaryKey(
1989 user.getCompanyId());
1990
1991 try {
1992 return Encryptor.encrypt(company.getKeyObj(), name);
1993 }
1994 catch (EncryptorException ee) {
1995 throw new SystemException(ee);
1996 }
1997 }
1998
1999
2008 @Override
2009 public User fetchUserByEmailAddress(long companyId, String emailAddress)
2010 throws SystemException {
2011
2012 emailAddress = getLogin(emailAddress);
2013
2014 return userPersistence.fetchByC_EA(companyId, emailAddress);
2015 }
2016
2017
2026 @Override
2027 public User fetchUserByFacebookId(long companyId, long facebookId)
2028 throws SystemException {
2029
2030 return userPersistence.fetchByC_FID(companyId, facebookId);
2031 }
2032
2033
2041 @Override
2042 public User fetchUserById(long userId) throws SystemException {
2043 return userPersistence.fetchByPrimaryKey(userId);
2044 }
2045
2046
2055 @Override
2056 public User fetchUserByOpenId(long companyId, String openId)
2057 throws SystemException {
2058
2059 return userPersistence.fetchByC_O(companyId, openId);
2060 }
2061
2062
2071 @Override
2072 public User fetchUserByScreenName(long companyId, String screenName)
2073 throws SystemException {
2074
2075 screenName = getLogin(screenName);
2076
2077 return userPersistence.fetchByC_SN(companyId, screenName);
2078 }
2079
2080
2099 @Override
2100 public List<User> getCompanyUsers(long companyId, int start, int end)
2101 throws SystemException {
2102
2103 return userPersistence.findByCompanyId(companyId, start, end);
2104 }
2105
2106
2113 @Override
2114 public int getCompanyUsersCount(long companyId) throws SystemException {
2115 return userPersistence.countByCompanyId(companyId);
2116 }
2117
2118
2127 @Override
2128 @Skip
2129 public User getDefaultUser(long companyId)
2130 throws PortalException, SystemException {
2131
2132 User userModel = _defaultUsers.get(companyId);
2133
2134 if (userModel == null) {
2135 userModel = userLocalService.loadGetDefaultUser(companyId);
2136
2137 _defaultUsers.put(companyId, userModel);
2138 }
2139
2140 return userModel;
2141 }
2142
2143
2152 @Override
2153 @Skip
2154 public long getDefaultUserId(long companyId)
2155 throws PortalException, SystemException {
2156
2157 User user = getDefaultUser(companyId);
2158
2159 return user.getUserId();
2160 }
2161
2162
2169 @Override
2170 public long[] getGroupUserIds(long groupId) throws SystemException {
2171 return getUserIds(getGroupUsers(groupId));
2172 }
2173
2174
2184 @Override
2185 public int getGroupUsersCount(long groupId, int status)
2186 throws PortalException, SystemException {
2187
2188 Group group = groupPersistence.findByPrimaryKey(groupId);
2189
2190 LinkedHashMap<String, Object> params =
2191 new LinkedHashMap<String, Object>();
2192
2193 params.put("usersGroups", new Long(groupId));
2194
2195 return searchCount(group.getCompanyId(), null, status, params);
2196 }
2197
2198 @Override
2199 public List<User> getInheritedRoleUsers(
2200 long roleId, int start, int end, OrderByComparator obc)
2201 throws PortalException, SystemException {
2202
2203 Role role = rolePersistence.findByPrimaryKey(roleId);
2204
2205 LinkedHashMap<String, Object> params =
2206 new LinkedHashMap<String, Object>();
2207
2208 params.put("inherit", Boolean.TRUE);
2209 params.put("usersRoles", roleId);
2210
2211 return search(
2212 role.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2213 params, start, end, obc);
2214 }
2215
2216
2224 @Override
2225 public List<User> getNoAnnouncementsDeliveries(String type)
2226 throws SystemException {
2227
2228 return userFinder.findByNoAnnouncementsDeliveries(type);
2229 }
2230
2231
2237 @Override
2238 public List<User> getNoContacts() throws SystemException {
2239 return userFinder.findByNoContacts();
2240 }
2241
2242
2249 @Override
2250 public List<User> getNoGroups() throws SystemException {
2251 return userFinder.findByNoGroups();
2252 }
2253
2254
2261 @Override
2262 public long[] getOrganizationUserIds(long organizationId)
2263 throws SystemException {
2264
2265 return getUserIds(getOrganizationUsers(organizationId));
2266 }
2267
2268
2279 @Override
2280 public int getOrganizationUsersCount(long organizationId, int status)
2281 throws PortalException, SystemException {
2282
2283 Organization organization = organizationPersistence.findByPrimaryKey(
2284 organizationId);
2285
2286 LinkedHashMap<String, Object> params =
2287 new LinkedHashMap<String, Object>();
2288
2289 params.put("usersOrgs", new Long(organizationId));
2290
2291 return searchCount(organization.getCompanyId(), null, status, params);
2292 }
2293
2294
2301 @Override
2302 public long[] getRoleUserIds(long roleId) throws SystemException {
2303 return getUserIds(getRoleUsers(roleId));
2304 }
2305
2306
2316 @Override
2317 public int getRoleUsersCount(long roleId, int status)
2318 throws PortalException, SystemException {
2319
2320 Role role = rolePersistence.findByPrimaryKey(roleId);
2321
2322 LinkedHashMap<String, Object> params =
2323 new LinkedHashMap<String, Object>();
2324
2325 params.put("usersRoles", new Long(roleId));
2326
2327 return searchCount(role.getCompanyId(), null, status, params);
2328 }
2329
2330
2357 @Override
2358 public List<User> getSocialUsers(
2359 long userId, int type, int start, int end, OrderByComparator obc)
2360 throws PortalException, SystemException {
2361
2362 User user = userPersistence.findByPrimaryKey(userId);
2363
2364 LinkedHashMap<String, Object> params =
2365 new LinkedHashMap<String, Object>();
2366
2367 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2368
2369 return search(
2370 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2371 params, start, end, obc);
2372 }
2373
2374
2397 @Override
2398 public List<User> getSocialUsers(
2399 long userId, int start, int end, OrderByComparator obc)
2400 throws PortalException, SystemException {
2401
2402 User user = userPersistence.findByPrimaryKey(userId);
2403
2404 LinkedHashMap<String, Object> params =
2405 new LinkedHashMap<String, Object>();
2406
2407 params.put("socialRelation", new Long[] {userId});
2408
2409 return search(
2410 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2411 params, start, end, obc);
2412 }
2413
2414
2442 @Override
2443 public List<User> getSocialUsers(
2444 long userId1, long userId2, int type, int start, int end,
2445 OrderByComparator obc)
2446 throws PortalException, SystemException {
2447
2448 User user1 = userPersistence.findByPrimaryKey(userId1);
2449
2450 LinkedHashMap<String, Object> params =
2451 new LinkedHashMap<String, Object>();
2452
2453 params.put(
2454 "socialMutualRelationType",
2455 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2456
2457 return search(
2458 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2459 params, start, end, obc);
2460 }
2461
2462
2487 @Override
2488 public List<User> getSocialUsers(
2489 long userId1, long userId2, int start, int end,
2490 OrderByComparator obc)
2491 throws PortalException, SystemException {
2492
2493 User user1 = userPersistence.findByPrimaryKey(userId1);
2494
2495 LinkedHashMap<String, Object> params =
2496 new LinkedHashMap<String, Object>();
2497
2498 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2499
2500 return search(
2501 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2502 params, start, end, obc);
2503 }
2504
2505
2513 @Override
2514 public int getSocialUsersCount(long userId)
2515 throws PortalException, SystemException {
2516
2517 User user = userPersistence.findByPrimaryKey(userId);
2518
2519 LinkedHashMap<String, Object> params =
2520 new LinkedHashMap<String, Object>();
2521
2522 params.put("socialRelation", new Long[] {userId});
2523
2524 return searchCount(
2525 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2526 params);
2527 }
2528
2529
2542 @Override
2543 public int getSocialUsersCount(long userId, int type)
2544 throws PortalException, SystemException {
2545
2546 User user = userPersistence.findByPrimaryKey(userId);
2547
2548 LinkedHashMap<String, Object> params =
2549 new LinkedHashMap<String, Object>();
2550
2551 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2552
2553 return searchCount(
2554 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2555 params);
2556 }
2557
2558
2568 @Override
2569 public int getSocialUsersCount(long userId1, long userId2)
2570 throws PortalException, SystemException {
2571
2572 User user1 = userPersistence.findByPrimaryKey(userId1);
2573
2574 LinkedHashMap<String, Object> params =
2575 new LinkedHashMap<String, Object>();
2576
2577 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2578
2579 return searchCount(
2580 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2581 params);
2582 }
2583
2584
2598 @Override
2599 public int getSocialUsersCount(long userId1, long userId2, int type)
2600 throws PortalException, SystemException {
2601
2602 User user1 = userPersistence.findByPrimaryKey(userId1);
2603
2604 LinkedHashMap<String, Object> params =
2605 new LinkedHashMap<String, Object>();
2606
2607 params.put(
2608 "socialMutualRelationType",
2609 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2610
2611 return searchCount(
2612 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2613 params);
2614 }
2615
2616
2624 @Override
2625 public User getUserByContactId(long contactId)
2626 throws PortalException, SystemException {
2627
2628 return userPersistence.findByContactId(contactId);
2629 }
2630
2631
2641 @Override
2642 public User getUserByEmailAddress(long companyId, String emailAddress)
2643 throws PortalException, SystemException {
2644
2645 emailAddress = getLogin(emailAddress);
2646
2647 return userPersistence.findByC_EA(companyId, emailAddress);
2648 }
2649
2650
2659 @Override
2660 public User getUserByFacebookId(long companyId, long facebookId)
2661 throws PortalException, SystemException {
2662
2663 return userPersistence.findByC_FID(companyId, facebookId);
2664 }
2665
2666
2674 @Override
2675 public User getUserById(long userId)
2676 throws PortalException, SystemException {
2677
2678 return userPersistence.findByPrimaryKey(userId);
2679 }
2680
2681
2691 @Override
2692 public User getUserById(long companyId, long userId)
2693 throws PortalException, SystemException {
2694
2695 return userPersistence.findByC_U(companyId, userId);
2696 }
2697
2698
2707 @Override
2708 public User getUserByOpenId(long companyId, String openId)
2709 throws PortalException, SystemException {
2710
2711 return userPersistence.findByC_O(companyId, openId);
2712 }
2713
2714
2722 @Override
2723 public User getUserByPortraitId(long portraitId)
2724 throws PortalException, SystemException {
2725
2726 return userPersistence.findByPortraitId(portraitId);
2727 }
2728
2729
2738 @Override
2739 public User getUserByScreenName(long companyId, String screenName)
2740 throws PortalException, SystemException {
2741
2742 screenName = getLogin(screenName);
2743
2744 return userPersistence.findByC_SN(companyId, screenName);
2745 }
2746
2747
2757 @Override
2758 public User getUserByUuid(String uuid)
2759 throws PortalException, SystemException {
2760
2761 List<User> users = userPersistence.findByUuid(uuid);
2762
2763 if (users.isEmpty()) {
2764 throw new NoSuchUserException();
2765 }
2766 else {
2767 return users.get(0);
2768 }
2769 }
2770
2771
2780 @Override
2781 public User getUserByUuidAndCompanyId(String uuid, long companyId)
2782 throws PortalException, SystemException {
2783
2784 List<User> users = userPersistence.findByUuid_C(uuid, companyId);
2785
2786 if (users.isEmpty()) {
2787 throw new NoSuchUserException();
2788 }
2789 else {
2790 return users.get(0);
2791 }
2792 }
2793
2794
2804 @Override
2805 public int getUserGroupUsersCount(long userGroupId, int status)
2806 throws PortalException, SystemException {
2807
2808 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
2809 userGroupId);
2810
2811 LinkedHashMap<String, Object> params =
2812 new LinkedHashMap<String, Object>();
2813
2814 params.put("usersUserGroups", new Long(userGroupId));
2815
2816 return searchCount(userGroup.getCompanyId(), null, status, params);
2817 }
2818
2819
2829 @Override
2830 public long getUserIdByEmailAddress(long companyId, String emailAddress)
2831 throws PortalException, SystemException {
2832
2833 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
2834
2835 User user = userPersistence.findByC_EA(companyId, emailAddress);
2836
2837 return user.getUserId();
2838 }
2839
2840
2849 @Override
2850 public long getUserIdByScreenName(long companyId, String screenName)
2851 throws PortalException, SystemException {
2852
2853 screenName = getLogin(screenName);
2854
2855 User user = userPersistence.findByC_SN(companyId, screenName);
2856
2857 return user.getUserId();
2858 }
2859
2860
2870 @Override
2871 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
2872 throws SystemException {
2873
2874 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
2875 passwordPolicyId, User.class.getName(), userId);
2876 }
2877
2878
2893 @Override
2894 public boolean hasRoleUser(
2895 long companyId, String name, long userId, boolean inherited)
2896 throws PortalException, SystemException {
2897
2898 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
2899 }
2900
2901
2911 @Override
2912 public boolean isPasswordExpired(User user)
2913 throws PortalException, SystemException {
2914
2915 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2916
2917 if ((passwordPolicy != null) && passwordPolicy.getExpireable()) {
2918 Date now = new Date();
2919
2920 if (user.getPasswordModifiedDate() == null) {
2921 user.setPasswordModifiedDate(now);
2922
2923 userLocalService.updateUser(user);
2924 }
2925
2926 long passwordStartTime = user.getPasswordModifiedDate().getTime();
2927 long elapsedTime = now.getTime() - passwordStartTime;
2928
2929 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
2930 return true;
2931 }
2932 else {
2933 return false;
2934 }
2935 }
2936
2937 return false;
2938 }
2939
2940
2952 @Override
2953 public boolean isPasswordExpiringSoon(User user)
2954 throws PortalException, SystemException {
2955
2956 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2957
2958 if ((passwordPolicy != null) && passwordPolicy.isExpireable() &&
2959 (passwordPolicy.getWarningTime() > 0)) {
2960
2961 Date now = new Date();
2962
2963 if (user.getPasswordModifiedDate() == null) {
2964 user.setPasswordModifiedDate(now);
2965
2966 userLocalService.updateUser(user);
2967 }
2968
2969 long timeModified = user.getPasswordModifiedDate().getTime();
2970 long passwordExpiresOn =
2971 (passwordPolicy.getMaxAge() * 1000) + timeModified;
2972
2973 long timeStartWarning =
2974 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
2975
2976 if (now.getTime() > timeStartWarning) {
2977 return true;
2978 }
2979 else {
2980 return false;
2981 }
2982 }
2983
2984 return false;
2985 }
2986
2987
2995 @Override
2996 public User loadGetDefaultUser(long companyId)
2997 throws PortalException, SystemException {
2998
2999 return userPersistence.findByC_DU(companyId, true);
3000 }
3001
3002
3034 @Override
3035 public List<User> search(
3036 long companyId, String keywords, int status,
3037 LinkedHashMap<String, Object> params, int start, int end,
3038 OrderByComparator obc)
3039 throws SystemException {
3040
3041 return userFinder.findByKeywords(
3042 companyId, keywords, status, params, start, end, obc);
3043 }
3044
3045
3076 @Override
3077 public Hits search(
3078 long companyId, String keywords, int status,
3079 LinkedHashMap<String, Object> params, int start, int end, Sort sort)
3080 throws SystemException {
3081
3082 String firstName = null;
3083 String middleName = null;
3084 String lastName = null;
3085 String fullName = null;
3086 String screenName = null;
3087 String emailAddress = null;
3088 String street = null;
3089 String city = null;
3090 String zip = null;
3091 String region = null;
3092 String country = null;
3093 boolean andOperator = false;
3094
3095 if (Validator.isNotNull(keywords)) {
3096 firstName = keywords;
3097 middleName = keywords;
3098 lastName = keywords;
3099 fullName = keywords;
3100 screenName = keywords;
3101 emailAddress = keywords;
3102 street = keywords;
3103 city = keywords;
3104 zip = keywords;
3105 region = keywords;
3106 country = keywords;
3107 }
3108 else {
3109 andOperator = true;
3110 }
3111
3112 if (params != null) {
3113 params.put("keywords", keywords);
3114 }
3115
3116 return search(
3117 companyId, firstName, middleName, lastName, fullName, screenName,
3118 emailAddress, street, city, zip, region, country, status, params,
3119 andOperator, start, end, sort);
3120 }
3121
3122
3162 @Override
3163 public List<User> search(
3164 long companyId, String firstName, String middleName,
3165 String lastName, String screenName, String emailAddress, int status,
3166 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3167 int end, OrderByComparator obc)
3168 throws SystemException {
3169
3170 return userFinder.findByC_FN_MN_LN_SN_EA_S(
3171 companyId, firstName, middleName, lastName, screenName,
3172 emailAddress, status, params, andSearch, start, end, obc);
3173 }
3174
3175
3214 @Override
3215 public Hits search(
3216 long companyId, String firstName, String middleName,
3217 String lastName, String screenName, String emailAddress, int status,
3218 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3219 int end, Sort sort)
3220 throws SystemException {
3221
3222 return search(
3223 companyId, firstName, middleName, lastName, null, screenName,
3224 emailAddress, null, null, null, null, null, status, params,
3225 andSearch, start, end, sort);
3226 }
3227
3228
3242 @Override
3243 public int searchCount(
3244 long companyId, String keywords, int status,
3245 LinkedHashMap<String, Object> params)
3246 throws SystemException {
3247
3248 return userFinder.countByKeywords(companyId, keywords, status, params);
3249 }
3250
3251
3273 @Override
3274 public int searchCount(
3275 long companyId, String firstName, String middleName,
3276 String lastName, String screenName, String emailAddress, int status,
3277 LinkedHashMap<String, Object> params, boolean andSearch)
3278 throws SystemException {
3279
3280 return userFinder.countByC_FN_MN_LN_SN_EA_S(
3281 companyId, firstName, middleName, lastName, screenName,
3282 emailAddress, status, params, andSearch);
3283 }
3284
3285
3296 @Override
3297 public void sendEmailAddressVerification(
3298 User user, String emailAddress, ServiceContext serviceContext)
3299 throws PortalException, SystemException {
3300
3301 if (user.isEmailAddressVerified() &&
3302 StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
3303
3304 return;
3305 }
3306
3307 Ticket ticket = ticketLocalService.addTicket(
3308 user.getCompanyId(), User.class.getName(), user.getUserId(),
3309 TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3310 serviceContext);
3311
3312 String verifyEmailAddressURL =
3313 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3314 "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3315
3316 Layout layout = layoutLocalService.getLayout(serviceContext.getPlid());
3317
3318 Group group = layout.getGroup();
3319
3320 if (!layout.isPrivateLayout() && !group.isUser()) {
3321 verifyEmailAddressURL += "&p_l_id=" + serviceContext.getPlid();
3322 }
3323
3324 String fromName = PrefsPropsUtil.getString(
3325 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3326 String fromAddress = PrefsPropsUtil.getString(
3327 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3328
3329 String toName = user.getFullName();
3330 String toAddress = emailAddress;
3331
3332 String subject = PrefsPropsUtil.getContent(
3333 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3334
3335 String body = PrefsPropsUtil.getContent(
3336 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3337
3338 SubscriptionSender subscriptionSender = new SubscriptionSender();
3339
3340 subscriptionSender.setBody(body);
3341 subscriptionSender.setCompanyId(user.getCompanyId());
3342 subscriptionSender.setContextAttributes(
3343 "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3344 "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3345 "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3346 "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_ID$]",
3347 user.getUserId(), "[$USER_SCREENNAME$]", user.getScreenName());
3348 subscriptionSender.setFrom(fromAddress, fromName);
3349 subscriptionSender.setHtmlFormat(true);
3350 subscriptionSender.setMailId(
3351 "user", user.getUserId(), System.currentTimeMillis(),
3352 PwdGenerator.getPassword());
3353 subscriptionSender.setServiceContext(serviceContext);
3354 subscriptionSender.setSubject(subject);
3355 subscriptionSender.setUserId(user.getUserId());
3356
3357 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3358
3359 subscriptionSender.flushNotificationsAsync();
3360 }
3361
3362
3381 @Override
3382 public void sendPassword(
3383 long companyId, String emailAddress, String fromName,
3384 String fromAddress, String subject, String body,
3385 ServiceContext serviceContext)
3386 throws PortalException, SystemException {
3387
3388 Company company = companyPersistence.findByPrimaryKey(companyId);
3389
3390 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3391 return;
3392 }
3393
3394 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
3395
3396 if (Validator.isNull(emailAddress)) {
3397 throw new UserEmailAddressException();
3398 }
3399
3400 User user = userPersistence.findByC_EA(companyId, emailAddress);
3401
3402 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3403
3404 String newPassword = StringPool.BLANK;
3405 String passwordResetURL = StringPool.BLANK;
3406
3407 if (company.isSendPasswordResetLink()) {
3408 Date expirationDate = null;
3409
3410 if ((passwordPolicy != null) &&
3411 (passwordPolicy.getResetTicketMaxAge() > 0)) {
3412
3413 expirationDate = new Date(
3414 System.currentTimeMillis() +
3415 (passwordPolicy.getResetTicketMaxAge() * 1000));
3416 }
3417
3418 Ticket ticket = ticketLocalService.addTicket(
3419 companyId, User.class.getName(), user.getUserId(),
3420 TicketConstants.TYPE_PASSWORD, null, expirationDate,
3421 serviceContext);
3422
3423 passwordResetURL =
3424 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3425 "/portal/update_password?p_l_id="+
3426 serviceContext.getPlid() +
3427 "&ticketKey=" + ticket.getKey();
3428 }
3429 else {
3430 if (!PasswordEncryptorUtil.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
3431 PasswordEncryptorUtil.TYPE_NONE)) {
3432
3433 if (LDAPSettingsUtil.isPasswordPolicyEnabled(
3434 user.getCompanyId())) {
3435
3436 if (_log.isWarnEnabled()) {
3437 StringBundler sb = new StringBundler(5);
3438
3439 sb.append("When LDAP password policy is enabled, ");
3440 sb.append("it is possible that portal generated ");
3441 sb.append("passwords will not match the LDAP policy.");
3442 sb.append("Using RegExpToolkit to generate new ");
3443 sb.append("password.");
3444
3445 _log.warn(sb.toString());
3446 }
3447
3448 RegExpToolkit regExpToolkit = new RegExpToolkit();
3449
3450 newPassword = regExpToolkit.generate(null);
3451 }
3452 else {
3453 newPassword = PwdToolkitUtil.generate(passwordPolicy);
3454 }
3455
3456 boolean passwordReset = false;
3457
3458 if (passwordPolicy.getChangeable() &&
3459 passwordPolicy.getChangeRequired()) {
3460
3461 passwordReset = true;
3462 }
3463
3464 user.setPassword(PasswordEncryptorUtil.encrypt(newPassword));
3465 user.setPasswordUnencrypted(newPassword);
3466 user.setPasswordEncrypted(true);
3467 user.setPasswordReset(passwordReset);
3468 user.setPasswordModified(true);
3469 user.setPasswordModifiedDate(new Date());
3470
3471 userPersistence.update(user);
3472
3473 user.setPasswordModified(false);
3474 }
3475 else {
3476 newPassword = user.getPassword();
3477 }
3478 }
3479
3480 if (Validator.isNull(fromName)) {
3481 fromName = PrefsPropsUtil.getString(
3482 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3483 }
3484
3485 if (Validator.isNull(fromAddress)) {
3486 fromAddress = PrefsPropsUtil.getString(
3487 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3488 }
3489
3490 String toName = user.getFullName();
3491 String toAddress = user.getEmailAddress();
3492
3493 if (Validator.isNull(subject)) {
3494 if (company.isSendPasswordResetLink()) {
3495 subject = PrefsPropsUtil.getContent(
3496 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
3497 }
3498 else {
3499 subject = PrefsPropsUtil.getContent(
3500 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
3501 }
3502 }
3503
3504 if (Validator.isNull(body)) {
3505 if (company.isSendPasswordResetLink()) {
3506 body = PrefsPropsUtil.getContent(
3507 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
3508 }
3509 else {
3510 body = PrefsPropsUtil.getContent(
3511 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
3512 }
3513 }
3514
3515 SubscriptionSender subscriptionSender = new SubscriptionSender();
3516
3517 subscriptionSender.setBody(body);
3518 subscriptionSender.setCompanyId(companyId);
3519 subscriptionSender.setContextAttributes(
3520 "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
3521 serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
3522 serviceContext.getRemoteHost(), "[$USER_ID$]", user.getUserId(),
3523 "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
3524 user.getScreenName());
3525 subscriptionSender.setFrom(fromAddress, fromName);
3526 subscriptionSender.setHtmlFormat(true);
3527 subscriptionSender.setMailId(
3528 "user", user.getUserId(), System.currentTimeMillis(),
3529 PwdGenerator.getPassword());
3530 subscriptionSender.setServiceContext(serviceContext);
3531 subscriptionSender.setSubject(subject);
3532 subscriptionSender.setUserId(user.getUserId());
3533
3534 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3535
3536 subscriptionSender.flushNotificationsAsync();
3537 }
3538
3539
3548 @Override
3549 public void setRoleUsers(long roleId, long[] userIds)
3550 throws PortalException, SystemException {
3551
3552 rolePersistence.setUsers(roleId, userIds);
3553
3554 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3555
3556 indexer.reindex(userIds);
3557
3558 PermissionCacheUtil.clearCache();
3559 }
3560
3561
3570 @Override
3571 @SuppressWarnings("deprecation")
3572 public void setUserGroupUsers(long userGroupId, long[] userIds)
3573 throws PortalException, SystemException {
3574
3575 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3576 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3577 }
3578
3579 userGroupPersistence.setUsers(userGroupId, userIds);
3580
3581 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3582
3583 indexer.reindex(userIds);
3584
3585 PermissionCacheUtil.clearCache();
3586 }
3587
3588
3596 @Override
3597 public void unsetGroupTeamsUsers(long groupId, long[] userIds)
3598 throws PortalException, SystemException {
3599
3600 List<Team> teams = teamPersistence.findByGroupId(groupId);
3601
3602 for (Team team : teams) {
3603 unsetTeamUsers(team.getTeamId(), userIds);
3604 }
3605
3606 PermissionCacheUtil.clearCache();
3607 }
3608
3609
3619 @Override
3620 public void unsetGroupUsers(
3621 final long groupId, final long[] userIds,
3622 ServiceContext serviceContext)
3623 throws PortalException, SystemException {
3624
3625 userGroupRoleLocalService.deleteUserGroupRoles(
3626 userIds, groupId, RoleConstants.TYPE_SITE);
3627
3628 userLocalService.unsetGroupTeamsUsers(groupId, userIds);
3629
3630 groupPersistence.removeUsers(groupId, userIds);
3631
3632 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3633
3634 indexer.reindex(userIds);
3635
3636 PermissionCacheUtil.clearCache();
3637
3638 Callable<Void> callable = new Callable<Void>() {
3639
3640 @Override
3641 public Void call() throws Exception {
3642 Message message = new Message();
3643
3644 message.put("groupId", groupId);
3645 message.put("userIds", userIds);
3646
3647 MessageBusUtil.sendMessage(
3648 DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
3649
3650 return null;
3651 }
3652
3653 };
3654
3655 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
3656 }
3657
3658
3666 @Override
3667 public void unsetOrganizationUsers(
3668 long organizationId, final long[] userIds)
3669 throws PortalException, SystemException {
3670
3671 Organization organization = organizationPersistence.findByPrimaryKey(
3672 organizationId);
3673
3674 final Group group = organization.getGroup();
3675
3676 userGroupRoleLocalService.deleteUserGroupRoles(
3677 userIds, group.getGroupId(), RoleConstants.TYPE_ORGANIZATION);
3678
3679 organizationPersistence.removeUsers(organizationId, userIds);
3680
3681 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3682
3683 indexer.reindex(userIds);
3684
3685 PermissionCacheUtil.clearCache();
3686
3687 Callable<Void> callable = new Callable<Void>() {
3688
3689 @Override
3690 public Void call() throws Exception {
3691 Message message = new Message();
3692
3693 message.put("groupId", group.getGroupId());
3694 message.put("userIds", userIds);
3695
3696 MessageBusUtil.sendMessage(
3697 DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
3698
3699 return null;
3700 }
3701
3702 };
3703
3704 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
3705 }
3706
3707
3714 @Override
3715 public void unsetPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
3716 throws SystemException {
3717
3718 passwordPolicyRelLocalService.deletePasswordPolicyRels(
3719 passwordPolicyId, User.class.getName(), userIds);
3720 }
3721
3722
3730 @Override
3731 public void unsetRoleUsers(long roleId, List<User> users)
3732 throws PortalException, SystemException {
3733
3734 Role role = rolePersistence.findByPrimaryKey(roleId);
3735
3736 String roleName = role.getName();
3737
3738 if ((roleName.equals(RoleConstants.ADMINISTRATOR) &&
3739 (getRoleUsersCount(role.getRoleId()) <= 1)) ||
3740 roleName.equals(RoleConstants.USER)) {
3741
3742 return;
3743 }
3744
3745 rolePersistence.removeUsers(roleId, users);
3746
3747 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3748
3749 indexer.reindex(users);
3750
3751 PermissionCacheUtil.clearCache();
3752 }
3753
3754
3762 @Override
3763 public void unsetRoleUsers(long roleId, long[] userIds)
3764 throws PortalException, SystemException {
3765
3766 Role role = rolePersistence.findByPrimaryKey(roleId);
3767
3768 String roleName = role.getName();
3769
3770 if (roleName.equals(RoleConstants.USER) ||
3771 (roleName.equals(RoleConstants.ADMINISTRATOR) &&
3772 getRoleUsersCount(role.getRoleId()) <= 1)) {
3773
3774 return;
3775 }
3776
3777 rolePersistence.removeUsers(roleId, userIds);
3778
3779 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3780
3781 indexer.reindex(userIds);
3782
3783 PermissionCacheUtil.clearCache();
3784 }
3785
3786
3794 @Override
3795 public void unsetTeamUsers(long teamId, long[] userIds)
3796 throws PortalException, SystemException {
3797
3798 teamPersistence.removeUsers(teamId, userIds);
3799
3800 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3801
3802 indexer.reindex(userIds);
3803
3804 PermissionCacheUtil.clearCache();
3805 }
3806
3807
3815 @Override
3816 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
3817 throws PortalException, SystemException {
3818
3819 userGroupPersistence.removeUsers(userGroupId, userIds);
3820
3821 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3822
3823 indexer.reindex(userIds);
3824
3825 PermissionCacheUtil.clearCache();
3826 }
3827
3828
3838 @Override
3839 public User updateAgreedToTermsOfUse(
3840 long userId, boolean agreedToTermsOfUse)
3841 throws PortalException, SystemException {
3842
3843 User user = userPersistence.findByPrimaryKey(userId);
3844
3845 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
3846
3847 userPersistence.update(user);
3848
3849 return user;
3850 }
3851
3852
3863 @Override
3864 public void updateAsset(
3865 long userId, User user, long[] assetCategoryIds,
3866 String[] assetTagNames)
3867 throws PortalException, SystemException {
3868
3869 User owner = userPersistence.findByPrimaryKey(userId);
3870
3871 Company company = companyPersistence.findByPrimaryKey(
3872 owner.getCompanyId());
3873
3874 Group companyGroup = company.getGroup();
3875
3876 assetEntryLocalService.updateEntry(
3877 userId, companyGroup.getGroupId(), user.getCreateDate(),
3878 user.getModifiedDate(), User.class.getName(), user.getUserId(),
3879 user.getUuid(), 0, assetCategoryIds, assetTagNames, false, null,
3880 null, null, null, user.getFullName(), null, null, null, null, 0, 0,
3881 null, false);
3882 }
3883
3884
3893 @Override
3894 public User updateCreateDate(long userId, Date createDate)
3895 throws PortalException, SystemException {
3896
3897 User user = userPersistence.findByPrimaryKey(userId);
3898
3899 user.setCreateDate(createDate);
3900
3901 userPersistence.update(user);
3902
3903 return user;
3904 }
3905
3906
3917 @Override
3918 public User updateEmailAddress(
3919 long userId, String password, String emailAddress1,
3920 String emailAddress2)
3921 throws PortalException, SystemException {
3922
3923 emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
3924 emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
3925
3926 User user = userPersistence.findByPrimaryKey(userId);
3927
3928 validateEmailAddress(user, emailAddress1, emailAddress2);
3929
3930 setEmailAddress(
3931 user, password, user.getFirstName(), user.getMiddleName(),
3932 user.getLastName(), emailAddress1);
3933
3934 userPersistence.update(user);
3935
3936 Contact contact = user.getContact();
3937
3938 contact.setEmailAddress(user.getEmailAddress());
3939
3940 contactPersistence.update(contact);
3941
3942 return user;
3943 }
3944
3945
3959 @Override
3960 public User updateEmailAddress(
3961 long userId, String password, String emailAddress1,
3962 String emailAddress2, ServiceContext serviceContext)
3963 throws PortalException, SystemException {
3964
3965 emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
3966 emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
3967
3968 User user = userPersistence.findByPrimaryKey(userId);
3969
3970 validateEmailAddress(user, emailAddress1, emailAddress2);
3971
3972 Company company = companyPersistence.findByPrimaryKey(
3973 user.getCompanyId());
3974
3975 if (!company.isStrangersVerify()) {
3976 setEmailAddress(
3977 user, password, user.getFirstName(), user.getMiddleName(),
3978 user.getLastName(), emailAddress1);
3979
3980 userPersistence.update(user);
3981
3982 Contact contact = user.getContact();
3983
3984 contact.setEmailAddress(user.getEmailAddress());
3985
3986 contactPersistence.update(contact);
3987 }
3988 else {
3989 sendEmailAddressVerification(user, emailAddress1, serviceContext);
3990 }
3991
3992 return user;
3993 }
3994
3995
4004 @Override
4005 public User updateEmailAddressVerified(
4006 long userId, boolean emailAddressVerified)
4007 throws PortalException, SystemException {
4008
4009 User user = userPersistence.findByPrimaryKey(userId);
4010
4011 user.setEmailAddressVerified(emailAddressVerified);
4012
4013 userPersistence.update(user);
4014
4015 return user;
4016 }
4017
4018
4027 @Override
4028 public User updateFacebookId(long userId, long facebookId)
4029 throws PortalException, SystemException {
4030
4031 User user = userPersistence.findByPrimaryKey(userId);
4032
4033 user.setFacebookId(facebookId);
4034
4035 userPersistence.update(user);
4036
4037 return user;
4038 }
4039
4040
4050 @Override
4051 public void updateGroups(
4052 long userId, long[] newGroupIds, ServiceContext serviceContext)
4053 throws PortalException, SystemException {
4054
4055 updateGroups(
4056 userId, newGroupIds, serviceContext,
4057 serviceContext.isIndexingEnabled());
4058 }
4059
4060
4099 @Override
4100 public User updateIncompleteUser(
4101 long creatorUserId, long companyId, boolean autoPassword,
4102 String password1, String password2, boolean autoScreenName,
4103 String screenName, String emailAddress, long facebookId,
4104 String openId, Locale locale, String firstName, String middleName,
4105 String lastName, int prefixId, int suffixId, boolean male,
4106 int birthdayMonth, int birthdayDay, int birthdayYear,
4107 String jobTitle, boolean updateUserInformation, boolean sendEmail,
4108 ServiceContext serviceContext)
4109 throws PortalException, SystemException {
4110
4111 User user = getUserByEmailAddress(companyId, emailAddress);
4112
4113 if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
4114 throw new PortalException("Invalid user status");
4115 }
4116
4117 User defaultUser = getDefaultUser(companyId);
4118
4119 if (facebookId > 0) {
4120 autoPassword = false;
4121
4122 if ((password1 == null) || (password2 == null)) {
4123 password1 = PwdGenerator.getPassword();
4124 password2 = password1;
4125 }
4126
4127 sendEmail = false;
4128 }
4129
4130 if (updateUserInformation) {
4131 autoScreenName = false;
4132
4133 if (PrefsPropsUtil.getBoolean(
4134 companyId,
4135 PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
4136
4137 autoScreenName = true;
4138 }
4139
4140 validate(
4141 companyId, user.getUserId(), autoPassword, password1, password2,
4142 autoScreenName, screenName, emailAddress, openId, firstName,
4143 middleName, lastName, null);
4144
4145 if (!autoPassword) {
4146 if (Validator.isNull(password1) ||
4147 Validator.isNull(password2)) {
4148 throw new UserPasswordException(
4149 UserPasswordException.PASSWORD_INVALID);
4150 }
4151 }
4152
4153 if (autoScreenName) {
4154 ScreenNameGenerator screenNameGenerator =
4155 ScreenNameGeneratorFactory.getInstance();
4156
4157 try {
4158 screenName = screenNameGenerator.generate(
4159 companyId, user.getUserId(), emailAddress);
4160 }
4161 catch (Exception e) {
4162 throw new SystemException(e);
4163 }
4164 }
4165
4166 FullNameGenerator fullNameGenerator =
4167 FullNameGeneratorFactory.getInstance();
4168
4169 String fullName = fullNameGenerator.getFullName(
4170 firstName, middleName, lastName);
4171
4172 String greeting = LanguageUtil.format(
4173 locale, "welcome-x", " " + fullName, false);
4174
4175 if (Validator.isNotNull(password1)) {
4176 user.setPassword(PasswordEncryptorUtil.encrypt(password1));
4177 user.setPasswordUnencrypted(password1);
4178 }
4179
4180 user.setPasswordEncrypted(true);
4181
4182 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
4183
4184 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
4185 passwordPolicy.isChangeRequired()) {
4186
4187 user.setPasswordReset(true);
4188 }
4189 else {
4190 user.setPasswordReset(false);
4191 }
4192
4193 user.setScreenName(screenName);
4194 user.setFacebookId(facebookId);
4195 user.setOpenId(openId);
4196 user.setLanguageId(locale.toString());
4197 user.setTimeZoneId(defaultUser.getTimeZoneId());
4198 user.setGreeting(greeting);
4199 user.setFirstName(firstName);
4200 user.setMiddleName(middleName);
4201 user.setLastName(lastName);
4202 user.setJobTitle(jobTitle);
4203 user.setExpandoBridgeAttributes(serviceContext);
4204
4205 Date birthday = getBirthday(
4206 birthdayMonth, birthdayDay, birthdayYear);
4207
4208 Contact contact = user.getContact();
4209
4210 contact.setFirstName(firstName);
4211 contact.setMiddleName(middleName);
4212 contact.setLastName(lastName);
4213 contact.setPrefixId(prefixId);
4214 contact.setSuffixId(suffixId);
4215 contact.setMale(male);
4216 contact.setBirthday(birthday);
4217 contact.setJobTitle(jobTitle);
4218
4219 contactPersistence.update(contact, serviceContext);
4220
4221
4222
4223 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4224 User.class);
4225
4226 indexer.reindex(user);
4227 }
4228
4229 user.setStatus(WorkflowConstants.STATUS_DRAFT);
4230
4231 userPersistence.update(user, serviceContext);
4232
4233
4234
4235 long workflowUserId = creatorUserId;
4236
4237 if (workflowUserId == user.getUserId()) {
4238 workflowUserId = defaultUser.getUserId();
4239 }
4240
4241 ServiceContext workflowServiceContext = serviceContext;
4242
4243 if (workflowServiceContext == null) {
4244 workflowServiceContext = new ServiceContext();
4245 }
4246
4247 workflowServiceContext.setAttribute("autoPassword", autoPassword);
4248 workflowServiceContext.setAttribute("sendEmail", sendEmail);
4249
4250 WorkflowHandlerRegistryUtil.startWorkflowInstance(
4251 companyId, workflowUserId, User.class.getName(), user.getUserId(),
4252 user, workflowServiceContext);
4253
4254 return getUserByEmailAddress(companyId, emailAddress);
4255 }
4256
4257
4267 @Override
4268 public User updateJobTitle(long userId, String jobTitle)
4269 throws PortalException, SystemException {
4270
4271 User user = userPersistence.findByPrimaryKey(userId);
4272
4273 user.setJobTitle(jobTitle);
4274
4275 userPersistence.update(user);
4276
4277 Contact contact = contactPersistence.findByPrimaryKey(
4278 user.getContactId());
4279
4280 contact.setJobTitle(jobTitle);
4281
4282 contactPersistence.update(contact);
4283
4284 return user;
4285 }
4286
4287
4296 @Override
4297 public User updateLastLogin(long userId, String loginIP)
4298 throws PortalException, SystemException {
4299
4300 User user = userPersistence.findByPrimaryKey(userId);
4301
4302 Date lastLoginDate = user.getLoginDate();
4303
4304 if (lastLoginDate == null) {
4305 lastLoginDate = new Date();
4306 }
4307
4308 user.setLoginDate(new Date());
4309 user.setLoginIP(loginIP);
4310 user.setLastLoginDate(lastLoginDate);
4311 user.setLastLoginIP(user.getLoginIP());
4312 user.setLastFailedLoginDate(null);
4313 user.setFailedLoginAttempts(0);
4314
4315 userPersistence.update(user);
4316
4317 return user;
4318 }
4319
4320
4329 @Override
4330 public User updateLockout(User user, boolean lockout)
4331 throws PortalException, SystemException {
4332
4333 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
4334
4335 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
4336 return user;
4337 }
4338
4339 Date lockoutDate = null;
4340
4341 if (lockout) {
4342 lockoutDate = new Date();
4343 }
4344
4345 user.setLockout(lockout);
4346 user.setLockoutDate(lockoutDate);
4347
4348 if (!lockout) {
4349 user.setLastFailedLoginDate(lockoutDate);
4350 user.setFailedLoginAttempts(0);
4351 }
4352
4353 userPersistence.update(user);
4354
4355 return user;
4356 }
4357
4358
4369 @Override
4370 public User updateLockoutByEmailAddress(
4371 long companyId, String emailAddress, boolean lockout)
4372 throws PortalException, SystemException {
4373
4374 User user = getUserByEmailAddress(companyId, emailAddress);
4375
4376 return updateLockout(user, lockout);
4377 }
4378
4379
4388 @Override
4389 public User updateLockoutById(long userId, boolean lockout)
4390 throws PortalException, SystemException {
4391
4392 User user = userPersistence.findByPrimaryKey(userId);
4393
4394 return updateLockout(user, lockout);
4395 }
4396
4397
4407 @Override
4408 public User updateLockoutByScreenName(
4409 long companyId, String screenName, boolean lockout)
4410 throws PortalException, SystemException {
4411
4412 User user = getUserByScreenName(companyId, screenName);
4413
4414 return updateLockout(user, lockout);
4415 }
4416
4417
4426 @Override
4427 public User updateModifiedDate(long userId, Date modifiedDate)
4428 throws PortalException, SystemException {
4429
4430 User user = userPersistence.findByPrimaryKey(userId);
4431
4432 user.setModifiedDate(modifiedDate);
4433
4434 userPersistence.update(user);
4435
4436 return user;
4437 }
4438
4439
4448 @Override
4449 public User updateOpenId(long userId, String openId)
4450 throws PortalException, SystemException {
4451
4452 openId = openId.trim();
4453
4454 User user = userPersistence.findByPrimaryKey(userId);
4455
4456 user.setOpenId(openId);
4457
4458 userPersistence.update(user);
4459
4460 return user;
4461 }
4462
4463
4474 @Override
4475 public void updateOrganizations(
4476 long userId, long[] newOrganizationIds,
4477 ServiceContext serviceContext)
4478 throws PortalException, SystemException {
4479
4480 updateOrganizations(
4481 userId, newOrganizationIds, serviceContext.isIndexingEnabled());
4482 }
4483
4484
4496 @Override
4497 public User updatePassword(
4498 long userId, String password1, String password2,
4499 boolean passwordReset)
4500 throws PortalException, SystemException {
4501
4502 return updatePassword(
4503 userId, password1, password2, passwordReset, false);
4504 }
4505
4506
4521 @Override
4522 public User updatePassword(
4523 long userId, String password1, String password2,
4524 boolean passwordReset, boolean silentUpdate)
4525 throws PortalException, SystemException {
4526
4527 User user = userPersistence.findByPrimaryKey(userId);
4528
4529 if (!silentUpdate) {
4530 validatePassword(user.getCompanyId(), userId, password1, password2);
4531 }
4532
4533 String oldEncPwd = user.getPassword();
4534
4535 if (!user.isPasswordEncrypted()) {
4536 oldEncPwd = PasswordEncryptorUtil.encrypt(user.getPassword());
4537 }
4538
4539 String newEncPwd = PasswordEncryptorUtil.encrypt(password1);
4540
4541 if (user.hasCompanyMx()) {
4542 mailService.updatePassword(user.getCompanyId(), userId, password1);
4543 }
4544
4545 user.setPassword(newEncPwd);
4546 user.setPasswordUnencrypted(password1);
4547 user.setPasswordEncrypted(true);
4548 user.setPasswordReset(passwordReset);
4549 user.setPasswordModifiedDate(new Date());
4550 user.setDigest(StringPool.BLANK);
4551 user.setGraceLoginCount(0);
4552
4553 if (!silentUpdate) {
4554 user.setPasswordModified(true);
4555 }
4556
4557 try {
4558 userPersistence.update(user);
4559 }
4560 catch (ModelListenerException mle) {
4561 String msg = GetterUtil.getString(mle.getCause().getMessage());
4562
4563 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
4564 String passwordHistory = PrefsPropsUtil.getString(
4565 user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
4566
4567 if (msg.contains(passwordHistory)) {
4568 throw new UserPasswordException(
4569 UserPasswordException.PASSWORD_ALREADY_USED);
4570 }
4571 }
4572
4573 throw new UserPasswordException(
4574 UserPasswordException.PASSWORD_INVALID);
4575 }
4576
4577 if (!silentUpdate) {
4578 user.setPasswordModified(false);
4579
4580 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
4581 }
4582
4583 return user;
4584 }
4585
4586
4600 @Override
4601 public User updatePasswordManually(
4602 long userId, String password, boolean passwordEncrypted,
4603 boolean passwordReset, Date passwordModifiedDate)
4604 throws PortalException, SystemException {
4605
4606
4607
4608 User user = userPersistence.findByPrimaryKey(userId);
4609
4610 user.setPassword(password);
4611 user.setPasswordEncrypted(passwordEncrypted);
4612 user.setPasswordReset(passwordReset);
4613 user.setPasswordModifiedDate(passwordModifiedDate);
4614 user.setDigest(StringPool.BLANK);
4615
4616 userPersistence.update(user);
4617
4618 return user;
4619 }
4620
4621
4632 @Override
4633 public User updatePasswordReset(long userId, boolean passwordReset)
4634 throws PortalException, SystemException {
4635
4636 User user = userPersistence.findByPrimaryKey(userId);
4637
4638 user.setPasswordReset(passwordReset);
4639
4640 userPersistence.update(user);
4641
4642 return user;
4643 }
4644
4645
4655 @Override
4656 public User updatePortrait(long userId, byte[] bytes)
4657 throws PortalException, SystemException {
4658
4659 User user = userPersistence.findByPrimaryKey(userId);
4660
4661 long imageMaxSize = PrefsPropsUtil.getLong(
4662 PropsKeys.USERS_IMAGE_MAX_SIZE);
4663
4664 if ((imageMaxSize > 0) &&
4665 ((bytes == null) || (bytes.length > imageMaxSize))) {
4666
4667 throw new UserPortraitSizeException();
4668 }
4669
4670 long portraitId = user.getPortraitId();
4671
4672 if (portraitId <= 0) {
4673 portraitId = counterLocalService.increment();
4674
4675 user.setPortraitId(portraitId);
4676 }
4677
4678 try {
4679 ImageBag imageBag = ImageToolUtil.read(bytes);
4680
4681 RenderedImage renderedImage = imageBag.getRenderedImage();
4682
4683 if (renderedImage == null) {
4684 throw new UserPortraitTypeException();
4685 }
4686
4687 renderedImage = ImageToolUtil.scale(
4688 renderedImage, PropsValues.USERS_IMAGE_MAX_HEIGHT,
4689 PropsValues.USERS_IMAGE_MAX_WIDTH);
4690
4691 String contentType = imageBag.getType();
4692
4693 imageLocalService.updateImage(
4694 portraitId,
4695 ImageToolUtil.getBytes(renderedImage, contentType));
4696 }
4697 catch (IOException ioe) {
4698 throw new ImageSizeException(ioe);
4699 }
4700
4701 userPersistence.update(user);
4702
4703 return user;
4704 }
4705
4706
4717 @Override
4718 public User updateReminderQuery(long userId, String question, String answer)
4719 throws PortalException, SystemException {
4720
4721 validateReminderQuery(question, answer);
4722
4723 User user = userPersistence.findByPrimaryKey(userId);
4724
4725 user.setReminderQueryQuestion(question);
4726 user.setReminderQueryAnswer(answer);
4727
4728 userPersistence.update(user);
4729
4730 return user;
4731 }
4732
4733
4743 @Override
4744 public User updateScreenName(long userId, String screenName)
4745 throws PortalException, SystemException {
4746
4747
4748
4749 User user = userPersistence.findByPrimaryKey(userId);
4750
4751 screenName = getLogin(screenName);
4752
4753 validateScreenName(user.getCompanyId(), userId, screenName);
4754
4755 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
4756 user.setDigest(StringPool.BLANK);
4757 }
4758
4759 user.setScreenName(screenName);
4760
4761 userPersistence.update(user);
4762
4763
4764
4765 Group group = groupLocalService.getUserGroup(
4766 user.getCompanyId(), userId);
4767
4768 group.setFriendlyURL(StringPool.SLASH + screenName);
4769
4770 groupPersistence.update(group);
4771
4772 return user;
4773 }
4774
4775
4784 @Override
4785 public User updateStatus(long userId, int status)
4786 throws PortalException, SystemException {
4787
4788 User user = userPersistence.findByPrimaryKey(userId);
4789
4790 if ((status == WorkflowConstants.STATUS_APPROVED) &&
4791 (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {
4792
4793 validateCompanyMaxUsers(user.getCompanyId());
4794 }
4795
4796 user.setStatus(status);
4797
4798 userPersistence.update(user);
4799
4800 reindex(user);
4801
4802 return user;
4803 }
4804
4805
4861 @Override
4862 @SuppressWarnings("deprecation")
4863 public User updateUser(
4864 long userId, String oldPassword, String newPassword1,
4865 String newPassword2, boolean passwordReset,
4866 String reminderQueryQuestion, String reminderQueryAnswer,
4867 String screenName, String emailAddress, long facebookId,
4868 String openId, String languageId, String timeZoneId,
4869 String greeting, String comments, String firstName,
4870 String middleName, String lastName, int prefixId, int suffixId,
4871 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
4872 String smsSn, String aimSn, String facebookSn, String icqSn,
4873 String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
4874 String twitterSn, String ymSn, String jobTitle, long[] groupIds,
4875 long[] organizationIds, long[] roleIds,
4876 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
4877 ServiceContext serviceContext)
4878 throws PortalException, SystemException {
4879
4880
4881
4882 User user = userPersistence.findByPrimaryKey(userId);
4883 Company company = companyPersistence.findByPrimaryKey(
4884 user.getCompanyId());
4885 String password = oldPassword;
4886 screenName = getLogin(screenName);
4887 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
4888 openId = openId.trim();
4889 String oldFullName = user.getFullName();
4890 aimSn = StringUtil.toLowerCase(aimSn.trim());
4891 facebookSn = StringUtil.toLowerCase(facebookSn.trim());
4892 icqSn = StringUtil.toLowerCase(icqSn.trim());
4893 jabberSn = StringUtil.toLowerCase(jabberSn.trim());
4894 msnSn = StringUtil.toLowerCase(msnSn.trim());
4895 mySpaceSn = StringUtil.toLowerCase(mySpaceSn.trim());
4896 skypeSn = StringUtil.toLowerCase(skypeSn.trim());
4897 twitterSn = StringUtil.toLowerCase(twitterSn.trim());
4898 ymSn = StringUtil.toLowerCase(ymSn.trim());
4899 Date now = new Date();
4900
4901 EmailAddressGenerator emailAddressGenerator =
4902 EmailAddressGeneratorFactory.getInstance();
4903
4904 if (emailAddressGenerator.isGenerated(emailAddress)) {
4905 emailAddress = StringPool.BLANK;
4906 }
4907
4908 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
4909 Validator.isNull(emailAddress)) {
4910
4911 emailAddress = emailAddressGenerator.generate(
4912 user.getCompanyId(), userId);
4913 }
4914
4915 validate(
4916 userId, screenName, emailAddress, openId, firstName, middleName,
4917 lastName, smsSn);
4918
4919 if (Validator.isNotNull(newPassword1) ||
4920 Validator.isNotNull(newPassword2)) {
4921
4922 user = updatePassword(
4923 userId, newPassword1, newPassword2, passwordReset);
4924
4925 password = newPassword1;
4926
4927 user.setDigest(StringPool.BLANK);
4928 }
4929
4930 user.setModifiedDate(now);
4931
4932 if (user.getContactId() <= 0) {
4933 user.setContactId(counterLocalService.increment());
4934 }
4935
4936 user.setPasswordReset(passwordReset);
4937
4938 if (Validator.isNotNull(reminderQueryQuestion) &&
4939 Validator.isNotNull(reminderQueryAnswer)) {
4940
4941 user.setReminderQueryQuestion(reminderQueryQuestion);
4942 user.setReminderQueryAnswer(reminderQueryAnswer);
4943 }
4944
4945 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
4946 user.setScreenName(screenName);
4947
4948 user.setDigest(StringPool.BLANK);
4949 }
4950
4951 boolean sendEmailAddressVerification = false;
4952
4953 if (!company.isStrangersVerify()) {
4954 setEmailAddress(
4955 user, password, firstName, middleName, lastName, emailAddress);
4956 }
4957 else {
4958 sendEmailAddressVerification = true;
4959 }
4960
4961 if (serviceContext != null) {
4962 String uuid = serviceContext.getUuid();
4963
4964 if (Validator.isNotNull(uuid)) {
4965 user.setUuid(uuid);
4966 }
4967 }
4968
4969 user.setFacebookId(facebookId);
4970
4971 Long ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
4972
4973 if (ldapServerId != null) {
4974 user.setLdapServerId(ldapServerId);
4975 }
4976
4977 user.setOpenId(openId);
4978 user.setLanguageId(languageId);
4979 user.setTimeZoneId(timeZoneId);
4980 user.setGreeting(greeting);
4981 user.setComments(comments);
4982 user.setFirstName(firstName);
4983 user.setMiddleName(middleName);
4984 user.setLastName(lastName);
4985 user.setJobTitle(jobTitle);
4986 user.setExpandoBridgeAttributes(serviceContext);
4987
4988 userPersistence.update(user, serviceContext);
4989
4990
4991
4992 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
4993
4994 long contactId = user.getContactId();
4995
4996 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
4997
4998 if (contact == null) {
4999 contact = contactPersistence.create(contactId);
5000
5001 contact.setCompanyId(user.getCompanyId());
5002 contact.setUserName(StringPool.BLANK);
5003 contact.setCreateDate(now);
5004 contact.setClassName(User.class.getName());
5005 contact.setClassPK(user.getUserId());
5006 contact.setAccountId(company.getAccountId());
5007 contact.setParentContactId(
5008 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
5009 }
5010
5011 contact.setModifiedDate(now);
5012 contact.setEmailAddress(user.getEmailAddress());
5013 contact.setFirstName(firstName);
5014 contact.setMiddleName(middleName);
5015 contact.setLastName(lastName);
5016 contact.setPrefixId(prefixId);
5017 contact.setSuffixId(suffixId);
5018 contact.setMale(male);
5019 contact.setBirthday(birthday);
5020 contact.setSmsSn(smsSn);
5021 contact.setAimSn(aimSn);
5022 contact.setFacebookSn(facebookSn);
5023 contact.setIcqSn(icqSn);
5024 contact.setJabberSn(jabberSn);
5025 contact.setMsnSn(msnSn);
5026 contact.setMySpaceSn(mySpaceSn);
5027 contact.setSkypeSn(skypeSn);
5028 contact.setTwitterSn(twitterSn);
5029 contact.setYmSn(ymSn);
5030 contact.setJobTitle(jobTitle);
5031
5032 contactPersistence.update(contact, serviceContext);
5033
5034
5035
5036 Group group = groupLocalService.getUserGroup(
5037 user.getCompanyId(), userId);
5038
5039 group.setFriendlyURL(StringPool.SLASH + screenName);
5040
5041 groupPersistence.update(group);
5042
5043
5044
5045
5046
5047
5048
5049 List<UserGroupRole> previousUserGroupRoles =
5050 userGroupRolePersistence.findByUserId(userId);
5051
5052 updateGroups(userId, groupIds, serviceContext, false);
5053 updateOrganizations(userId, organizationIds, false);
5054
5055
5056
5057 if (roleIds != null) {
5058 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
5059
5060 userPersistence.setRoles(userId, roleIds);
5061 }
5062
5063
5064
5065 updateUserGroupRoles(
5066 user, groupIds, organizationIds, userGroupRoles,
5067 previousUserGroupRoles);
5068
5069
5070
5071 if (userGroupIds != null) {
5072 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
5073 userGroupLocalService.copyUserGroupLayouts(
5074 userGroupIds, userId);
5075 }
5076
5077 userPersistence.setUserGroups(userId, userGroupIds);
5078 }
5079
5080
5081
5082 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
5083
5084
5085
5086 if (serviceContext != null) {
5087 updateAsset(
5088 userId, user, serviceContext.getAssetCategoryIds(),
5089 serviceContext.getAssetTagNames());
5090 }
5091
5092
5093
5094 if (GetterUtil.getBoolean(
5095 PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
5096 !oldFullName.equals(user.getFullName())) {
5097
5098 mbMessageLocalService.updateUserName(userId, user.getFullName());
5099 }
5100
5101
5102
5103 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
5104 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5105 User.class);
5106
5107 indexer.reindex(user);
5108 }
5109
5110
5111
5112 if ((serviceContext != null) && sendEmailAddressVerification) {
5113 sendEmailAddressVerification(user, emailAddress, serviceContext);
5114 }
5115
5116
5117
5118 PermissionCacheUtil.clearCache();
5119
5120 return user;
5121 }
5122
5123
5132 @Override
5133 public void verifyEmailAddress(String ticketKey)
5134 throws PortalException, SystemException {
5135
5136 Ticket ticket = ticketLocalService.getTicket(ticketKey);
5137
5138 if (ticket.isExpired() ||
5139 (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
5140
5141 throw new NoSuchTicketException();
5142 }
5143
5144 User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
5145
5146 String emailAddress = ticket.getExtraInfo();
5147
5148 emailAddress = StringUtil.toLowerCase(emailAddress).trim();
5149
5150 if (!emailAddress.equals(user.getEmailAddress())) {
5151 if (userPersistence.fetchByC_EA(
5152 user.getCompanyId(), emailAddress) != null) {
5153
5154 throw new DuplicateUserEmailAddressException();
5155 }
5156
5157 setEmailAddress(
5158 user, StringPool.BLANK, user.getFirstName(),
5159 user.getMiddleName(), user.getLastName(), emailAddress);
5160
5161 Contact contact = user.getContact();
5162
5163 contact.setEmailAddress(user.getEmailAddress());
5164
5165 contactPersistence.update(contact);
5166 }
5167
5168 user.setEmailAddressVerified(true);
5169
5170 userPersistence.update(user);
5171
5172 ticketLocalService.deleteTicket(ticket);
5173 }
5174
5175 protected void addDefaultRolesAndTeams(long groupId, long[] userIds)
5176 throws PortalException, SystemException {
5177
5178 List<Role> defaultSiteRoles = new ArrayList<Role>();
5179
5180 Group group = groupLocalService.getGroup(groupId);
5181
5182 UnicodeProperties typeSettingsProperties =
5183 group.getTypeSettingsProperties();
5184
5185 long[] defaultSiteRoleIds = StringUtil.split(
5186 typeSettingsProperties.getProperty("defaultSiteRoleIds"), 0L);
5187
5188 for (long defaultSiteRoleId : defaultSiteRoleIds) {
5189 Role defaultSiteRole = rolePersistence.fetchByPrimaryKey(
5190 defaultSiteRoleId);
5191
5192 if (defaultSiteRole == null) {
5193 if (_log.isWarnEnabled()) {
5194 _log.warn("Unable to find role " + defaultSiteRoleId);
5195 }
5196
5197 continue;
5198 }
5199
5200 defaultSiteRoles.add(defaultSiteRole);
5201 }
5202
5203 List<Team> defaultTeams = new ArrayList<Team>();
5204
5205 long[] defaultTeamIds = StringUtil.split(
5206 typeSettingsProperties.getProperty("defaultTeamIds"), 0L);
5207
5208 for (long defaultTeamId : defaultTeamIds) {
5209 Team defaultTeam = teamPersistence.findByPrimaryKey(defaultTeamId);
5210
5211 if (defaultTeam == null) {
5212 if (_log.isWarnEnabled()) {
5213 _log.warn("Unable to find team " + defaultTeamId);
5214 }
5215
5216 continue;
5217 }
5218
5219 defaultTeams.add(defaultTeam);
5220 }
5221
5222 for (long userId : userIds) {
5223 Set<Long> userRoleIdsSet = new HashSet<Long>();
5224
5225 for (Role role : defaultSiteRoles) {
5226 if (!userPersistence.containsRole(userId, role.getRoleId())) {
5227 userRoleIdsSet.add(role.getRoleId());
5228 }
5229 }
5230
5231 long[] userRoleIds = ArrayUtil.toArray(
5232 userRoleIdsSet.toArray(new Long[userRoleIdsSet.size()]));
5233
5234 userGroupRoleLocalService.addUserGroupRoles(
5235 userId, groupId, userRoleIds);
5236
5237 Set<Long> userTeamIdsSet = new HashSet<Long>();
5238
5239 for (Team team : defaultTeams) {
5240 if (!userPersistence.containsTeam(userId, team.getTeamId())) {
5241 userTeamIdsSet.add(team.getTeamId());
5242 }
5243 }
5244
5245 long[] userTeamIds = ArrayUtil.toArray(
5246 userTeamIdsSet.toArray(new Long[userTeamIdsSet.size()]));
5247
5248 userPersistence.addTeams(userId, userTeamIds);
5249 }
5250 }
5251
5252
5298 protected int authenticate(
5299 long companyId, String login, String password, String authType,
5300 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
5301 Map<String, Object> resultsMap)
5302 throws PortalException, SystemException {
5303
5304 if (PropsValues.AUTH_LOGIN_DISABLED) {
5305 return Authenticator.FAILURE;
5306 }
5307
5308 login = StringUtil.toLowerCase(login.trim());
5309
5310 long userId = GetterUtil.getLong(login);
5311
5312
5313
5314 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5315 if (Validator.isNull(login)) {
5316 throw new UserEmailAddressException();
5317 }
5318 }
5319 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5320 if (Validator.isNull(login)) {
5321 throw new UserScreenNameException();
5322 }
5323 }
5324 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5325 if (Validator.isNull(login)) {
5326 throw new UserIdException();
5327 }
5328 }
5329
5330 if (Validator.isNull(password)) {
5331 throw new UserPasswordException(
5332 UserPasswordException.PASSWORD_INVALID);
5333 }
5334
5335 int authResult = Authenticator.FAILURE;
5336
5337
5338
5339 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5340 authResult = AuthPipeline.authenticateByEmailAddress(
5341 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5342 headerMap, parameterMap);
5343 }
5344 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5345 authResult = AuthPipeline.authenticateByScreenName(
5346 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5347 headerMap, parameterMap);
5348 }
5349 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5350 authResult = AuthPipeline.authenticateByUserId(
5351 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
5352 headerMap, parameterMap);
5353 }
5354
5355
5356
5357 User user = null;
5358
5359 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5360 user = fetchUserByEmailAddress(companyId, login);
5361 }
5362 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5363 user = fetchUserByScreenName(companyId, login);
5364 }
5365 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5366 user = userPersistence.fetchByPrimaryKey(GetterUtil.getLong(login));
5367 }
5368
5369 if (user == null) {
5370 return Authenticator.DNE;
5371 }
5372
5373 if (user.isDefaultUser()) {
5374 if (_log.isInfoEnabled()) {
5375 _log.info("Authentication is disabled for the default user");
5376 }
5377
5378 return Authenticator.DNE;
5379 }
5380 else if (!user.isActive()) {
5381 if (_log.isInfoEnabled()) {
5382 _log.info(
5383 "Authentication is disabled for inactive user " +
5384 user.getUserId());
5385 }
5386
5387 return Authenticator.FAILURE;
5388 }
5389
5390 if (!user.isPasswordEncrypted()) {
5391 user.setPassword(PasswordEncryptorUtil.encrypt(user.getPassword()));
5392 user.setPasswordEncrypted(true);
5393
5394 userPersistence.update(user);
5395 }
5396
5397
5398
5399
5400 checkLockout(user);
5401
5402 checkPasswordExpired(user);
5403
5404
5405
5406 boolean skipLiferayCheck = false;
5407
5408 if (authResult == Authenticator.SKIP_LIFERAY_CHECK) {
5409 authResult = Authenticator.SUCCESS;
5410
5411 skipLiferayCheck = true;
5412 }
5413 else if ((authResult == Authenticator.SUCCESS) &&
5414 PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5415
5416 boolean authenticated = PwdAuthenticator.authenticate(
5417 login, password, user.getPassword());
5418
5419 if (authenticated) {
5420 authResult = Authenticator.SUCCESS;
5421 }
5422 else {
5423 authResult = Authenticator.FAILURE;
5424 }
5425 }
5426
5427
5428
5429 if (authResult == Authenticator.SUCCESS) {
5430 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5431 authResult = AuthPipeline.authenticateByEmailAddress(
5432 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5433 headerMap, parameterMap);
5434 }
5435 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5436 authResult = AuthPipeline.authenticateByScreenName(
5437 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5438 headerMap, parameterMap);
5439 }
5440 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5441 authResult = AuthPipeline.authenticateByUserId(
5442 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5443 headerMap, parameterMap);
5444 }
5445 }
5446
5447 if (authResult == Authenticator.SUCCESS) {
5448 if (resultsMap != null) {
5449 resultsMap.put("userId", user.getUserId());
5450 }
5451
5452
5453
5454 if (skipLiferayCheck ||
5455 !PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK ||
5456 Validator.isNull(user.getDigest())) {
5457
5458 String digest = user.getDigest(password);
5459
5460 user.setDigest(digest);
5461
5462 userPersistence.update(user);
5463 }
5464 }
5465
5466
5467
5468 if (authResult == Authenticator.FAILURE) {
5469 try {
5470 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5471 AuthPipeline.onFailureByEmailAddress(
5472 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5473 parameterMap);
5474 }
5475 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5476 AuthPipeline.onFailureByScreenName(
5477 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5478 parameterMap);
5479 }
5480 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5481 AuthPipeline.onFailureByUserId(
5482 PropsKeys.AUTH_FAILURE, companyId, userId, headerMap,
5483 parameterMap);
5484 }
5485
5486 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5487
5488 if (user == null) {
5489 return Authenticator.DNE;
5490 }
5491
5492
5493
5494 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5495 user.getCompanyId())) {
5496
5497 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5498
5499 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5500
5501 int failedLoginAttempts = user.getFailedLoginAttempts();
5502 int maxFailures = passwordPolicy.getMaxFailure();
5503
5504 if ((failedLoginAttempts >= maxFailures) &&
5505 (maxFailures != 0)) {
5506
5507 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5508 AuthPipeline.onMaxFailuresByEmailAddress(
5509 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5510 headerMap, parameterMap);
5511 }
5512 else if (authType.equals(
5513 CompanyConstants.AUTH_TYPE_SN)) {
5514
5515 AuthPipeline.onMaxFailuresByScreenName(
5516 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5517 headerMap, parameterMap);
5518 }
5519 else if (authType.equals(
5520 CompanyConstants.AUTH_TYPE_ID)) {
5521
5522 AuthPipeline.onMaxFailuresByUserId(
5523 PropsKeys.AUTH_MAX_FAILURES, companyId, userId,
5524 headerMap, parameterMap);
5525 }
5526 }
5527 }
5528 }
5529 catch (Exception e) {
5530 _log.error(e, e);
5531 }
5532 }
5533
5534
5535
5536 return authResult;
5537 }
5538
5539 protected Date getBirthday(
5540 int birthdayMonth, int birthdayDay, int birthdayYear)
5541 throws PortalException {
5542
5543 Date birthday = PortalUtil.getDate(
5544 birthdayMonth, birthdayDay, birthdayYear,
5545 ContactBirthdayException.class);
5546
5547 Date now = new Date();
5548
5549 if (birthday.after(now)) {
5550 throw new ContactBirthdayException();
5551 }
5552
5553 return birthday;
5554 }
5555
5556 protected String getLogin(String login) {
5557 return StringUtil.lowerCase(StringUtil.trim(login));
5558 }
5559
5560 protected long[] getUserIds(List<User> users) {
5561 long[] userIds = new long[users.size()];
5562
5563 for (int i = 0; i < users.size(); i++) {
5564 User user = users.get(i);
5565
5566 userIds[i] = user.getUserId();
5567 }
5568
5569 return userIds;
5570 }
5571
5572 protected void reindex(final User user) {
5573 final Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5574 User.class);
5575
5576 Callable<Void> callable = new ShardCallable<Void>(
5577 user.getCompanyId()) {
5578
5579 @Override
5580 protected Void doCall() throws Exception {
5581 indexer.reindex(user);
5582
5583 return null;
5584 }
5585
5586 };
5587
5588 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
5589 }
5590
5591 protected Hits search(
5592 long companyId, String firstName, String middleName,
5593 String lastName, String fullName, String screenName,
5594 String emailAddress, String street, String city, String zip,
5595 String region, String country, int status,
5596 LinkedHashMap<String, Object> params, boolean andSearch, int start,
5597 int end, Sort sort)
5598 throws SystemException {
5599
5600 try {
5601 SearchContext searchContext = new SearchContext();
5602
5603 searchContext.setAndSearch(andSearch);
5604
5605 Map<String, Serializable> attributes =
5606 new HashMap<String, Serializable>();
5607
5608 attributes.put("city", city);
5609 attributes.put("country", country);
5610 attributes.put("emailAddress", emailAddress);
5611 attributes.put("firstName", firstName);
5612 attributes.put("fullName", fullName);
5613 attributes.put("lastName", lastName);
5614 attributes.put("middleName", middleName);
5615 attributes.put("params", params);
5616 attributes.put("region", region);
5617 attributes.put("screenName", screenName);
5618 attributes.put("street", street);
5619 attributes.put("status", status);
5620 attributes.put("zip", zip);
5621
5622 searchContext.setAttributes(attributes);
5623
5624 searchContext.setCompanyId(companyId);
5625 searchContext.setEnd(end);
5626
5627 if (params != null) {
5628 String keywords = (String)params.remove("keywords");
5629
5630 if (Validator.isNotNull(keywords)) {
5631 searchContext.setKeywords(keywords);
5632 }
5633 }
5634
5635 QueryConfig queryConfig = new QueryConfig();
5636
5637 queryConfig.setHighlightEnabled(false);
5638 queryConfig.setScoreEnabled(false);
5639
5640 searchContext.setQueryConfig(queryConfig);
5641
5642 if (sort != null) {
5643 searchContext.setSorts(sort);
5644 }
5645
5646 searchContext.setStart(start);
5647
5648 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5649 User.class);
5650
5651 return indexer.search(searchContext);
5652 }
5653 catch (Exception e) {
5654 throw new SystemException(e);
5655 }
5656 }
5657
5658 protected void sendEmail(
5659 User user, String password, ServiceContext serviceContext)
5660 throws SystemException {
5661
5662 if (!PrefsPropsUtil.getBoolean(
5663 user.getCompanyId(),
5664 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
5665
5666 return;
5667 }
5668
5669 String fromName = PrefsPropsUtil.getString(
5670 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
5671 String fromAddress = PrefsPropsUtil.getString(
5672 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
5673
5674 String toName = user.getFullName();
5675 String toAddress = user.getEmailAddress();
5676
5677 String subject = PrefsPropsUtil.getContent(
5678 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
5679
5680 String body = null;
5681
5682 if (Validator.isNotNull(password)) {
5683 body = PrefsPropsUtil.getContent(
5684 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
5685 }
5686 else {
5687 body = PrefsPropsUtil.getContent(
5688 user.getCompanyId(),
5689 PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
5690 }
5691
5692 SubscriptionSender subscriptionSender = new SubscriptionSender();
5693
5694 subscriptionSender.setBody(body);
5695 subscriptionSender.setCompanyId(user.getCompanyId());
5696 subscriptionSender.setContextAttributes(
5697 "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
5698 "[$USER_SCREENNAME$]", user.getScreenName());
5699 subscriptionSender.setFrom(fromAddress, fromName);
5700 subscriptionSender.setHtmlFormat(true);
5701 subscriptionSender.setMailId(
5702 "user", user.getUserId(), System.currentTimeMillis(),
5703 PwdGenerator.getPassword());
5704 subscriptionSender.setServiceContext(serviceContext);
5705 subscriptionSender.setSubject(subject);
5706 subscriptionSender.setUserId(user.getUserId());
5707
5708 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
5709
5710 subscriptionSender.flushNotificationsAsync();
5711 }
5712
5713 protected void setEmailAddress(
5714 User user, String password, String firstName, String middleName,
5715 String lastName, String emailAddress)
5716 throws PortalException, SystemException {
5717
5718 if (StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
5719 return;
5720 }
5721
5722 long userId = user.getUserId();
5723
5724
5725
5726 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
5727 Validator.isNotNull(password)) {
5728
5729 mailService.addUser(
5730 user.getCompanyId(), userId, password, firstName, middleName,
5731 lastName, emailAddress);
5732 }
5733
5734
5735
5736 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
5737 mailService.updateEmailAddress(
5738 user.getCompanyId(), userId, emailAddress);
5739 }
5740
5741
5742
5743 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
5744 mailService.deleteEmailAddress(user.getCompanyId(), userId);
5745 }
5746
5747 user.setEmailAddress(emailAddress);
5748 user.setDigest(StringPool.BLANK);
5749 }
5750
5751 protected void updateGroups(
5752 long userId, long[] newGroupIds, ServiceContext serviceContext,
5753 boolean indexingEnabled)
5754 throws PortalException, SystemException {
5755
5756 if (newGroupIds == null) {
5757 return;
5758 }
5759
5760 List<Group> oldGroups = userPersistence.getGroups(userId);
5761
5762 Set<Long> oldGroupIds = new HashSet<Long>(oldGroups.size());
5763
5764 for (Group oldGroup : oldGroups) {
5765 long oldGroupId = oldGroup.getGroupId();
5766
5767 oldGroupIds.add(oldGroupId);
5768
5769 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
5770 unsetGroupUsers(
5771 oldGroupId, new long[] {userId}, serviceContext);
5772 }
5773 }
5774
5775 for (long newGroupId : newGroupIds) {
5776 if (!oldGroupIds.contains(newGroupId)) {
5777 addGroupUsers(newGroupId, new long[] {userId});
5778 }
5779 }
5780
5781 if (indexingEnabled) {
5782 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5783 User.class);
5784
5785 indexer.reindex(new long[] {userId});
5786 }
5787
5788 PermissionCacheUtil.clearCache();
5789 }
5790
5791 protected void updateOrganizations(
5792 long userId, long[] newOrganizationIds, boolean indexingEnabled)
5793 throws PortalException, SystemException {
5794
5795 if (newOrganizationIds == null) {
5796 return;
5797 }
5798
5799 List<Organization> oldOrganizations = userPersistence.getOrganizations(
5800 userId);
5801
5802 Set<Long> oldOrganizationIds = new HashSet<Long>(
5803 oldOrganizations.size());
5804
5805 for (Organization oldOrganization : oldOrganizations) {
5806 long oldOrganizationId = oldOrganization.getOrganizationId();
5807
5808 oldOrganizationIds.add(oldOrganizationId);
5809
5810 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
5811 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
5812 }
5813 }
5814
5815 for (long newOrganizationId : newOrganizationIds) {
5816 if (!oldOrganizationIds.contains(newOrganizationId)) {
5817 addOrganizationUsers(newOrganizationId, new long[] {userId});
5818 }
5819 }
5820
5821 if (indexingEnabled) {
5822 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5823 User.class);
5824
5825 indexer.reindex(new long[] {userId});
5826 }
5827
5828 PermissionCacheUtil.clearCache();
5829 }
5830
5831 protected void updateUserGroupRoles(
5832 User user, long[] groupIds, long[] organizationIds,
5833 List<UserGroupRole> userGroupRoles,
5834 List<UserGroupRole> previousUserGroupRoles)
5835 throws PortalException, SystemException {
5836
5837 if (userGroupRoles == null) {
5838 return;
5839 }
5840
5841 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
5842 if (userGroupRoles.contains(userGroupRole)) {
5843 userGroupRoles.remove(userGroupRole);
5844 }
5845 else {
5846 userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
5847 }
5848 }
5849
5850 long[] validGroupIds = null;
5851
5852 if (groupIds != null) {
5853 validGroupIds = ArrayUtil.clone(groupIds);
5854 }
5855 else {
5856 validGroupIds = user.getGroupIds();
5857 }
5858
5859 if (organizationIds == null) {
5860 organizationIds = user.getOrganizationIds();
5861 }
5862
5863 long[] organizationGroupIds = new long[organizationIds.length];
5864
5865 for (int i = 0; i < organizationIds.length; i++) {
5866 long organizationId = organizationIds[i];
5867
5868 Organization organization =
5869 organizationPersistence.findByPrimaryKey(organizationId);
5870
5871 organizationGroupIds[i] = organization.getGroupId();
5872 }
5873
5874 validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
5875
5876 Arrays.sort(validGroupIds);
5877
5878 for (UserGroupRole userGroupRole : userGroupRoles) {
5879 if (Arrays.binarySearch(
5880 validGroupIds, userGroupRole.getGroupId()) >= 0) {
5881
5882 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
5883 }
5884 }
5885 }
5886
5887 protected void validate(
5888 long companyId, long userId, boolean autoPassword, String password1,
5889 String password2, boolean autoScreenName, String screenName,
5890 String emailAddress, String openId, String firstName,
5891 String middleName, String lastName, long[] organizationIds)
5892 throws PortalException, SystemException {
5893
5894 validateCompanyMaxUsers(companyId);
5895
5896 if (!autoScreenName) {
5897 validateScreenName(companyId, userId, screenName);
5898 }
5899
5900 if (!autoPassword) {
5901 PasswordPolicy passwordPolicy =
5902 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
5903
5904 PwdToolkitUtil.validate(
5905 companyId, 0, password1, password2, passwordPolicy);
5906 }
5907
5908 validateEmailAddress(companyId, emailAddress);
5909
5910 if (Validator.isNotNull(emailAddress)) {
5911 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
5912
5913 if ((user != null) && (user.getUserId() != userId)) {
5914 throw new DuplicateUserEmailAddressException();
5915 }
5916 }
5917
5918 validateOpenId(companyId, userId, openId);
5919
5920 validateFullName(companyId, firstName, middleName, lastName);
5921
5922 if (organizationIds != null) {
5923 for (long organizationId : organizationIds) {
5924 Organization organization =
5925 organizationPersistence.fetchByPrimaryKey(organizationId);
5926
5927 if (organization == null) {
5928 throw new NoSuchOrganizationException();
5929 }
5930 }
5931 }
5932 }
5933
5934 protected void validate(
5935 long userId, String screenName, String emailAddress, String openId,
5936 String firstName, String middleName, String lastName, String smsSn)
5937 throws PortalException, SystemException {
5938
5939 User user = userPersistence.findByPrimaryKey(userId);
5940
5941 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
5942 validateScreenName(user.getCompanyId(), userId, screenName);
5943 }
5944
5945 validateEmailAddress(user.getCompanyId(), emailAddress);
5946
5947 validateOpenId(user.getCompanyId(), userId, openId);
5948
5949 if (!user.isDefaultUser()) {
5950 if (Validator.isNotNull(emailAddress) &&
5951 !StringUtil.equalsIgnoreCase(
5952 user.getEmailAddress(), emailAddress)) {
5953
5954 if (userPersistence.fetchByC_EA(
5955 user.getCompanyId(), emailAddress) != null) {
5956
5957 throw new DuplicateUserEmailAddressException();
5958 }
5959 }
5960
5961 validateFullName(
5962 user.getCompanyId(), firstName, middleName, lastName);
5963 }
5964
5965 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
5966 throw new UserSmsException();
5967 }
5968 }
5969
5970 protected void validateCompanyMaxUsers(long companyId)
5971 throws PortalException, SystemException {
5972
5973 Company company = companyPersistence.findByPrimaryKey(companyId);
5974
5975 if (company.isSystem() || (company.getMaxUsers() == 0)) {
5976 return;
5977 }
5978
5979 int userCount = searchCount(
5980 companyId, null, WorkflowConstants.STATUS_APPROVED, null);
5981
5982 if (userCount >= company.getMaxUsers()) {
5983 throw new CompanyMaxUsersException();
5984 }
5985 }
5986
5987 protected void validateEmailAddress(long companyId, String emailAddress)
5988 throws PortalException, SystemException {
5989
5990 if (Validator.isNull(emailAddress) &&
5991 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
5992
5993 return;
5994 }
5995
5996 EmailAddressValidator emailAddressValidator =
5997 EmailAddressValidatorFactory.getInstance();
5998
5999 if (!emailAddressValidator.validate(companyId, emailAddress)) {
6000 throw new UserEmailAddressException();
6001 }
6002
6003 String pop3User = PrefsPropsUtil.getString(
6004 PropsKeys.MAIL_SESSION_MAIL_POP3_USER,
6005 PropsValues.MAIL_SESSION_MAIL_POP3_USER);
6006
6007 if (StringUtil.equalsIgnoreCase(emailAddress, pop3User)) {
6008 throw new ReservedUserEmailAddressException();
6009 }
6010
6011 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
6012 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
6013 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
6014
6015 for (String reservedEmailAddress : reservedEmailAddresses) {
6016 if (StringUtil.equalsIgnoreCase(
6017 emailAddress, reservedEmailAddress)) {
6018
6019 throw new ReservedUserEmailAddressException();
6020 }
6021 }
6022 }
6023
6024 protected void validateEmailAddress(
6025 User user, String emailAddress1, String emailAddress2)
6026 throws PortalException, SystemException {
6027
6028 if (!emailAddress1.equals(emailAddress2)) {
6029 throw new UserEmailAddressException();
6030 }
6031
6032 validateEmailAddress(user.getCompanyId(), emailAddress1);
6033 validateEmailAddress(user.getCompanyId(), emailAddress2);
6034
6035 if (!StringUtil.equalsIgnoreCase(
6036 emailAddress1, user.getEmailAddress())) {
6037
6038 if (userPersistence.fetchByC_EA(
6039 user.getCompanyId(), emailAddress1) != null) {
6040
6041 throw new DuplicateUserEmailAddressException();
6042 }
6043 }
6044 }
6045
6046 protected void validateFullName(
6047 long companyId, String firstName, String middleName,
6048 String lastName)
6049 throws PortalException, SystemException {
6050
6051 if (Validator.isNull(firstName)) {
6052 throw new ContactFirstNameException();
6053 }
6054 else if (Validator.isNull(lastName) &&
6055 PrefsPropsUtil.getBoolean(
6056 companyId, PropsKeys.USERS_LAST_NAME_REQUIRED,
6057 PropsValues.USERS_LAST_NAME_REQUIRED)) {
6058
6059 throw new ContactLastNameException();
6060 }
6061
6062 FullNameValidator fullNameValidator =
6063 FullNameValidatorFactory.getInstance();
6064
6065 if (!fullNameValidator.validate(
6066 companyId, firstName, middleName, lastName)) {
6067
6068 throw new ContactFullNameException();
6069 }
6070 }
6071
6072 protected void validateOpenId(long companyId, long userId, String openId)
6073 throws PortalException, SystemException {
6074
6075 if (Validator.isNull(openId)) {
6076 return;
6077 }
6078
6079 User user = userPersistence.fetchByC_O(companyId, openId);
6080
6081 if ((user != null) && (user.getUserId() != userId)) {
6082 throw new DuplicateOpenIdException();
6083 }
6084 }
6085
6086 protected void validatePassword(
6087 long companyId, long userId, String password1, String password2)
6088 throws PortalException, SystemException {
6089
6090 if (Validator.isNull(password1) || Validator.isNull(password2)) {
6091 throw new UserPasswordException(
6092 UserPasswordException.PASSWORD_INVALID);
6093 }
6094
6095 if (!password1.equals(password2)) {
6096 throw new UserPasswordException(
6097 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
6098 }
6099
6100 PasswordPolicy passwordPolicy =
6101 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
6102
6103 PwdToolkitUtil.validate(
6104 companyId, userId, password1, password2, passwordPolicy);
6105 }
6106
6107 protected void validateReminderQuery(String question, String answer)
6108 throws PortalException {
6109
6110 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
6111 return;
6112 }
6113
6114 if (Validator.isNull(question)) {
6115 throw new UserReminderQueryException("Question is null");
6116 }
6117
6118 if (Validator.isNull(answer)) {
6119 throw new UserReminderQueryException("Answer is null");
6120 }
6121 }
6122
6123 protected void validateScreenName(
6124 long companyId, long userId, String screenName)
6125 throws PortalException, SystemException {
6126
6127 if (Validator.isNull(screenName)) {
6128 throw new UserScreenNameException();
6129 }
6130
6131 ScreenNameValidator screenNameValidator =
6132 ScreenNameValidatorFactory.getInstance();
6133
6134 if (!screenNameValidator.validate(companyId, screenName)) {
6135 throw new UserScreenNameException();
6136 }
6137
6138 if (Validator.isNumber(screenName)) {
6139 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
6140 throw new UserScreenNameException();
6141 }
6142
6143 if (!screenName.equals(String.valueOf(userId))) {
6144 Group group = groupPersistence.fetchByPrimaryKey(
6145 GetterUtil.getLong(screenName));
6146
6147 if (group != null) {
6148 throw new UserScreenNameException();
6149 }
6150 }
6151 }
6152
6153 for (char c : screenName.toCharArray()) {
6154 if (!Validator.isChar(c) && !Validator.isDigit(c) &&
6155 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
6156 (c != CharPool.UNDERLINE)) {
6157
6158 throw new UserScreenNameException();
6159 }
6160 }
6161
6162 String[] anonymousNames = BaseServiceImpl.ANONYMOUS_NAMES;
6163
6164 for (String anonymousName : anonymousNames) {
6165 if (StringUtil.equalsIgnoreCase(screenName, anonymousName)) {
6166 throw new UserScreenNameException();
6167 }
6168 }
6169
6170 User user = userPersistence.fetchByC_SN(companyId, screenName);
6171
6172 if ((user != null) && (user.getUserId() != userId)) {
6173 throw new DuplicateUserScreenNameException();
6174 }
6175
6176 String friendlyURL = StringPool.SLASH + screenName;
6177
6178 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
6179
6180 if ((group != null) && (group.getClassPK() != userId)) {
6181 throw new GroupFriendlyURLException(
6182 GroupFriendlyURLException.DUPLICATE);
6183 }
6184
6185 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
6186
6187 if (exceptionType != -1) {
6188 throw new UserScreenNameException(
6189 new GroupFriendlyURLException(exceptionType));
6190 }
6191
6192 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
6193 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
6194 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
6195
6196 for (String reservedScreenName : reservedScreenNames) {
6197 if (StringUtil.equalsIgnoreCase(screenName, reservedScreenName)) {
6198 throw new ReservedUserScreenNameException();
6199 }
6200 }
6201 }
6202
6203 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
6204
6205 private Map<Long, User> _defaultUsers = new ConcurrentHashMap<Long, User>();
6206
6207 }