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.cache.PortalCache;
047 import com.liferay.portal.kernel.cache.PortalCacheMapSynchronizeUtil;
048 import com.liferay.portal.kernel.cache.PortalCacheMapSynchronizeUtil.Synchronizer;
049 import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
050 import com.liferay.portal.kernel.dao.shard.ShardCallable;
051 import com.liferay.portal.kernel.exception.PortalException;
052 import com.liferay.portal.kernel.exception.SystemException;
053 import com.liferay.portal.kernel.image.ImageBag;
054 import com.liferay.portal.kernel.image.ImageToolUtil;
055 import com.liferay.portal.kernel.language.LanguageUtil;
056 import com.liferay.portal.kernel.log.Log;
057 import com.liferay.portal.kernel.log.LogFactoryUtil;
058 import com.liferay.portal.kernel.messaging.DestinationNames;
059 import com.liferay.portal.kernel.messaging.Message;
060 import com.liferay.portal.kernel.messaging.MessageBusUtil;
061 import com.liferay.portal.kernel.search.Hits;
062 import com.liferay.portal.kernel.search.Indexer;
063 import com.liferay.portal.kernel.search.IndexerRegistryUtil;
064 import com.liferay.portal.kernel.search.QueryConfig;
065 import com.liferay.portal.kernel.search.SearchContext;
066 import com.liferay.portal.kernel.search.Sort;
067 import com.liferay.portal.kernel.spring.aop.Skip;
068 import com.liferay.portal.kernel.transaction.Propagation;
069 import com.liferay.portal.kernel.transaction.TransactionCommitCallbackRegistryUtil;
070 import com.liferay.portal.kernel.transaction.Transactional;
071 import com.liferay.portal.kernel.util.ArrayUtil;
072 import com.liferay.portal.kernel.util.CharPool;
073 import com.liferay.portal.kernel.util.Digester;
074 import com.liferay.portal.kernel.util.DigesterUtil;
075 import com.liferay.portal.kernel.util.GetterUtil;
076 import com.liferay.portal.kernel.util.KeyValuePair;
077 import com.liferay.portal.kernel.util.LocaleUtil;
078 import com.liferay.portal.kernel.util.OrderByComparator;
079 import com.liferay.portal.kernel.util.ParamUtil;
080 import com.liferay.portal.kernel.util.PropsKeys;
081 import com.liferay.portal.kernel.util.SetUtil;
082 import com.liferay.portal.kernel.util.StringBundler;
083 import com.liferay.portal.kernel.util.StringPool;
084 import com.liferay.portal.kernel.util.StringUtil;
085 import com.liferay.portal.kernel.util.UnicodeProperties;
086 import com.liferay.portal.kernel.util.Validator;
087 import com.liferay.portal.kernel.workflow.WorkflowConstants;
088 import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil;
089 import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
090 import com.liferay.portal.model.Account;
091 import com.liferay.portal.model.Company;
092 import com.liferay.portal.model.CompanyConstants;
093 import com.liferay.portal.model.Contact;
094 import com.liferay.portal.model.ContactConstants;
095 import com.liferay.portal.model.Group;
096 import com.liferay.portal.model.GroupConstants;
097 import com.liferay.portal.model.Layout;
098 import com.liferay.portal.model.Organization;
099 import com.liferay.portal.model.PasswordPolicy;
100 import com.liferay.portal.model.ResourceConstants;
101 import com.liferay.portal.model.Role;
102 import com.liferay.portal.model.RoleConstants;
103 import com.liferay.portal.model.Team;
104 import com.liferay.portal.model.Ticket;
105 import com.liferay.portal.model.TicketConstants;
106 import com.liferay.portal.model.User;
107 import com.liferay.portal.model.UserGroup;
108 import com.liferay.portal.model.UserGroupRole;
109 import com.liferay.portal.model.impl.LayoutImpl;
110 import com.liferay.portal.model.impl.UserCacheModel;
111 import com.liferay.portal.model.impl.UserImpl;
112 import com.liferay.portal.security.auth.AuthPipeline;
113 import com.liferay.portal.security.auth.Authenticator;
114 import com.liferay.portal.security.auth.EmailAddressGenerator;
115 import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
116 import com.liferay.portal.security.auth.EmailAddressValidator;
117 import com.liferay.portal.security.auth.EmailAddressValidatorFactory;
118 import com.liferay.portal.security.auth.FullNameGenerator;
119 import com.liferay.portal.security.auth.FullNameGeneratorFactory;
120 import com.liferay.portal.security.auth.FullNameValidator;
121 import com.liferay.portal.security.auth.FullNameValidatorFactory;
122 import com.liferay.portal.security.auth.PrincipalException;
123 import com.liferay.portal.security.auth.ScreenNameGenerator;
124 import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
125 import com.liferay.portal.security.auth.ScreenNameValidator;
126 import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
127 import com.liferay.portal.security.ldap.LDAPSettingsUtil;
128 import com.liferay.portal.security.permission.PermissionCacheUtil;
129 import com.liferay.portal.security.pwd.PasswordEncryptorUtil;
130 import com.liferay.portal.security.pwd.PwdAuthenticator;
131 import com.liferay.portal.security.pwd.PwdToolkitUtil;
132 import com.liferay.portal.security.pwd.RegExpToolkit;
133 import com.liferay.portal.service.BaseServiceImpl;
134 import com.liferay.portal.service.ServiceContext;
135 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
136 import com.liferay.portal.util.PortalUtil;
137 import com.liferay.portal.util.PrefsPropsUtil;
138 import com.liferay.portal.util.PropsValues;
139 import com.liferay.portal.util.SubscriptionSender;
140 import com.liferay.portlet.documentlibrary.ImageSizeException;
141 import com.liferay.portlet.messageboards.model.MBMessage;
142 import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
143 import com.liferay.util.Encryptor;
144 import com.liferay.util.EncryptorException;
145 import com.liferay.util.PwdGenerator;
146
147 import java.awt.image.RenderedImage;
148
149 import java.io.IOException;
150 import java.io.Serializable;
151
152 import java.util.ArrayList;
153 import java.util.Arrays;
154 import java.util.Calendar;
155 import java.util.Date;
156 import java.util.HashMap;
157 import java.util.HashSet;
158 import java.util.LinkedHashMap;
159 import java.util.List;
160 import java.util.Locale;
161 import java.util.Map;
162 import java.util.Set;
163 import java.util.concurrent.Callable;
164 import java.util.concurrent.ConcurrentHashMap;
165
166
178 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
179
180
194 @Override
195 public User addDefaultAdminUser(
196 long companyId, String screenName, String emailAddress,
197 Locale locale, String firstName, String middleName, String lastName)
198 throws PortalException, SystemException {
199
200 long creatorUserId = 0;
201 boolean autoPassword = false;
202 String password1 = PropsValues.DEFAULT_ADMIN_PASSWORD;
203 String password2 = password1;
204 boolean autoScreenName = false;
205
206 screenName = getLogin(screenName);
207
208 for (int i = 1;; i++) {
209 User screenNameUser = userPersistence.fetchByC_SN(
210 companyId, screenName);
211
212 if (screenNameUser == null) {
213 break;
214 }
215
216 screenName = screenName + i;
217 }
218
219 long facebookId = 0;
220 String openId = StringPool.BLANK;
221 int prefixId = 0;
222 int suffixId = 0;
223 boolean male = true;
224 int birthdayMonth = Calendar.JANUARY;
225 int birthdayDay = 1;
226 int birthdayYear = 1970;
227 String jobTitle = StringPool.BLANK;
228
229 Group guestGroup = groupLocalService.getGroup(
230 companyId, GroupConstants.GUEST);
231
232 long[] groupIds = {guestGroup.getGroupId()};
233
234 long[] organizationIds = null;
235
236 Role adminRole = roleLocalService.getRole(
237 companyId, RoleConstants.ADMINISTRATOR);
238
239 Role powerUserRole = roleLocalService.getRole(
240 companyId, RoleConstants.POWER_USER);
241
242 long[] roleIds = {adminRole.getRoleId(), powerUserRole.getRoleId()};
243
244 long[] userGroupIds = null;
245 boolean sendEmail = false;
246 ServiceContext serviceContext = new ServiceContext();
247
248 User defaultAdminUser = addUser(
249 creatorUserId, companyId, autoPassword, password1, password2,
250 autoScreenName, screenName, emailAddress, facebookId, openId,
251 locale, firstName, middleName, lastName, prefixId, suffixId, male,
252 birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
253 organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
254
255 updateEmailAddressVerified(defaultAdminUser.getUserId(), true);
256
257 updateLastLogin(
258 defaultAdminUser.getUserId(), defaultAdminUser.getLoginIP());
259
260 updatePasswordReset(defaultAdminUser.getUserId(), false);
261
262 return defaultAdminUser;
263 }
264
265
275 @Override
276 public void addDefaultGroups(long userId)
277 throws PortalException, SystemException {
278
279 User user = userPersistence.findByPrimaryKey(userId);
280
281 Set<Long> groupIdsSet = new HashSet<Long>();
282
283 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
284 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
285 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
286
287 for (String defaultGroupName : defaultGroupNames) {
288 Company company = companyPersistence.findByPrimaryKey(
289 user.getCompanyId());
290
291 Account account = company.getAccount();
292
293 if (StringUtil.equalsIgnoreCase(
294 defaultGroupName, account.getName())) {
295
296 defaultGroupName = GroupConstants.GUEST;
297 }
298
299 Group group = groupPersistence.fetchByC_N(
300 user.getCompanyId(), defaultGroupName);
301
302 if ((group != null) &&
303 !userPersistence.containsGroup(
304 userId, group.getGroupId())) {
305
306 groupIdsSet.add(group.getGroupId());
307 }
308 }
309
310 String[] defaultOrganizationGroupNames = PrefsPropsUtil.getStringArray(
311 user.getCompanyId(),
312 PropsKeys.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES,
313 StringPool.NEW_LINE,
314 PropsValues.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES);
315
316 for (String defaultOrganizationGroupName :
317 defaultOrganizationGroupNames) {
318
319 defaultOrganizationGroupName +=
320 GroupLocalServiceImpl.ORGANIZATION_NAME_SUFFIX;
321
322 Group group = groupPersistence.fetchByC_N(
323 user.getCompanyId(), defaultOrganizationGroupName);
324
325 if ((group != null) &&
326 !userPersistence.containsGroup(
327 userId, group.getGroupId())) {
328
329 groupIdsSet.add(group.getGroupId());
330 }
331 }
332
333 long[] groupIds = ArrayUtil.toArray(
334 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
335
336 groupLocalService.addUserGroups(userId, groupIds);
337 }
338
339
349 @Override
350 public void addDefaultRoles(long userId)
351 throws PortalException, SystemException {
352
353 User user = userPersistence.findByPrimaryKey(userId);
354
355 Set<Long> roleIdSet = new HashSet<Long>();
356
357 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
358 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
359 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
360
361 for (String defaultRoleName : defaultRoleNames) {
362 try {
363 Role role = rolePersistence.findByC_N(
364 user.getCompanyId(), defaultRoleName);
365
366 if (!userPersistence.containsRole(userId, role.getRoleId())) {
367 roleIdSet.add(role.getRoleId());
368 }
369 }
370 catch (NoSuchRoleException nsre) {
371 }
372 }
373
374 long[] roleIds = ArrayUtil.toArray(
375 roleIdSet.toArray(new Long[roleIdSet.size()]));
376
377 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
378
379 userPersistence.addRoles(userId, roleIds);
380 }
381
382
392 @Override
393 @SuppressWarnings("deprecation")
394 public void addDefaultUserGroups(long userId)
395 throws PortalException, SystemException {
396
397 User user = userPersistence.findByPrimaryKey(userId);
398
399 Set<Long> userGroupIdSet = new HashSet<Long>();
400
401 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
402 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
403 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
404
405 for (String defaultUserGroupName : defaultUserGroupNames) {
406 try {
407 UserGroup userGroup = userGroupPersistence.findByC_N(
408 user.getCompanyId(), defaultUserGroupName);
409
410 if (!userPersistence.containsUserGroup(
411 userId, userGroup.getUserGroupId())) {
412
413 userGroupIdSet.add(userGroup.getUserGroupId());
414 }
415 }
416 catch (NoSuchUserGroupException nsuge) {
417 }
418 }
419
420 long[] userGroupIds = ArrayUtil.toArray(
421 userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
422
423 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
424 for (long userGroupId : userGroupIds) {
425 userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
426 }
427 }
428
429 userPersistence.addUserGroups(userId, userGroupIds);
430 }
431
432
441 @Override
442 public void addGroupUsers(long groupId, long[] userIds)
443 throws PortalException, SystemException {
444
445 groupPersistence.addUsers(groupId, userIds);
446
447 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
448
449 indexer.reindex(userIds);
450
451 PermissionCacheUtil.clearCache(userIds);
452
453 addDefaultRolesAndTeams(groupId, userIds);
454 }
455
456
465 @Override
466 public void addOrganizationUsers(long organizationId, long[] userIds)
467 throws PortalException, SystemException {
468
469 organizationPersistence.addUsers(organizationId, userIds);
470
471 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
472
473 indexer.reindex(userIds);
474
475 PermissionCacheUtil.clearCache(userIds);
476 }
477
478
486 @Override
487 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
488 throws SystemException {
489
490 passwordPolicyRelLocalService.addPasswordPolicyRels(
491 passwordPolicyId, User.class.getName(), userIds);
492 }
493
494
503 @Override
504 public void addRoleUsers(long roleId, long[] userIds)
505 throws PortalException, SystemException {
506
507 rolePersistence.addUsers(roleId, userIds);
508
509 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
510
511 indexer.reindex(userIds);
512
513 PermissionCacheUtil.clearCache(userIds);
514 }
515
516
525 @Override
526 public void addTeamUsers(long teamId, long[] userIds)
527 throws PortalException, SystemException {
528
529 teamPersistence.addUsers(teamId, userIds);
530
531 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
532
533 indexer.reindex(userIds);
534
535 PermissionCacheUtil.clearCache(userIds);
536 }
537
538
586 @Override
587 public User addUser(
588 long creatorUserId, long companyId, boolean autoPassword,
589 String password1, String password2, boolean autoScreenName,
590 String screenName, String emailAddress, long facebookId,
591 String openId, Locale locale, String firstName, String middleName,
592 String lastName, int prefixId, int suffixId, boolean male,
593 int birthdayMonth, int birthdayDay, int birthdayYear,
594 String jobTitle, long[] groupIds, long[] organizationIds,
595 long[] roleIds, long[] userGroupIds, boolean sendEmail,
596 ServiceContext serviceContext)
597 throws PortalException, SystemException {
598
599 boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
600
601 try {
602 WorkflowThreadLocal.setEnabled(false);
603
604 if (serviceContext == null) {
605 serviceContext = new ServiceContext();
606 }
607
608 if (serviceContext.getWorkflowAction() !=
609 WorkflowConstants.ACTION_PUBLISH) {
610
611 serviceContext.setWorkflowAction(
612 WorkflowConstants.ACTION_PUBLISH);
613 }
614
615 return addUserWithWorkflow(
616 creatorUserId, companyId, autoPassword, password1, password2,
617 autoScreenName, screenName, emailAddress, facebookId, openId,
618 locale, firstName, middleName, lastName, prefixId, suffixId,
619 male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
620 groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
621 serviceContext);
622 }
623 finally {
624 WorkflowThreadLocal.setEnabled(workflowEnabled);
625 }
626 }
627
628
637 @Override
638 @SuppressWarnings("deprecation")
639 public void addUserGroupUsers(long userGroupId, long[] userIds)
640 throws PortalException, SystemException {
641
642 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
643 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
644 }
645
646 userGroupPersistence.addUsers(userGroupId, userIds);
647
648 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
649
650 indexer.reindex(userIds);
651
652 PermissionCacheUtil.clearCache(userIds);
653 }
654
655
703 @Override
704 @SuppressWarnings("deprecation")
705 public User addUserWithWorkflow(
706 long creatorUserId, long companyId, boolean autoPassword,
707 String password1, String password2, boolean autoScreenName,
708 String screenName, String emailAddress, long facebookId,
709 String openId, Locale locale, String firstName, String middleName,
710 String lastName, int prefixId, int suffixId, boolean male,
711 int birthdayMonth, int birthdayDay, int birthdayYear,
712 String jobTitle, long[] groupIds, long[] organizationIds,
713 long[] roleIds, long[] userGroupIds, boolean sendEmail,
714 ServiceContext serviceContext)
715 throws PortalException, SystemException {
716
717
718
719 Company company = companyPersistence.findByPrimaryKey(companyId);
720 screenName = getLogin(screenName);
721 openId = StringUtil.trim(openId);
722 Date now = new Date();
723
724 if (PrefsPropsUtil.getBoolean(
725 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
726
727 autoScreenName = true;
728 }
729
730
731
732 long userId = counterLocalService.increment();
733
734 EmailAddressGenerator emailAddressGenerator =
735 EmailAddressGeneratorFactory.getInstance();
736
737 if ((emailAddress == null) ||
738 emailAddressGenerator.isGenerated(emailAddress)) {
739
740 emailAddress = StringPool.BLANK;
741 }
742 else {
743 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
744 }
745
746 if (!PrefsPropsUtil.getBoolean(
747 companyId, PropsKeys.USERS_EMAIL_ADDRESS_REQUIRED) &&
748 Validator.isNull(emailAddress)) {
749
750 emailAddress = emailAddressGenerator.generate(companyId, userId);
751 }
752
753 validate(
754 companyId, userId, autoPassword, password1, password2,
755 autoScreenName, screenName, emailAddress, openId, firstName,
756 middleName, lastName, organizationIds);
757
758 if (!autoPassword) {
759 if (Validator.isNull(password1) || Validator.isNull(password2)) {
760 throw new UserPasswordException(
761 UserPasswordException.PASSWORD_INVALID);
762 }
763 }
764
765 if (autoScreenName) {
766 ScreenNameGenerator screenNameGenerator =
767 ScreenNameGeneratorFactory.getInstance();
768
769 try {
770 screenName = screenNameGenerator.generate(
771 companyId, userId, emailAddress);
772 }
773 catch (Exception e) {
774 throw new SystemException(e);
775 }
776 }
777
778 User defaultUser = getDefaultUser(companyId);
779
780 FullNameGenerator fullNameGenerator =
781 FullNameGeneratorFactory.getInstance();
782
783 String fullName = fullNameGenerator.getFullName(
784 firstName, middleName, lastName);
785
786 String greeting = LanguageUtil.format(
787 locale, "welcome-x", " " + fullName, false);
788
789 User user = userPersistence.create(userId);
790
791 if (serviceContext != null) {
792 String uuid = serviceContext.getUuid();
793
794 if (Validator.isNotNull(uuid)) {
795 user.setUuid(uuid);
796 }
797 }
798
799 user.setCompanyId(companyId);
800 user.setCreateDate(now);
801 user.setModifiedDate(now);
802 user.setDefaultUser(false);
803 user.setContactId(counterLocalService.increment());
804
805 if (Validator.isNotNull(password1)) {
806 user.setPassword(PasswordEncryptorUtil.encrypt(password1));
807 user.setPasswordUnencrypted(password1);
808 }
809
810 user.setPasswordEncrypted(true);
811
812 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
813
814 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
815 passwordPolicy.isChangeRequired()) {
816
817 user.setPasswordReset(true);
818 }
819 else {
820 user.setPasswordReset(false);
821 }
822
823 user.setDigest(StringPool.BLANK);
824 user.setScreenName(screenName);
825 user.setEmailAddress(emailAddress);
826 user.setFacebookId(facebookId);
827
828 Long ldapServerId = null;
829
830 if (serviceContext != null) {
831 ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
832 }
833
834 if (ldapServerId != null) {
835 user.setLdapServerId(ldapServerId);
836 }
837 else {
838 user.setLdapServerId(-1);
839 }
840
841 user.setOpenId(openId);
842 user.setLanguageId(LocaleUtil.toLanguageId(locale));
843 user.setTimeZoneId(defaultUser.getTimeZoneId());
844 user.setGreeting(greeting);
845 user.setFirstName(firstName);
846 user.setMiddleName(middleName);
847 user.setLastName(lastName);
848 user.setJobTitle(jobTitle);
849 user.setStatus(WorkflowConstants.STATUS_DRAFT);
850 user.setExpandoBridgeAttributes(serviceContext);
851
852 userPersistence.update(user, serviceContext);
853
854
855
856 String creatorUserName = StringPool.BLANK;
857
858 if (creatorUserId <= 0) {
859 creatorUserId = user.getUserId();
860
861
862
863
864
865 }
866 else {
867 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
868
869 creatorUserName = creatorUser.getFullName();
870 }
871
872 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
873
874 Contact contact = contactPersistence.create(user.getContactId());
875
876 contact.setCompanyId(user.getCompanyId());
877 contact.setUserId(creatorUserId);
878 contact.setUserName(creatorUserName);
879 contact.setCreateDate(now);
880 contact.setModifiedDate(now);
881 contact.setClassName(User.class.getName());
882 contact.setClassPK(user.getUserId());
883 contact.setAccountId(company.getAccountId());
884 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
885 contact.setEmailAddress(user.getEmailAddress());
886 contact.setFirstName(firstName);
887 contact.setMiddleName(middleName);
888 contact.setLastName(lastName);
889 contact.setPrefixId(prefixId);
890 contact.setSuffixId(suffixId);
891 contact.setMale(male);
892 contact.setBirthday(birthday);
893 contact.setJobTitle(jobTitle);
894
895 contactPersistence.update(contact, serviceContext);
896
897
898
899 groupLocalService.addGroup(
900 user.getUserId(), GroupConstants.DEFAULT_PARENT_GROUP_ID,
901 User.class.getName(), user.getUserId(), null, null, 0,
902 StringPool.SLASH + screenName, false, true, null);
903
904
905
906 if (groupIds != null) {
907 List<Group> groups = new ArrayList<Group>();
908
909 for (long groupId : groupIds) {
910 Group group = groupLocalService.fetchGroup(groupId);
911
912 if (group != null) {
913 groups.add(group);
914 }
915 else {
916 if (_log.isWarnEnabled()) {
917 _log.warn("Group " + groupId + " does not exist");
918 }
919 }
920 }
921
922 groupLocalService.addUserGroups(userId, groups);
923 }
924
925 addDefaultGroups(userId);
926
927
928
929 updateOrganizations(userId, organizationIds, false);
930
931
932
933 if (roleIds != null) {
934 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
935
936 userPersistence.setRoles(userId, roleIds);
937 }
938
939 addDefaultRoles(userId);
940
941
942
943 if (userGroupIds != null) {
944 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
945 for (long userGroupId : userGroupIds) {
946 userGroupLocalService.copyUserGroupLayouts(
947 userGroupId, new long[] {userId});
948 }
949 }
950
951 userPersistence.setUserGroups(userId, userGroupIds);
952 }
953
954 addDefaultUserGroups(userId);
955
956
957
958 resourceLocalService.addResources(
959 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
960 false, false, false);
961
962
963
964 if (serviceContext != null) {
965 updateAsset(
966 creatorUserId, user, serviceContext.getAssetCategoryIds(),
967 serviceContext.getAssetTagNames());
968 }
969
970
971
972 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
973 reindex(user);
974 }
975
976
977
978 long workflowUserId = creatorUserId;
979
980 if (workflowUserId == userId) {
981 workflowUserId = defaultUser.getUserId();
982 }
983
984 ServiceContext workflowServiceContext = serviceContext;
985
986 if (workflowServiceContext == null) {
987 workflowServiceContext = new ServiceContext();
988 }
989
990 workflowServiceContext.setAttribute("autoPassword", autoPassword);
991 workflowServiceContext.setAttribute("passwordUnencrypted", password1);
992 workflowServiceContext.setAttribute("sendEmail", sendEmail);
993
994 WorkflowHandlerRegistryUtil.startWorkflowInstance(
995 companyId, workflowUserId, User.class.getName(), userId, user,
996 workflowServiceContext);
997
998 if (serviceContext != null) {
999 String passwordUnencrypted = (String)serviceContext.getAttribute(
1000 "passwordUnencrypted");
1001
1002 if (Validator.isNotNull(passwordUnencrypted)) {
1003 user.setPasswordUnencrypted(passwordUnencrypted);
1004 }
1005 }
1006
1007 return user;
1008 }
1009
1010 @Override
1011 public void afterPropertiesSet() {
1012 super.afterPropertiesSet();
1013
1014 PortalCache<Serializable, Serializable> portalCache =
1015 EntityCacheUtil.getPortalCache(UserImpl.class);
1016
1017 PortalCacheMapSynchronizeUtil.synchronize(
1018 portalCache, _defaultUsers,
1019 new Synchronizer<Serializable, Serializable>() {
1020
1021 @Override
1022 public void onSynchronize(
1023 Map<? extends Serializable, ? extends Serializable> map,
1024 Serializable key, Serializable value) {
1025
1026 if (!(value instanceof UserCacheModel)) {
1027 return;
1028 }
1029
1030 UserCacheModel userCacheModel = (UserCacheModel)value;
1031
1032 if (userCacheModel.defaultUser) {
1033 _defaultUsers.remove(userCacheModel.companyId);
1034 }
1035 }
1036
1037 });
1038 }
1039
1040
1064 @Override
1065 public int authenticateByEmailAddress(
1066 long companyId, String emailAddress, 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, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
1073 headerMap, parameterMap, resultsMap);
1074 }
1075
1076
1100 @Override
1101 public int authenticateByScreenName(
1102 long companyId, String screenName, 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, screenName, password, CompanyConstants.AUTH_TYPE_SN,
1109 headerMap, parameterMap, resultsMap);
1110 }
1111
1112
1136 @Override
1137 public int authenticateByUserId(
1138 long companyId, long userId, String password,
1139 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1140 Map<String, Object> resultsMap)
1141 throws PortalException, SystemException {
1142
1143 return authenticate(
1144 companyId, String.valueOf(userId), password,
1145 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap, resultsMap);
1146 }
1147
1148
1188 @Override
1189 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1190 public long authenticateForBasic(
1191 long companyId, String authType, String login, String password)
1192 throws PortalException, SystemException {
1193
1194 if (PropsValues.AUTH_LOGIN_DISABLED) {
1195 return 0;
1196 }
1197
1198 User user = null;
1199
1200 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1201 user = fetchUserByEmailAddress(companyId, login);
1202 }
1203 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1204 user = fetchUserByScreenName(companyId, login);
1205 }
1206 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1207 user = userPersistence.fetchByPrimaryKey(GetterUtil.getLong(login));
1208 }
1209
1210 if (user == null) {
1211 return 0;
1212 }
1213
1214 if (user.isDefaultUser()) {
1215 if (_log.isInfoEnabled()) {
1216 _log.info(
1217 "Basic authentication is disabled for the default " +
1218 "user");
1219 }
1220
1221 return 0;
1222 }
1223 else if (!user.isActive()) {
1224 if (_log.isInfoEnabled()) {
1225 _log.info(
1226 "Basic authentication is disabled for inactive user " +
1227 user.getUserId());
1228 }
1229
1230 return 0;
1231 }
1232
1233 if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
1234 return user.getUserId();
1235 }
1236
1237 String userPassword = user.getPassword();
1238
1239 if (!user.isPasswordEncrypted()) {
1240 userPassword = PasswordEncryptorUtil.encrypt(userPassword);
1241 }
1242
1243 String encPassword = PasswordEncryptorUtil.encrypt(
1244 password, userPassword);
1245
1246 if (userPassword.equals(password) || userPassword.equals(encPassword)) {
1247 return user.getUserId();
1248 }
1249
1250 return 0;
1251 }
1252
1253
1271 @Override
1272 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1273 public long authenticateForDigest(
1274 long companyId, String username, String realm, String nonce,
1275 String method, String uri, String response)
1276 throws PortalException, SystemException {
1277
1278 if (PropsValues.AUTH_LOGIN_DISABLED) {
1279 return 0;
1280 }
1281
1282
1283
1284 User user = fetchUserByEmailAddress(companyId, username);
1285
1286 if (user == null) {
1287 user = fetchUserByScreenName(companyId, username);
1288 }
1289
1290 if (user == null) {
1291 user = userPersistence.fetchByPrimaryKey(
1292 GetterUtil.getLong(username));
1293 }
1294
1295 if (user == null) {
1296 return 0;
1297 }
1298
1299 if (user.isDefaultUser()) {
1300 if (_log.isInfoEnabled()) {
1301 _log.info(
1302 "Digest authentication is disabled for the default user");
1303 }
1304
1305 return 0;
1306 }
1307 else if (!user.isActive()) {
1308 if (_log.isInfoEnabled()) {
1309 _log.info(
1310 "Digest authentication is disabled for inactive user " +
1311 user.getUserId());
1312 }
1313
1314 return 0;
1315 }
1316
1317
1318
1319 String digest = user.getDigest();
1320
1321 if (Validator.isNull(digest)) {
1322 _log.error(
1323 "User must first login through the portal " + user.getUserId());
1324
1325 return 0;
1326 }
1327
1328 String[] digestArray = StringUtil.split(user.getDigest());
1329
1330 for (String ha1 : digestArray) {
1331 String ha2 = DigesterUtil.digestHex(Digester.MD5, method, uri);
1332
1333 String curResponse = DigesterUtil.digestHex(
1334 Digester.MD5, ha1, nonce, ha2);
1335
1336 if (response.equals(curResponse)) {
1337 return user.getUserId();
1338 }
1339 }
1340
1341 return 0;
1342 }
1343
1344
1353 @Override
1354 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1355 public boolean authenticateForJAAS(long userId, String encPassword) {
1356 if (PropsValues.AUTH_LOGIN_DISABLED) {
1357 return false;
1358 }
1359
1360 try {
1361 User user = userPersistence.findByPrimaryKey(userId);
1362
1363 if (user.isDefaultUser()) {
1364 if (_log.isInfoEnabled()) {
1365 _log.info(
1366 "JAAS authentication is disabled for the default user");
1367 }
1368
1369 return false;
1370 }
1371 else if (!user.isActive()) {
1372 if (_log.isInfoEnabled()) {
1373 _log.info(
1374 "JAAS authentication is disabled for inactive user " +
1375 userId);
1376 }
1377
1378 return false;
1379 }
1380
1381 String userPassword = user.getPassword();
1382
1383 if (user.isPasswordEncrypted()) {
1384 if (userPassword.equals(encPassword)) {
1385 return true;
1386 }
1387
1388 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1389 encPassword = PasswordEncryptorUtil.encrypt(
1390 encPassword, userPassword);
1391
1392 if (userPassword.equals(encPassword)) {
1393 return true;
1394 }
1395 }
1396 }
1397 else {
1398 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1399 if (userPassword.equals(encPassword)) {
1400 return true;
1401 }
1402 }
1403
1404 userPassword = PasswordEncryptorUtil.encrypt(
1405 userPassword, encPassword);
1406
1407 if (userPassword.equals(encPassword)) {
1408 return true;
1409 }
1410 }
1411 }
1412 catch (Exception e) {
1413 _log.error(e);
1414 }
1415
1416 return false;
1417 }
1418
1419
1427 @Override
1428 public void checkLockout(User user)
1429 throws PortalException, SystemException {
1430
1431 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1432 return;
1433 }
1434
1435 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1436
1437 if (!passwordPolicy.isLockout()) {
1438 return;
1439 }
1440
1441
1442
1443 Date now = new Date();
1444 int failedLoginAttempts = user.getFailedLoginAttempts();
1445
1446 if (failedLoginAttempts > 0) {
1447 long failedLoginTime = user.getLastFailedLoginDate().getTime();
1448 long elapsedTime = now.getTime() - failedLoginTime;
1449 long requiredElapsedTime =
1450 passwordPolicy.getResetFailureCount() * 1000;
1451
1452 if ((requiredElapsedTime != 0) &&
1453 (elapsedTime > requiredElapsedTime)) {
1454
1455 user.setFailedLoginAttempts(0);
1456
1457 userPersistence.update(user);
1458 }
1459 }
1460
1461
1462
1463 if (user.isLockout()) {
1464 long lockoutTime = user.getLockoutDate().getTime();
1465 long elapsedTime = now.getTime() - lockoutTime;
1466 long requiredElapsedTime =
1467 passwordPolicy.getLockoutDuration() * 1000;
1468
1469 if ((requiredElapsedTime != 0) &&
1470 (elapsedTime > requiredElapsedTime)) {
1471
1472 user.setLockout(false);
1473 user.setLockoutDate(null);
1474
1475 userPersistence.update(user);
1476 }
1477 }
1478
1479 if (user.isLockout()) {
1480 throw new UserLockoutException();
1481 }
1482 }
1483
1484
1491 @Override
1492 public void checkLoginFailure(User user) throws SystemException {
1493 Date now = new Date();
1494
1495 int failedLoginAttempts = user.getFailedLoginAttempts();
1496
1497 user.setLastFailedLoginDate(now);
1498 user.setFailedLoginAttempts(++failedLoginAttempts);
1499
1500 userPersistence.update(user);
1501 }
1502
1503
1513 @Override
1514 public void checkLoginFailureByEmailAddress(
1515 long companyId, String emailAddress)
1516 throws PortalException, SystemException {
1517
1518 User user = getUserByEmailAddress(companyId, emailAddress);
1519
1520 checkLoginFailure(user);
1521 }
1522
1523
1531 @Override
1532 public void checkLoginFailureById(long userId)
1533 throws PortalException, SystemException {
1534
1535 User user = userPersistence.findByPrimaryKey(userId);
1536
1537 checkLoginFailure(user);
1538 }
1539
1540
1549 @Override
1550 public void checkLoginFailureByScreenName(long companyId, String screenName)
1551 throws PortalException, SystemException {
1552
1553 User user = getUserByScreenName(companyId, screenName);
1554
1555 checkLoginFailure(user);
1556 }
1557
1558
1568 @Override
1569 public void checkPasswordExpired(User user)
1570 throws PortalException, SystemException {
1571
1572 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1573 return;
1574 }
1575
1576 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1577
1578
1579
1580 if (isPasswordExpired(user)) {
1581 int graceLoginCount = user.getGraceLoginCount();
1582
1583 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
1584 user.setGraceLoginCount(++graceLoginCount);
1585
1586 userPersistence.update(user);
1587 }
1588 else {
1589 user.setDigest(StringPool.BLANK);
1590
1591 userPersistence.update(user);
1592
1593 throw new PasswordExpiredException();
1594 }
1595 }
1596
1597
1598
1599 if (passwordPolicy.isChangeable() &&
1600 passwordPolicy.isChangeRequired()) {
1601
1602 if (user.getLastLoginDate() == null) {
1603 user.setPasswordReset(true);
1604
1605 userPersistence.update(user);
1606 }
1607 }
1608 }
1609
1610
1616 @Override
1617 public void clearOrganizationUsers(long organizationId)
1618 throws SystemException {
1619
1620 organizationPersistence.clearUsers(organizationId);
1621
1622 PermissionCacheUtil.clearCache();
1623 }
1624
1625
1631 @Override
1632 public void clearUserGroupUsers(long userGroupId) throws SystemException {
1633 userGroupPersistence.clearUsers(userGroupId);
1634
1635 PermissionCacheUtil.clearCache();
1636 }
1637
1638
1653 @Override
1654 public void completeUserRegistration(
1655 User user, ServiceContext serviceContext)
1656 throws PortalException, SystemException {
1657
1658 boolean autoPassword = ParamUtil.getBoolean(
1659 serviceContext, "autoPassword");
1660
1661 String password = (String)serviceContext.getAttribute(
1662 "passwordUnencrypted");
1663
1664 if (autoPassword) {
1665 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1666 if (_log.isWarnEnabled()) {
1667 StringBundler sb = new StringBundler(4);
1668
1669 sb.append("When LDAP password policy is enabled, it is ");
1670 sb.append("possible that portal generated passwords will ");
1671 sb.append("not match the LDAP policy. Using ");
1672 sb.append("RegExpToolkit to generate new password.");
1673
1674 _log.warn(sb.toString());
1675 }
1676
1677 RegExpToolkit regExpToolkit = new RegExpToolkit();
1678
1679 password = regExpToolkit.generate(null);
1680 }
1681 else {
1682 PasswordPolicy passwordPolicy =
1683 passwordPolicyLocalService.getPasswordPolicy(
1684 user.getCompanyId(), user.getOrganizationIds());
1685
1686 password = PwdToolkitUtil.generate(passwordPolicy);
1687 }
1688
1689 serviceContext.setAttribute("passwordUnencrypted", password);
1690
1691 user.setPassword(PasswordEncryptorUtil.encrypt(password));
1692 user.setPasswordUnencrypted(password);
1693 user.setPasswordEncrypted(true);
1694 user.setPasswordModified(true);
1695 user.setPasswordModifiedDate(new Date());
1696
1697 userPersistence.update(user);
1698
1699 user.setPasswordModified(false);
1700 }
1701
1702 if (user.hasCompanyMx()) {
1703 mailService.addUser(
1704 user.getCompanyId(), user.getUserId(), password,
1705 user.getFirstName(), user.getMiddleName(), user.getLastName(),
1706 user.getEmailAddress());
1707 }
1708
1709 boolean sendEmail = ParamUtil.getBoolean(serviceContext, "sendEmail");
1710
1711 if (sendEmail) {
1712 sendEmail(user, password, serviceContext);
1713 }
1714
1715 Company company = companyPersistence.findByPrimaryKey(
1716 user.getCompanyId());
1717
1718 if (company.isStrangersVerify()) {
1719 sendEmailAddressVerification(
1720 user, user.getEmailAddress(), serviceContext);
1721 }
1722 }
1723
1724
1737 @Override
1738 public KeyValuePair decryptUserId(
1739 long companyId, String name, String password)
1740 throws PortalException, SystemException {
1741
1742 Company company = companyPersistence.findByPrimaryKey(companyId);
1743
1744 try {
1745 name = Encryptor.decrypt(company.getKeyObj(), name);
1746 }
1747 catch (EncryptorException ee) {
1748 throw new SystemException(ee);
1749 }
1750
1751 long userId = GetterUtil.getLong(name);
1752
1753 User user = userPersistence.findByPrimaryKey(userId);
1754
1755 try {
1756 password = Encryptor.decrypt(company.getKeyObj(), password);
1757 }
1758 catch (EncryptorException ee) {
1759 throw new SystemException(ee);
1760 }
1761
1762 String userPassword = user.getPassword();
1763 String encPassword = PasswordEncryptorUtil.encrypt(
1764 password, userPassword);
1765
1766 if (userPassword.equals(encPassword)) {
1767 if (isPasswordExpired(user)) {
1768 user.setPasswordReset(true);
1769
1770 userPersistence.update(user);
1771 }
1772
1773 return new KeyValuePair(name, password);
1774 }
1775 else {
1776 throw new PrincipalException();
1777 }
1778 }
1779
1780
1788 @Override
1789 public void deletePortrait(long userId)
1790 throws PortalException, SystemException {
1791
1792 User user = userPersistence.findByPrimaryKey(userId);
1793
1794 long portraitId = user.getPortraitId();
1795
1796 if (portraitId > 0) {
1797 user.setPortraitId(0);
1798
1799 userPersistence.update(user);
1800
1801 imageLocalService.deleteImage(portraitId);
1802 }
1803 }
1804
1805
1814 @Override
1815 public void deleteRoleUser(long roleId, long userId)
1816 throws PortalException, SystemException {
1817
1818 rolePersistence.removeUser(roleId, userId);
1819
1820 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1821
1822 indexer.reindex(userId);
1823
1824 PermissionCacheUtil.clearCache(userId);
1825 }
1826
1827
1835 @Override
1836 public User deleteUser(long userId)
1837 throws PortalException, SystemException {
1838
1839 User user = userPersistence.findByPrimaryKey(userId);
1840
1841 return deleteUser(user);
1842 }
1843
1844
1852 @Override
1853 public User deleteUser(User user) throws PortalException, SystemException {
1854 if (!PropsValues.USERS_DELETE) {
1855 throw new RequiredUserException();
1856 }
1857
1858
1859
1860 browserTrackerLocalService.deleteUserBrowserTracker(user.getUserId());
1861
1862
1863
1864 Group group = null;
1865
1866 if (!user.isDefaultUser()) {
1867 group = user.getGroup();
1868 }
1869
1870 if (group != null) {
1871 groupLocalService.deleteGroup(group);
1872 }
1873
1874
1875
1876 try {
1877 imageLocalService.deleteImage(user.getPortraitId());
1878 }
1879 catch (NoSuchImageException nsie) {
1880 if (_log.isWarnEnabled()) {
1881 _log.warn("Unable to delete image " + user.getPortraitId());
1882 }
1883 }
1884
1885
1886
1887 passwordPolicyRelLocalService.deletePasswordPolicyRel(
1888 User.class.getName(), user.getUserId());
1889
1890
1891
1892 passwordTrackerLocalService.deletePasswordTrackers(user.getUserId());
1893
1894
1895
1896 subscriptionLocalService.deleteSubscriptions(user.getUserId());
1897
1898
1899
1900 userIdMapperLocalService.deleteUserIdMappers(user.getUserId());
1901
1902
1903
1904 announcementsDeliveryLocalService.deleteDeliveries(user.getUserId());
1905
1906
1907
1908 assetEntryLocalService.deleteEntry(
1909 User.class.getName(), user.getUserId());
1910
1911
1912
1913 blogsStatsUserLocalService.deleteStatsUserByUserId(user.getUserId());
1914
1915
1916
1917 dlFileRankLocalService.deleteFileRanksByUserId(user.getUserId());
1918
1919
1920
1921 expandoRowLocalService.deleteRows(user.getUserId());
1922
1923
1924
1925 mbBanLocalService.deleteBansByBanUserId(user.getUserId());
1926 mbStatsUserLocalService.deleteStatsUsersByUserId(user.getUserId());
1927 mbThreadFlagLocalService.deleteThreadFlagsByUserId(user.getUserId());
1928
1929
1930
1931 membershipRequestLocalService.deleteMembershipRequestsByUserId(
1932 user.getUserId());
1933
1934
1935
1936 shoppingCartLocalService.deleteUserCarts(user.getUserId());
1937
1938
1939
1940 socialActivityLocalService.deleteUserActivities(user.getUserId());
1941 socialRequestLocalService.deleteReceiverUserRequests(user.getUserId());
1942 socialRequestLocalService.deleteUserRequests(user.getUserId());
1943
1944
1945
1946 mailService.deleteUser(user.getCompanyId(), user.getUserId());
1947
1948
1949
1950 Contact contact = contactLocalService.fetchContact(user.getContactId());
1951
1952 if (contact != null) {
1953 contactLocalService.deleteContact(contact);
1954 }
1955
1956
1957
1958 userGroupRoleLocalService.deleteUserGroupRolesByUserId(
1959 user.getUserId());
1960
1961
1962
1963 resourceLocalService.deleteResource(
1964 user.getCompanyId(), User.class.getName(),
1965 ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
1966
1967
1968
1969 userPersistence.remove(user);
1970
1971
1972
1973 PermissionCacheUtil.clearCache(user.getUserId());
1974
1975
1976
1977 workflowInstanceLinkLocalService.deleteWorkflowInstanceLinks(
1978 user.getCompanyId(), 0, User.class.getName(), user.getUserId());
1979
1980 return user;
1981 }
1982
1983
1991 @Override
1992 public void deleteUserGroupUser(long userGroupId, long userId)
1993 throws PortalException, SystemException {
1994
1995 userGroupPersistence.removeUser(userGroupId, userId);
1996
1997 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1998
1999 indexer.reindex(userId);
2000
2001 PermissionCacheUtil.clearCache(userId);
2002 }
2003
2004
2013 @Override
2014 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
2015 public String encryptUserId(String name)
2016 throws PortalException, SystemException {
2017
2018 long userId = GetterUtil.getLong(name);
2019
2020 User user = userPersistence.findByPrimaryKey(userId);
2021
2022 Company company = companyPersistence.findByPrimaryKey(
2023 user.getCompanyId());
2024
2025 try {
2026 return Encryptor.encrypt(company.getKeyObj(), name);
2027 }
2028 catch (EncryptorException ee) {
2029 throw new SystemException(ee);
2030 }
2031 }
2032
2033
2042 @Override
2043 public User fetchUserByEmailAddress(long companyId, String emailAddress)
2044 throws SystemException {
2045
2046 emailAddress = getLogin(emailAddress);
2047
2048 return userPersistence.fetchByC_EA(companyId, emailAddress);
2049 }
2050
2051
2060 @Override
2061 public User fetchUserByFacebookId(long companyId, long facebookId)
2062 throws SystemException {
2063
2064 return userPersistence.fetchByC_FID(companyId, facebookId);
2065 }
2066
2067
2075 @Override
2076 public User fetchUserById(long userId) throws SystemException {
2077 return userPersistence.fetchByPrimaryKey(userId);
2078 }
2079
2080
2089 @Override
2090 public User fetchUserByOpenId(long companyId, String openId)
2091 throws SystemException {
2092
2093 return userPersistence.fetchByC_O(companyId, openId);
2094 }
2095
2096
2105 @Override
2106 public User fetchUserByScreenName(long companyId, String screenName)
2107 throws SystemException {
2108
2109 screenName = getLogin(screenName);
2110
2111 return userPersistence.fetchByC_SN(companyId, screenName);
2112 }
2113
2114
2133 @Override
2134 public List<User> getCompanyUsers(long companyId, int start, int end)
2135 throws SystemException {
2136
2137 return userPersistence.findByCompanyId(companyId, start, end);
2138 }
2139
2140
2147 @Override
2148 public int getCompanyUsersCount(long companyId) throws SystemException {
2149 return userPersistence.countByCompanyId(companyId);
2150 }
2151
2152
2161 @Override
2162 @Skip
2163 public User getDefaultUser(long companyId)
2164 throws PortalException, SystemException {
2165
2166 User userModel = _defaultUsers.get(companyId);
2167
2168 if (userModel == null) {
2169 userModel = userLocalService.loadGetDefaultUser(companyId);
2170
2171 _defaultUsers.put(companyId, userModel);
2172 }
2173
2174 return userModel;
2175 }
2176
2177
2186 @Override
2187 @Skip
2188 public long getDefaultUserId(long companyId)
2189 throws PortalException, SystemException {
2190
2191 User user = getDefaultUser(companyId);
2192
2193 return user.getUserId();
2194 }
2195
2196
2203 @Override
2204 public long[] getGroupUserIds(long groupId) throws SystemException {
2205 return getUserIds(getGroupUsers(groupId));
2206 }
2207
2208
2218 @Override
2219 public int getGroupUsersCount(long groupId, int status)
2220 throws PortalException, SystemException {
2221
2222 Group group = groupPersistence.findByPrimaryKey(groupId);
2223
2224 LinkedHashMap<String, Object> params =
2225 new LinkedHashMap<String, Object>();
2226
2227 params.put("usersGroups", new Long(groupId));
2228
2229 return searchCount(group.getCompanyId(), null, status, params);
2230 }
2231
2232 @Override
2233 public List<User> getInheritedRoleUsers(
2234 long roleId, int start, int end, OrderByComparator obc)
2235 throws PortalException, SystemException {
2236
2237 Role role = rolePersistence.findByPrimaryKey(roleId);
2238
2239 LinkedHashMap<String, Object> params =
2240 new LinkedHashMap<String, Object>();
2241
2242 params.put("inherit", Boolean.TRUE);
2243 params.put("usersRoles", roleId);
2244
2245 return search(
2246 role.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2247 params, start, end, obc);
2248 }
2249
2250
2258 @Override
2259 public List<User> getNoAnnouncementsDeliveries(String type)
2260 throws SystemException {
2261
2262 return userFinder.findByNoAnnouncementsDeliveries(type);
2263 }
2264
2265
2271 @Override
2272 public List<User> getNoContacts() throws SystemException {
2273 return userFinder.findByNoContacts();
2274 }
2275
2276
2283 @Override
2284 public List<User> getNoGroups() throws SystemException {
2285 return userFinder.findByNoGroups();
2286 }
2287
2288
2295 @Override
2296 public long[] getOrganizationUserIds(long organizationId)
2297 throws SystemException {
2298
2299 return getUserIds(getOrganizationUsers(organizationId));
2300 }
2301
2302
2313 @Override
2314 public int getOrganizationUsersCount(long organizationId, int status)
2315 throws PortalException, SystemException {
2316
2317 Organization organization = organizationPersistence.findByPrimaryKey(
2318 organizationId);
2319
2320 LinkedHashMap<String, Object> params =
2321 new LinkedHashMap<String, Object>();
2322
2323 params.put("usersOrgs", new Long(organizationId));
2324
2325 return searchCount(organization.getCompanyId(), null, status, params);
2326 }
2327
2328
2335 @Override
2336 public long[] getRoleUserIds(long roleId) throws SystemException {
2337 return getUserIds(getRoleUsers(roleId));
2338 }
2339
2340
2350 @Override
2351 public int getRoleUsersCount(long roleId, int status)
2352 throws PortalException, SystemException {
2353
2354 Role role = rolePersistence.findByPrimaryKey(roleId);
2355
2356 LinkedHashMap<String, Object> params =
2357 new LinkedHashMap<String, Object>();
2358
2359 params.put("usersRoles", new Long(roleId));
2360
2361 return searchCount(role.getCompanyId(), null, status, params);
2362 }
2363
2364
2391 @Override
2392 public List<User> getSocialUsers(
2393 long userId, int type, int start, int end, OrderByComparator obc)
2394 throws PortalException, SystemException {
2395
2396 User user = userPersistence.findByPrimaryKey(userId);
2397
2398 LinkedHashMap<String, Object> params =
2399 new LinkedHashMap<String, Object>();
2400
2401 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2402
2403 return search(
2404 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2405 params, start, end, obc);
2406 }
2407
2408
2431 @Override
2432 public List<User> getSocialUsers(
2433 long userId, int start, int end, OrderByComparator obc)
2434 throws PortalException, SystemException {
2435
2436 User user = userPersistence.findByPrimaryKey(userId);
2437
2438 LinkedHashMap<String, Object> params =
2439 new LinkedHashMap<String, Object>();
2440
2441 params.put("socialRelation", new Long[] {userId});
2442
2443 return search(
2444 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2445 params, start, end, obc);
2446 }
2447
2448
2476 @Override
2477 public List<User> getSocialUsers(
2478 long userId1, long userId2, int type, int start, int end,
2479 OrderByComparator obc)
2480 throws PortalException, SystemException {
2481
2482 User user1 = userPersistence.findByPrimaryKey(userId1);
2483
2484 LinkedHashMap<String, Object> params =
2485 new LinkedHashMap<String, Object>();
2486
2487 params.put(
2488 "socialMutualRelationType",
2489 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2490
2491 return search(
2492 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2493 params, start, end, obc);
2494 }
2495
2496
2521 @Override
2522 public List<User> getSocialUsers(
2523 long userId1, long userId2, int start, int end,
2524 OrderByComparator obc)
2525 throws PortalException, SystemException {
2526
2527 User user1 = userPersistence.findByPrimaryKey(userId1);
2528
2529 LinkedHashMap<String, Object> params =
2530 new LinkedHashMap<String, Object>();
2531
2532 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2533
2534 return search(
2535 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2536 params, start, end, obc);
2537 }
2538
2539
2547 @Override
2548 public int getSocialUsersCount(long userId)
2549 throws PortalException, SystemException {
2550
2551 User user = userPersistence.findByPrimaryKey(userId);
2552
2553 LinkedHashMap<String, Object> params =
2554 new LinkedHashMap<String, Object>();
2555
2556 params.put("socialRelation", new Long[] {userId});
2557
2558 return searchCount(
2559 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2560 params);
2561 }
2562
2563
2576 @Override
2577 public int getSocialUsersCount(long userId, int type)
2578 throws PortalException, SystemException {
2579
2580 User user = userPersistence.findByPrimaryKey(userId);
2581
2582 LinkedHashMap<String, Object> params =
2583 new LinkedHashMap<String, Object>();
2584
2585 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2586
2587 return searchCount(
2588 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2589 params);
2590 }
2591
2592
2602 @Override
2603 public int getSocialUsersCount(long userId1, long userId2)
2604 throws PortalException, SystemException {
2605
2606 User user1 = userPersistence.findByPrimaryKey(userId1);
2607
2608 LinkedHashMap<String, Object> params =
2609 new LinkedHashMap<String, Object>();
2610
2611 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2612
2613 return searchCount(
2614 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2615 params);
2616 }
2617
2618
2632 @Override
2633 public int getSocialUsersCount(long userId1, long userId2, int type)
2634 throws PortalException, SystemException {
2635
2636 User user1 = userPersistence.findByPrimaryKey(userId1);
2637
2638 LinkedHashMap<String, Object> params =
2639 new LinkedHashMap<String, Object>();
2640
2641 params.put(
2642 "socialMutualRelationType",
2643 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2644
2645 return searchCount(
2646 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2647 params);
2648 }
2649
2650
2658 @Override
2659 public User getUserByContactId(long contactId)
2660 throws PortalException, SystemException {
2661
2662 return userPersistence.findByContactId(contactId);
2663 }
2664
2665
2675 @Override
2676 public User getUserByEmailAddress(long companyId, String emailAddress)
2677 throws PortalException, SystemException {
2678
2679 emailAddress = getLogin(emailAddress);
2680
2681 return userPersistence.findByC_EA(companyId, emailAddress);
2682 }
2683
2684
2693 @Override
2694 public User getUserByFacebookId(long companyId, long facebookId)
2695 throws PortalException, SystemException {
2696
2697 return userPersistence.findByC_FID(companyId, facebookId);
2698 }
2699
2700
2708 @Override
2709 public User getUserById(long userId)
2710 throws PortalException, SystemException {
2711
2712 return userPersistence.findByPrimaryKey(userId);
2713 }
2714
2715
2725 @Override
2726 public User getUserById(long companyId, long userId)
2727 throws PortalException, SystemException {
2728
2729 return userPersistence.findByC_U(companyId, userId);
2730 }
2731
2732
2741 @Override
2742 public User getUserByOpenId(long companyId, String openId)
2743 throws PortalException, SystemException {
2744
2745 return userPersistence.findByC_O(companyId, openId);
2746 }
2747
2748
2756 @Override
2757 public User getUserByPortraitId(long portraitId)
2758 throws PortalException, SystemException {
2759
2760 return userPersistence.findByPortraitId(portraitId);
2761 }
2762
2763
2772 @Override
2773 public User getUserByScreenName(long companyId, String screenName)
2774 throws PortalException, SystemException {
2775
2776 screenName = getLogin(screenName);
2777
2778 return userPersistence.findByC_SN(companyId, screenName);
2779 }
2780
2781
2791 @Override
2792 public User getUserByUuid(String uuid)
2793 throws PortalException, SystemException {
2794
2795 List<User> users = userPersistence.findByUuid(uuid);
2796
2797 if (users.isEmpty()) {
2798 throw new NoSuchUserException("{uuid=" + uuid + "}");
2799 }
2800 else {
2801 return users.get(0);
2802 }
2803 }
2804
2805
2814 @Override
2815 public User getUserByUuidAndCompanyId(String uuid, long companyId)
2816 throws PortalException, SystemException {
2817
2818 List<User> users = userPersistence.findByUuid_C(uuid, companyId);
2819
2820 if (users.isEmpty()) {
2821 StringBundler sb = new StringBundler(5);
2822
2823 sb.append("{uuid=");
2824 sb.append(uuid);
2825 sb.append(", companyId=");
2826 sb.append(companyId);
2827 sb.append("}");
2828
2829 throw new NoSuchUserException(sb.toString());
2830 }
2831 else {
2832 return users.get(0);
2833 }
2834 }
2835
2836
2846 @Override
2847 public int getUserGroupUsersCount(long userGroupId, int status)
2848 throws PortalException, SystemException {
2849
2850 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
2851 userGroupId);
2852
2853 LinkedHashMap<String, Object> params =
2854 new LinkedHashMap<String, Object>();
2855
2856 params.put("usersUserGroups", new Long(userGroupId));
2857
2858 return searchCount(userGroup.getCompanyId(), null, status, params);
2859 }
2860
2861
2871 @Override
2872 public long getUserIdByEmailAddress(long companyId, String emailAddress)
2873 throws PortalException, SystemException {
2874
2875 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
2876
2877 User user = userPersistence.findByC_EA(companyId, emailAddress);
2878
2879 return user.getUserId();
2880 }
2881
2882
2891 @Override
2892 public long getUserIdByScreenName(long companyId, String screenName)
2893 throws PortalException, SystemException {
2894
2895 screenName = getLogin(screenName);
2896
2897 User user = userPersistence.findByC_SN(companyId, screenName);
2898
2899 return user.getUserId();
2900 }
2901
2902
2912 @Override
2913 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
2914 throws SystemException {
2915
2916 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
2917 passwordPolicyId, User.class.getName(), userId);
2918 }
2919
2920
2935 @Override
2936 public boolean hasRoleUser(
2937 long companyId, String name, long userId, boolean inherited)
2938 throws PortalException, SystemException {
2939
2940 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
2941 }
2942
2943
2953 @Override
2954 public boolean isPasswordExpired(User user)
2955 throws PortalException, SystemException {
2956
2957 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2958
2959 if ((passwordPolicy != null) && passwordPolicy.getExpireable()) {
2960 Date now = new Date();
2961
2962 if (user.getPasswordModifiedDate() == null) {
2963 user.setPasswordModifiedDate(now);
2964
2965 userLocalService.updateUser(user);
2966 }
2967
2968 long passwordStartTime = user.getPasswordModifiedDate().getTime();
2969 long elapsedTime = now.getTime() - passwordStartTime;
2970
2971 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
2972 return true;
2973 }
2974 else {
2975 return false;
2976 }
2977 }
2978
2979 return false;
2980 }
2981
2982
2994 @Override
2995 public boolean isPasswordExpiringSoon(User user)
2996 throws PortalException, SystemException {
2997
2998 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2999
3000 if ((passwordPolicy != null) && passwordPolicy.isExpireable() &&
3001 (passwordPolicy.getWarningTime() > 0)) {
3002
3003 Date now = new Date();
3004
3005 if (user.getPasswordModifiedDate() == null) {
3006 user.setPasswordModifiedDate(now);
3007
3008 userLocalService.updateUser(user);
3009 }
3010
3011 long timeModified = user.getPasswordModifiedDate().getTime();
3012 long passwordExpiresOn =
3013 (passwordPolicy.getMaxAge() * 1000) + timeModified;
3014
3015 long timeStartWarning =
3016 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
3017
3018 if (now.getTime() > timeStartWarning) {
3019 return true;
3020 }
3021 else {
3022 return false;
3023 }
3024 }
3025
3026 return false;
3027 }
3028
3029
3037 @Override
3038 public User loadGetDefaultUser(long companyId)
3039 throws PortalException, SystemException {
3040
3041 return userPersistence.findByC_DU(companyId, true);
3042 }
3043
3044
3076 @Override
3077 public List<User> search(
3078 long companyId, String keywords, int status,
3079 LinkedHashMap<String, Object> params, int start, int end,
3080 OrderByComparator obc)
3081 throws SystemException {
3082
3083 return userFinder.findByKeywords(
3084 companyId, keywords, status, params, start, end, obc);
3085 }
3086
3087
3118 @Override
3119 public Hits search(
3120 long companyId, String keywords, int status,
3121 LinkedHashMap<String, Object> params, int start, int end, Sort sort)
3122 throws SystemException {
3123
3124 String firstName = null;
3125 String middleName = null;
3126 String lastName = null;
3127 String fullName = null;
3128 String screenName = null;
3129 String emailAddress = null;
3130 String street = null;
3131 String city = null;
3132 String zip = null;
3133 String region = null;
3134 String country = null;
3135 boolean andOperator = false;
3136
3137 if (Validator.isNotNull(keywords)) {
3138 firstName = keywords;
3139 middleName = keywords;
3140 lastName = keywords;
3141 fullName = keywords;
3142 screenName = keywords;
3143 emailAddress = keywords;
3144 street = keywords;
3145 city = keywords;
3146 zip = keywords;
3147 region = keywords;
3148 country = keywords;
3149 }
3150 else {
3151 andOperator = true;
3152 }
3153
3154 if (params != null) {
3155 params.put("keywords", keywords);
3156 }
3157
3158 return search(
3159 companyId, firstName, middleName, lastName, fullName, screenName,
3160 emailAddress, street, city, zip, region, country, status, params,
3161 andOperator, start, end, sort);
3162 }
3163
3164
3204 @Override
3205 public List<User> search(
3206 long companyId, String firstName, String middleName,
3207 String lastName, String screenName, String emailAddress, int status,
3208 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3209 int end, OrderByComparator obc)
3210 throws SystemException {
3211
3212 return userFinder.findByC_FN_MN_LN_SN_EA_S(
3213 companyId, firstName, middleName, lastName, screenName,
3214 emailAddress, status, params, andSearch, start, end, obc);
3215 }
3216
3217
3256 @Override
3257 public Hits search(
3258 long companyId, String firstName, String middleName,
3259 String lastName, String screenName, String emailAddress, int status,
3260 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3261 int end, Sort sort)
3262 throws SystemException {
3263
3264 return search(
3265 companyId, firstName, middleName, lastName, null, screenName,
3266 emailAddress, null, null, null, null, null, status, params,
3267 andSearch, start, end, sort);
3268 }
3269
3270
3284 @Override
3285 public int searchCount(
3286 long companyId, String keywords, int status,
3287 LinkedHashMap<String, Object> params)
3288 throws SystemException {
3289
3290 return userFinder.countByKeywords(companyId, keywords, status, params);
3291 }
3292
3293
3315 @Override
3316 public int searchCount(
3317 long companyId, String firstName, String middleName,
3318 String lastName, String screenName, String emailAddress, int status,
3319 LinkedHashMap<String, Object> params, boolean andSearch)
3320 throws SystemException {
3321
3322 return userFinder.countByC_FN_MN_LN_SN_EA_S(
3323 companyId, firstName, middleName, lastName, screenName,
3324 emailAddress, status, params, andSearch);
3325 }
3326
3327
3338 @Override
3339 public void sendEmailAddressVerification(
3340 User user, String emailAddress, ServiceContext serviceContext)
3341 throws PortalException, SystemException {
3342
3343 if (user.isEmailAddressVerified() &&
3344 StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
3345
3346 return;
3347 }
3348
3349 Ticket ticket = ticketLocalService.addDistinctTicket(
3350 user.getCompanyId(), User.class.getName(), user.getUserId(),
3351 TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3352 serviceContext);
3353
3354 String verifyEmailAddressURL =
3355 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3356 "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3357
3358 long plid = serviceContext.getPlid();
3359
3360 if (plid > 0) {
3361 Layout layout = layoutLocalService.fetchLayout(plid);
3362
3363 if (layout != null) {
3364 Group group = layout.getGroup();
3365
3366 if (!layout.isPrivateLayout() && !group.isUser()) {
3367 verifyEmailAddressURL +=
3368 "&p_l_id=" + serviceContext.getPlid();
3369 }
3370 }
3371 }
3372
3373 String fromName = PrefsPropsUtil.getString(
3374 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3375 String fromAddress = PrefsPropsUtil.getString(
3376 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3377
3378 String toName = user.getFullName();
3379 String toAddress = emailAddress;
3380
3381 String subject = PrefsPropsUtil.getContent(
3382 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3383
3384 String body = PrefsPropsUtil.getContent(
3385 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3386
3387 SubscriptionSender subscriptionSender = new SubscriptionSender();
3388
3389 subscriptionSender.setBody(body);
3390 subscriptionSender.setCompanyId(user.getCompanyId());
3391 subscriptionSender.setContextAttributes(
3392 "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3393 "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3394 "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3395 "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_ID$]",
3396 user.getUserId(), "[$USER_SCREENNAME$]", user.getScreenName());
3397 subscriptionSender.setFrom(fromAddress, fromName);
3398 subscriptionSender.setHtmlFormat(true);
3399 subscriptionSender.setMailId(
3400 "user", user.getUserId(), System.currentTimeMillis(),
3401 PwdGenerator.getPassword());
3402 subscriptionSender.setServiceContext(serviceContext);
3403 subscriptionSender.setSubject(subject);
3404 subscriptionSender.setUserId(user.getUserId());
3405
3406 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3407
3408 subscriptionSender.flushNotificationsAsync();
3409 }
3410
3411
3430 @Override
3431 public void sendPassword(
3432 long companyId, String emailAddress, String fromName,
3433 String fromAddress, String subject, String body,
3434 ServiceContext serviceContext)
3435 throws PortalException, SystemException {
3436
3437 Company company = companyPersistence.findByPrimaryKey(companyId);
3438
3439 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3440 return;
3441 }
3442
3443 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
3444
3445 if (Validator.isNull(emailAddress)) {
3446 throw new UserEmailAddressException();
3447 }
3448
3449 User user = userPersistence.findByC_EA(companyId, emailAddress);
3450
3451 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3452
3453 String newPassword = StringPool.BLANK;
3454 String passwordResetURL = StringPool.BLANK;
3455
3456 if (company.isSendPasswordResetLink()) {
3457 Date expirationDate = null;
3458
3459 if ((passwordPolicy != null) &&
3460 (passwordPolicy.getResetTicketMaxAge() > 0)) {
3461
3462 expirationDate = new Date(
3463 System.currentTimeMillis() +
3464 (passwordPolicy.getResetTicketMaxAge() * 1000));
3465 }
3466
3467 Ticket ticket = ticketLocalService.addDistinctTicket(
3468 companyId, User.class.getName(), user.getUserId(),
3469 TicketConstants.TYPE_PASSWORD, null, expirationDate,
3470 serviceContext);
3471
3472 passwordResetURL =
3473 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3474 "/portal/update_password?p_l_id="+
3475 serviceContext.getPlid() +
3476 "&ticketKey=" + ticket.getKey();
3477 }
3478 else {
3479 if (!PasswordEncryptorUtil.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
3480 PasswordEncryptorUtil.TYPE_NONE)) {
3481
3482 if (LDAPSettingsUtil.isPasswordPolicyEnabled(
3483 user.getCompanyId())) {
3484
3485 if (_log.isWarnEnabled()) {
3486 StringBundler sb = new StringBundler(5);
3487
3488 sb.append("When LDAP password policy is enabled, ");
3489 sb.append("it is possible that portal generated ");
3490 sb.append("passwords will not match the LDAP policy.");
3491 sb.append("Using RegExpToolkit to generate new ");
3492 sb.append("password.");
3493
3494 _log.warn(sb.toString());
3495 }
3496
3497 RegExpToolkit regExpToolkit = new RegExpToolkit();
3498
3499 newPassword = regExpToolkit.generate(null);
3500 }
3501 else {
3502 newPassword = PwdToolkitUtil.generate(passwordPolicy);
3503 }
3504
3505 boolean passwordReset = false;
3506
3507 if (passwordPolicy.getChangeable() &&
3508 passwordPolicy.getChangeRequired()) {
3509
3510 passwordReset = true;
3511 }
3512
3513 user.setPassword(PasswordEncryptorUtil.encrypt(newPassword));
3514 user.setPasswordUnencrypted(newPassword);
3515 user.setPasswordEncrypted(true);
3516 user.setPasswordReset(passwordReset);
3517 user.setPasswordModified(true);
3518 user.setPasswordModifiedDate(new Date());
3519
3520 userPersistence.update(user);
3521
3522 user.setPasswordModified(false);
3523 }
3524 else {
3525 newPassword = user.getPassword();
3526 }
3527 }
3528
3529 if (Validator.isNull(fromName)) {
3530 fromName = PrefsPropsUtil.getString(
3531 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3532 }
3533
3534 if (Validator.isNull(fromAddress)) {
3535 fromAddress = PrefsPropsUtil.getString(
3536 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3537 }
3538
3539 String toName = user.getFullName();
3540 String toAddress = user.getEmailAddress();
3541
3542 if (Validator.isNull(subject)) {
3543 if (company.isSendPasswordResetLink()) {
3544 subject = PrefsPropsUtil.getContent(
3545 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
3546 }
3547 else {
3548 subject = PrefsPropsUtil.getContent(
3549 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
3550 }
3551 }
3552
3553 if (Validator.isNull(body)) {
3554 if (company.isSendPasswordResetLink()) {
3555 body = PrefsPropsUtil.getContent(
3556 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
3557 }
3558 else {
3559 body = PrefsPropsUtil.getContent(
3560 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
3561 }
3562 }
3563
3564 SubscriptionSender subscriptionSender = new SubscriptionSender();
3565
3566 subscriptionSender.setBody(body);
3567 subscriptionSender.setCompanyId(companyId);
3568 subscriptionSender.setContextAttributes(
3569 "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
3570 serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
3571 serviceContext.getRemoteHost(), "[$USER_ID$]", user.getUserId(),
3572 "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
3573 user.getScreenName());
3574 subscriptionSender.setFrom(fromAddress, fromName);
3575 subscriptionSender.setHtmlFormat(true);
3576 subscriptionSender.setMailId(
3577 "user", user.getUserId(), System.currentTimeMillis(),
3578 PwdGenerator.getPassword());
3579 subscriptionSender.setServiceContext(serviceContext);
3580 subscriptionSender.setSubject(subject);
3581 subscriptionSender.setUserId(user.getUserId());
3582
3583 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3584
3585 subscriptionSender.flushNotificationsAsync();
3586 }
3587
3588
3597 @Override
3598 public void setRoleUsers(long roleId, long[] userIds)
3599 throws PortalException, SystemException {
3600
3601 List<User> oldUsers = rolePersistence.getUsers(roleId);
3602
3603 long[] oldUserIds = new long[oldUsers.size()];
3604
3605 for (int i = 0; i < oldUsers.size(); i++) {
3606 User user = oldUsers.get(i);
3607
3608 oldUserIds[i] = user.getUserId();
3609 }
3610
3611 Set<Long> updatedUserIdsSet = SetUtil.symmetricDifference(
3612 userIds, oldUserIds);
3613
3614 long[] updateUserIds = ArrayUtil.toLongArray(updatedUserIdsSet);
3615
3616 rolePersistence.setUsers(roleId, userIds);
3617
3618 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3619
3620 indexer.reindex(updateUserIds);
3621
3622 PermissionCacheUtil.clearCache(updateUserIds);
3623 }
3624
3625
3634 @Override
3635 @SuppressWarnings("deprecation")
3636 public void setUserGroupUsers(long userGroupId, long[] userIds)
3637 throws PortalException, SystemException {
3638
3639 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3640 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3641 }
3642
3643 List<User> oldUsers = userGroupPersistence.getUsers(userGroupId);
3644
3645 long[] oldUserIds = new long[oldUsers.size()];
3646
3647 for (int i = 0; i < oldUsers.size(); i++) {
3648 User user = oldUsers.get(i);
3649
3650 oldUserIds[i] = user.getUserId();
3651 }
3652
3653 Set<Long> updatedUserIdsSet = SetUtil.symmetricDifference(
3654 userIds, oldUserIds);
3655
3656 long[] updateUserIds = ArrayUtil.toLongArray(updatedUserIdsSet);
3657
3658 userGroupPersistence.setUsers(userGroupId, userIds);
3659
3660 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3661
3662 indexer.reindex(updateUserIds);
3663
3664 PermissionCacheUtil.clearCache(updateUserIds);
3665 }
3666
3667
3675 @Override
3676 public void unsetGroupTeamsUsers(long groupId, long[] userIds)
3677 throws PortalException, SystemException {
3678
3679 List<Team> teams = teamPersistence.findByGroupId(groupId);
3680
3681 for (Team team : teams) {
3682 unsetTeamUsers(team.getTeamId(), userIds);
3683 }
3684
3685 PermissionCacheUtil.clearCache(userIds);
3686 }
3687
3688
3698 @Override
3699 public void unsetGroupUsers(
3700 final long groupId, final long[] userIds,
3701 ServiceContext serviceContext)
3702 throws PortalException, SystemException {
3703
3704 userGroupRoleLocalService.deleteUserGroupRoles(
3705 userIds, groupId, RoleConstants.TYPE_SITE);
3706
3707 userLocalService.unsetGroupTeamsUsers(groupId, userIds);
3708
3709 groupPersistence.removeUsers(groupId, userIds);
3710
3711 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3712
3713 indexer.reindex(userIds);
3714
3715 PermissionCacheUtil.clearCache(userIds);
3716
3717 Callable<Void> callable = new Callable<Void>() {
3718
3719 @Override
3720 public Void call() throws Exception {
3721 Message message = new Message();
3722
3723 message.put("groupId", groupId);
3724 message.put("userIds", userIds);
3725
3726 MessageBusUtil.sendMessage(
3727 DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
3728
3729 return null;
3730 }
3731
3732 };
3733
3734 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
3735 }
3736
3737
3745 @Override
3746 public void unsetOrganizationUsers(
3747 long organizationId, final long[] userIds)
3748 throws PortalException, SystemException {
3749
3750 Organization organization = organizationPersistence.findByPrimaryKey(
3751 organizationId);
3752
3753 final Group group = organization.getGroup();
3754
3755 userGroupRoleLocalService.deleteUserGroupRoles(
3756 userIds, group.getGroupId());
3757
3758 organizationPersistence.removeUsers(organizationId, userIds);
3759
3760 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3761
3762 indexer.reindex(userIds);
3763
3764 PermissionCacheUtil.clearCache(userIds);
3765
3766 Callable<Void> callable = new Callable<Void>() {
3767
3768 @Override
3769 public Void call() throws Exception {
3770 Message message = new Message();
3771
3772 message.put("groupId", group.getGroupId());
3773 message.put("userIds", userIds);
3774
3775 MessageBusUtil.sendMessage(
3776 DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
3777
3778 return null;
3779 }
3780
3781 };
3782
3783 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
3784 }
3785
3786
3793 @Override
3794 public void unsetPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
3795 throws SystemException {
3796
3797 passwordPolicyRelLocalService.deletePasswordPolicyRels(
3798 passwordPolicyId, User.class.getName(), userIds);
3799 }
3800
3801
3809 @Override
3810 public void unsetRoleUsers(long roleId, List<User> users)
3811 throws PortalException, SystemException {
3812
3813 Role role = rolePersistence.findByPrimaryKey(roleId);
3814
3815 String roleName = role.getName();
3816
3817 if ((roleName.equals(RoleConstants.ADMINISTRATOR) &&
3818 (getRoleUsersCount(role.getRoleId()) <= 1)) ||
3819 roleName.equals(RoleConstants.USER)) {
3820
3821 return;
3822 }
3823
3824 rolePersistence.removeUsers(roleId, users);
3825
3826 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3827
3828 indexer.reindex(users);
3829
3830 long[] userIds = new long[users.size()];
3831
3832 for (int i = 0; i < users.size(); i++) {
3833 User user = users.get(i);
3834
3835 userIds[i] = user.getUserId();
3836 }
3837
3838 PermissionCacheUtil.clearCache(userIds);
3839 }
3840
3841
3849 @Override
3850 public void unsetRoleUsers(long roleId, long[] userIds)
3851 throws PortalException, SystemException {
3852
3853 Role role = rolePersistence.findByPrimaryKey(roleId);
3854
3855 String roleName = role.getName();
3856
3857 if (roleName.equals(RoleConstants.USER) ||
3858 (roleName.equals(RoleConstants.ADMINISTRATOR) &&
3859 getRoleUsersCount(role.getRoleId()) <= 1)) {
3860
3861 return;
3862 }
3863
3864 rolePersistence.removeUsers(roleId, userIds);
3865
3866 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3867
3868 indexer.reindex(userIds);
3869
3870 PermissionCacheUtil.clearCache(userIds);
3871 }
3872
3873
3881 @Override
3882 public void unsetTeamUsers(long teamId, long[] userIds)
3883 throws PortalException, SystemException {
3884
3885 teamPersistence.removeUsers(teamId, userIds);
3886
3887 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3888
3889 indexer.reindex(userIds);
3890
3891 PermissionCacheUtil.clearCache(userIds);
3892 }
3893
3894
3902 @Override
3903 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
3904 throws PortalException, SystemException {
3905
3906 userGroupPersistence.removeUsers(userGroupId, userIds);
3907
3908 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3909
3910 indexer.reindex(userIds);
3911
3912 PermissionCacheUtil.clearCache(userIds);
3913 }
3914
3915
3925 @Override
3926 public User updateAgreedToTermsOfUse(
3927 long userId, boolean agreedToTermsOfUse)
3928 throws PortalException, SystemException {
3929
3930 User user = userPersistence.findByPrimaryKey(userId);
3931
3932 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
3933
3934 userPersistence.update(user);
3935
3936 return user;
3937 }
3938
3939
3950 @Override
3951 public void updateAsset(
3952 long userId, User user, long[] assetCategoryIds,
3953 String[] assetTagNames)
3954 throws PortalException, SystemException {
3955
3956 User owner = userPersistence.findByPrimaryKey(userId);
3957
3958 Company company = companyPersistence.findByPrimaryKey(
3959 owner.getCompanyId());
3960
3961 Group companyGroup = company.getGroup();
3962
3963 assetEntryLocalService.updateEntry(
3964 userId, companyGroup.getGroupId(), user.getCreateDate(),
3965 user.getModifiedDate(), User.class.getName(), user.getUserId(),
3966 user.getUuid(), 0, assetCategoryIds, assetTagNames, false, null,
3967 null, null, null, user.getFullName(), null, null, null, null, 0, 0,
3968 null, false);
3969 }
3970
3971
3980 @Override
3981 public User updateCreateDate(long userId, Date createDate)
3982 throws PortalException, SystemException {
3983
3984 User user = userPersistence.findByPrimaryKey(userId);
3985
3986 user.setCreateDate(createDate);
3987
3988 userPersistence.update(user);
3989
3990 return user;
3991 }
3992
3993
4004 @Override
4005 public User updateEmailAddress(
4006 long userId, String password, String emailAddress1,
4007 String emailAddress2)
4008 throws PortalException, SystemException {
4009
4010 emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
4011 emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
4012
4013 User user = userPersistence.findByPrimaryKey(userId);
4014
4015 validateEmailAddress(user, emailAddress1, emailAddress2);
4016
4017 setEmailAddress(
4018 user, password, user.getFirstName(), user.getMiddleName(),
4019 user.getLastName(), emailAddress1);
4020
4021 userPersistence.update(user);
4022
4023 Contact contact = user.getContact();
4024
4025 contact.setEmailAddress(user.getEmailAddress());
4026
4027 contactPersistence.update(contact);
4028
4029 return user;
4030 }
4031
4032
4046 @Override
4047 public User updateEmailAddress(
4048 long userId, String password, String emailAddress1,
4049 String emailAddress2, ServiceContext serviceContext)
4050 throws PortalException, SystemException {
4051
4052 emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
4053 emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
4054
4055 User user = userPersistence.findByPrimaryKey(userId);
4056
4057 validateEmailAddress(user, emailAddress1, emailAddress2);
4058
4059 Company company = companyPersistence.findByPrimaryKey(
4060 user.getCompanyId());
4061
4062 if (company.isStrangersVerify() &&
4063 !StringUtil.equalsIgnoreCase(
4064 emailAddress1, user.getEmailAddress())) {
4065
4066 sendEmailAddressVerification(user, emailAddress1, serviceContext);
4067 }
4068 else {
4069 setEmailAddress(
4070 user, password, user.getFirstName(), user.getMiddleName(),
4071 user.getLastName(), emailAddress1);
4072
4073 userPersistence.update(user);
4074
4075 Contact contact = user.getContact();
4076
4077 contact.setEmailAddress(user.getEmailAddress());
4078
4079 contactPersistence.update(contact);
4080 }
4081
4082 return user;
4083 }
4084
4085
4094 @Override
4095 public User updateEmailAddressVerified(
4096 long userId, boolean emailAddressVerified)
4097 throws PortalException, SystemException {
4098
4099 User user = userPersistence.findByPrimaryKey(userId);
4100
4101 user.setEmailAddressVerified(emailAddressVerified);
4102
4103 userPersistence.update(user);
4104
4105 return user;
4106 }
4107
4108
4117 @Override
4118 public User updateFacebookId(long userId, long facebookId)
4119 throws PortalException, SystemException {
4120
4121 User user = userPersistence.findByPrimaryKey(userId);
4122
4123 user.setFacebookId(facebookId);
4124
4125 userPersistence.update(user);
4126
4127 return user;
4128 }
4129
4130
4140 @Override
4141 public void updateGroups(
4142 long userId, long[] newGroupIds, ServiceContext serviceContext)
4143 throws PortalException, SystemException {
4144
4145 boolean indexingEnabled = true;
4146
4147 if (serviceContext != null) {
4148 indexingEnabled = serviceContext.isIndexingEnabled();
4149 }
4150
4151 updateGroups(userId, newGroupIds, serviceContext, indexingEnabled);
4152 }
4153
4154
4193 @Override
4194 public User updateIncompleteUser(
4195 long creatorUserId, long companyId, boolean autoPassword,
4196 String password1, String password2, boolean autoScreenName,
4197 String screenName, String emailAddress, long facebookId,
4198 String openId, Locale locale, String firstName, String middleName,
4199 String lastName, int prefixId, int suffixId, boolean male,
4200 int birthdayMonth, int birthdayDay, int birthdayYear,
4201 String jobTitle, boolean updateUserInformation, boolean sendEmail,
4202 ServiceContext serviceContext)
4203 throws PortalException, SystemException {
4204
4205 User user = getUserByEmailAddress(companyId, emailAddress);
4206
4207 if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
4208 throw new PortalException("Invalid user status");
4209 }
4210
4211 User defaultUser = getDefaultUser(companyId);
4212
4213 if (facebookId > 0) {
4214 autoPassword = false;
4215
4216 if ((password1 == null) || (password2 == null)) {
4217 password1 = PwdGenerator.getPassword();
4218 password2 = password1;
4219 }
4220
4221 sendEmail = false;
4222 }
4223
4224 if (updateUserInformation) {
4225 autoScreenName = false;
4226
4227 if (PrefsPropsUtil.getBoolean(
4228 companyId,
4229 PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
4230
4231 autoScreenName = true;
4232 }
4233
4234 validate(
4235 companyId, user.getUserId(), autoPassword, password1, password2,
4236 autoScreenName, screenName, emailAddress, openId, firstName,
4237 middleName, lastName, null);
4238
4239 if (!autoPassword) {
4240 if (Validator.isNull(password1) ||
4241 Validator.isNull(password2)) {
4242 throw new UserPasswordException(
4243 UserPasswordException.PASSWORD_INVALID);
4244 }
4245 }
4246
4247 if (autoScreenName) {
4248 ScreenNameGenerator screenNameGenerator =
4249 ScreenNameGeneratorFactory.getInstance();
4250
4251 try {
4252 screenName = screenNameGenerator.generate(
4253 companyId, user.getUserId(), emailAddress);
4254 }
4255 catch (Exception e) {
4256 throw new SystemException(e);
4257 }
4258 }
4259
4260 FullNameGenerator fullNameGenerator =
4261 FullNameGeneratorFactory.getInstance();
4262
4263 String fullName = fullNameGenerator.getFullName(
4264 firstName, middleName, lastName);
4265
4266 String greeting = LanguageUtil.format(
4267 locale, "welcome-x", " " + fullName, false);
4268
4269 if (Validator.isNotNull(password1)) {
4270 user.setPassword(PasswordEncryptorUtil.encrypt(password1));
4271 user.setPasswordUnencrypted(password1);
4272 }
4273
4274 user.setPasswordEncrypted(true);
4275
4276 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
4277
4278 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
4279 passwordPolicy.isChangeRequired()) {
4280
4281 user.setPasswordReset(true);
4282 }
4283 else {
4284 user.setPasswordReset(false);
4285 }
4286
4287 user.setScreenName(screenName);
4288 user.setFacebookId(facebookId);
4289 user.setOpenId(openId);
4290 user.setLanguageId(locale.toString());
4291 user.setTimeZoneId(defaultUser.getTimeZoneId());
4292 user.setGreeting(greeting);
4293 user.setFirstName(firstName);
4294 user.setMiddleName(middleName);
4295 user.setLastName(lastName);
4296 user.setJobTitle(jobTitle);
4297 user.setExpandoBridgeAttributes(serviceContext);
4298
4299 Date birthday = getBirthday(
4300 birthdayMonth, birthdayDay, birthdayYear);
4301
4302 Contact contact = user.getContact();
4303
4304 contact.setFirstName(firstName);
4305 contact.setMiddleName(middleName);
4306 contact.setLastName(lastName);
4307 contact.setPrefixId(prefixId);
4308 contact.setSuffixId(suffixId);
4309 contact.setMale(male);
4310 contact.setBirthday(birthday);
4311 contact.setJobTitle(jobTitle);
4312
4313 contactPersistence.update(contact, serviceContext);
4314
4315
4316
4317 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4318 User.class);
4319
4320 indexer.reindex(user);
4321 }
4322
4323 user.setStatus(WorkflowConstants.STATUS_DRAFT);
4324
4325 userPersistence.update(user, serviceContext);
4326
4327
4328
4329 long workflowUserId = creatorUserId;
4330
4331 if (workflowUserId == user.getUserId()) {
4332 workflowUserId = defaultUser.getUserId();
4333 }
4334
4335 ServiceContext workflowServiceContext = serviceContext;
4336
4337 if (workflowServiceContext == null) {
4338 workflowServiceContext = new ServiceContext();
4339 }
4340
4341 workflowServiceContext.setAttribute("autoPassword", autoPassword);
4342 workflowServiceContext.setAttribute("passwordUnencrypted", password1);
4343 workflowServiceContext.setAttribute("sendEmail", sendEmail);
4344
4345 WorkflowHandlerRegistryUtil.startWorkflowInstance(
4346 companyId, workflowUserId, User.class.getName(), user.getUserId(),
4347 user, workflowServiceContext);
4348
4349 return getUserByEmailAddress(companyId, emailAddress);
4350 }
4351
4352
4362 @Override
4363 public User updateJobTitle(long userId, String jobTitle)
4364 throws PortalException, SystemException {
4365
4366 User user = userPersistence.findByPrimaryKey(userId);
4367
4368 user.setJobTitle(jobTitle);
4369
4370 userPersistence.update(user);
4371
4372 Contact contact = contactPersistence.findByPrimaryKey(
4373 user.getContactId());
4374
4375 contact.setJobTitle(jobTitle);
4376
4377 contactPersistence.update(contact);
4378
4379 return user;
4380 }
4381
4382
4391 @Override
4392 public User updateLastLogin(long userId, String loginIP)
4393 throws PortalException, SystemException {
4394
4395 User user = userPersistence.findByPrimaryKey(userId);
4396
4397 Date lastLoginDate = user.getLoginDate();
4398
4399 if (lastLoginDate == null) {
4400 lastLoginDate = new Date();
4401 }
4402
4403 user.setLoginDate(new Date());
4404 user.setLoginIP(loginIP);
4405 user.setLastLoginDate(lastLoginDate);
4406 user.setLastLoginIP(user.getLoginIP());
4407 user.setFailedLoginAttempts(0);
4408
4409 userPersistence.update(user);
4410
4411 return user;
4412 }
4413
4414
4423 @Override
4424 public User updateLockout(User user, boolean lockout)
4425 throws PortalException, SystemException {
4426
4427 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
4428
4429 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
4430 return user;
4431 }
4432
4433 Date lockoutDate = null;
4434
4435 if (lockout) {
4436 lockoutDate = new Date();
4437 }
4438
4439 user.setLockout(lockout);
4440 user.setLockoutDate(lockoutDate);
4441
4442 if (!lockout) {
4443 user.setLastFailedLoginDate(lockoutDate);
4444 user.setFailedLoginAttempts(0);
4445 }
4446
4447 userPersistence.update(user);
4448
4449 return user;
4450 }
4451
4452
4463 @Override
4464 public User updateLockoutByEmailAddress(
4465 long companyId, String emailAddress, boolean lockout)
4466 throws PortalException, SystemException {
4467
4468 User user = getUserByEmailAddress(companyId, emailAddress);
4469
4470 return updateLockout(user, lockout);
4471 }
4472
4473
4482 @Override
4483 public User updateLockoutById(long userId, boolean lockout)
4484 throws PortalException, SystemException {
4485
4486 User user = userPersistence.findByPrimaryKey(userId);
4487
4488 return updateLockout(user, lockout);
4489 }
4490
4491
4501 @Override
4502 public User updateLockoutByScreenName(
4503 long companyId, String screenName, boolean lockout)
4504 throws PortalException, SystemException {
4505
4506 User user = getUserByScreenName(companyId, screenName);
4507
4508 return updateLockout(user, lockout);
4509 }
4510
4511
4520 @Override
4521 public User updateModifiedDate(long userId, Date modifiedDate)
4522 throws PortalException, SystemException {
4523
4524 User user = userPersistence.findByPrimaryKey(userId);
4525
4526 user.setModifiedDate(modifiedDate);
4527
4528 userPersistence.update(user);
4529
4530 return user;
4531 }
4532
4533
4542 @Override
4543 public User updateOpenId(long userId, String openId)
4544 throws PortalException, SystemException {
4545
4546 openId = openId.trim();
4547
4548 User user = userPersistence.findByPrimaryKey(userId);
4549
4550 user.setOpenId(openId);
4551
4552 userPersistence.update(user);
4553
4554 return user;
4555 }
4556
4557
4568 @Override
4569 public void updateOrganizations(
4570 long userId, long[] newOrganizationIds,
4571 ServiceContext serviceContext)
4572 throws PortalException, SystemException {
4573
4574 updateOrganizations(
4575 userId, newOrganizationIds, serviceContext.isIndexingEnabled());
4576 }
4577
4578
4590 @Override
4591 public User updatePassword(
4592 long userId, String password1, String password2,
4593 boolean passwordReset)
4594 throws PortalException, SystemException {
4595
4596 return updatePassword(
4597 userId, password1, password2, passwordReset, false);
4598 }
4599
4600
4615 @Override
4616 public User updatePassword(
4617 long userId, String password1, String password2,
4618 boolean passwordReset, boolean silentUpdate)
4619 throws PortalException, SystemException {
4620
4621 User user = userPersistence.findByPrimaryKey(userId);
4622
4623 if (!silentUpdate) {
4624 validatePassword(user.getCompanyId(), userId, password1, password2);
4625 }
4626
4627 String oldEncPwd = user.getPassword();
4628
4629 if (!user.isPasswordEncrypted()) {
4630 oldEncPwd = PasswordEncryptorUtil.encrypt(user.getPassword());
4631 }
4632
4633 String newEncPwd = PasswordEncryptorUtil.encrypt(password1);
4634
4635 if (user.hasCompanyMx()) {
4636 mailService.updatePassword(user.getCompanyId(), userId, password1);
4637 }
4638
4639 user.setPassword(newEncPwd);
4640 user.setPasswordUnencrypted(password1);
4641 user.setPasswordEncrypted(true);
4642 user.setPasswordReset(passwordReset);
4643 user.setPasswordModifiedDate(new Date());
4644 user.setDigest(StringPool.BLANK);
4645 user.setGraceLoginCount(0);
4646
4647 if (!silentUpdate) {
4648 user.setPasswordModified(true);
4649 }
4650
4651 try {
4652 userPersistence.update(user);
4653 }
4654 catch (ModelListenerException mle) {
4655 String msg = GetterUtil.getString(mle.getCause().getMessage());
4656
4657 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
4658 String passwordHistory = PrefsPropsUtil.getString(
4659 user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
4660
4661 if (msg.contains(passwordHistory)) {
4662 throw new UserPasswordException(
4663 UserPasswordException.PASSWORD_ALREADY_USED);
4664 }
4665 }
4666
4667 throw new UserPasswordException(
4668 UserPasswordException.PASSWORD_INVALID);
4669 }
4670
4671 if (!silentUpdate) {
4672 user.setPasswordModified(false);
4673
4674 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
4675 }
4676
4677 return user;
4678 }
4679
4680
4694 @Override
4695 public User updatePasswordManually(
4696 long userId, String password, boolean passwordEncrypted,
4697 boolean passwordReset, Date passwordModifiedDate)
4698 throws PortalException, SystemException {
4699
4700
4701
4702 User user = userPersistence.findByPrimaryKey(userId);
4703
4704 user.setPassword(password);
4705 user.setPasswordEncrypted(passwordEncrypted);
4706 user.setPasswordReset(passwordReset);
4707 user.setPasswordModifiedDate(passwordModifiedDate);
4708 user.setDigest(StringPool.BLANK);
4709
4710 userPersistence.update(user);
4711
4712 return user;
4713 }
4714
4715
4726 @Override
4727 public User updatePasswordReset(long userId, boolean passwordReset)
4728 throws PortalException, SystemException {
4729
4730 User user = userPersistence.findByPrimaryKey(userId);
4731
4732 user.setPasswordReset(passwordReset);
4733
4734 userPersistence.update(user);
4735
4736 return user;
4737 }
4738
4739
4749 @Override
4750 public User updatePortrait(long userId, byte[] bytes)
4751 throws PortalException, SystemException {
4752
4753 User user = userPersistence.findByPrimaryKey(userId);
4754
4755 long imageMaxSize = PrefsPropsUtil.getLong(
4756 PropsKeys.USERS_IMAGE_MAX_SIZE);
4757
4758 if ((imageMaxSize > 0) &&
4759 ((bytes == null) || (bytes.length > imageMaxSize))) {
4760
4761 throw new UserPortraitSizeException();
4762 }
4763
4764 long portraitId = user.getPortraitId();
4765
4766 if (portraitId <= 0) {
4767 portraitId = counterLocalService.increment();
4768
4769 user.setPortraitId(portraitId);
4770 }
4771
4772 try {
4773 ImageBag imageBag = ImageToolUtil.read(bytes);
4774
4775 RenderedImage renderedImage = imageBag.getRenderedImage();
4776
4777 if (renderedImage == null) {
4778 throw new UserPortraitTypeException();
4779 }
4780
4781 renderedImage = ImageToolUtil.scale(
4782 renderedImage, PropsValues.USERS_IMAGE_MAX_HEIGHT,
4783 PropsValues.USERS_IMAGE_MAX_WIDTH);
4784
4785 String contentType = imageBag.getType();
4786
4787 imageLocalService.updateImage(
4788 portraitId,
4789 ImageToolUtil.getBytes(renderedImage, contentType));
4790 }
4791 catch (IOException ioe) {
4792 throw new ImageSizeException(ioe);
4793 }
4794
4795 userPersistence.update(user);
4796
4797 return user;
4798 }
4799
4800
4811 @Override
4812 public User updateReminderQuery(long userId, String question, String answer)
4813 throws PortalException, SystemException {
4814
4815 validateReminderQuery(question, answer);
4816
4817 User user = userPersistence.findByPrimaryKey(userId);
4818
4819 user.setReminderQueryQuestion(question);
4820 user.setReminderQueryAnswer(answer);
4821
4822 userPersistence.update(user);
4823
4824 return user;
4825 }
4826
4827
4837 @Override
4838 public User updateScreenName(long userId, String screenName)
4839 throws PortalException, SystemException {
4840
4841
4842
4843 User user = userPersistence.findByPrimaryKey(userId);
4844
4845 screenName = getLogin(screenName);
4846
4847 validateScreenName(user.getCompanyId(), userId, screenName);
4848
4849 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
4850 user.setDigest(StringPool.BLANK);
4851 }
4852
4853 user.setScreenName(screenName);
4854
4855 userPersistence.update(user);
4856
4857
4858
4859 Group group = groupLocalService.getUserGroup(
4860 user.getCompanyId(), userId);
4861
4862 group.setFriendlyURL(StringPool.SLASH + screenName);
4863
4864 groupPersistence.update(group);
4865
4866 return user;
4867 }
4868
4869
4881 @Deprecated
4882 @Override
4883 public User updateStatus(long userId, int status)
4884 throws PortalException, SystemException {
4885
4886 return updateStatus(userId, status, new ServiceContext());
4887 }
4888
4889
4901 @Override
4902 public User updateStatus(
4903 long userId, int status, ServiceContext serviceContext)
4904 throws PortalException, SystemException {
4905
4906 User user = userPersistence.findByPrimaryKey(userId);
4907
4908 if ((status == WorkflowConstants.STATUS_APPROVED) &&
4909 (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {
4910
4911 validateCompanyMaxUsers(user.getCompanyId());
4912 }
4913
4914 String passwordUnencrypted = (String)serviceContext.getAttribute(
4915 "passwordUnencrypted");
4916
4917 if (Validator.isNotNull(passwordUnencrypted)) {
4918 user.setPasswordUnencrypted(passwordUnencrypted);
4919 }
4920
4921 user.setStatus(status);
4922
4923 userPersistence.update(user);
4924
4925 reindex(user);
4926
4927 return user;
4928 }
4929
4930
4986 @Override
4987 @SuppressWarnings("deprecation")
4988 public User updateUser(
4989 long userId, String oldPassword, String newPassword1,
4990 String newPassword2, boolean passwordReset,
4991 String reminderQueryQuestion, String reminderQueryAnswer,
4992 String screenName, String emailAddress, long facebookId,
4993 String openId, String languageId, String timeZoneId,
4994 String greeting, String comments, String firstName,
4995 String middleName, String lastName, int prefixId, int suffixId,
4996 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
4997 String smsSn, String aimSn, String facebookSn, String icqSn,
4998 String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
4999 String twitterSn, String ymSn, String jobTitle, long[] groupIds,
5000 long[] organizationIds, long[] roleIds,
5001 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
5002 ServiceContext serviceContext)
5003 throws PortalException, SystemException {
5004
5005
5006
5007 User user = userPersistence.findByPrimaryKey(userId);
5008 Company company = companyPersistence.findByPrimaryKey(
5009 user.getCompanyId());
5010 String password = oldPassword;
5011 screenName = getLogin(screenName);
5012 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
5013 openId = openId.trim();
5014 String oldFullName = user.getFullName();
5015 aimSn = StringUtil.toLowerCase(aimSn.trim());
5016 facebookSn = StringUtil.toLowerCase(facebookSn.trim());
5017 icqSn = StringUtil.toLowerCase(icqSn.trim());
5018 jabberSn = StringUtil.toLowerCase(jabberSn.trim());
5019 msnSn = StringUtil.toLowerCase(msnSn.trim());
5020 mySpaceSn = StringUtil.toLowerCase(mySpaceSn.trim());
5021 skypeSn = StringUtil.toLowerCase(skypeSn.trim());
5022 twitterSn = StringUtil.toLowerCase(twitterSn.trim());
5023 ymSn = StringUtil.toLowerCase(ymSn.trim());
5024 Date now = new Date();
5025
5026 EmailAddressGenerator emailAddressGenerator =
5027 EmailAddressGeneratorFactory.getInstance();
5028
5029 if (emailAddressGenerator.isGenerated(emailAddress)) {
5030 emailAddress = StringPool.BLANK;
5031 }
5032
5033 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
5034 Validator.isNull(emailAddress)) {
5035
5036 emailAddress = emailAddressGenerator.generate(
5037 user.getCompanyId(), userId);
5038 }
5039
5040 validate(
5041 userId, screenName, emailAddress, openId, firstName, middleName,
5042 lastName, smsSn);
5043
5044 if (Validator.isNotNull(newPassword1) ||
5045 Validator.isNotNull(newPassword2)) {
5046
5047 user = updatePassword(
5048 userId, newPassword1, newPassword2, passwordReset);
5049
5050 password = newPassword1;
5051
5052 user.setDigest(StringPool.BLANK);
5053 }
5054
5055 user.setModifiedDate(now);
5056
5057 if (user.getContactId() <= 0) {
5058 user.setContactId(counterLocalService.increment());
5059 }
5060
5061 user.setPasswordReset(passwordReset);
5062
5063 if (Validator.isNotNull(reminderQueryQuestion) &&
5064 Validator.isNotNull(reminderQueryAnswer)) {
5065
5066 user.setReminderQueryQuestion(reminderQueryQuestion);
5067 user.setReminderQueryAnswer(reminderQueryAnswer);
5068 }
5069
5070 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
5071 user.setScreenName(screenName);
5072
5073 user.setDigest(StringPool.BLANK);
5074 }
5075
5076 boolean sendEmailAddressVerification = false;
5077
5078 if (company.isStrangersVerify() &&
5079 !StringUtil.equalsIgnoreCase(
5080 emailAddress, user.getEmailAddress())) {
5081
5082 sendEmailAddressVerification = true;
5083 }
5084 else {
5085 setEmailAddress(
5086 user, password, firstName, middleName, lastName, emailAddress);
5087 }
5088
5089 if (serviceContext != null) {
5090 String uuid = serviceContext.getUuid();
5091
5092 if (Validator.isNotNull(uuid)) {
5093 user.setUuid(uuid);
5094 }
5095 }
5096
5097 user.setFacebookId(facebookId);
5098
5099 Long ldapServerId = null;
5100
5101 if (serviceContext != null) {
5102 ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
5103 }
5104
5105 if (ldapServerId != null) {
5106 user.setLdapServerId(ldapServerId);
5107 }
5108
5109 user.setOpenId(openId);
5110 user.setLanguageId(languageId);
5111 user.setTimeZoneId(timeZoneId);
5112 user.setGreeting(greeting);
5113 user.setComments(comments);
5114 user.setFirstName(firstName);
5115 user.setMiddleName(middleName);
5116 user.setLastName(lastName);
5117 user.setJobTitle(jobTitle);
5118 user.setExpandoBridgeAttributes(serviceContext);
5119
5120 userPersistence.update(user, serviceContext);
5121
5122
5123
5124 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
5125
5126 long contactId = user.getContactId();
5127
5128 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
5129
5130 if (contact == null) {
5131 contact = contactPersistence.create(contactId);
5132
5133 contact.setCompanyId(user.getCompanyId());
5134 contact.setUserName(StringPool.BLANK);
5135 contact.setCreateDate(now);
5136 contact.setClassName(User.class.getName());
5137 contact.setClassPK(user.getUserId());
5138 contact.setAccountId(company.getAccountId());
5139 contact.setParentContactId(
5140 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
5141 }
5142
5143 contact.setModifiedDate(now);
5144 contact.setEmailAddress(user.getEmailAddress());
5145 contact.setFirstName(firstName);
5146 contact.setMiddleName(middleName);
5147 contact.setLastName(lastName);
5148 contact.setPrefixId(prefixId);
5149 contact.setSuffixId(suffixId);
5150 contact.setMale(male);
5151 contact.setBirthday(birthday);
5152 contact.setSmsSn(smsSn);
5153 contact.setAimSn(aimSn);
5154 contact.setFacebookSn(facebookSn);
5155 contact.setIcqSn(icqSn);
5156 contact.setJabberSn(jabberSn);
5157 contact.setMsnSn(msnSn);
5158 contact.setMySpaceSn(mySpaceSn);
5159 contact.setSkypeSn(skypeSn);
5160 contact.setTwitterSn(twitterSn);
5161 contact.setYmSn(ymSn);
5162 contact.setJobTitle(jobTitle);
5163
5164 contactPersistence.update(contact, serviceContext);
5165
5166
5167
5168 Group group = groupLocalService.getUserGroup(
5169 user.getCompanyId(), userId);
5170
5171 group.setFriendlyURL(StringPool.SLASH + screenName);
5172
5173 groupPersistence.update(group);
5174
5175
5176
5177
5178
5179
5180
5181 List<UserGroupRole> previousUserGroupRoles =
5182 userGroupRolePersistence.findByUserId(userId);
5183
5184 updateGroups(userId, groupIds, serviceContext, false);
5185 updateOrganizations(userId, organizationIds, false);
5186
5187
5188
5189 if (roleIds != null) {
5190 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
5191
5192 userPersistence.setRoles(userId, roleIds);
5193 }
5194
5195
5196
5197 updateUserGroupRoles(
5198 user, groupIds, organizationIds, userGroupRoles,
5199 previousUserGroupRoles);
5200
5201
5202
5203 if (userGroupIds != null) {
5204 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
5205 userGroupLocalService.copyUserGroupLayouts(
5206 userGroupIds, userId);
5207 }
5208
5209 userPersistence.setUserGroups(userId, userGroupIds);
5210 }
5211
5212
5213
5214 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
5215
5216
5217
5218 if (serviceContext != null) {
5219 updateAsset(
5220 userId, user, serviceContext.getAssetCategoryIds(),
5221 serviceContext.getAssetTagNames());
5222 }
5223
5224
5225
5226 if (GetterUtil.getBoolean(
5227 PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
5228 !oldFullName.equals(user.getFullName())) {
5229
5230 mbMessageLocalService.updateUserName(userId, user.getFullName());
5231 }
5232
5233
5234
5235 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
5236 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5237 User.class);
5238
5239 indexer.reindex(user);
5240 }
5241
5242
5243
5244 if ((serviceContext != null) && sendEmailAddressVerification) {
5245 sendEmailAddressVerification(user, emailAddress, serviceContext);
5246 }
5247
5248
5249
5250 PermissionCacheUtil.clearCache(userId);
5251
5252 return user;
5253 }
5254
5255
5264 @Override
5265 public void verifyEmailAddress(String ticketKey)
5266 throws PortalException, SystemException {
5267
5268 Ticket ticket = ticketLocalService.getTicket(ticketKey);
5269
5270 if (ticket.isExpired() ||
5271 (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
5272
5273 throw new NoSuchTicketException("{ticketKey=" + ticketKey + "}");
5274 }
5275
5276 User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
5277
5278 String emailAddress = ticket.getExtraInfo();
5279
5280 emailAddress = StringUtil.toLowerCase(emailAddress).trim();
5281
5282 if (!emailAddress.equals(user.getEmailAddress())) {
5283 if (userPersistence.fetchByC_EA(
5284 user.getCompanyId(), emailAddress) != null) {
5285
5286 throw new DuplicateUserEmailAddressException(
5287 "{userId=" + user.getUserId() + "}");
5288 }
5289
5290 setEmailAddress(
5291 user, StringPool.BLANK, user.getFirstName(),
5292 user.getMiddleName(), user.getLastName(), emailAddress);
5293
5294 Contact contact = user.getContact();
5295
5296 contact.setEmailAddress(user.getEmailAddress());
5297
5298 contactPersistence.update(contact);
5299 }
5300
5301 user.setEmailAddressVerified(true);
5302
5303 userPersistence.update(user);
5304
5305 ticketLocalService.deleteTicket(ticket);
5306 }
5307
5308 protected void addDefaultRolesAndTeams(long groupId, long[] userIds)
5309 throws PortalException, SystemException {
5310
5311 List<Role> defaultSiteRoles = new ArrayList<Role>();
5312
5313 Group group = groupLocalService.getGroup(groupId);
5314
5315 UnicodeProperties typeSettingsProperties =
5316 group.getTypeSettingsProperties();
5317
5318 long[] defaultSiteRoleIds = StringUtil.split(
5319 typeSettingsProperties.getProperty("defaultSiteRoleIds"), 0L);
5320
5321 for (long defaultSiteRoleId : defaultSiteRoleIds) {
5322 Role defaultSiteRole = rolePersistence.fetchByPrimaryKey(
5323 defaultSiteRoleId);
5324
5325 if (defaultSiteRole == null) {
5326 if (_log.isWarnEnabled()) {
5327 _log.warn("Unable to find role " + defaultSiteRoleId);
5328 }
5329
5330 continue;
5331 }
5332
5333 defaultSiteRoles.add(defaultSiteRole);
5334 }
5335
5336 List<Team> defaultTeams = new ArrayList<Team>();
5337
5338 long[] defaultTeamIds = StringUtil.split(
5339 typeSettingsProperties.getProperty("defaultTeamIds"), 0L);
5340
5341 for (long defaultTeamId : defaultTeamIds) {
5342 Team defaultTeam = teamPersistence.findByPrimaryKey(defaultTeamId);
5343
5344 if (defaultTeam == null) {
5345 if (_log.isWarnEnabled()) {
5346 _log.warn("Unable to find team " + defaultTeamId);
5347 }
5348
5349 continue;
5350 }
5351
5352 defaultTeams.add(defaultTeam);
5353 }
5354
5355 for (long userId : userIds) {
5356 Set<Long> userRoleIdsSet = new HashSet<Long>();
5357
5358 for (Role role : defaultSiteRoles) {
5359 if (!userPersistence.containsRole(userId, role.getRoleId())) {
5360 userRoleIdsSet.add(role.getRoleId());
5361 }
5362 }
5363
5364 long[] userRoleIds = ArrayUtil.toArray(
5365 userRoleIdsSet.toArray(new Long[userRoleIdsSet.size()]));
5366
5367 userGroupRoleLocalService.addUserGroupRoles(
5368 userId, groupId, userRoleIds);
5369
5370 Set<Long> userTeamIdsSet = new HashSet<Long>();
5371
5372 for (Team team : defaultTeams) {
5373 if (!userPersistence.containsTeam(userId, team.getTeamId())) {
5374 userTeamIdsSet.add(team.getTeamId());
5375 }
5376 }
5377
5378 long[] userTeamIds = ArrayUtil.toArray(
5379 userTeamIdsSet.toArray(new Long[userTeamIdsSet.size()]));
5380
5381 userPersistence.addTeams(userId, userTeamIds);
5382 }
5383 }
5384
5385
5431 protected int authenticate(
5432 long companyId, String login, String password, String authType,
5433 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
5434 Map<String, Object> resultsMap)
5435 throws PortalException, SystemException {
5436
5437 if (PropsValues.AUTH_LOGIN_DISABLED) {
5438 return Authenticator.FAILURE;
5439 }
5440
5441 login = StringUtil.toLowerCase(login.trim());
5442
5443 long userId = GetterUtil.getLong(login);
5444
5445
5446
5447 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5448 if (Validator.isNull(login)) {
5449 throw new UserEmailAddressException();
5450 }
5451 }
5452 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5453 if (Validator.isNull(login)) {
5454 throw new UserScreenNameException();
5455 }
5456 }
5457 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5458 if (Validator.isNull(login)) {
5459 throw new UserIdException();
5460 }
5461 }
5462
5463 if (Validator.isNull(password)) {
5464 throw new UserPasswordException(
5465 UserPasswordException.PASSWORD_INVALID);
5466 }
5467
5468 int authResult = Authenticator.FAILURE;
5469
5470
5471
5472 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5473 authResult = AuthPipeline.authenticateByEmailAddress(
5474 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5475 headerMap, parameterMap);
5476 }
5477 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5478 authResult = AuthPipeline.authenticateByScreenName(
5479 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5480 headerMap, parameterMap);
5481 }
5482 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5483 authResult = AuthPipeline.authenticateByUserId(
5484 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
5485 headerMap, parameterMap);
5486 }
5487
5488
5489
5490 User user = null;
5491
5492 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5493 user = fetchUserByEmailAddress(companyId, login);
5494 }
5495 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5496 user = fetchUserByScreenName(companyId, login);
5497 }
5498 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5499 user = userPersistence.fetchByPrimaryKey(GetterUtil.getLong(login));
5500 }
5501
5502 if (user == null) {
5503 return Authenticator.DNE;
5504 }
5505
5506 if (user.isDefaultUser()) {
5507 if (_log.isInfoEnabled()) {
5508 _log.info("Authentication is disabled for the default user");
5509 }
5510
5511 return Authenticator.DNE;
5512 }
5513 else if (!user.isActive()) {
5514 if (_log.isInfoEnabled()) {
5515 _log.info(
5516 "Authentication is disabled for inactive user " +
5517 user.getUserId());
5518 }
5519
5520 return Authenticator.FAILURE;
5521 }
5522
5523 if (!user.isPasswordEncrypted()) {
5524 user.setPassword(PasswordEncryptorUtil.encrypt(user.getPassword()));
5525 user.setPasswordEncrypted(true);
5526
5527 userPersistence.update(user);
5528 }
5529
5530
5531
5532
5533 checkLockout(user);
5534
5535 checkPasswordExpired(user);
5536
5537
5538
5539 boolean skipLiferayCheck = false;
5540
5541 if (authResult == Authenticator.SKIP_LIFERAY_CHECK) {
5542 authResult = Authenticator.SUCCESS;
5543
5544 skipLiferayCheck = true;
5545 }
5546 else if ((authResult == Authenticator.SUCCESS) &&
5547 PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5548
5549 boolean authenticated = PwdAuthenticator.authenticate(
5550 login, password, user.getPassword());
5551
5552 if (authenticated) {
5553 authResult = Authenticator.SUCCESS;
5554 }
5555 else {
5556 authResult = Authenticator.FAILURE;
5557 }
5558 }
5559
5560
5561
5562 if (authResult == Authenticator.SUCCESS) {
5563 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5564 authResult = AuthPipeline.authenticateByEmailAddress(
5565 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5566 headerMap, parameterMap);
5567 }
5568 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5569 authResult = AuthPipeline.authenticateByScreenName(
5570 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5571 headerMap, parameterMap);
5572 }
5573 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5574 authResult = AuthPipeline.authenticateByUserId(
5575 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5576 headerMap, parameterMap);
5577 }
5578 }
5579
5580 if (authResult == Authenticator.SUCCESS) {
5581 if (resultsMap != null) {
5582 resultsMap.put("userId", user.getUserId());
5583 }
5584
5585
5586
5587 if (skipLiferayCheck ||
5588 !PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK ||
5589 Validator.isNull(user.getDigest())) {
5590
5591 String digest = user.getDigest(password);
5592
5593 user.setDigest(digest);
5594
5595 userPersistence.update(user);
5596 }
5597 }
5598
5599
5600
5601 if (authResult == Authenticator.FAILURE) {
5602 try {
5603 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5604 AuthPipeline.onFailureByEmailAddress(
5605 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5606 parameterMap);
5607 }
5608 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5609 AuthPipeline.onFailureByScreenName(
5610 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5611 parameterMap);
5612 }
5613 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5614 AuthPipeline.onFailureByUserId(
5615 PropsKeys.AUTH_FAILURE, companyId, userId, headerMap,
5616 parameterMap);
5617 }
5618
5619 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5620
5621 if (user == null) {
5622 return Authenticator.DNE;
5623 }
5624
5625
5626
5627 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5628 user.getCompanyId())) {
5629
5630 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5631
5632 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5633
5634 int failedLoginAttempts = user.getFailedLoginAttempts();
5635 int maxFailures = passwordPolicy.getMaxFailure();
5636
5637 if ((failedLoginAttempts >= maxFailures) &&
5638 (maxFailures != 0)) {
5639
5640 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5641 AuthPipeline.onMaxFailuresByEmailAddress(
5642 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5643 headerMap, parameterMap);
5644 }
5645 else if (authType.equals(
5646 CompanyConstants.AUTH_TYPE_SN)) {
5647
5648 AuthPipeline.onMaxFailuresByScreenName(
5649 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5650 headerMap, parameterMap);
5651 }
5652 else if (authType.equals(
5653 CompanyConstants.AUTH_TYPE_ID)) {
5654
5655 AuthPipeline.onMaxFailuresByUserId(
5656 PropsKeys.AUTH_MAX_FAILURES, companyId, userId,
5657 headerMap, parameterMap);
5658 }
5659 }
5660 }
5661 }
5662 catch (Exception e) {
5663 _log.error(e, e);
5664 }
5665 }
5666
5667
5668
5669 return authResult;
5670 }
5671
5672 protected Date getBirthday(
5673 int birthdayMonth, int birthdayDay, int birthdayYear)
5674 throws PortalException {
5675
5676 Date birthday = PortalUtil.getDate(
5677 birthdayMonth, birthdayDay, birthdayYear,
5678 ContactBirthdayException.class);
5679
5680 Date now = new Date();
5681
5682 if (birthday.after(now)) {
5683 throw new ContactBirthdayException();
5684 }
5685
5686 return birthday;
5687 }
5688
5689 protected String getLogin(String login) {
5690 return StringUtil.lowerCase(StringUtil.trim(login));
5691 }
5692
5693 protected long[] getUserIds(List<User> users) {
5694 long[] userIds = new long[users.size()];
5695
5696 for (int i = 0; i < users.size(); i++) {
5697 User user = users.get(i);
5698
5699 userIds[i] = user.getUserId();
5700 }
5701
5702 return userIds;
5703 }
5704
5705 protected void reindex(final User user) {
5706 final Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5707 User.class);
5708
5709 Callable<Void> callable = new ShardCallable<Void>(
5710 user.getCompanyId()) {
5711
5712 @Override
5713 protected Void doCall() throws Exception {
5714 indexer.reindex(user);
5715
5716 return null;
5717 }
5718
5719 };
5720
5721 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
5722 }
5723
5724 protected Hits search(
5725 long companyId, String firstName, String middleName,
5726 String lastName, String fullName, String screenName,
5727 String emailAddress, String street, String city, String zip,
5728 String region, String country, int status,
5729 LinkedHashMap<String, Object> params, boolean andSearch, int start,
5730 int end, Sort sort)
5731 throws SystemException {
5732
5733 try {
5734 SearchContext searchContext = new SearchContext();
5735
5736 searchContext.setAndSearch(andSearch);
5737
5738 Map<String, Serializable> attributes =
5739 new HashMap<String, Serializable>();
5740
5741 attributes.put("city", city);
5742 attributes.put("country", country);
5743 attributes.put("emailAddress", emailAddress);
5744 attributes.put("firstName", firstName);
5745 attributes.put("fullName", fullName);
5746 attributes.put("lastName", lastName);
5747 attributes.put("middleName", middleName);
5748 attributes.put("params", params);
5749 attributes.put("region", region);
5750 attributes.put("screenName", screenName);
5751 attributes.put("street", street);
5752 attributes.put("status", status);
5753 attributes.put("zip", zip);
5754
5755 searchContext.setAttributes(attributes);
5756
5757 searchContext.setCompanyId(companyId);
5758 searchContext.setEnd(end);
5759
5760 if (params != null) {
5761 String keywords = (String)params.remove("keywords");
5762
5763 if (Validator.isNotNull(keywords)) {
5764 searchContext.setKeywords(keywords);
5765 }
5766 }
5767
5768 QueryConfig queryConfig = new QueryConfig();
5769
5770 queryConfig.setHighlightEnabled(false);
5771 queryConfig.setScoreEnabled(false);
5772
5773 searchContext.setQueryConfig(queryConfig);
5774
5775 if (sort != null) {
5776 searchContext.setSorts(sort);
5777 }
5778
5779 searchContext.setStart(start);
5780
5781 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5782 User.class);
5783
5784 return indexer.search(searchContext);
5785 }
5786 catch (Exception e) {
5787 throw new SystemException(e);
5788 }
5789 }
5790
5791 protected void sendEmail(
5792 User user, String password, ServiceContext serviceContext)
5793 throws SystemException {
5794
5795 if (!PrefsPropsUtil.getBoolean(
5796 user.getCompanyId(),
5797 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
5798
5799 return;
5800 }
5801
5802 String fromName = PrefsPropsUtil.getString(
5803 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
5804 String fromAddress = PrefsPropsUtil.getString(
5805 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
5806
5807 String toName = user.getFullName();
5808 String toAddress = user.getEmailAddress();
5809
5810 String subject = PrefsPropsUtil.getContent(
5811 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
5812
5813 String body = null;
5814
5815 if (Validator.isNotNull(password)) {
5816 body = PrefsPropsUtil.getContent(
5817 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
5818 }
5819 else {
5820 body = PrefsPropsUtil.getContent(
5821 user.getCompanyId(),
5822 PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
5823 }
5824
5825 SubscriptionSender subscriptionSender = new SubscriptionSender();
5826
5827 subscriptionSender.setBody(body);
5828 subscriptionSender.setCompanyId(user.getCompanyId());
5829 subscriptionSender.setContextAttributes(
5830 "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
5831 "[$USER_SCREENNAME$]", user.getScreenName());
5832 subscriptionSender.setFrom(fromAddress, fromName);
5833 subscriptionSender.setHtmlFormat(true);
5834 subscriptionSender.setMailId(
5835 "user", user.getUserId(), System.currentTimeMillis(),
5836 PwdGenerator.getPassword());
5837 subscriptionSender.setServiceContext(serviceContext);
5838 subscriptionSender.setSubject(subject);
5839 subscriptionSender.setUserId(user.getUserId());
5840
5841 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
5842
5843 subscriptionSender.flushNotificationsAsync();
5844 }
5845
5846 protected void setEmailAddress(
5847 User user, String password, String firstName, String middleName,
5848 String lastName, String emailAddress)
5849 throws PortalException, SystemException {
5850
5851 if (StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
5852 return;
5853 }
5854
5855 long userId = user.getUserId();
5856
5857
5858
5859 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
5860 Validator.isNotNull(password)) {
5861
5862 mailService.addUser(
5863 user.getCompanyId(), userId, password, firstName, middleName,
5864 lastName, emailAddress);
5865 }
5866
5867
5868
5869 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
5870 mailService.updateEmailAddress(
5871 user.getCompanyId(), userId, emailAddress);
5872 }
5873
5874
5875
5876 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
5877 mailService.deleteEmailAddress(user.getCompanyId(), userId);
5878 }
5879
5880 user.setEmailAddress(emailAddress);
5881 user.setDigest(StringPool.BLANK);
5882 }
5883
5884 protected void updateGroups(
5885 long userId, long[] newGroupIds, ServiceContext serviceContext,
5886 boolean indexingEnabled)
5887 throws PortalException, SystemException {
5888
5889 if (newGroupIds == null) {
5890 return;
5891 }
5892
5893 List<Group> oldGroups = userPersistence.getGroups(userId);
5894
5895 Set<Long> oldGroupIds = new HashSet<Long>(oldGroups.size());
5896
5897 for (Group oldGroup : oldGroups) {
5898 long oldGroupId = oldGroup.getGroupId();
5899
5900 oldGroupIds.add(oldGroupId);
5901
5902 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
5903 unsetGroupUsers(
5904 oldGroupId, new long[] {userId}, serviceContext);
5905 }
5906 }
5907
5908 for (long newGroupId : newGroupIds) {
5909 if (!oldGroupIds.contains(newGroupId)) {
5910 addGroupUsers(newGroupId, new long[] {userId});
5911 }
5912 }
5913
5914 if (indexingEnabled) {
5915 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5916 User.class);
5917
5918 indexer.reindex(new long[] {userId});
5919 }
5920
5921 PermissionCacheUtil.clearCache(userId);
5922 }
5923
5924 protected void updateOrganizations(
5925 long userId, long[] newOrganizationIds, boolean indexingEnabled)
5926 throws PortalException, SystemException {
5927
5928 if (newOrganizationIds == null) {
5929 return;
5930 }
5931
5932 List<Organization> oldOrganizations = userPersistence.getOrganizations(
5933 userId);
5934
5935 Set<Long> oldOrganizationIds = new HashSet<Long>(
5936 oldOrganizations.size());
5937
5938 for (Organization oldOrganization : oldOrganizations) {
5939 long oldOrganizationId = oldOrganization.getOrganizationId();
5940
5941 oldOrganizationIds.add(oldOrganizationId);
5942
5943 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
5944 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
5945 }
5946 }
5947
5948 for (long newOrganizationId : newOrganizationIds) {
5949 if (!oldOrganizationIds.contains(newOrganizationId)) {
5950 addOrganizationUsers(newOrganizationId, new long[] {userId});
5951 }
5952 }
5953
5954 if (indexingEnabled) {
5955 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5956 User.class);
5957
5958 indexer.reindex(new long[] {userId});
5959 }
5960
5961 PermissionCacheUtil.clearCache(userId);
5962 }
5963
5964 protected void updateUserGroupRoles(
5965 User user, long[] groupIds, long[] organizationIds,
5966 List<UserGroupRole> userGroupRoles,
5967 List<UserGroupRole> previousUserGroupRoles)
5968 throws PortalException, SystemException {
5969
5970 if (userGroupRoles == null) {
5971 return;
5972 }
5973
5974 userGroupRoles = new ArrayList<UserGroupRole>(userGroupRoles);
5975
5976 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
5977 if (userGroupRoles.contains(userGroupRole)) {
5978 userGroupRoles.remove(userGroupRole);
5979 }
5980 else {
5981 userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
5982 }
5983 }
5984
5985 if (userGroupRoles.isEmpty()) {
5986 return;
5987 }
5988
5989 long[] validGroupIds = null;
5990
5991 if (groupIds != null) {
5992 validGroupIds = ArrayUtil.clone(groupIds);
5993 }
5994 else {
5995 validGroupIds = user.getGroupIds();
5996 }
5997
5998 if (organizationIds == null) {
5999 organizationIds = user.getOrganizationIds();
6000 }
6001
6002 long[] organizationGroupIds = new long[organizationIds.length];
6003
6004 for (int i = 0; i < organizationIds.length; i++) {
6005 long organizationId = organizationIds[i];
6006
6007 Organization organization =
6008 organizationPersistence.findByPrimaryKey(organizationId);
6009
6010 organizationGroupIds[i] = organization.getGroupId();
6011 }
6012
6013 validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
6014
6015 Arrays.sort(validGroupIds);
6016
6017 for (UserGroupRole userGroupRole : userGroupRoles) {
6018 if (Arrays.binarySearch(
6019 validGroupIds, userGroupRole.getGroupId()) >= 0) {
6020
6021 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
6022 }
6023 }
6024 }
6025
6026 protected void validate(
6027 long companyId, long userId, boolean autoPassword, String password1,
6028 String password2, boolean autoScreenName, String screenName,
6029 String emailAddress, String openId, String firstName,
6030 String middleName, String lastName, long[] organizationIds)
6031 throws PortalException, SystemException {
6032
6033 validateCompanyMaxUsers(companyId);
6034
6035 if (!autoScreenName) {
6036 validateScreenName(companyId, userId, screenName);
6037 }
6038
6039 if (!autoPassword) {
6040 PasswordPolicy passwordPolicy =
6041 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
6042
6043 PwdToolkitUtil.validate(
6044 companyId, 0, password1, password2, passwordPolicy);
6045 }
6046
6047 validateEmailAddress(companyId, emailAddress);
6048
6049 if (Validator.isNotNull(emailAddress)) {
6050 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
6051
6052 if ((user != null) && (user.getUserId() != userId)) {
6053 throw new DuplicateUserEmailAddressException(
6054 "{userId=" + userId + "}");
6055 }
6056 }
6057
6058 validateOpenId(companyId, userId, openId);
6059
6060 validateFullName(companyId, firstName, middleName, lastName);
6061
6062 if (organizationIds != null) {
6063 for (long organizationId : organizationIds) {
6064 Organization organization =
6065 organizationPersistence.fetchByPrimaryKey(organizationId);
6066
6067 if (organization == null) {
6068 throw new NoSuchOrganizationException(
6069 "{organizationId=" + organizationId + "}");
6070 }
6071 }
6072 }
6073 }
6074
6075 protected void validate(
6076 long userId, String screenName, String emailAddress, String openId,
6077 String firstName, String middleName, String lastName, String smsSn)
6078 throws PortalException, SystemException {
6079
6080 User user = userPersistence.findByPrimaryKey(userId);
6081
6082 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
6083 validateScreenName(user.getCompanyId(), userId, screenName);
6084 }
6085
6086 validateEmailAddress(user.getCompanyId(), emailAddress);
6087
6088 validateOpenId(user.getCompanyId(), userId, openId);
6089
6090 if (!user.isDefaultUser()) {
6091 if (Validator.isNotNull(emailAddress) &&
6092 !StringUtil.equalsIgnoreCase(
6093 user.getEmailAddress(), emailAddress)) {
6094
6095 if (userPersistence.fetchByC_EA(
6096 user.getCompanyId(), emailAddress) != null) {
6097
6098 throw new DuplicateUserEmailAddressException(
6099 "{userId=" + userId + "}");
6100 }
6101 }
6102
6103 validateFullName(
6104 user.getCompanyId(), firstName, middleName, lastName);
6105 }
6106
6107 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
6108 throw new UserSmsException();
6109 }
6110 }
6111
6112 protected void validateCompanyMaxUsers(long companyId)
6113 throws PortalException, SystemException {
6114
6115 Company company = companyPersistence.findByPrimaryKey(companyId);
6116
6117 if (company.isSystem() || (company.getMaxUsers() == 0)) {
6118 return;
6119 }
6120
6121 int userCount = searchCount(
6122 companyId, null, WorkflowConstants.STATUS_APPROVED, null);
6123
6124 if (userCount >= company.getMaxUsers()) {
6125 throw new CompanyMaxUsersException();
6126 }
6127 }
6128
6129 protected void validateEmailAddress(long companyId, String emailAddress)
6130 throws PortalException, SystemException {
6131
6132 if (Validator.isNull(emailAddress) &&
6133 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
6134
6135 return;
6136 }
6137
6138 EmailAddressValidator emailAddressValidator =
6139 EmailAddressValidatorFactory.getInstance();
6140
6141 if (!emailAddressValidator.validate(companyId, emailAddress)) {
6142 throw new UserEmailAddressException();
6143 }
6144
6145 String pop3User = PrefsPropsUtil.getString(
6146 PropsKeys.MAIL_SESSION_MAIL_POP3_USER,
6147 PropsValues.MAIL_SESSION_MAIL_POP3_USER);
6148
6149 if (StringUtil.equalsIgnoreCase(emailAddress, pop3User)) {
6150 throw new ReservedUserEmailAddressException();
6151 }
6152
6153 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
6154 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
6155 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
6156
6157 for (String reservedEmailAddress : reservedEmailAddresses) {
6158 if (StringUtil.equalsIgnoreCase(
6159 emailAddress, reservedEmailAddress)) {
6160
6161 throw new ReservedUserEmailAddressException();
6162 }
6163 }
6164 }
6165
6166 protected void validateEmailAddress(
6167 User user, String emailAddress1, String emailAddress2)
6168 throws PortalException, SystemException {
6169
6170 if (!emailAddress1.equals(emailAddress2)) {
6171 throw new UserEmailAddressException();
6172 }
6173
6174 validateEmailAddress(user.getCompanyId(), emailAddress1);
6175 validateEmailAddress(user.getCompanyId(), emailAddress2);
6176
6177 if (!StringUtil.equalsIgnoreCase(
6178 emailAddress1, user.getEmailAddress())) {
6179
6180 if (userPersistence.fetchByC_EA(
6181 user.getCompanyId(), emailAddress1) != null) {
6182
6183 throw new DuplicateUserEmailAddressException(
6184 "{userId=" + user.getUserId() + "}");
6185 }
6186 }
6187 }
6188
6189 protected void validateFullName(
6190 long companyId, String firstName, String middleName,
6191 String lastName)
6192 throws PortalException, SystemException {
6193
6194 if (Validator.isNull(firstName)) {
6195 throw new ContactFirstNameException();
6196 }
6197 else if (Validator.isNull(lastName) &&
6198 PrefsPropsUtil.getBoolean(
6199 companyId, PropsKeys.USERS_LAST_NAME_REQUIRED,
6200 PropsValues.USERS_LAST_NAME_REQUIRED)) {
6201
6202 throw new ContactLastNameException();
6203 }
6204
6205 FullNameValidator fullNameValidator =
6206 FullNameValidatorFactory.getInstance();
6207
6208 if (!fullNameValidator.validate(
6209 companyId, firstName, middleName, lastName)) {
6210
6211 throw new ContactFullNameException();
6212 }
6213 }
6214
6215 protected void validateOpenId(long companyId, long userId, String openId)
6216 throws PortalException, SystemException {
6217
6218 if (Validator.isNull(openId)) {
6219 return;
6220 }
6221
6222 User user = userPersistence.fetchByC_O(companyId, openId);
6223
6224 if ((user != null) && (user.getUserId() != userId)) {
6225 throw new DuplicateOpenIdException("{userId=" + userId + "}");
6226 }
6227 }
6228
6229 protected void validatePassword(
6230 long companyId, long userId, String password1, String password2)
6231 throws PortalException, SystemException {
6232
6233 if (Validator.isNull(password1) || Validator.isNull(password2)) {
6234 throw new UserPasswordException(
6235 UserPasswordException.PASSWORD_INVALID);
6236 }
6237
6238 if (!password1.equals(password2)) {
6239 throw new UserPasswordException(
6240 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
6241 }
6242
6243 PasswordPolicy passwordPolicy =
6244 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
6245
6246 PwdToolkitUtil.validate(
6247 companyId, userId, password1, password2, passwordPolicy);
6248 }
6249
6250 protected void validateReminderQuery(String question, String answer)
6251 throws PortalException {
6252
6253 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
6254 return;
6255 }
6256
6257 if (Validator.isNull(question)) {
6258 throw new UserReminderQueryException("Question is null");
6259 }
6260
6261 if (Validator.isNull(answer)) {
6262 throw new UserReminderQueryException("Answer is null");
6263 }
6264 }
6265
6266 protected void validateScreenName(
6267 long companyId, long userId, String screenName)
6268 throws PortalException, SystemException {
6269
6270 if (Validator.isNull(screenName)) {
6271 throw new UserScreenNameException();
6272 }
6273
6274 ScreenNameValidator screenNameValidator =
6275 ScreenNameValidatorFactory.getInstance();
6276
6277 if (!screenNameValidator.validate(companyId, screenName)) {
6278 throw new UserScreenNameException();
6279 }
6280
6281 if (Validator.isNumber(screenName)) {
6282 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
6283 throw new UserScreenNameException();
6284 }
6285
6286 if (!screenName.equals(String.valueOf(userId))) {
6287 Group group = groupPersistence.fetchByPrimaryKey(
6288 GetterUtil.getLong(screenName));
6289
6290 if (group != null) {
6291 throw new UserScreenNameException();
6292 }
6293 }
6294 }
6295
6296 for (char c : screenName.toCharArray()) {
6297 if (!Validator.isChar(c) && !Validator.isDigit(c) &&
6298 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
6299 (c != CharPool.UNDERLINE)) {
6300
6301 throw new UserScreenNameException();
6302 }
6303 }
6304
6305 String[] anonymousNames = BaseServiceImpl.ANONYMOUS_NAMES;
6306
6307 for (String anonymousName : anonymousNames) {
6308 if (StringUtil.equalsIgnoreCase(screenName, anonymousName)) {
6309 throw new UserScreenNameException();
6310 }
6311 }
6312
6313 User user = userPersistence.fetchByC_SN(companyId, screenName);
6314
6315 if ((user != null) && (user.getUserId() != userId)) {
6316 throw new DuplicateUserScreenNameException(
6317 "{userId=" + userId + "}");
6318 }
6319
6320 String friendlyURL = StringPool.SLASH + screenName;
6321
6322 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
6323
6324 if ((group != null) && (group.getClassPK() != userId)) {
6325 throw new GroupFriendlyURLException(
6326 GroupFriendlyURLException.DUPLICATE);
6327 }
6328
6329 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
6330
6331 if (exceptionType != -1) {
6332 throw new UserScreenNameException(
6333 new GroupFriendlyURLException(exceptionType));
6334 }
6335
6336 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
6337 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
6338 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
6339
6340 for (String reservedScreenName : reservedScreenNames) {
6341 if (StringUtil.equalsIgnoreCase(screenName, reservedScreenName)) {
6342 throw new ReservedUserScreenNameException();
6343 }
6344 }
6345 }
6346
6347 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
6348
6349 private Map<Long, User> _defaultUsers = new ConcurrentHashMap<Long, User>();
6350
6351 }