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.orm.QueryUtil;
051 import com.liferay.portal.kernel.dao.shard.ShardCallable;
052 import com.liferay.portal.kernel.exception.PortalException;
053 import com.liferay.portal.kernel.exception.SystemException;
054 import com.liferay.portal.kernel.image.ImageBag;
055 import com.liferay.portal.kernel.image.ImageToolUtil;
056 import com.liferay.portal.kernel.language.LanguageUtil;
057 import com.liferay.portal.kernel.log.Log;
058 import com.liferay.portal.kernel.log.LogFactoryUtil;
059 import com.liferay.portal.kernel.messaging.DestinationNames;
060 import com.liferay.portal.kernel.messaging.Message;
061 import com.liferay.portal.kernel.messaging.MessageBusUtil;
062 import com.liferay.portal.kernel.search.Hits;
063 import com.liferay.portal.kernel.search.Indexer;
064 import com.liferay.portal.kernel.search.IndexerRegistryUtil;
065 import com.liferay.portal.kernel.search.QueryConfig;
066 import com.liferay.portal.kernel.search.SearchContext;
067 import com.liferay.portal.kernel.search.Sort;
068 import com.liferay.portal.kernel.spring.aop.Skip;
069 import com.liferay.portal.kernel.transaction.Propagation;
070 import com.liferay.portal.kernel.transaction.TransactionCommitCallbackRegistryUtil;
071 import com.liferay.portal.kernel.transaction.Transactional;
072 import com.liferay.portal.kernel.util.ArrayUtil;
073 import com.liferay.portal.kernel.util.CharPool;
074 import com.liferay.portal.kernel.util.Digester;
075 import com.liferay.portal.kernel.util.DigesterUtil;
076 import com.liferay.portal.kernel.util.GetterUtil;
077 import com.liferay.portal.kernel.util.KeyValuePair;
078 import com.liferay.portal.kernel.util.ListUtil;
079 import com.liferay.portal.kernel.util.LocaleUtil;
080 import com.liferay.portal.kernel.util.OrderByComparator;
081 import com.liferay.portal.kernel.util.ParamUtil;
082 import com.liferay.portal.kernel.util.PropsKeys;
083 import com.liferay.portal.kernel.util.SetUtil;
084 import com.liferay.portal.kernel.util.StringBundler;
085 import com.liferay.portal.kernel.util.StringPool;
086 import com.liferay.portal.kernel.util.StringUtil;
087 import com.liferay.portal.kernel.util.UnicodeProperties;
088 import com.liferay.portal.kernel.util.Validator;
089 import com.liferay.portal.kernel.workflow.WorkflowConstants;
090 import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil;
091 import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
092 import com.liferay.portal.model.Account;
093 import com.liferay.portal.model.Company;
094 import com.liferay.portal.model.CompanyConstants;
095 import com.liferay.portal.model.Contact;
096 import com.liferay.portal.model.ContactConstants;
097 import com.liferay.portal.model.Group;
098 import com.liferay.portal.model.GroupConstants;
099 import com.liferay.portal.model.Layout;
100 import com.liferay.portal.model.Organization;
101 import com.liferay.portal.model.PasswordPolicy;
102 import com.liferay.portal.model.ResourceConstants;
103 import com.liferay.portal.model.Role;
104 import com.liferay.portal.model.RoleConstants;
105 import com.liferay.portal.model.Team;
106 import com.liferay.portal.model.Ticket;
107 import com.liferay.portal.model.TicketConstants;
108 import com.liferay.portal.model.User;
109 import com.liferay.portal.model.UserGroup;
110 import com.liferay.portal.model.UserGroupRole;
111 import com.liferay.portal.model.impl.LayoutImpl;
112 import com.liferay.portal.model.impl.UserCacheModel;
113 import com.liferay.portal.model.impl.UserImpl;
114 import com.liferay.portal.security.auth.AuthPipeline;
115 import com.liferay.portal.security.auth.Authenticator;
116 import com.liferay.portal.security.auth.EmailAddressGenerator;
117 import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
118 import com.liferay.portal.security.auth.EmailAddressValidator;
119 import com.liferay.portal.security.auth.EmailAddressValidatorFactory;
120 import com.liferay.portal.security.auth.FullNameGenerator;
121 import com.liferay.portal.security.auth.FullNameGeneratorFactory;
122 import com.liferay.portal.security.auth.FullNameValidator;
123 import com.liferay.portal.security.auth.FullNameValidatorFactory;
124 import com.liferay.portal.security.auth.PrincipalException;
125 import com.liferay.portal.security.auth.ScreenNameGenerator;
126 import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
127 import com.liferay.portal.security.auth.ScreenNameValidator;
128 import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
129 import com.liferay.portal.security.ldap.LDAPSettingsUtil;
130 import com.liferay.portal.security.permission.ActionKeys;
131 import com.liferay.portal.security.permission.PermissionCacheUtil;
132 import com.liferay.portal.security.permission.PermissionChecker;
133 import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil;
134 import com.liferay.portal.security.pwd.PasswordEncryptorUtil;
135 import com.liferay.portal.security.pwd.PwdAuthenticator;
136 import com.liferay.portal.security.pwd.PwdToolkitUtil;
137 import com.liferay.portal.security.pwd.RegExpToolkit;
138 import com.liferay.portal.service.BaseServiceImpl;
139 import com.liferay.portal.service.ClassNameLocalServiceUtil;
140 import com.liferay.portal.service.PortalPreferencesLocalServiceUtil;
141 import com.liferay.portal.service.ServiceContext;
142 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
143 import com.liferay.portal.service.permission.GroupPermissionUtil;
144 import com.liferay.portal.util.PortalUtil;
145 import com.liferay.portal.util.PortletKeys;
146 import com.liferay.portal.util.PrefsPropsUtil;
147 import com.liferay.portal.util.PropsValues;
148 import com.liferay.portal.util.SessionClicks;
149 import com.liferay.portal.util.SubscriptionSender;
150 import com.liferay.portlet.PortalPreferences;
151 import com.liferay.portlet.PortletPreferencesFactoryImpl;
152 import com.liferay.portlet.documentlibrary.ImageSizeException;
153 import com.liferay.portlet.messageboards.model.MBMessage;
154 import com.liferay.portlet.social.model.SocialRelation;
155 import com.liferay.portlet.social.model.SocialRelationConstants;
156 import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
157 import com.liferay.util.Encryptor;
158 import com.liferay.util.EncryptorException;
159 import com.liferay.util.PwdGenerator;
160
161 import java.awt.image.RenderedImage;
162
163 import java.io.IOException;
164 import java.io.Serializable;
165
166 import java.util.ArrayList;
167 import java.util.Arrays;
168 import java.util.Calendar;
169 import java.util.Collections;
170 import java.util.Date;
171 import java.util.HashMap;
172 import java.util.HashSet;
173 import java.util.LinkedHashMap;
174 import java.util.List;
175 import java.util.Locale;
176 import java.util.Map;
177 import java.util.Set;
178 import java.util.concurrent.Callable;
179 import java.util.concurrent.ConcurrentHashMap;
180
181
193 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
194
195
209 @Override
210 public User addDefaultAdminUser(
211 long companyId, String screenName, String emailAddress,
212 Locale locale, String firstName, String middleName, String lastName)
213 throws PortalException, SystemException {
214
215 long creatorUserId = 0;
216 boolean autoPassword = false;
217 String password1 = PropsValues.DEFAULT_ADMIN_PASSWORD;
218 String password2 = password1;
219 boolean autoScreenName = false;
220
221 screenName = getLogin(screenName);
222
223 for (int i = 1;; i++) {
224 User screenNameUser = userPersistence.fetchByC_SN(
225 companyId, screenName);
226
227 if (screenNameUser == null) {
228 break;
229 }
230
231 screenName = screenName + i;
232 }
233
234 long facebookId = 0;
235 String openId = StringPool.BLANK;
236 int prefixId = 0;
237 int suffixId = 0;
238 boolean male = true;
239 int birthdayMonth = Calendar.JANUARY;
240 int birthdayDay = 1;
241 int birthdayYear = 1970;
242 String jobTitle = StringPool.BLANK;
243
244 Group guestGroup = groupLocalService.getGroup(
245 companyId, GroupConstants.GUEST);
246
247 long[] groupIds = {guestGroup.getGroupId()};
248
249 long[] organizationIds = null;
250
251 Role adminRole = roleLocalService.getRole(
252 companyId, RoleConstants.ADMINISTRATOR);
253
254 Role powerUserRole = roleLocalService.getRole(
255 companyId, RoleConstants.POWER_USER);
256
257 long[] roleIds = {adminRole.getRoleId(), powerUserRole.getRoleId()};
258
259 long[] userGroupIds = null;
260 boolean sendEmail = false;
261 ServiceContext serviceContext = new ServiceContext();
262
263 User defaultAdminUser = addUser(
264 creatorUserId, companyId, autoPassword, password1, password2,
265 autoScreenName, screenName, emailAddress, facebookId, openId,
266 locale, firstName, middleName, lastName, prefixId, suffixId, male,
267 birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
268 organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
269
270 updateEmailAddressVerified(defaultAdminUser.getUserId(), true);
271
272 updateLastLogin(
273 defaultAdminUser.getUserId(), defaultAdminUser.getLoginIP());
274
275 updatePasswordReset(defaultAdminUser.getUserId(), false);
276
277 return defaultAdminUser;
278 }
279
280
290 @Override
291 public void addDefaultGroups(long userId)
292 throws PortalException, SystemException {
293
294 User user = userPersistence.findByPrimaryKey(userId);
295
296 Set<Long> groupIdsSet = new HashSet<Long>();
297
298 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
299 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
300 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
301
302 for (String defaultGroupName : defaultGroupNames) {
303 Company company = companyPersistence.findByPrimaryKey(
304 user.getCompanyId());
305
306 Account account = company.getAccount();
307
308 if (StringUtil.equalsIgnoreCase(
309 defaultGroupName, account.getName())) {
310
311 defaultGroupName = GroupConstants.GUEST;
312 }
313
314 Group group = groupPersistence.fetchByC_N(
315 user.getCompanyId(), defaultGroupName);
316
317 if ((group != null) &&
318 !userPersistence.containsGroup(
319 userId, group.getGroupId())) {
320
321 groupIdsSet.add(group.getGroupId());
322 }
323 }
324
325 String[] defaultOrganizationGroupNames = PrefsPropsUtil.getStringArray(
326 user.getCompanyId(),
327 PropsKeys.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES,
328 StringPool.NEW_LINE,
329 PropsValues.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES);
330
331 for (String defaultOrganizationGroupName :
332 defaultOrganizationGroupNames) {
333
334 defaultOrganizationGroupName +=
335 GroupLocalServiceImpl.ORGANIZATION_NAME_SUFFIX;
336
337 Group group = groupPersistence.fetchByC_N(
338 user.getCompanyId(), defaultOrganizationGroupName);
339
340 if ((group != null) &&
341 !userPersistence.containsGroup(
342 userId, group.getGroupId())) {
343
344 groupIdsSet.add(group.getGroupId());
345 }
346 }
347
348 long[] groupIds = ArrayUtil.toArray(
349 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
350
351 groupLocalService.addUserGroups(userId, groupIds);
352 }
353
354
364 @Override
365 public void addDefaultRoles(long userId)
366 throws PortalException, SystemException {
367
368 User user = userPersistence.findByPrimaryKey(userId);
369
370 Set<Long> roleIdSet = new HashSet<Long>();
371
372 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
373 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
374 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
375
376 for (String defaultRoleName : defaultRoleNames) {
377 try {
378 Role role = rolePersistence.findByC_N(
379 user.getCompanyId(), defaultRoleName);
380
381 if (!userPersistence.containsRole(userId, role.getRoleId())) {
382 roleIdSet.add(role.getRoleId());
383 }
384 }
385 catch (NoSuchRoleException nsre) {
386 }
387 }
388
389 long[] roleIds = ArrayUtil.toArray(
390 roleIdSet.toArray(new Long[roleIdSet.size()]));
391
392 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
393
394 userPersistence.addRoles(userId, roleIds);
395 }
396
397
407 @Override
408 @SuppressWarnings("deprecation")
409 public void addDefaultUserGroups(long userId)
410 throws PortalException, SystemException {
411
412 User user = userPersistence.findByPrimaryKey(userId);
413
414 Set<Long> userGroupIdSet = new HashSet<Long>();
415
416 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
417 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
418 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
419
420 for (String defaultUserGroupName : defaultUserGroupNames) {
421 try {
422 UserGroup userGroup = userGroupPersistence.findByC_N(
423 user.getCompanyId(), defaultUserGroupName);
424
425 if (!userPersistence.containsUserGroup(
426 userId, userGroup.getUserGroupId())) {
427
428 userGroupIdSet.add(userGroup.getUserGroupId());
429 }
430 }
431 catch (NoSuchUserGroupException nsuge) {
432 }
433 }
434
435 long[] userGroupIds = ArrayUtil.toArray(
436 userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
437
438 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
439 for (long userGroupId : userGroupIds) {
440 userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
441 }
442 }
443
444 userPersistence.addUserGroups(userId, userGroupIds);
445 }
446
447
456 @Override
457 public void addGroupUsers(long groupId, long[] userIds)
458 throws PortalException, SystemException {
459
460 groupPersistence.addUsers(groupId, userIds);
461
462 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
463
464 indexer.reindex(userIds);
465
466 PermissionCacheUtil.clearCache(userIds);
467
468 addDefaultRolesAndTeams(groupId, userIds);
469 }
470
471
480 @Override
481 public void addOrganizationUsers(long organizationId, long[] userIds)
482 throws PortalException, SystemException {
483
484 organizationPersistence.addUsers(organizationId, userIds);
485
486 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
487
488 indexer.reindex(userIds);
489
490 PermissionCacheUtil.clearCache(userIds);
491 }
492
493
501 @Override
502 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
503 throws SystemException {
504
505 passwordPolicyRelLocalService.addPasswordPolicyRels(
506 passwordPolicyId, User.class.getName(), userIds);
507 }
508
509
518 @Override
519 public void addRoleUsers(long roleId, long[] userIds)
520 throws PortalException, SystemException {
521
522 rolePersistence.addUsers(roleId, userIds);
523
524 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
525
526 indexer.reindex(userIds);
527
528 PermissionCacheUtil.clearCache(userIds);
529 }
530
531
540 @Override
541 public void addTeamUsers(long teamId, long[] userIds)
542 throws PortalException, SystemException {
543
544 teamPersistence.addUsers(teamId, userIds);
545
546 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
547
548 indexer.reindex(userIds);
549
550 PermissionCacheUtil.clearCache(userIds);
551 }
552
553
601 @Override
602 public User addUser(
603 long creatorUserId, long companyId, boolean autoPassword,
604 String password1, String password2, boolean autoScreenName,
605 String screenName, String emailAddress, long facebookId,
606 String openId, Locale locale, String firstName, String middleName,
607 String lastName, int prefixId, int suffixId, boolean male,
608 int birthdayMonth, int birthdayDay, int birthdayYear,
609 String jobTitle, long[] groupIds, long[] organizationIds,
610 long[] roleIds, long[] userGroupIds, boolean sendEmail,
611 ServiceContext serviceContext)
612 throws PortalException, SystemException {
613
614 boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
615
616 try {
617 WorkflowThreadLocal.setEnabled(false);
618
619 if (serviceContext == null) {
620 serviceContext = new ServiceContext();
621 }
622
623 if (serviceContext.getWorkflowAction() !=
624 WorkflowConstants.ACTION_PUBLISH) {
625
626 serviceContext.setWorkflowAction(
627 WorkflowConstants.ACTION_PUBLISH);
628 }
629
630 return addUserWithWorkflow(
631 creatorUserId, companyId, autoPassword, password1, password2,
632 autoScreenName, screenName, emailAddress, facebookId, openId,
633 locale, firstName, middleName, lastName, prefixId, suffixId,
634 male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
635 groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
636 serviceContext);
637 }
638 finally {
639 WorkflowThreadLocal.setEnabled(workflowEnabled);
640 }
641 }
642
643
652 @Override
653 @SuppressWarnings("deprecation")
654 public void addUserGroupUsers(long userGroupId, long[] userIds)
655 throws PortalException, SystemException {
656
657 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
658 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
659 }
660
661 userGroupPersistence.addUsers(userGroupId, userIds);
662
663 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
664
665 indexer.reindex(userIds);
666
667 PermissionCacheUtil.clearCache(userIds);
668 }
669
670
718 @Override
719 @SuppressWarnings("deprecation")
720 public User addUserWithWorkflow(
721 long creatorUserId, long companyId, boolean autoPassword,
722 String password1, String password2, boolean autoScreenName,
723 String screenName, String emailAddress, long facebookId,
724 String openId, Locale locale, String firstName, String middleName,
725 String lastName, int prefixId, int suffixId, boolean male,
726 int birthdayMonth, int birthdayDay, int birthdayYear,
727 String jobTitle, long[] groupIds, long[] organizationIds,
728 long[] roleIds, long[] userGroupIds, boolean sendEmail,
729 ServiceContext serviceContext)
730 throws PortalException, SystemException {
731
732
733
734 Company company = companyPersistence.findByPrimaryKey(companyId);
735 screenName = getLogin(screenName);
736 openId = StringUtil.trim(openId);
737 Date now = new Date();
738
739 if (PrefsPropsUtil.getBoolean(
740 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
741
742 autoScreenName = true;
743 }
744
745
746
747 long userId = counterLocalService.increment();
748
749 EmailAddressGenerator emailAddressGenerator =
750 EmailAddressGeneratorFactory.getInstance();
751
752 if ((emailAddress == null) ||
753 emailAddressGenerator.isGenerated(emailAddress)) {
754
755 emailAddress = StringPool.BLANK;
756 }
757 else {
758 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
759 }
760
761 if (!PrefsPropsUtil.getBoolean(
762 companyId, PropsKeys.USERS_EMAIL_ADDRESS_REQUIRED) &&
763 Validator.isNull(emailAddress)) {
764
765 emailAddress = emailAddressGenerator.generate(companyId, userId);
766 }
767
768 validate(
769 companyId, userId, autoPassword, password1, password2,
770 autoScreenName, screenName, emailAddress, openId, firstName,
771 middleName, lastName, organizationIds);
772
773 if (!autoPassword) {
774 if (Validator.isNull(password1) || Validator.isNull(password2)) {
775 throw new UserPasswordException(
776 UserPasswordException.PASSWORD_INVALID);
777 }
778 }
779
780 if (autoScreenName) {
781 ScreenNameGenerator screenNameGenerator =
782 ScreenNameGeneratorFactory.getInstance();
783
784 try {
785 screenName = screenNameGenerator.generate(
786 companyId, userId, emailAddress);
787 }
788 catch (Exception e) {
789 throw new SystemException(e);
790 }
791 }
792
793 User defaultUser = getDefaultUser(companyId);
794
795 FullNameGenerator fullNameGenerator =
796 FullNameGeneratorFactory.getInstance();
797
798 String fullName = fullNameGenerator.getFullName(
799 firstName, middleName, lastName);
800
801 String greeting = LanguageUtil.format(
802 locale, "welcome-x", " " + fullName, false);
803
804 User user = userPersistence.create(userId);
805
806 if (serviceContext != null) {
807 String uuid = serviceContext.getUuid();
808
809 if (Validator.isNotNull(uuid)) {
810 user.setUuid(uuid);
811 }
812 }
813
814 user.setCompanyId(companyId);
815 user.setCreateDate(now);
816 user.setModifiedDate(now);
817 user.setDefaultUser(false);
818 user.setContactId(counterLocalService.increment());
819
820 if (Validator.isNotNull(password1)) {
821 user.setPassword(PasswordEncryptorUtil.encrypt(password1));
822 user.setPasswordUnencrypted(password1);
823 }
824
825 user.setPasswordEncrypted(true);
826
827 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
828
829 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
830 passwordPolicy.isChangeRequired()) {
831
832 user.setPasswordReset(true);
833 }
834 else {
835 user.setPasswordReset(false);
836 }
837
838 user.setDigest(StringPool.BLANK);
839 user.setScreenName(screenName);
840 user.setEmailAddress(emailAddress);
841 user.setFacebookId(facebookId);
842
843 Long ldapServerId = null;
844
845 if (serviceContext != null) {
846 ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
847 }
848
849 if (ldapServerId != null) {
850 user.setLdapServerId(ldapServerId);
851 }
852 else {
853 user.setLdapServerId(-1);
854 }
855
856 user.setOpenId(openId);
857 user.setLanguageId(LocaleUtil.toLanguageId(locale));
858 user.setTimeZoneId(defaultUser.getTimeZoneId());
859 user.setGreeting(greeting);
860 user.setFirstName(firstName);
861 user.setMiddleName(middleName);
862 user.setLastName(lastName);
863 user.setJobTitle(jobTitle);
864 user.setStatus(WorkflowConstants.STATUS_DRAFT);
865 user.setExpandoBridgeAttributes(serviceContext);
866
867 userPersistence.update(user, serviceContext);
868
869
870
871 String creatorUserName = StringPool.BLANK;
872
873 if (creatorUserId <= 0) {
874 creatorUserId = user.getUserId();
875
876
877
878
879
880 }
881 else {
882 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
883
884 creatorUserName = creatorUser.getFullName();
885 }
886
887 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
888
889 Contact contact = contactPersistence.create(user.getContactId());
890
891 contact.setCompanyId(user.getCompanyId());
892 contact.setUserId(creatorUserId);
893 contact.setUserName(creatorUserName);
894 contact.setCreateDate(now);
895 contact.setModifiedDate(now);
896 contact.setClassName(User.class.getName());
897 contact.setClassPK(user.getUserId());
898 contact.setAccountId(company.getAccountId());
899 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
900 contact.setEmailAddress(user.getEmailAddress());
901 contact.setFirstName(firstName);
902 contact.setMiddleName(middleName);
903 contact.setLastName(lastName);
904 contact.setPrefixId(prefixId);
905 contact.setSuffixId(suffixId);
906 contact.setMale(male);
907 contact.setBirthday(birthday);
908 contact.setJobTitle(jobTitle);
909
910 contactPersistence.update(contact, serviceContext);
911
912
913
914 groupLocalService.addGroup(
915 user.getUserId(), GroupConstants.DEFAULT_PARENT_GROUP_ID,
916 User.class.getName(), user.getUserId(), null, null, 0,
917 StringPool.SLASH + screenName, false, true, null);
918
919
920
921 if (groupIds != null) {
922 List<Group> groups = new ArrayList<Group>();
923
924 for (long groupId : groupIds) {
925 Group group = groupLocalService.fetchGroup(groupId);
926
927 if (group != null) {
928 groups.add(group);
929 }
930 else {
931 if (_log.isWarnEnabled()) {
932 _log.warn("Group " + groupId + " does not exist");
933 }
934 }
935 }
936
937 groupLocalService.addUserGroups(userId, groups);
938 }
939
940 addDefaultGroups(userId);
941
942
943
944 updateOrganizations(userId, organizationIds, false);
945
946
947
948 if (roleIds != null) {
949 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
950
951 userPersistence.setRoles(userId, roleIds);
952 }
953
954 addDefaultRoles(userId);
955
956
957
958 if (userGroupIds != null) {
959 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
960 for (long userGroupId : userGroupIds) {
961 userGroupLocalService.copyUserGroupLayouts(
962 userGroupId, new long[] {userId});
963 }
964 }
965
966 userPersistence.setUserGroups(userId, userGroupIds);
967 }
968
969 addDefaultUserGroups(userId);
970
971
972
973 resourceLocalService.addResources(
974 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
975 false, false, false);
976
977
978
979 if (serviceContext != null) {
980 updateAsset(
981 creatorUserId, user, serviceContext.getAssetCategoryIds(),
982 serviceContext.getAssetTagNames());
983 }
984
985
986
987 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
988 reindex(user);
989 }
990
991
992
993 long workflowUserId = creatorUserId;
994
995 if (workflowUserId == userId) {
996 workflowUserId = defaultUser.getUserId();
997 }
998
999 ServiceContext workflowServiceContext = serviceContext;
1000
1001 if (workflowServiceContext == null) {
1002 workflowServiceContext = new ServiceContext();
1003 }
1004
1005 workflowServiceContext.setAttribute("autoPassword", autoPassword);
1006 workflowServiceContext.setAttribute("passwordUnencrypted", password1);
1007 workflowServiceContext.setAttribute("sendEmail", sendEmail);
1008
1009 WorkflowHandlerRegistryUtil.startWorkflowInstance(
1010 companyId, workflowUserId, User.class.getName(), userId, user,
1011 workflowServiceContext);
1012
1013 if (serviceContext != null) {
1014 String passwordUnencrypted = (String)serviceContext.getAttribute(
1015 "passwordUnencrypted");
1016
1017 if (Validator.isNotNull(passwordUnencrypted)) {
1018 user.setPasswordUnencrypted(passwordUnencrypted);
1019 }
1020 }
1021
1022 return user;
1023 }
1024
1025 @Override
1026 public void afterPropertiesSet() {
1027 super.afterPropertiesSet();
1028
1029 PortalCache<Serializable, Serializable> portalCache =
1030 EntityCacheUtil.getPortalCache(UserImpl.class);
1031
1032 PortalCacheMapSynchronizeUtil.synchronize(
1033 portalCache, _defaultUsers,
1034 new Synchronizer<Serializable, Serializable>() {
1035
1036 @Override
1037 public void onSynchronize(
1038 Map<? extends Serializable, ? extends Serializable> map,
1039 Serializable key, Serializable value) {
1040
1041 if (!(value instanceof UserCacheModel)) {
1042 return;
1043 }
1044
1045 UserCacheModel userCacheModel = (UserCacheModel)value;
1046
1047 if (userCacheModel.defaultUser) {
1048 _defaultUsers.remove(userCacheModel.companyId);
1049 }
1050 }
1051
1052 });
1053 }
1054
1055
1079 @Override
1080 public int authenticateByEmailAddress(
1081 long companyId, String emailAddress, String password,
1082 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1083 Map<String, Object> resultsMap)
1084 throws PortalException, SystemException {
1085
1086 return authenticate(
1087 companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
1088 headerMap, parameterMap, resultsMap);
1089 }
1090
1091
1115 @Override
1116 public int authenticateByScreenName(
1117 long companyId, String screenName, String password,
1118 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1119 Map<String, Object> resultsMap)
1120 throws PortalException, SystemException {
1121
1122 return authenticate(
1123 companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
1124 headerMap, parameterMap, resultsMap);
1125 }
1126
1127
1151 @Override
1152 public int authenticateByUserId(
1153 long companyId, long userId, String password,
1154 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1155 Map<String, Object> resultsMap)
1156 throws PortalException, SystemException {
1157
1158 return authenticate(
1159 companyId, String.valueOf(userId), password,
1160 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap, resultsMap);
1161 }
1162
1163
1203 @Override
1204 @Transactional(propagation = Propagation.SUPPORTS)
1205 public long authenticateForBasic(
1206 long companyId, String authType, String login, String password)
1207 throws PortalException, SystemException {
1208
1209 if (PropsValues.AUTH_LOGIN_DISABLED) {
1210 return 0;
1211 }
1212
1213 User user = null;
1214
1215 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1216 user = fetchUserByEmailAddress(companyId, login);
1217 }
1218 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1219 user = fetchUserByScreenName(companyId, login);
1220 }
1221 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1222 user = userPersistence.fetchByPrimaryKey(GetterUtil.getLong(login));
1223 }
1224
1225 if (user == null) {
1226 return 0;
1227 }
1228
1229 if (!isUserAllowedToAuthenticate(user)) {
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 resetFailedLoginAttempts(user);
1248
1249 return user.getUserId();
1250 }
1251
1252 handleAuthenticationFailure(
1253 login, authType, user, Collections.<String, String[]>emptyMap(),
1254 Collections.<String, String[]>emptyMap());
1255
1256 return 0;
1257 }
1258
1259
1277 @Override
1278 @Transactional(propagation = Propagation.SUPPORTS)
1279 public long authenticateForDigest(
1280 long companyId, String username, String realm, String nonce,
1281 String method, String uri, String response)
1282 throws PortalException, SystemException {
1283
1284 if (PropsValues.AUTH_LOGIN_DISABLED) {
1285 return 0;
1286 }
1287
1288
1289
1290 User user = fetchUserByEmailAddress(companyId, username);
1291
1292 if (user == null) {
1293 user = fetchUserByScreenName(companyId, username);
1294 }
1295
1296 if (user == null) {
1297 user = userPersistence.fetchByPrimaryKey(
1298 GetterUtil.getLong(username));
1299 }
1300
1301 if (user == null) {
1302 return 0;
1303 }
1304
1305 if (!isUserAllowedToAuthenticate(user)) {
1306 return 0;
1307 }
1308
1309
1310
1311 String digest = user.getDigest();
1312
1313 if (Validator.isNull(digest)) {
1314 _log.error(
1315 "User must first login through the portal " + user.getUserId());
1316
1317 return 0;
1318 }
1319
1320 String[] digestArray = StringUtil.split(user.getDigest());
1321
1322 for (String ha1 : digestArray) {
1323 String ha2 = DigesterUtil.digestHex(Digester.MD5, method, uri);
1324
1325 String curResponse = DigesterUtil.digestHex(
1326 Digester.MD5, ha1, nonce, ha2);
1327
1328 if (response.equals(curResponse)) {
1329 resetFailedLoginAttempts(user);
1330
1331 return user.getUserId();
1332 }
1333 }
1334
1335 Company company = companyPersistence.findByPrimaryKey(companyId);
1336
1337 handleAuthenticationFailure(
1338 username, company.getAuthType(), user,
1339 new HashMap<String, String[]>(), new HashMap<String, String[]>());
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
2041 @Override
2042 public User fetchUserByContactId(long contactId) throws SystemException {
2043 return userPersistence.fetchByContactId(contactId);
2044 }
2045
2046
2055 @Override
2056 public User fetchUserByEmailAddress(long companyId, String emailAddress)
2057 throws SystemException {
2058
2059 emailAddress = getLogin(emailAddress);
2060
2061 return userPersistence.fetchByC_EA(companyId, emailAddress);
2062 }
2063
2064
2073 @Override
2074 public User fetchUserByFacebookId(long companyId, long facebookId)
2075 throws SystemException {
2076
2077 return userPersistence.fetchByC_FID(companyId, facebookId);
2078 }
2079
2080
2088 @Override
2089 public User fetchUserById(long userId) throws SystemException {
2090 return userPersistence.fetchByPrimaryKey(userId);
2091 }
2092
2093
2102 @Override
2103 public User fetchUserByOpenId(long companyId, String openId)
2104 throws SystemException {
2105
2106 return userPersistence.fetchByC_O(companyId, openId);
2107 }
2108
2109
2118 @Override
2119 public User fetchUserByScreenName(long companyId, String screenName)
2120 throws SystemException {
2121
2122 screenName = getLogin(screenName);
2123
2124 return userPersistence.fetchByC_SN(companyId, screenName);
2125 }
2126
2127
2146 @Override
2147 public List<User> getCompanyUsers(long companyId, int start, int end)
2148 throws SystemException {
2149
2150 return userPersistence.findByCompanyId(companyId, start, end);
2151 }
2152
2153
2160 @Override
2161 public int getCompanyUsersCount(long companyId) throws SystemException {
2162 return userPersistence.countByCompanyId(companyId);
2163 }
2164
2165
2174 @Override
2175 @Skip
2176 public User getDefaultUser(long companyId)
2177 throws PortalException, SystemException {
2178
2179 User userModel = _defaultUsers.get(companyId);
2180
2181 if (userModel == null) {
2182 userModel = userLocalService.loadGetDefaultUser(companyId);
2183
2184 _defaultUsers.put(companyId, userModel);
2185 }
2186
2187 return userModel;
2188 }
2189
2190
2199 @Override
2200 @Skip
2201 public long getDefaultUserId(long companyId)
2202 throws PortalException, SystemException {
2203
2204 User user = getDefaultUser(companyId);
2205
2206 return user.getUserId();
2207 }
2208
2209
2216 @Override
2217 public long[] getGroupUserIds(long groupId) throws SystemException {
2218 return getUserIds(getGroupUsers(groupId));
2219 }
2220
2221
2231 @Override
2232 public int getGroupUsersCount(long groupId, int status)
2233 throws PortalException, SystemException {
2234
2235 Group group = groupPersistence.findByPrimaryKey(groupId);
2236
2237 LinkedHashMap<String, Object> params =
2238 new LinkedHashMap<String, Object>();
2239
2240 params.put("usersGroups", new Long(groupId));
2241
2242 return searchCount(group.getCompanyId(), null, status, params);
2243 }
2244
2245 @Override
2246 public List<User> getInheritedRoleUsers(
2247 long roleId, int start, int end, OrderByComparator obc)
2248 throws PortalException, SystemException {
2249
2250 Role role = rolePersistence.findByPrimaryKey(roleId);
2251
2252 LinkedHashMap<String, Object> params =
2253 new LinkedHashMap<String, Object>();
2254
2255 params.put("inherit", Boolean.TRUE);
2256 params.put("usersRoles", roleId);
2257
2258 return search(
2259 role.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2260 params, start, end, obc);
2261 }
2262
2263
2271 @Override
2272 public List<User> getNoAnnouncementsDeliveries(String type)
2273 throws SystemException {
2274
2275 return userFinder.findByNoAnnouncementsDeliveries(type);
2276 }
2277
2278
2284 @Override
2285 public List<User> getNoContacts() throws SystemException {
2286 return userFinder.findByNoContacts();
2287 }
2288
2289
2296 @Override
2297 public List<User> getNoGroups() throws SystemException {
2298 return userFinder.findByNoGroups();
2299 }
2300
2301
2308 @Override
2309 public long[] getOrganizationUserIds(long organizationId)
2310 throws SystemException {
2311
2312 return getUserIds(getOrganizationUsers(organizationId));
2313 }
2314
2315
2326 @Override
2327 public int getOrganizationUsersCount(long organizationId, int status)
2328 throws PortalException, SystemException {
2329
2330 Organization organization = organizationPersistence.findByPrimaryKey(
2331 organizationId);
2332
2333 LinkedHashMap<String, Object> params =
2334 new LinkedHashMap<String, Object>();
2335
2336 params.put("usersOrgs", new Long(organizationId));
2337
2338 return searchCount(organization.getCompanyId(), null, status, params);
2339 }
2340
2341
2348 @Override
2349 public long[] getRoleUserIds(long roleId) throws SystemException {
2350 return getUserIds(getRoleUsers(roleId));
2351 }
2352
2353
2363 @Override
2364 public int getRoleUsersCount(long roleId, int status)
2365 throws PortalException, SystemException {
2366
2367 Role role = rolePersistence.findByPrimaryKey(roleId);
2368
2369 LinkedHashMap<String, Object> params =
2370 new LinkedHashMap<String, Object>();
2371
2372 params.put("usersRoles", new Long(roleId));
2373
2374 return searchCount(role.getCompanyId(), null, status, params);
2375 }
2376
2377
2407 @Deprecated
2408 @Override
2409 public List<User> getSocialUsers(
2410 long userId, int socialRelationType, int start, int end,
2411 OrderByComparator obc)
2412 throws PortalException, SystemException {
2413
2414 return getSocialUsers(
2415 userId, socialRelationType, StringPool.EQUAL, start, end, obc);
2416 }
2417
2418
2445 @Deprecated
2446 @Override
2447 public List<User> getSocialUsers(
2448 long userId, int start, int end, OrderByComparator obc)
2449 throws PortalException, SystemException {
2450
2451 return getSocialUsers(
2452 userId, SocialRelationConstants.TYPE_UNI_ENEMY,
2453 StringPool.NOT_EQUAL, start, end, obc);
2454 }
2455
2456 @Override
2457 public List<User> getSocialUsers(
2458 long userId, int socialRelationType,
2459 String socialRelationTypeComparator, int start, int end,
2460 OrderByComparator obc)
2461 throws PortalException, SystemException {
2462
2463 if (!socialRelationTypeComparator.equals(StringPool.EQUAL) &&
2464 !socialRelationTypeComparator.equals(StringPool.NOT_EQUAL)) {
2465
2466 throw new IllegalArgumentException(
2467 "Invalid social relation type comparator " +
2468 socialRelationTypeComparator);
2469 }
2470
2471 if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS)) {
2472 List<SocialRelation> socialRelations =
2473 socialRelationPersistence.findByU1_T(
2474 userId, socialRelationType);
2475
2476 if (socialRelationTypeComparator.equals(StringPool.NOT_EQUAL)) {
2477 socialRelations = ListUtil.remove(
2478 socialRelationPersistence.findByUserId1(userId),
2479 socialRelations);
2480 }
2481
2482 List<User> users = new ArrayList<User>();
2483
2484 for (SocialRelation socialRelation : socialRelations) {
2485 User user = userPersistence.findByPrimaryKey(
2486 socialRelation.getUserId2());
2487
2488 if (user.isDefaultUser() ||
2489 (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {
2490
2491 continue;
2492 }
2493
2494 if (!users.contains(user)) {
2495 users.add(user);
2496 }
2497 }
2498
2499 if (obc != null) {
2500 users = ListUtil.sort(users, obc);
2501 }
2502
2503 return users;
2504 }
2505
2506 User user = userPersistence.findByPrimaryKey(userId);
2507
2508 return userFinder.findBySocialUsers(
2509 user.getCompanyId(), userId, socialRelationType,
2510 socialRelationTypeComparator, WorkflowConstants.STATUS_APPROVED,
2511 start, end, obc);
2512 }
2513
2514
2542 @Override
2543 public List<User> getSocialUsers(
2544 long userId1, long userId2, int socialRelationType, int start,
2545 int end, OrderByComparator obc)
2546 throws PortalException, SystemException {
2547
2548 User user1 = userPersistence.findByPrimaryKey(userId1);
2549
2550 LinkedHashMap<String, Object> params =
2551 new LinkedHashMap<String, Object>();
2552
2553 params.put(
2554 "socialMutualRelationType",
2555 new Long[] {userId1, new Long(socialRelationType), userId2,
2556 new Long(socialRelationType)});
2557
2558 return search(
2559 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2560 params, start, end, obc);
2561 }
2562
2563
2588 @Override
2589 public List<User> getSocialUsers(
2590 long userId1, long userId2, int start, int end,
2591 OrderByComparator obc)
2592 throws PortalException, SystemException {
2593
2594 User user1 = userPersistence.findByPrimaryKey(userId1);
2595
2596 LinkedHashMap<String, Object> params =
2597 new LinkedHashMap<String, Object>();
2598
2599 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2600
2601 return search(
2602 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2603 params, start, end, obc);
2604 }
2605
2606
2617 @Deprecated
2618 @Override
2619 public int getSocialUsersCount(long userId)
2620 throws PortalException, SystemException {
2621
2622 return getSocialUsersCount(
2623 userId, SocialRelationConstants.TYPE_UNI_ENEMY,
2624 StringPool.NOT_EQUAL);
2625 }
2626
2627
2643 @Deprecated
2644 @Override
2645 public int getSocialUsersCount(long userId, int socialRelationType)
2646 throws PortalException, SystemException {
2647
2648 return getSocialUsersCount(
2649 userId, socialRelationType, StringPool.EQUAL);
2650 }
2651
2652
2663 @Override
2664 public int getSocialUsersCount(
2665 long userId, int socialRelationType,
2666 String socialRelationTypeComparator)
2667 throws PortalException, SystemException {
2668
2669 User user = userPersistence.findByPrimaryKey(userId);
2670
2671 if (!socialRelationTypeComparator.equals(StringPool.EQUAL) &&
2672 !socialRelationTypeComparator.equals(StringPool.NOT_EQUAL)) {
2673
2674 throw new IllegalArgumentException(
2675 "Invalid social relation type comparator " +
2676 socialRelationTypeComparator);
2677 }
2678
2679 return userFinder.countBySocialUsers(
2680 user.getCompanyId(), user.getUserId(), socialRelationType,
2681 socialRelationTypeComparator, WorkflowConstants.STATUS_APPROVED);
2682 }
2683
2684
2694 @Override
2695 public int getSocialUsersCount(long userId1, long userId2)
2696 throws PortalException, SystemException {
2697
2698 User user1 = userPersistence.findByPrimaryKey(userId1);
2699
2700 LinkedHashMap<String, Object> params =
2701 new LinkedHashMap<String, Object>();
2702
2703 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2704
2705 return searchCount(
2706 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2707 params);
2708 }
2709
2710
2724 @Override
2725 public int getSocialUsersCount(
2726 long userId1, long userId2, int socialRelationType)
2727 throws PortalException, SystemException {
2728
2729 User user1 = userPersistence.findByPrimaryKey(userId1);
2730
2731 LinkedHashMap<String, Object> params =
2732 new LinkedHashMap<String, Object>();
2733
2734 params.put(
2735 "socialMutualRelationType",
2736 new Long[] {userId1, new Long(socialRelationType), userId2,
2737 new Long(socialRelationType)});
2738
2739 return searchCount(
2740 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2741 params);
2742 }
2743
2744
2752 @Override
2753 public User getUserByContactId(long contactId)
2754 throws PortalException, SystemException {
2755
2756 return userPersistence.findByContactId(contactId);
2757 }
2758
2759
2769 @Override
2770 public User getUserByEmailAddress(long companyId, String emailAddress)
2771 throws PortalException, SystemException {
2772
2773 emailAddress = getLogin(emailAddress);
2774
2775 return userPersistence.findByC_EA(companyId, emailAddress);
2776 }
2777
2778
2787 @Override
2788 public User getUserByFacebookId(long companyId, long facebookId)
2789 throws PortalException, SystemException {
2790
2791 return userPersistence.findByC_FID(companyId, facebookId);
2792 }
2793
2794
2802 @Override
2803 public User getUserById(long userId)
2804 throws PortalException, SystemException {
2805
2806 return userPersistence.findByPrimaryKey(userId);
2807 }
2808
2809
2819 @Override
2820 public User getUserById(long companyId, long userId)
2821 throws PortalException, SystemException {
2822
2823 return userPersistence.findByC_U(companyId, userId);
2824 }
2825
2826
2835 @Override
2836 public User getUserByOpenId(long companyId, String openId)
2837 throws PortalException, SystemException {
2838
2839 return userPersistence.findByC_O(companyId, openId);
2840 }
2841
2842
2850 @Override
2851 public User getUserByPortraitId(long portraitId)
2852 throws PortalException, SystemException {
2853
2854 return userPersistence.findByPortraitId(portraitId);
2855 }
2856
2857
2866 @Override
2867 public User getUserByScreenName(long companyId, String screenName)
2868 throws PortalException, SystemException {
2869
2870 screenName = getLogin(screenName);
2871
2872 return userPersistence.findByC_SN(companyId, screenName);
2873 }
2874
2875
2885 @Deprecated
2886 @Override
2887 public User getUserByUuid(String uuid)
2888 throws PortalException, SystemException {
2889
2890 List<User> users = userPersistence.findByUuid(uuid);
2891
2892 if (users.isEmpty()) {
2893 throw new NoSuchUserException("{uuid=" + uuid + "}");
2894 }
2895 else {
2896 return users.get(0);
2897 }
2898 }
2899
2900
2909 @Override
2910 public User getUserByUuidAndCompanyId(String uuid, long companyId)
2911 throws PortalException, SystemException {
2912
2913 List<User> users = userPersistence.findByUuid_C(uuid, companyId);
2914
2915 if (users.isEmpty()) {
2916 StringBundler sb = new StringBundler(5);
2917
2918 sb.append("{uuid=");
2919 sb.append(uuid);
2920 sb.append(", companyId=");
2921 sb.append(companyId);
2922 sb.append("}");
2923
2924 throw new NoSuchUserException(sb.toString());
2925 }
2926 else {
2927 return users.get(0);
2928 }
2929 }
2930
2931
2941 @Override
2942 public int getUserGroupUsersCount(long userGroupId, int status)
2943 throws PortalException, SystemException {
2944
2945 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
2946 userGroupId);
2947
2948 LinkedHashMap<String, Object> params =
2949 new LinkedHashMap<String, Object>();
2950
2951 params.put("usersUserGroups", new Long(userGroupId));
2952
2953 return searchCount(userGroup.getCompanyId(), null, status, params);
2954 }
2955
2956
2966 @Override
2967 public long getUserIdByEmailAddress(long companyId, String emailAddress)
2968 throws PortalException, SystemException {
2969
2970 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
2971
2972 User user = userPersistence.findByC_EA(companyId, emailAddress);
2973
2974 return user.getUserId();
2975 }
2976
2977
2986 @Override
2987 public long getUserIdByScreenName(long companyId, String screenName)
2988 throws PortalException, SystemException {
2989
2990 screenName = getLogin(screenName);
2991
2992 User user = userPersistence.findByC_SN(companyId, screenName);
2993
2994 return user.getUserId();
2995 }
2996
2997
3007 @Override
3008 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
3009 throws SystemException {
3010
3011 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
3012 passwordPolicyId, User.class.getName(), userId);
3013 }
3014
3015
3030 @Override
3031 public boolean hasRoleUser(
3032 long companyId, String name, long userId, boolean inherited)
3033 throws PortalException, SystemException {
3034
3035 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
3036 }
3037
3038
3048 @Override
3049 public boolean isPasswordExpired(User user)
3050 throws PortalException, SystemException {
3051
3052 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3053
3054 if ((passwordPolicy != null) && passwordPolicy.getExpireable()) {
3055 Date now = new Date();
3056
3057 if (user.getPasswordModifiedDate() == null) {
3058 user.setPasswordModifiedDate(now);
3059
3060 userLocalService.updateUser(user);
3061 }
3062
3063 long passwordStartTime = user.getPasswordModifiedDate().getTime();
3064 long elapsedTime = now.getTime() - passwordStartTime;
3065
3066 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
3067 return true;
3068 }
3069 else {
3070 return false;
3071 }
3072 }
3073
3074 return false;
3075 }
3076
3077
3089 @Override
3090 public boolean isPasswordExpiringSoon(User user)
3091 throws PortalException, SystemException {
3092
3093 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3094
3095 if ((passwordPolicy != null) && passwordPolicy.isExpireable() &&
3096 (passwordPolicy.getWarningTime() > 0)) {
3097
3098 Date now = new Date();
3099
3100 if (user.getPasswordModifiedDate() == null) {
3101 user.setPasswordModifiedDate(now);
3102
3103 userLocalService.updateUser(user);
3104 }
3105
3106 long timeModified = user.getPasswordModifiedDate().getTime();
3107 long passwordExpiresOn =
3108 (passwordPolicy.getMaxAge() * 1000) + timeModified;
3109
3110 long timeStartWarning =
3111 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
3112
3113 if (now.getTime() > timeStartWarning) {
3114 return true;
3115 }
3116 else {
3117 return false;
3118 }
3119 }
3120
3121 return false;
3122 }
3123
3124
3132 @Override
3133 public User loadGetDefaultUser(long companyId)
3134 throws PortalException, SystemException {
3135
3136 return userPersistence.findByC_DU(companyId, true);
3137 }
3138
3139
3171 @Override
3172 public List<User> search(
3173 long companyId, String keywords, int status,
3174 LinkedHashMap<String, Object> params, int start, int end,
3175 OrderByComparator obc)
3176 throws SystemException {
3177
3178 return userFinder.findByKeywords(
3179 companyId, keywords, status, params, start, end, obc);
3180 }
3181
3182
3213 @Override
3214 public Hits search(
3215 long companyId, String keywords, int status,
3216 LinkedHashMap<String, Object> params, int start, int end, Sort sort)
3217 throws SystemException {
3218
3219 String firstName = null;
3220 String middleName = null;
3221 String lastName = null;
3222 String fullName = null;
3223 String screenName = null;
3224 String emailAddress = null;
3225 String street = null;
3226 String city = null;
3227 String zip = null;
3228 String region = null;
3229 String country = null;
3230 boolean andOperator = false;
3231
3232 if (Validator.isNotNull(keywords)) {
3233 firstName = keywords;
3234 middleName = keywords;
3235 lastName = keywords;
3236 fullName = keywords;
3237 screenName = keywords;
3238 emailAddress = keywords;
3239 street = keywords;
3240 city = keywords;
3241 zip = keywords;
3242 region = keywords;
3243 country = keywords;
3244 }
3245 else {
3246 andOperator = true;
3247 }
3248
3249 if (params != null) {
3250 params.put("keywords", keywords);
3251 }
3252
3253 try {
3254 SearchContext searchContext = buildSearchContext(
3255 companyId, firstName, middleName, lastName, fullName,
3256 screenName, emailAddress, street, city, zip, region, country,
3257 status, params, andOperator, start, end, sort);
3258
3259 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3260 User.class);
3261
3262 return indexer.search(searchContext);
3263 }
3264 catch (Exception e) {
3265 throw new SystemException(e);
3266 }
3267 }
3268
3269
3309 @Override
3310 public List<User> search(
3311 long companyId, String firstName, String middleName,
3312 String lastName, String screenName, String emailAddress, int status,
3313 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3314 int end, OrderByComparator obc)
3315 throws SystemException {
3316
3317 return userFinder.findByC_FN_MN_LN_SN_EA_S(
3318 companyId, firstName, middleName, lastName, screenName,
3319 emailAddress, status, params, andSearch, start, end, obc);
3320 }
3321
3322
3361 @Override
3362 public Hits search(
3363 long companyId, String firstName, String middleName,
3364 String lastName, String screenName, String emailAddress, int status,
3365 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3366 int end, Sort sort)
3367 throws SystemException {
3368
3369 try {
3370 SearchContext searchContext = buildSearchContext(
3371 companyId, firstName, middleName, lastName, null, screenName,
3372 emailAddress, null, null, null, null, null, status, params,
3373 andSearch, start, end, sort);
3374
3375 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3376 User.class);
3377
3378 return indexer.search(searchContext);
3379 }
3380 catch (Exception e) {
3381 throw new SystemException(e);
3382 }
3383 }
3384
3385
3399 @Override
3400 public int searchCount(
3401 long companyId, String keywords, int status,
3402 LinkedHashMap<String, Object> params)
3403 throws SystemException {
3404
3405 if (!PropsValues.USERS_INDEXER_ENABLED ||
3406 !PropsValues.USERS_SEARCH_WITH_INDEX || isUseCustomSQL(params)) {
3407
3408 return userFinder.countByKeywords(
3409 companyId, keywords, status, params);
3410 }
3411
3412 try {
3413 String firstName = null;
3414 String middleName = null;
3415 String lastName = null;
3416 String fullName = null;
3417 String screenName = null;
3418 String emailAddress = null;
3419 String street = null;
3420 String city = null;
3421 String zip = null;
3422 String region = null;
3423 String country = null;
3424 boolean andOperator = false;
3425
3426 if (Validator.isNotNull(keywords)) {
3427 firstName = keywords;
3428 middleName = keywords;
3429 lastName = keywords;
3430 fullName = keywords;
3431 screenName = keywords;
3432 emailAddress = keywords;
3433 street = keywords;
3434 city = keywords;
3435 zip = keywords;
3436 region = keywords;
3437 country = keywords;
3438 }
3439 else {
3440 andOperator = true;
3441 }
3442
3443 if (params != null) {
3444 params.put("keywords", keywords);
3445 }
3446
3447 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3448 User.class);
3449
3450 SearchContext searchContext = buildSearchContext(
3451 companyId, firstName, middleName, lastName, fullName,
3452 screenName, emailAddress, street, city, zip, region, country,
3453 status, params, andOperator, QueryUtil.ALL_POS,
3454 QueryUtil.ALL_POS, null);
3455
3456 Hits hits = indexer.search(searchContext);
3457
3458 return hits.getLength();
3459 }
3460 catch (Exception e) {
3461 throw new SystemException(e);
3462 }
3463 }
3464
3465
3487 @Override
3488 public int searchCount(
3489 long companyId, String firstName, String middleName,
3490 String lastName, String screenName, String emailAddress, int status,
3491 LinkedHashMap<String, Object> params, boolean andSearch)
3492 throws SystemException {
3493
3494 if (!PropsValues.USERS_INDEXER_ENABLED ||
3495 !PropsValues.USERS_SEARCH_WITH_INDEX || isUseCustomSQL(params)) {
3496
3497 return userFinder.countByC_FN_MN_LN_SN_EA_S(
3498 companyId, firstName, middleName, lastName, screenName,
3499 emailAddress, status, params, andSearch);
3500 }
3501
3502 try {
3503 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3504 User.class);
3505
3506 FullNameGenerator fullNameGenerator =
3507 FullNameGeneratorFactory.getInstance();
3508
3509 String fullName = fullNameGenerator.getFullName(
3510 firstName, middleName, lastName);
3511
3512 SearchContext searchContext = buildSearchContext(
3513 companyId, firstName, middleName, lastName, fullName,
3514 screenName, emailAddress, null, null, null, null, null, status,
3515 params, true, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
3516
3517 Hits hits = indexer.search(searchContext);
3518
3519 return hits.getLength();
3520 }
3521 catch (Exception e) {
3522 throw new SystemException(e);
3523 }
3524 }
3525
3526
3537 @Override
3538 public void sendEmailAddressVerification(
3539 User user, String emailAddress, ServiceContext serviceContext)
3540 throws PortalException, SystemException {
3541
3542 if (user.isEmailAddressVerified() &&
3543 StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
3544
3545 return;
3546 }
3547
3548 Ticket ticket = ticketLocalService.addDistinctTicket(
3549 user.getCompanyId(), User.class.getName(), user.getUserId(),
3550 TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3551 serviceContext);
3552
3553 String verifyEmailAddressURL =
3554 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3555 "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3556
3557 long plid = serviceContext.getPlid();
3558
3559 if (plid > 0) {
3560 Layout layout = layoutLocalService.fetchLayout(plid);
3561
3562 if (layout != null) {
3563 Group group = layout.getGroup();
3564
3565 if (!layout.isPrivateLayout() && !group.isUser()) {
3566 verifyEmailAddressURL +=
3567 "&p_l_id=" + serviceContext.getPlid();
3568 }
3569 }
3570 }
3571
3572 String fromName = PrefsPropsUtil.getString(
3573 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3574 String fromAddress = PrefsPropsUtil.getString(
3575 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3576
3577 String toName = user.getFullName();
3578 String toAddress = emailAddress;
3579
3580 String subject = PrefsPropsUtil.getContent(
3581 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3582
3583 String body = PrefsPropsUtil.getContent(
3584 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3585
3586 SubscriptionSender subscriptionSender = new SubscriptionSender();
3587
3588 subscriptionSender.setBody(body);
3589 subscriptionSender.setCompanyId(user.getCompanyId());
3590 subscriptionSender.setContextAttributes(
3591 "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3592 "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3593 "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3594 "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_ID$]",
3595 user.getUserId(), "[$USER_SCREENNAME$]", user.getScreenName());
3596 subscriptionSender.setFrom(fromAddress, fromName);
3597 subscriptionSender.setHtmlFormat(true);
3598 subscriptionSender.setMailId("user", user.getUserId());
3599 subscriptionSender.setServiceContext(serviceContext);
3600 subscriptionSender.setSubject(subject);
3601 subscriptionSender.setUserId(user.getUserId());
3602
3603 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3604
3605 subscriptionSender.flushNotificationsAsync();
3606 }
3607
3608
3627 @Override
3628 public void sendPassword(
3629 long companyId, String emailAddress, String fromName,
3630 String fromAddress, String subject, String body,
3631 ServiceContext serviceContext)
3632 throws PortalException, SystemException {
3633
3634 Company company = companyPersistence.findByPrimaryKey(companyId);
3635
3636 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3637 return;
3638 }
3639
3640 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
3641
3642 if (Validator.isNull(emailAddress)) {
3643 throw new UserEmailAddressException();
3644 }
3645
3646 User user = userPersistence.findByC_EA(companyId, emailAddress);
3647
3648 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3649
3650 String newPassword = StringPool.BLANK;
3651 String passwordResetURL = StringPool.BLANK;
3652
3653 if (company.isSendPasswordResetLink()) {
3654 Date expirationDate = null;
3655
3656 if ((passwordPolicy != null) &&
3657 (passwordPolicy.getResetTicketMaxAge() > 0)) {
3658
3659 expirationDate = new Date(
3660 System.currentTimeMillis() +
3661 (passwordPolicy.getResetTicketMaxAge() * 1000));
3662 }
3663
3664 Ticket ticket = ticketLocalService.addDistinctTicket(
3665 companyId, User.class.getName(), user.getUserId(),
3666 TicketConstants.TYPE_PASSWORD, null, expirationDate,
3667 serviceContext);
3668
3669 passwordResetURL =
3670 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3671 "/portal/update_password?p_l_id="+
3672 serviceContext.getPlid() +
3673 "&ticketKey=" + ticket.getKey();
3674 }
3675 else {
3676 if (!PasswordEncryptorUtil.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
3677 PasswordEncryptorUtil.TYPE_NONE)) {
3678
3679 if (LDAPSettingsUtil.isPasswordPolicyEnabled(
3680 user.getCompanyId())) {
3681
3682 if (_log.isWarnEnabled()) {
3683 StringBundler sb = new StringBundler(5);
3684
3685 sb.append("When LDAP password policy is enabled, ");
3686 sb.append("it is possible that portal generated ");
3687 sb.append("passwords will not match the LDAP policy.");
3688 sb.append("Using RegExpToolkit to generate new ");
3689 sb.append("password.");
3690
3691 _log.warn(sb.toString());
3692 }
3693
3694 RegExpToolkit regExpToolkit = new RegExpToolkit();
3695
3696 newPassword = regExpToolkit.generate(null);
3697 }
3698 else {
3699 newPassword = PwdToolkitUtil.generate(passwordPolicy);
3700 }
3701
3702 boolean passwordReset = false;
3703
3704 if (passwordPolicy.getChangeable() &&
3705 passwordPolicy.getChangeRequired()) {
3706
3707 passwordReset = true;
3708 }
3709
3710 trackPassword(user);
3711
3712 user.setPassword(PasswordEncryptorUtil.encrypt(newPassword));
3713 user.setPasswordUnencrypted(newPassword);
3714 user.setPasswordEncrypted(true);
3715 user.setPasswordReset(passwordReset);
3716 user.setPasswordModified(true);
3717 user.setPasswordModifiedDate(new Date());
3718
3719 userPersistence.update(user);
3720
3721 user.setPasswordModified(false);
3722 }
3723 else {
3724 newPassword = user.getPassword();
3725 }
3726 }
3727
3728 if (Validator.isNull(fromName)) {
3729 fromName = PrefsPropsUtil.getString(
3730 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3731 }
3732
3733 if (Validator.isNull(fromAddress)) {
3734 fromAddress = PrefsPropsUtil.getString(
3735 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3736 }
3737
3738 String toName = user.getFullName();
3739 String toAddress = user.getEmailAddress();
3740
3741 if (Validator.isNull(subject)) {
3742 if (company.isSendPasswordResetLink()) {
3743 subject = PrefsPropsUtil.getContent(
3744 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
3745 }
3746 else {
3747 subject = PrefsPropsUtil.getContent(
3748 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
3749 }
3750 }
3751
3752 if (Validator.isNull(body)) {
3753 if (company.isSendPasswordResetLink()) {
3754 body = PrefsPropsUtil.getContent(
3755 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
3756 }
3757 else {
3758 body = PrefsPropsUtil.getContent(
3759 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
3760 }
3761 }
3762
3763 SubscriptionSender subscriptionSender = new SubscriptionSender();
3764
3765 subscriptionSender.setBody(body);
3766 subscriptionSender.setCompanyId(companyId);
3767 subscriptionSender.setContextAttributes(
3768 "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
3769 serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
3770 serviceContext.getRemoteHost(), "[$USER_ID$]", user.getUserId(),
3771 "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
3772 user.getScreenName());
3773 subscriptionSender.setFrom(fromAddress, fromName);
3774 subscriptionSender.setHtmlFormat(true);
3775 subscriptionSender.setMailId("user", user.getUserId());
3776 subscriptionSender.setServiceContext(serviceContext);
3777 subscriptionSender.setSubject(subject);
3778 subscriptionSender.setUserId(user.getUserId());
3779
3780 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3781
3782 subscriptionSender.flushNotificationsAsync();
3783 }
3784
3785
3794 @Override
3795 public void setRoleUsers(long roleId, long[] userIds)
3796 throws PortalException, SystemException {
3797
3798 List<User> oldUsers = rolePersistence.getUsers(roleId);
3799
3800 long[] oldUserIds = new long[oldUsers.size()];
3801
3802 for (int i = 0; i < oldUsers.size(); i++) {
3803 User user = oldUsers.get(i);
3804
3805 oldUserIds[i] = user.getUserId();
3806 }
3807
3808 Set<Long> updatedUserIdsSet = SetUtil.symmetricDifference(
3809 userIds, oldUserIds);
3810
3811 long[] updateUserIds = ArrayUtil.toLongArray(updatedUserIdsSet);
3812
3813 rolePersistence.setUsers(roleId, userIds);
3814
3815 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3816
3817 indexer.reindex(updateUserIds);
3818
3819 PermissionCacheUtil.clearCache(updateUserIds);
3820 }
3821
3822
3831 @Override
3832 @SuppressWarnings("deprecation")
3833 public void setUserGroupUsers(long userGroupId, long[] userIds)
3834 throws PortalException, SystemException {
3835
3836 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3837 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3838 }
3839
3840 List<User> oldUsers = userGroupPersistence.getUsers(userGroupId);
3841
3842 long[] oldUserIds = new long[oldUsers.size()];
3843
3844 for (int i = 0; i < oldUsers.size(); i++) {
3845 User user = oldUsers.get(i);
3846
3847 oldUserIds[i] = user.getUserId();
3848 }
3849
3850 Set<Long> updatedUserIdsSet = SetUtil.symmetricDifference(
3851 userIds, oldUserIds);
3852
3853 long[] updateUserIds = ArrayUtil.toLongArray(updatedUserIdsSet);
3854
3855 userGroupPersistence.setUsers(userGroupId, userIds);
3856
3857 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3858
3859 indexer.reindex(updateUserIds);
3860
3861 PermissionCacheUtil.clearCache(updateUserIds);
3862 }
3863
3864
3872 @Override
3873 public void unsetGroupTeamsUsers(long groupId, long[] userIds)
3874 throws PortalException, SystemException {
3875
3876 List<Team> teams = teamPersistence.findByGroupId(groupId);
3877
3878 for (Team team : teams) {
3879 unsetTeamUsers(team.getTeamId(), userIds);
3880 }
3881
3882 PermissionCacheUtil.clearCache(userIds);
3883 }
3884
3885
3895 @Override
3896 public void unsetGroupUsers(
3897 final long groupId, final long[] userIds,
3898 ServiceContext serviceContext)
3899 throws PortalException, SystemException {
3900
3901 userGroupRoleLocalService.deleteUserGroupRoles(
3902 userIds, groupId, RoleConstants.TYPE_SITE);
3903
3904 userLocalService.unsetGroupTeamsUsers(groupId, userIds);
3905
3906 groupPersistence.removeUsers(groupId, userIds);
3907
3908 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3909
3910 indexer.reindex(userIds);
3911
3912 PermissionCacheUtil.clearCache(userIds);
3913
3914 Callable<Void> callable = new Callable<Void>() {
3915
3916 @Override
3917 public Void call() throws Exception {
3918 Message message = new Message();
3919
3920 message.put("groupId", groupId);
3921 message.put("userIds", userIds);
3922
3923 MessageBusUtil.sendMessage(
3924 DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
3925
3926 return null;
3927 }
3928
3929 };
3930
3931 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
3932 }
3933
3934
3942 @Override
3943 public void unsetOrganizationUsers(
3944 long organizationId, final long[] userIds)
3945 throws PortalException, SystemException {
3946
3947 Organization organization = organizationPersistence.findByPrimaryKey(
3948 organizationId);
3949
3950 final Group group = organization.getGroup();
3951
3952 userGroupRoleLocalService.deleteUserGroupRoles(
3953 userIds, group.getGroupId());
3954
3955 organizationPersistence.removeUsers(organizationId, userIds);
3956
3957 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3958
3959 indexer.reindex(userIds);
3960
3961 PermissionCacheUtil.clearCache(userIds);
3962
3963 Callable<Void> callable = new Callable<Void>() {
3964
3965 @Override
3966 public Void call() throws Exception {
3967 Message message = new Message();
3968
3969 message.put("groupId", group.getGroupId());
3970 message.put("userIds", userIds);
3971
3972 MessageBusUtil.sendMessage(
3973 DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
3974
3975 return null;
3976 }
3977
3978 };
3979
3980 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
3981 }
3982
3983
3990 @Override
3991 public void unsetPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
3992 throws SystemException {
3993
3994 passwordPolicyRelLocalService.deletePasswordPolicyRels(
3995 passwordPolicyId, User.class.getName(), userIds);
3996 }
3997
3998
4006 @Override
4007 public void unsetRoleUsers(long roleId, List<User> users)
4008 throws PortalException, SystemException {
4009
4010 Role role = rolePersistence.findByPrimaryKey(roleId);
4011
4012 String roleName = role.getName();
4013
4014 if ((roleName.equals(RoleConstants.ADMINISTRATOR) &&
4015 (getRoleUsersCount(role.getRoleId()) <= 1)) ||
4016 roleName.equals(RoleConstants.USER)) {
4017
4018 return;
4019 }
4020
4021 rolePersistence.removeUsers(roleId, users);
4022
4023 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
4024
4025 indexer.reindex(users);
4026
4027 long[] userIds = new long[users.size()];
4028
4029 for (int i = 0; i < users.size(); i++) {
4030 User user = users.get(i);
4031
4032 userIds[i] = user.getUserId();
4033 }
4034
4035 PermissionCacheUtil.clearCache(userIds);
4036 }
4037
4038
4046 @Override
4047 public void unsetRoleUsers(long roleId, long[] userIds)
4048 throws PortalException, SystemException {
4049
4050 Role role = rolePersistence.findByPrimaryKey(roleId);
4051
4052 String roleName = role.getName();
4053
4054 if (roleName.equals(RoleConstants.USER) ||
4055 (roleName.equals(RoleConstants.ADMINISTRATOR) &&
4056 getRoleUsersCount(role.getRoleId()) <= 1)) {
4057
4058 return;
4059 }
4060
4061 rolePersistence.removeUsers(roleId, userIds);
4062
4063 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
4064
4065 indexer.reindex(userIds);
4066
4067 PermissionCacheUtil.clearCache(userIds);
4068 }
4069
4070
4078 @Override
4079 public void unsetTeamUsers(long teamId, long[] userIds)
4080 throws PortalException, SystemException {
4081
4082 teamPersistence.removeUsers(teamId, userIds);
4083
4084 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
4085
4086 indexer.reindex(userIds);
4087
4088 PermissionCacheUtil.clearCache(userIds);
4089 }
4090
4091
4099 @Override
4100 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
4101 throws PortalException, SystemException {
4102
4103 userGroupPersistence.removeUsers(userGroupId, userIds);
4104
4105 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
4106
4107 indexer.reindex(userIds);
4108
4109 PermissionCacheUtil.clearCache(userIds);
4110 }
4111
4112
4122 @Override
4123 public User updateAgreedToTermsOfUse(
4124 long userId, boolean agreedToTermsOfUse)
4125 throws PortalException, SystemException {
4126
4127 User user = userPersistence.findByPrimaryKey(userId);
4128
4129 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
4130
4131 userPersistence.update(user);
4132
4133 return user;
4134 }
4135
4136
4147 @Override
4148 public void updateAsset(
4149 long userId, User user, long[] assetCategoryIds,
4150 String[] assetTagNames)
4151 throws PortalException, SystemException {
4152
4153 User owner = userPersistence.findByPrimaryKey(userId);
4154
4155 Company company = companyPersistence.findByPrimaryKey(
4156 owner.getCompanyId());
4157
4158 Group companyGroup = company.getGroup();
4159
4160 assetEntryLocalService.updateEntry(
4161 userId, companyGroup.getGroupId(), user.getCreateDate(),
4162 user.getModifiedDate(), User.class.getName(), user.getUserId(),
4163 user.getUuid(), 0, assetCategoryIds, assetTagNames, false, null,
4164 null, null, null, user.getFullName(), null, null, null, null, 0, 0,
4165 null, false);
4166 }
4167
4168
4177 @Override
4178 public User updateCreateDate(long userId, Date createDate)
4179 throws PortalException, SystemException {
4180
4181 User user = userPersistence.findByPrimaryKey(userId);
4182
4183 user.setCreateDate(createDate);
4184
4185 userPersistence.update(user);
4186
4187 return user;
4188 }
4189
4190
4201 @Override
4202 public User updateEmailAddress(
4203 long userId, String password, String emailAddress1,
4204 String emailAddress2)
4205 throws PortalException, SystemException {
4206
4207 emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
4208 emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
4209
4210 User user = userPersistence.findByPrimaryKey(userId);
4211
4212 validateEmailAddress(user, emailAddress1, emailAddress2);
4213
4214 setEmailAddress(
4215 user, password, user.getFirstName(), user.getMiddleName(),
4216 user.getLastName(), emailAddress1);
4217
4218 userPersistence.update(user);
4219
4220 Contact contact = user.getContact();
4221
4222 contact.setEmailAddress(user.getEmailAddress());
4223
4224 contactPersistence.update(contact);
4225
4226 return user;
4227 }
4228
4229
4243 @Override
4244 public User updateEmailAddress(
4245 long userId, String password, String emailAddress1,
4246 String emailAddress2, ServiceContext serviceContext)
4247 throws PortalException, SystemException {
4248
4249 emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
4250 emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
4251
4252 User user = userPersistence.findByPrimaryKey(userId);
4253
4254 validateEmailAddress(user, emailAddress1, emailAddress2);
4255
4256 Company company = companyPersistence.findByPrimaryKey(
4257 user.getCompanyId());
4258
4259 if (company.isStrangersVerify() &&
4260 !StringUtil.equalsIgnoreCase(
4261 emailAddress1, user.getEmailAddress())) {
4262
4263 sendEmailAddressVerification(user, emailAddress1, serviceContext);
4264 }
4265 else {
4266 setEmailAddress(
4267 user, password, user.getFirstName(), user.getMiddleName(),
4268 user.getLastName(), emailAddress1);
4269
4270 userPersistence.update(user);
4271
4272 Contact contact = user.getContact();
4273
4274 contact.setEmailAddress(user.getEmailAddress());
4275
4276 contactPersistence.update(contact);
4277 }
4278
4279 return user;
4280 }
4281
4282
4291 @Override
4292 public User updateEmailAddressVerified(
4293 long userId, boolean emailAddressVerified)
4294 throws PortalException, SystemException {
4295
4296 User user = userPersistence.findByPrimaryKey(userId);
4297
4298 user.setEmailAddressVerified(emailAddressVerified);
4299
4300 userPersistence.update(user);
4301
4302 return user;
4303 }
4304
4305
4314 @Override
4315 public User updateFacebookId(long userId, long facebookId)
4316 throws PortalException, SystemException {
4317
4318 User user = userPersistence.findByPrimaryKey(userId);
4319
4320 user.setFacebookId(facebookId);
4321
4322 userPersistence.update(user);
4323
4324 return user;
4325 }
4326
4327
4337 @Override
4338 public void updateGroups(
4339 long userId, long[] newGroupIds, ServiceContext serviceContext)
4340 throws PortalException, SystemException {
4341
4342 boolean indexingEnabled = true;
4343
4344 if (serviceContext != null) {
4345 indexingEnabled = serviceContext.isIndexingEnabled();
4346 }
4347
4348 updateGroups(userId, newGroupIds, serviceContext, indexingEnabled);
4349 }
4350
4351
4390 @Override
4391 public User updateIncompleteUser(
4392 long creatorUserId, long companyId, boolean autoPassword,
4393 String password1, String password2, boolean autoScreenName,
4394 String screenName, String emailAddress, long facebookId,
4395 String openId, Locale locale, String firstName, String middleName,
4396 String lastName, int prefixId, int suffixId, boolean male,
4397 int birthdayMonth, int birthdayDay, int birthdayYear,
4398 String jobTitle, boolean updateUserInformation, boolean sendEmail,
4399 ServiceContext serviceContext)
4400 throws PortalException, SystemException {
4401
4402 User user = getUserByEmailAddress(companyId, emailAddress);
4403
4404 if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
4405 throw new PortalException("Invalid user status");
4406 }
4407
4408 User defaultUser = getDefaultUser(companyId);
4409
4410 if (facebookId > 0) {
4411 autoPassword = false;
4412
4413 if ((password1 == null) || (password2 == null)) {
4414 password1 = PwdGenerator.getPassword();
4415 password2 = password1;
4416 }
4417
4418 sendEmail = false;
4419 }
4420
4421 if (updateUserInformation) {
4422 autoScreenName = false;
4423
4424 if (PrefsPropsUtil.getBoolean(
4425 companyId,
4426 PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
4427
4428 autoScreenName = true;
4429 }
4430
4431 validate(
4432 companyId, user.getUserId(), autoPassword, password1, password2,
4433 autoScreenName, screenName, emailAddress, openId, firstName,
4434 middleName, lastName, null);
4435
4436 if (!autoPassword) {
4437 if (Validator.isNull(password1) ||
4438 Validator.isNull(password2)) {
4439 throw new UserPasswordException(
4440 UserPasswordException.PASSWORD_INVALID);
4441 }
4442 }
4443
4444 if (autoScreenName) {
4445 ScreenNameGenerator screenNameGenerator =
4446 ScreenNameGeneratorFactory.getInstance();
4447
4448 try {
4449 screenName = screenNameGenerator.generate(
4450 companyId, user.getUserId(), emailAddress);
4451 }
4452 catch (Exception e) {
4453 throw new SystemException(e);
4454 }
4455 }
4456
4457 FullNameGenerator fullNameGenerator =
4458 FullNameGeneratorFactory.getInstance();
4459
4460 String fullName = fullNameGenerator.getFullName(
4461 firstName, middleName, lastName);
4462
4463 String greeting = LanguageUtil.format(
4464 locale, "welcome-x", " " + fullName, false);
4465
4466 if (Validator.isNotNull(password1)) {
4467 user.setPassword(PasswordEncryptorUtil.encrypt(password1));
4468 user.setPasswordUnencrypted(password1);
4469 }
4470
4471 user.setPasswordEncrypted(true);
4472
4473 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
4474
4475 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
4476 passwordPolicy.isChangeRequired()) {
4477
4478 user.setPasswordReset(true);
4479 }
4480 else {
4481 user.setPasswordReset(false);
4482 }
4483
4484 user.setScreenName(screenName);
4485 user.setFacebookId(facebookId);
4486 user.setOpenId(openId);
4487 user.setLanguageId(locale.toString());
4488 user.setTimeZoneId(defaultUser.getTimeZoneId());
4489 user.setGreeting(greeting);
4490 user.setFirstName(firstName);
4491 user.setMiddleName(middleName);
4492 user.setLastName(lastName);
4493 user.setJobTitle(jobTitle);
4494 user.setExpandoBridgeAttributes(serviceContext);
4495
4496 Date birthday = getBirthday(
4497 birthdayMonth, birthdayDay, birthdayYear);
4498
4499 Contact contact = user.getContact();
4500
4501 contact.setFirstName(firstName);
4502 contact.setMiddleName(middleName);
4503 contact.setLastName(lastName);
4504 contact.setPrefixId(prefixId);
4505 contact.setSuffixId(suffixId);
4506 contact.setMale(male);
4507 contact.setBirthday(birthday);
4508 contact.setJobTitle(jobTitle);
4509
4510 contactPersistence.update(contact, serviceContext);
4511
4512
4513
4514 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4515 User.class);
4516
4517 indexer.reindex(user);
4518 }
4519
4520 user.setStatus(WorkflowConstants.STATUS_DRAFT);
4521
4522 userPersistence.update(user, serviceContext);
4523
4524
4525
4526 long workflowUserId = creatorUserId;
4527
4528 if (workflowUserId == user.getUserId()) {
4529 workflowUserId = defaultUser.getUserId();
4530 }
4531
4532 ServiceContext workflowServiceContext = serviceContext;
4533
4534 if (workflowServiceContext == null) {
4535 workflowServiceContext = new ServiceContext();
4536 }
4537
4538 workflowServiceContext.setAttribute("autoPassword", autoPassword);
4539 workflowServiceContext.setAttribute("passwordUnencrypted", password1);
4540 workflowServiceContext.setAttribute("sendEmail", sendEmail);
4541
4542 WorkflowHandlerRegistryUtil.startWorkflowInstance(
4543 companyId, workflowUserId, User.class.getName(), user.getUserId(),
4544 user, workflowServiceContext);
4545
4546 return getUserByEmailAddress(companyId, emailAddress);
4547 }
4548
4549
4559 @Override
4560 public User updateJobTitle(long userId, String jobTitle)
4561 throws PortalException, SystemException {
4562
4563 User user = userPersistence.findByPrimaryKey(userId);
4564
4565 user.setJobTitle(jobTitle);
4566
4567 userPersistence.update(user);
4568
4569 Contact contact = contactPersistence.findByPrimaryKey(
4570 user.getContactId());
4571
4572 contact.setJobTitle(jobTitle);
4573
4574 contactPersistence.update(contact);
4575
4576 return user;
4577 }
4578
4579
4588 @Override
4589 public User updateLastLogin(long userId, String loginIP)
4590 throws PortalException, SystemException {
4591
4592 User user = userPersistence.findByPrimaryKey(userId);
4593
4594 Date lastLoginDate = user.getLoginDate();
4595
4596 if (lastLoginDate == null) {
4597 lastLoginDate = new Date();
4598 }
4599
4600 user.setLoginDate(new Date());
4601 user.setLoginIP(loginIP);
4602 user.setLastLoginDate(lastLoginDate);
4603 user.setLastLoginIP(user.getLoginIP());
4604
4605 resetFailedLoginAttempts(user, true);
4606
4607 return user;
4608 }
4609
4610
4619 @Override
4620 public User updateLockout(User user, boolean lockout)
4621 throws PortalException, SystemException {
4622
4623 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
4624
4625 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
4626 return user;
4627 }
4628
4629 Date lockoutDate = null;
4630
4631 if (lockout) {
4632 lockoutDate = new Date();
4633 }
4634
4635 user.setLockout(lockout);
4636 user.setLockoutDate(lockoutDate);
4637
4638 if (!lockout) {
4639 user.setLastFailedLoginDate(lockoutDate);
4640 user.setFailedLoginAttempts(0);
4641 }
4642
4643 userPersistence.update(user);
4644
4645 return user;
4646 }
4647
4648
4659 @Override
4660 public User updateLockoutByEmailAddress(
4661 long companyId, String emailAddress, boolean lockout)
4662 throws PortalException, SystemException {
4663
4664 User user = getUserByEmailAddress(companyId, emailAddress);
4665
4666 return updateLockout(user, lockout);
4667 }
4668
4669
4678 @Override
4679 public User updateLockoutById(long userId, boolean lockout)
4680 throws PortalException, SystemException {
4681
4682 User user = userPersistence.findByPrimaryKey(userId);
4683
4684 return updateLockout(user, lockout);
4685 }
4686
4687
4697 @Override
4698 public User updateLockoutByScreenName(
4699 long companyId, String screenName, boolean lockout)
4700 throws PortalException, SystemException {
4701
4702 User user = getUserByScreenName(companyId, screenName);
4703
4704 return updateLockout(user, lockout);
4705 }
4706
4707
4716 @Override
4717 public User updateModifiedDate(long userId, Date modifiedDate)
4718 throws PortalException, SystemException {
4719
4720 User user = userPersistence.findByPrimaryKey(userId);
4721
4722 user.setModifiedDate(modifiedDate);
4723
4724 userPersistence.update(user);
4725
4726 return user;
4727 }
4728
4729
4738 @Override
4739 public User updateOpenId(long userId, String openId)
4740 throws PortalException, SystemException {
4741
4742 openId = openId.trim();
4743
4744 User user = userPersistence.findByPrimaryKey(userId);
4745
4746 user.setOpenId(openId);
4747
4748 userPersistence.update(user);
4749
4750 return user;
4751 }
4752
4753
4764 @Override
4765 public void updateOrganizations(
4766 long userId, long[] newOrganizationIds,
4767 ServiceContext serviceContext)
4768 throws PortalException, SystemException {
4769
4770 updateOrganizations(
4771 userId, newOrganizationIds, serviceContext.isIndexingEnabled());
4772 }
4773
4774
4786 @Override
4787 public User updatePassword(
4788 long userId, String password1, String password2,
4789 boolean passwordReset)
4790 throws PortalException, SystemException {
4791
4792 return updatePassword(
4793 userId, password1, password2, passwordReset, false);
4794 }
4795
4796
4811 @Override
4812 public User updatePassword(
4813 long userId, String password1, String password2,
4814 boolean passwordReset, boolean silentUpdate)
4815 throws PortalException, SystemException {
4816
4817 User user = userPersistence.findByPrimaryKey(userId);
4818
4819 if (!silentUpdate) {
4820 validatePassword(user.getCompanyId(), userId, password1, password2);
4821
4822 trackPassword(user);
4823 }
4824
4825 String newEncPwd = PasswordEncryptorUtil.encrypt(password1);
4826
4827 if (user.hasCompanyMx()) {
4828 mailService.updatePassword(user.getCompanyId(), userId, password1);
4829 }
4830
4831 user.setPassword(newEncPwd);
4832 user.setPasswordUnencrypted(password1);
4833 user.setPasswordEncrypted(true);
4834 user.setPasswordReset(passwordReset);
4835
4836 if (!silentUpdate || (user.getPasswordModifiedDate() == null)) {
4837 user.setPasswordModifiedDate(new Date());
4838 }
4839
4840 user.setDigest(StringPool.BLANK);
4841 user.setGraceLoginCount(0);
4842
4843 if (!silentUpdate) {
4844 user.setPasswordModified(true);
4845 }
4846
4847 try {
4848 userPersistence.update(user);
4849 }
4850 catch (ModelListenerException mle) {
4851 String msg = GetterUtil.getString(mle.getCause().getMessage());
4852
4853 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
4854 String passwordHistory = PrefsPropsUtil.getString(
4855 user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
4856
4857 if (msg.contains(passwordHistory)) {
4858 throw new UserPasswordException(
4859 UserPasswordException.PASSWORD_ALREADY_USED);
4860 }
4861 }
4862
4863 throw new UserPasswordException(
4864 UserPasswordException.PASSWORD_INVALID);
4865 }
4866
4867 if (!silentUpdate) {
4868 user.setPasswordModified(false);
4869 }
4870
4871 return user;
4872 }
4873
4874
4888 @Override
4889 public User updatePasswordManually(
4890 long userId, String password, boolean passwordEncrypted,
4891 boolean passwordReset, Date passwordModifiedDate)
4892 throws PortalException, SystemException {
4893
4894
4895
4896 User user = userPersistence.findByPrimaryKey(userId);
4897
4898 user.setPassword(password);
4899 user.setPasswordEncrypted(passwordEncrypted);
4900 user.setPasswordReset(passwordReset);
4901 user.setPasswordModifiedDate(passwordModifiedDate);
4902 user.setDigest(StringPool.BLANK);
4903
4904 userPersistence.update(user);
4905
4906 return user;
4907 }
4908
4909
4920 @Override
4921 public User updatePasswordReset(long userId, boolean passwordReset)
4922 throws PortalException, SystemException {
4923
4924 User user = userPersistence.findByPrimaryKey(userId);
4925
4926 user.setPasswordReset(passwordReset);
4927
4928 userPersistence.update(user);
4929
4930 return user;
4931 }
4932
4933
4943 @Override
4944 public User updatePortrait(long userId, byte[] bytes)
4945 throws PortalException, SystemException {
4946
4947 User user = userPersistence.findByPrimaryKey(userId);
4948
4949 long imageMaxSize = PrefsPropsUtil.getLong(
4950 PropsKeys.USERS_IMAGE_MAX_SIZE);
4951
4952 if ((imageMaxSize > 0) &&
4953 ((bytes == null) || (bytes.length > imageMaxSize))) {
4954
4955 throw new UserPortraitSizeException();
4956 }
4957
4958 long portraitId = user.getPortraitId();
4959
4960 if (portraitId <= 0) {
4961 portraitId = counterLocalService.increment();
4962
4963 user.setPortraitId(portraitId);
4964 }
4965
4966 try {
4967 ImageBag imageBag = ImageToolUtil.read(bytes);
4968
4969 RenderedImage renderedImage = imageBag.getRenderedImage();
4970
4971 if (renderedImage == null) {
4972 throw new UserPortraitTypeException();
4973 }
4974
4975 renderedImage = ImageToolUtil.scale(
4976 renderedImage, PropsValues.USERS_IMAGE_MAX_HEIGHT,
4977 PropsValues.USERS_IMAGE_MAX_WIDTH);
4978
4979 String contentType = imageBag.getType();
4980
4981 imageLocalService.updateImage(
4982 portraitId,
4983 ImageToolUtil.getBytes(renderedImage, contentType));
4984 }
4985 catch (IOException ioe) {
4986 throw new ImageSizeException(ioe);
4987 }
4988
4989 userPersistence.update(user);
4990
4991 return user;
4992 }
4993
4994
5005 @Override
5006 public User updateReminderQuery(long userId, String question, String answer)
5007 throws PortalException, SystemException {
5008
5009 validateReminderQuery(question, answer);
5010
5011 User user = userPersistence.findByPrimaryKey(userId);
5012
5013 user.setReminderQueryQuestion(question);
5014 user.setReminderQueryAnswer(answer);
5015
5016 userPersistence.update(user);
5017
5018 return user;
5019 }
5020
5021
5031 @Override
5032 public User updateScreenName(long userId, String screenName)
5033 throws PortalException, SystemException {
5034
5035
5036
5037 User user = userPersistence.findByPrimaryKey(userId);
5038
5039 screenName = getLogin(screenName);
5040
5041 validateScreenName(user.getCompanyId(), userId, screenName);
5042
5043 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
5044 user.setDigest(StringPool.BLANK);
5045 }
5046
5047 user.setScreenName(screenName);
5048
5049 userPersistence.update(user);
5050
5051
5052
5053 Group group = groupLocalService.getUserGroup(
5054 user.getCompanyId(), userId);
5055
5056 group.setFriendlyURL(StringPool.SLASH + screenName);
5057
5058 groupPersistence.update(group);
5059
5060 return user;
5061 }
5062
5063
5075 @Deprecated
5076 @Override
5077 public User updateStatus(long userId, int status)
5078 throws PortalException, SystemException {
5079
5080 return updateStatus(userId, status, new ServiceContext());
5081 }
5082
5083
5095 @Override
5096 public User updateStatus(
5097 long userId, int status, ServiceContext serviceContext)
5098 throws PortalException, SystemException {
5099
5100 User user = userPersistence.findByPrimaryKey(userId);
5101
5102 if ((status == WorkflowConstants.STATUS_APPROVED) &&
5103 (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {
5104
5105 validateCompanyMaxUsers(user.getCompanyId());
5106 }
5107
5108 String passwordUnencrypted = (String)serviceContext.getAttribute(
5109 "passwordUnencrypted");
5110
5111 if (Validator.isNotNull(passwordUnencrypted)) {
5112 user.setPasswordUnencrypted(passwordUnencrypted);
5113 }
5114
5115 user.setStatus(status);
5116
5117 userPersistence.update(user);
5118
5119 reindex(user);
5120
5121 return user;
5122 }
5123
5124
5180 @Override
5181 @SuppressWarnings("deprecation")
5182 public User updateUser(
5183 long userId, String oldPassword, String newPassword1,
5184 String newPassword2, boolean passwordReset,
5185 String reminderQueryQuestion, String reminderQueryAnswer,
5186 String screenName, String emailAddress, long facebookId,
5187 String openId, String languageId, String timeZoneId,
5188 String greeting, String comments, String firstName,
5189 String middleName, String lastName, int prefixId, int suffixId,
5190 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
5191 String smsSn, String aimSn, String facebookSn, String icqSn,
5192 String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
5193 String twitterSn, String ymSn, String jobTitle, long[] groupIds,
5194 long[] organizationIds, long[] roleIds,
5195 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
5196 ServiceContext serviceContext)
5197 throws PortalException, SystemException {
5198
5199
5200
5201 User user = userPersistence.findByPrimaryKey(userId);
5202 Company company = companyPersistence.findByPrimaryKey(
5203 user.getCompanyId());
5204 String password = oldPassword;
5205 screenName = getLogin(screenName);
5206 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
5207 openId = openId.trim();
5208 String oldFullName = user.getFullName();
5209 aimSn = StringUtil.toLowerCase(aimSn.trim());
5210 facebookSn = StringUtil.toLowerCase(facebookSn.trim());
5211 icqSn = StringUtil.toLowerCase(icqSn.trim());
5212 jabberSn = StringUtil.toLowerCase(jabberSn.trim());
5213 msnSn = StringUtil.toLowerCase(msnSn.trim());
5214 mySpaceSn = StringUtil.toLowerCase(mySpaceSn.trim());
5215 skypeSn = StringUtil.toLowerCase(skypeSn.trim());
5216 twitterSn = StringUtil.toLowerCase(twitterSn.trim());
5217 ymSn = StringUtil.toLowerCase(ymSn.trim());
5218 Date now = new Date();
5219
5220 EmailAddressGenerator emailAddressGenerator =
5221 EmailAddressGeneratorFactory.getInstance();
5222
5223 if (emailAddressGenerator.isGenerated(emailAddress)) {
5224 emailAddress = StringPool.BLANK;
5225 }
5226
5227 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
5228 Validator.isNull(emailAddress)) {
5229
5230 emailAddress = emailAddressGenerator.generate(
5231 user.getCompanyId(), userId);
5232 }
5233
5234 validate(
5235 userId, screenName, emailAddress, openId, firstName, middleName,
5236 lastName, smsSn);
5237
5238 if (Validator.isNotNull(newPassword1) ||
5239 Validator.isNotNull(newPassword2)) {
5240
5241 user = updatePassword(
5242 userId, newPassword1, newPassword2, passwordReset);
5243
5244 password = newPassword1;
5245
5246 user.setDigest(StringPool.BLANK);
5247 }
5248
5249 user.setModifiedDate(now);
5250
5251 if (user.getContactId() <= 0) {
5252 user.setContactId(counterLocalService.increment());
5253 }
5254
5255 user.setPasswordReset(passwordReset);
5256
5257 if (Validator.isNotNull(reminderQueryQuestion) &&
5258 Validator.isNotNull(reminderQueryAnswer)) {
5259
5260 user.setReminderQueryQuestion(reminderQueryQuestion);
5261 user.setReminderQueryAnswer(reminderQueryAnswer);
5262 }
5263
5264 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
5265 user.setScreenName(screenName);
5266
5267 user.setDigest(StringPool.BLANK);
5268 }
5269
5270 boolean sendEmailAddressVerification = false;
5271
5272 if (company.isStrangersVerify() &&
5273 !StringUtil.equalsIgnoreCase(
5274 emailAddress, user.getEmailAddress())) {
5275
5276 sendEmailAddressVerification = true;
5277 }
5278 else {
5279 setEmailAddress(
5280 user, password, firstName, middleName, lastName, emailAddress);
5281 }
5282
5283 if (serviceContext != null) {
5284 String uuid = serviceContext.getUuid();
5285
5286 if (Validator.isNotNull(uuid)) {
5287 user.setUuid(uuid);
5288 }
5289 }
5290
5291 user.setFacebookId(facebookId);
5292
5293 Long ldapServerId = null;
5294
5295 if (serviceContext != null) {
5296 ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
5297 }
5298
5299 if (ldapServerId != null) {
5300 user.setLdapServerId(ldapServerId);
5301 }
5302
5303 user.setOpenId(openId);
5304 user.setLanguageId(languageId);
5305 user.setTimeZoneId(timeZoneId);
5306 user.setGreeting(greeting);
5307 user.setComments(comments);
5308 user.setFirstName(firstName);
5309 user.setMiddleName(middleName);
5310 user.setLastName(lastName);
5311 user.setJobTitle(jobTitle);
5312 user.setExpandoBridgeAttributes(serviceContext);
5313
5314 userPersistence.update(user, serviceContext);
5315
5316
5317
5318 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
5319
5320 long contactId = user.getContactId();
5321
5322 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
5323
5324 if (contact == null) {
5325 contact = contactPersistence.create(contactId);
5326
5327 contact.setCompanyId(user.getCompanyId());
5328 contact.setUserName(StringPool.BLANK);
5329 contact.setCreateDate(now);
5330 contact.setClassName(User.class.getName());
5331 contact.setClassPK(user.getUserId());
5332 contact.setAccountId(company.getAccountId());
5333 contact.setParentContactId(
5334 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
5335 }
5336
5337 contact.setModifiedDate(now);
5338 contact.setEmailAddress(user.getEmailAddress());
5339 contact.setFirstName(firstName);
5340 contact.setMiddleName(middleName);
5341 contact.setLastName(lastName);
5342 contact.setPrefixId(prefixId);
5343 contact.setSuffixId(suffixId);
5344 contact.setMale(male);
5345 contact.setBirthday(birthday);
5346 contact.setSmsSn(smsSn);
5347 contact.setAimSn(aimSn);
5348 contact.setFacebookSn(facebookSn);
5349 contact.setIcqSn(icqSn);
5350 contact.setJabberSn(jabberSn);
5351 contact.setMsnSn(msnSn);
5352 contact.setMySpaceSn(mySpaceSn);
5353 contact.setSkypeSn(skypeSn);
5354 contact.setTwitterSn(twitterSn);
5355 contact.setYmSn(ymSn);
5356 contact.setJobTitle(jobTitle);
5357
5358 contactPersistence.update(contact, serviceContext);
5359
5360
5361
5362 Group group = groupLocalService.getUserGroup(
5363 user.getCompanyId(), userId);
5364
5365 group.setFriendlyURL(StringPool.SLASH + screenName);
5366
5367 groupPersistence.update(group);
5368
5369
5370
5371
5372
5373
5374
5375 List<UserGroupRole> previousUserGroupRoles =
5376 userGroupRolePersistence.findByUserId(userId);
5377
5378 updateGroups(userId, groupIds, serviceContext, false);
5379 updateOrganizations(userId, organizationIds, false);
5380
5381
5382
5383 if (roleIds != null) {
5384 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
5385
5386 userPersistence.setRoles(userId, roleIds);
5387 }
5388
5389
5390
5391 updateUserGroupRoles(
5392 user, groupIds, organizationIds, userGroupRoles,
5393 previousUserGroupRoles);
5394
5395
5396
5397 if (userGroupIds != null) {
5398 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
5399 userGroupLocalService.copyUserGroupLayouts(
5400 userGroupIds, userId);
5401 }
5402
5403 userPersistence.setUserGroups(userId, userGroupIds);
5404 }
5405
5406 if (!hasManageLayoutsRolePermission(user) &&
5407 !hasManageLayoutsOrgPermission(organizationIds, user) &&
5408 !hasManageLayoutsSitePermission(groupIds, user)) {
5409
5410 unsetToggleControlsPreference(userId);
5411 }
5412
5413
5414
5415 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
5416
5417
5418
5419 if (serviceContext != null) {
5420 updateAsset(
5421 userId, user, serviceContext.getAssetCategoryIds(),
5422 serviceContext.getAssetTagNames());
5423 }
5424
5425
5426
5427 if (GetterUtil.getBoolean(
5428 PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
5429 !oldFullName.equals(user.getFullName())) {
5430
5431 mbMessageLocalService.updateUserName(userId, user.getFullName());
5432 }
5433
5434
5435
5436 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
5437 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5438 User.class);
5439
5440 indexer.reindex(user);
5441 }
5442
5443
5444
5445 if ((serviceContext != null) && sendEmailAddressVerification) {
5446 sendEmailAddressVerification(user, emailAddress, serviceContext);
5447 }
5448
5449
5450
5451 PermissionCacheUtil.clearCache(userId);
5452
5453 return user;
5454 }
5455
5456
5465 @Override
5466 public void verifyEmailAddress(String ticketKey)
5467 throws PortalException, SystemException {
5468
5469 Ticket ticket = ticketLocalService.getTicket(ticketKey);
5470
5471 if (ticket.isExpired() ||
5472 (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
5473
5474 throw new NoSuchTicketException("{ticketKey=" + ticketKey + "}");
5475 }
5476
5477 User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
5478
5479 String emailAddress = ticket.getExtraInfo();
5480
5481 emailAddress = StringUtil.toLowerCase(emailAddress).trim();
5482
5483 if (!emailAddress.equals(user.getEmailAddress())) {
5484 if (userPersistence.fetchByC_EA(
5485 user.getCompanyId(), emailAddress) != null) {
5486
5487 throw new DuplicateUserEmailAddressException(
5488 "{userId=" + user.getUserId() + "}");
5489 }
5490
5491 setEmailAddress(
5492 user, StringPool.BLANK, user.getFirstName(),
5493 user.getMiddleName(), user.getLastName(), emailAddress);
5494
5495 Contact contact = user.getContact();
5496
5497 contact.setEmailAddress(user.getEmailAddress());
5498
5499 contactPersistence.update(contact);
5500 }
5501
5502 user.setEmailAddressVerified(true);
5503
5504 userPersistence.update(user);
5505
5506 ticketLocalService.deleteTicket(ticket);
5507 }
5508
5509 protected void addDefaultRolesAndTeams(long groupId, long[] userIds)
5510 throws PortalException, SystemException {
5511
5512 List<Role> defaultSiteRoles = new ArrayList<Role>();
5513
5514 Group group = groupLocalService.getGroup(groupId);
5515
5516 UnicodeProperties typeSettingsProperties =
5517 group.getTypeSettingsProperties();
5518
5519 long[] defaultSiteRoleIds = StringUtil.split(
5520 typeSettingsProperties.getProperty("defaultSiteRoleIds"), 0L);
5521
5522 for (long defaultSiteRoleId : defaultSiteRoleIds) {
5523 Role defaultSiteRole = rolePersistence.fetchByPrimaryKey(
5524 defaultSiteRoleId);
5525
5526 if (defaultSiteRole == null) {
5527 if (_log.isWarnEnabled()) {
5528 _log.warn("Unable to find role " + defaultSiteRoleId);
5529 }
5530
5531 continue;
5532 }
5533
5534 defaultSiteRoles.add(defaultSiteRole);
5535 }
5536
5537 List<Team> defaultTeams = new ArrayList<Team>();
5538
5539 long[] defaultTeamIds = StringUtil.split(
5540 typeSettingsProperties.getProperty("defaultTeamIds"), 0L);
5541
5542 for (long defaultTeamId : defaultTeamIds) {
5543 Team defaultTeam = teamPersistence.findByPrimaryKey(defaultTeamId);
5544
5545 if (defaultTeam == null) {
5546 if (_log.isWarnEnabled()) {
5547 _log.warn("Unable to find team " + defaultTeamId);
5548 }
5549
5550 continue;
5551 }
5552
5553 defaultTeams.add(defaultTeam);
5554 }
5555
5556 for (long userId : userIds) {
5557 Set<Long> userRoleIdsSet = new HashSet<Long>();
5558
5559 for (Role role : defaultSiteRoles) {
5560 if (!userPersistence.containsRole(userId, role.getRoleId())) {
5561 userRoleIdsSet.add(role.getRoleId());
5562 }
5563 }
5564
5565 long[] userRoleIds = ArrayUtil.toArray(
5566 userRoleIdsSet.toArray(new Long[userRoleIdsSet.size()]));
5567
5568 userGroupRoleLocalService.addUserGroupRoles(
5569 userId, groupId, userRoleIds);
5570
5571 Set<Long> userTeamIdsSet = new HashSet<Long>();
5572
5573 for (Team team : defaultTeams) {
5574 if (!userPersistence.containsTeam(userId, team.getTeamId())) {
5575 userTeamIdsSet.add(team.getTeamId());
5576 }
5577 }
5578
5579 long[] userTeamIds = ArrayUtil.toArray(
5580 userTeamIdsSet.toArray(new Long[userTeamIdsSet.size()]));
5581
5582 userPersistence.addTeams(userId, userTeamIds);
5583 }
5584 }
5585
5586
5632 protected int authenticate(
5633 long companyId, String login, String password, String authType,
5634 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
5635 Map<String, Object> resultsMap)
5636 throws PortalException, SystemException {
5637
5638 if (PropsValues.AUTH_LOGIN_DISABLED) {
5639 return Authenticator.FAILURE;
5640 }
5641
5642 login = StringUtil.toLowerCase(login.trim());
5643
5644 long userId = GetterUtil.getLong(login);
5645
5646
5647
5648 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5649 if (Validator.isNull(login)) {
5650 throw new UserEmailAddressException();
5651 }
5652 }
5653 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5654 if (Validator.isNull(login)) {
5655 throw new UserScreenNameException();
5656 }
5657 }
5658 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5659 if (Validator.isNull(login)) {
5660 throw new UserIdException();
5661 }
5662 }
5663
5664 if (Validator.isNull(password)) {
5665 throw new UserPasswordException(
5666 UserPasswordException.PASSWORD_INVALID);
5667 }
5668
5669 int authResult = Authenticator.FAILURE;
5670
5671
5672
5673 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5674 authResult = AuthPipeline.authenticateByEmailAddress(
5675 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5676 headerMap, parameterMap);
5677 }
5678 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5679 authResult = AuthPipeline.authenticateByScreenName(
5680 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5681 headerMap, parameterMap);
5682 }
5683 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5684 authResult = AuthPipeline.authenticateByUserId(
5685 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
5686 headerMap, parameterMap);
5687 }
5688
5689
5690
5691 User user = null;
5692
5693 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5694 user = fetchUserByEmailAddress(companyId, login);
5695 }
5696 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5697 user = fetchUserByScreenName(companyId, login);
5698 }
5699 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5700 user = userPersistence.fetchByPrimaryKey(GetterUtil.getLong(login));
5701 }
5702
5703 if (user == null) {
5704 return Authenticator.DNE;
5705 }
5706
5707 if (!isUserAllowedToAuthenticate(user)) {
5708 return Authenticator.FAILURE;
5709 }
5710
5711 if (!user.isPasswordEncrypted()) {
5712 user.setPassword(PasswordEncryptorUtil.encrypt(user.getPassword()));
5713 user.setPasswordEncrypted(true);
5714
5715 userPersistence.update(user);
5716 }
5717
5718
5719
5720 boolean skipLiferayCheck = false;
5721
5722 if (authResult == Authenticator.SKIP_LIFERAY_CHECK) {
5723 authResult = Authenticator.SUCCESS;
5724
5725 skipLiferayCheck = true;
5726 }
5727 else if ((authResult == Authenticator.SUCCESS) &&
5728 PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5729
5730 boolean authenticated = PwdAuthenticator.authenticate(
5731 login, password, user.getPassword());
5732
5733 if (authenticated) {
5734 authResult = Authenticator.SUCCESS;
5735 }
5736 else {
5737 authResult = Authenticator.FAILURE;
5738 }
5739 }
5740
5741
5742
5743 if (authResult == Authenticator.SUCCESS) {
5744 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5745 authResult = AuthPipeline.authenticateByEmailAddress(
5746 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5747 headerMap, parameterMap);
5748 }
5749 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5750 authResult = AuthPipeline.authenticateByScreenName(
5751 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5752 headerMap, parameterMap);
5753 }
5754 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5755 authResult = AuthPipeline.authenticateByUserId(
5756 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5757 headerMap, parameterMap);
5758 }
5759 }
5760
5761 if (resultsMap != null) {
5762 resultsMap.put("userId", user.getUserId());
5763 }
5764
5765 if (authResult == Authenticator.SUCCESS) {
5766
5767
5768
5769 if (skipLiferayCheck ||
5770 !PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK ||
5771 Validator.isNull(user.getDigest())) {
5772
5773 String digest = user.getDigest(password);
5774
5775 user.setDigest(digest);
5776
5777 userPersistence.update(user);
5778 }
5779 }
5780
5781
5782
5783 if (authResult == Authenticator.FAILURE) {
5784 authResult = handleAuthenticationFailure(
5785 login, authType, user, headerMap, parameterMap);
5786 }
5787 else {
5788 resetFailedLoginAttempts(user);
5789 }
5790
5791
5792
5793 return authResult;
5794 }
5795
5796 protected SearchContext buildSearchContext(
5797 long companyId, String firstName, String middleName, String lastName,
5798 String fullName, String screenName, String emailAddress, String street,
5799 String city, String zip, String region, String country, int status,
5800 LinkedHashMap<String, Object> params, boolean andSearch, int start,
5801 int end, Sort sort) {
5802
5803 SearchContext searchContext = new SearchContext();
5804
5805 searchContext.setAndSearch(andSearch);
5806
5807 Map<String, Serializable> attributes =
5808 new HashMap<String, Serializable>();
5809
5810 attributes.put("city", city);
5811 attributes.put("country", country);
5812 attributes.put("emailAddress", emailAddress);
5813 attributes.put("firstName", firstName);
5814 attributes.put("fullName", fullName);
5815 attributes.put("lastName", lastName);
5816 attributes.put("middleName", middleName);
5817 attributes.put("params", params);
5818 attributes.put("region", region);
5819 attributes.put("screenName", screenName);
5820 attributes.put("street", street);
5821 attributes.put("status", status);
5822 attributes.put("zip", zip);
5823
5824 searchContext.setAttributes(attributes);
5825
5826 searchContext.setCompanyId(companyId);
5827 searchContext.setEnd(end);
5828
5829 if (params != null) {
5830 String keywords = (String)params.remove("keywords");
5831
5832 if (Validator.isNotNull(keywords)) {
5833 searchContext.setKeywords(keywords);
5834 }
5835 }
5836
5837 QueryConfig queryConfig = new QueryConfig();
5838
5839 queryConfig.setHighlightEnabled(false);
5840 queryConfig.setScoreEnabled(false);
5841
5842 searchContext.setQueryConfig(queryConfig);
5843
5844 if (sort != null) {
5845 searchContext.setSorts(sort);
5846 }
5847
5848 searchContext.setStart(start);
5849
5850 return searchContext;
5851 }
5852
5853 protected Date getBirthday(
5854 int birthdayMonth, int birthdayDay, int birthdayYear)
5855 throws PortalException {
5856
5857 Date birthday = PortalUtil.getDate(
5858 birthdayMonth, birthdayDay, birthdayYear,
5859 ContactBirthdayException.class);
5860
5861 Date now = new Date();
5862
5863 if (birthday.after(now)) {
5864 throw new ContactBirthdayException();
5865 }
5866
5867 return birthday;
5868 }
5869
5870 protected String getLogin(String login) {
5871 return StringUtil.lowerCase(StringUtil.trim(login));
5872 }
5873
5874 protected long[] getUserIds(List<User> users) {
5875 long[] userIds = new long[users.size()];
5876
5877 for (int i = 0; i < users.size(); i++) {
5878 User user = users.get(i);
5879
5880 userIds[i] = user.getUserId();
5881 }
5882
5883 return userIds;
5884 }
5885
5886 protected int handleAuthenticationFailure(
5887 String login, String authType, User user,
5888 Map<String, String[]> headerMap, Map<String, String[]> parameterMap) {
5889
5890 if (user == null) {
5891 return Authenticator.DNE;
5892 }
5893
5894 try {
5895 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5896 AuthPipeline.onFailureByEmailAddress(
5897 PropsKeys.AUTH_FAILURE, user.getCompanyId(), login,
5898 headerMap, parameterMap);
5899 }
5900 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5901 AuthPipeline.onFailureByScreenName(
5902 PropsKeys.AUTH_FAILURE, user.getCompanyId(), login,
5903 headerMap, parameterMap);
5904 }
5905 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5906 AuthPipeline.onFailureByUserId(
5907 PropsKeys.AUTH_FAILURE, user.getCompanyId(),
5908 user.getUserId(), headerMap, parameterMap);
5909 }
5910
5911 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5912
5913 if (user == null) {
5914 return Authenticator.DNE;
5915 }
5916
5917
5918
5919 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5920 user.getCompanyId())) {
5921
5922 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5923
5924 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5925
5926 int failedLoginAttempts = user.getFailedLoginAttempts();
5927 int maxFailures = passwordPolicy.getMaxFailure();
5928
5929 if ((failedLoginAttempts >= maxFailures) &&
5930 (maxFailures != 0)) {
5931
5932 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5933 AuthPipeline.onMaxFailuresByEmailAddress(
5934 PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
5935 login, headerMap, parameterMap);
5936 }
5937 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5938 AuthPipeline.onMaxFailuresByScreenName(
5939 PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
5940 login, headerMap, parameterMap);
5941 }
5942 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5943 AuthPipeline.onMaxFailuresByUserId(
5944 PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
5945 user.getUserId(), headerMap, parameterMap);
5946 }
5947 }
5948 }
5949 }
5950 catch (Exception e) {
5951 _log.error(e, e);
5952 }
5953
5954 return Authenticator.FAILURE;
5955 }
5956
5957
5968 protected boolean hasManageLayoutsPermission(
5969 long groupId, PermissionChecker permissionChecker)
5970 throws PortalException, SystemException {
5971
5972 return GroupPermissionUtil.contains(
5973 permissionChecker, groupId, ActionKeys.MANAGE_LAYOUTS);
5974 }
5975
5976
5988 protected boolean hasManageLayoutsOrgPermission(
5989 long[] organizationIds, User user)
5990 throws PortalException, SystemException {
5991
5992 if (ArrayUtil.isEmpty(organizationIds)) {
5993 return false;
5994 }
5995
5996 try {
5997 PermissionChecker permissionChecker =
5998 PermissionCheckerFactoryUtil.create(user);
5999
6000 long organizationClassId =
6001 ClassNameLocalServiceUtil.fetchClassNameId(
6002 Organization.class.getName());
6003
6004 for (long organizationId : organizationIds) {
6005 Group group = groupPersistence.fetchByC_C_C(
6006 user.getCompanyId(), organizationClassId, organizationId);
6007
6008 if (hasManageLayoutsPermission(
6009 group.getGroupId(), permissionChecker)) {
6010
6011 return true;
6012 }
6013 }
6014 }
6015 catch (Exception e) {
6016 }
6017
6018 return false;
6019 }
6020
6021
6034 protected boolean hasManageLayoutsRolePermission(User user)
6035 throws PortalException, SystemException {
6036
6037 try {
6038 PermissionChecker permissionChecker =
6039 PermissionCheckerFactoryUtil.create(user);
6040
6041 return GroupPermissionUtil.contains(
6042 permissionChecker, ActionKeys.MANAGE_LAYOUTS);
6043 }
6044 catch (Exception e) {
6045 }
6046
6047 return false;
6048 }
6049
6050
6062 protected boolean hasManageLayoutsSitePermission(long[] groupIds, User user)
6063 throws PortalException, SystemException {
6064
6065 if (ArrayUtil.isEmpty(groupIds)) {
6066 return false;
6067 }
6068
6069 try {
6070 PermissionChecker permissionChecker =
6071 PermissionCheckerFactoryUtil.create(user);
6072
6073 for (long groupId : groupIds) {
6074 if (hasManageLayoutsPermission(groupId, permissionChecker)) {
6075 return true;
6076 }
6077 }
6078 }
6079 catch (Exception e) {
6080 }
6081
6082 return false;
6083 }
6084
6085 protected boolean isUserAllowedToAuthenticate(User user)
6086 throws PortalException, SystemException {
6087
6088 if (user.isDefaultUser()) {
6089 if (_log.isInfoEnabled()) {
6090 _log.info("Authentication is disabled for the default user");
6091 }
6092
6093 return false;
6094 }
6095 else if (!user.isActive()) {
6096 if (_log.isInfoEnabled()) {
6097 _log.info(
6098 "Authentication is disabled for inactive user " +
6099 user.getUserId());
6100 }
6101
6102 return false;
6103 }
6104
6105
6106
6107
6108 checkLockout(user);
6109
6110 checkPasswordExpired(user);
6111
6112 return true;
6113 }
6114
6115 protected boolean isUseCustomSQL(LinkedHashMap<String, Object> params) {
6116 if ((params == null) || params.isEmpty()) {
6117 return false;
6118 }
6119
6120 for (String key : params.keySet()) {
6121 if (!key.equals("forceDatabase") &&
6122 !key.equals("inherit") &&
6123 !key.equals("usersGroups") &&
6124 !key.equals("usersOrgs") &&
6125 !key.equals("usersOrgsCount") &&
6126 !key.equals("usersRoles") &&
6127 !key.equals("usersTeams") &&
6128 !key.equals("usersUserGroups")) {
6129
6130 return true;
6131 }
6132 }
6133
6134 Boolean inherit = (Boolean)params.get("inherit");
6135
6136 if ((inherit != null) && inherit) {
6137 return true;
6138 }
6139
6140 Boolean forceDatabase = (Boolean)params.get("forceDatabase");
6141
6142 if ((forceDatabase != null) && forceDatabase) {
6143 return true;
6144 }
6145
6146 return false;
6147 }
6148
6149 protected void reindex(final User user) {
6150 final Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6151 User.class);
6152
6153 Callable<Void> callable = new ShardCallable<Void>(
6154 user.getCompanyId()) {
6155
6156 @Override
6157 protected Void doCall() throws Exception {
6158 indexer.reindex(user);
6159
6160 return null;
6161 }
6162
6163 };
6164
6165 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
6166 }
6167
6168 protected void resetFailedLoginAttempts(User user) throws SystemException {
6169 resetFailedLoginAttempts(user, false);
6170 }
6171
6172 protected void resetFailedLoginAttempts(User user, boolean forceUpdate)
6173 throws SystemException {
6174
6175 if (forceUpdate || (user.getFailedLoginAttempts() > 0)) {
6176 user.setFailedLoginAttempts(0);
6177
6178 userPersistence.update(user);
6179 }
6180 }
6181
6182 protected Hits search(
6183 long companyId, String firstName, String middleName,
6184 String lastName, String fullName, String screenName,
6185 String emailAddress, String street, String city, String zip,
6186 String region, String country, int status,
6187 LinkedHashMap<String, Object> params, boolean andSearch, int start,
6188 int end, Sort sort)
6189 throws SystemException {
6190
6191 try {
6192 SearchContext searchContext = new SearchContext();
6193
6194 searchContext.setAndSearch(andSearch);
6195
6196 Map<String, Serializable> attributes =
6197 new HashMap<String, Serializable>();
6198
6199 attributes.put("city", city);
6200 attributes.put("country", country);
6201 attributes.put("emailAddress", emailAddress);
6202 attributes.put("firstName", firstName);
6203 attributes.put("fullName", fullName);
6204 attributes.put("lastName", lastName);
6205 attributes.put("middleName", middleName);
6206 attributes.put("params", params);
6207 attributes.put("region", region);
6208 attributes.put("screenName", screenName);
6209 attributes.put("street", street);
6210 attributes.put("status", status);
6211 attributes.put("zip", zip);
6212
6213 searchContext.setAttributes(attributes);
6214
6215 searchContext.setCompanyId(companyId);
6216 searchContext.setEnd(end);
6217
6218 if (params != null) {
6219 String keywords = (String)params.remove("keywords");
6220
6221 if (Validator.isNotNull(keywords)) {
6222 searchContext.setKeywords(keywords);
6223 }
6224 }
6225
6226 QueryConfig queryConfig = new QueryConfig();
6227
6228 queryConfig.setHighlightEnabled(false);
6229 queryConfig.setScoreEnabled(false);
6230
6231 searchContext.setQueryConfig(queryConfig);
6232
6233 if (sort != null) {
6234 searchContext.setSorts(sort);
6235 }
6236
6237 searchContext.setStart(start);
6238
6239 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6240 User.class);
6241
6242 return indexer.search(searchContext);
6243 }
6244 catch (Exception e) {
6245 throw new SystemException(e);
6246 }
6247 }
6248
6249 protected void sendEmail(
6250 User user, String password, ServiceContext serviceContext)
6251 throws SystemException {
6252
6253 if (!PrefsPropsUtil.getBoolean(
6254 user.getCompanyId(),
6255 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
6256
6257 return;
6258 }
6259
6260 String fromName = PrefsPropsUtil.getString(
6261 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
6262 String fromAddress = PrefsPropsUtil.getString(
6263 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
6264
6265 String toName = user.getFullName();
6266 String toAddress = user.getEmailAddress();
6267
6268 String subject = PrefsPropsUtil.getContent(
6269 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
6270
6271 String body = null;
6272
6273 if (Validator.isNotNull(password)) {
6274 body = PrefsPropsUtil.getContent(
6275 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
6276 }
6277 else {
6278 body = PrefsPropsUtil.getContent(
6279 user.getCompanyId(),
6280 PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
6281 }
6282
6283 SubscriptionSender subscriptionSender = new SubscriptionSender();
6284
6285 subscriptionSender.setBody(body);
6286 subscriptionSender.setCompanyId(user.getCompanyId());
6287 subscriptionSender.setContextAttributes(
6288 "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
6289 "[$USER_SCREENNAME$]", user.getScreenName());
6290 subscriptionSender.setFrom(fromAddress, fromName);
6291 subscriptionSender.setHtmlFormat(true);
6292 subscriptionSender.setMailId("user", user.getUserId());
6293 subscriptionSender.setServiceContext(serviceContext);
6294 subscriptionSender.setSubject(subject);
6295 subscriptionSender.setUserId(user.getUserId());
6296
6297 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
6298
6299 subscriptionSender.flushNotificationsAsync();
6300 }
6301
6302 protected void setEmailAddress(
6303 User user, String password, String firstName, String middleName,
6304 String lastName, String emailAddress)
6305 throws PortalException, SystemException {
6306
6307 if (StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
6308 return;
6309 }
6310
6311 long userId = user.getUserId();
6312
6313
6314
6315 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
6316 Validator.isNotNull(password)) {
6317
6318 mailService.addUser(
6319 user.getCompanyId(), userId, password, firstName, middleName,
6320 lastName, emailAddress);
6321 }
6322
6323
6324
6325 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
6326 mailService.updateEmailAddress(
6327 user.getCompanyId(), userId, emailAddress);
6328 }
6329
6330
6331
6332 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
6333 mailService.deleteEmailAddress(user.getCompanyId(), userId);
6334 }
6335
6336 user.setEmailAddress(emailAddress);
6337 user.setDigest(StringPool.BLANK);
6338 }
6339
6340 protected void trackPassword(User user)
6341 throws PortalException, SystemException {
6342
6343 String oldEncPwd = user.getPassword();
6344
6345 if (!user.isPasswordEncrypted()) {
6346 oldEncPwd = PasswordEncryptorUtil.encrypt(user.getPassword());
6347 }
6348
6349 passwordTrackerLocalService.trackPassword(user.getUserId(), oldEncPwd);
6350 }
6351
6352
6359 protected void unsetToggleControlsPreference(long userId)
6360 throws PortalException, SystemException {
6361
6362 PortletPreferencesFactoryImpl portletPreferencesFactory =
6363 new PortletPreferencesFactoryImpl();
6364
6365 PortalPreferences portalPreferences =
6366 portletPreferencesFactory.getPortalPreferences(userId, false);
6367
6368 String toggleControls = portalPreferences.getValue(
6369 SessionClicks.class.getName(),"liferay_toggle_controls", null);
6370
6371 if (Validator.isNotNull(toggleControls) &&
6372 !toggleControls.equals("visible")) {
6373
6374 portalPreferences.setValue(
6375 SessionClicks.class.getName(),"liferay_toggle_controls",
6376 "visible");
6377
6378 String xml = portletPreferencesFactory.toXML(portalPreferences);
6379
6380 PortalPreferencesLocalServiceUtil.updatePreferences(
6381 userId, PortletKeys.PREFS_OWNER_TYPE_USER, xml);
6382 }
6383 }
6384
6385 protected void updateGroups(
6386 long userId, long[] newGroupIds, ServiceContext serviceContext,
6387 boolean indexingEnabled)
6388 throws PortalException, SystemException {
6389
6390 if (newGroupIds == null) {
6391 return;
6392 }
6393
6394 List<Group> oldGroups = userPersistence.getGroups(userId);
6395
6396 Set<Long> oldGroupIds = new HashSet<Long>(oldGroups.size());
6397
6398 for (Group oldGroup : oldGroups) {
6399 long oldGroupId = oldGroup.getGroupId();
6400
6401 oldGroupIds.add(oldGroupId);
6402
6403 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
6404 unsetGroupUsers(
6405 oldGroupId, new long[] {userId}, serviceContext);
6406 }
6407 }
6408
6409 for (long newGroupId : newGroupIds) {
6410 if (!oldGroupIds.contains(newGroupId)) {
6411 addGroupUsers(newGroupId, new long[] {userId});
6412 }
6413 }
6414
6415 if (indexingEnabled) {
6416 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6417 User.class);
6418
6419 indexer.reindex(new long[] {userId});
6420 }
6421
6422 PermissionCacheUtil.clearCache(userId);
6423 }
6424
6425 protected void updateOrganizations(
6426 long userId, long[] newOrganizationIds, boolean indexingEnabled)
6427 throws PortalException, SystemException {
6428
6429 if (newOrganizationIds == null) {
6430 return;
6431 }
6432
6433 List<Organization> oldOrganizations = userPersistence.getOrganizations(
6434 userId);
6435
6436 Set<Long> oldOrganizationIds = new HashSet<Long>(
6437 oldOrganizations.size());
6438
6439 for (Organization oldOrganization : oldOrganizations) {
6440 long oldOrganizationId = oldOrganization.getOrganizationId();
6441
6442 oldOrganizationIds.add(oldOrganizationId);
6443
6444 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
6445 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
6446 }
6447 }
6448
6449 for (long newOrganizationId : newOrganizationIds) {
6450 if (!oldOrganizationIds.contains(newOrganizationId)) {
6451 addOrganizationUsers(newOrganizationId, new long[] {userId});
6452 }
6453 }
6454
6455 if (indexingEnabled) {
6456 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6457 User.class);
6458
6459 indexer.reindex(new long[] {userId});
6460 }
6461
6462 PermissionCacheUtil.clearCache(userId);
6463 }
6464
6465 protected void updateUserGroupRoles(
6466 User user, long[] groupIds, long[] organizationIds,
6467 List<UserGroupRole> userGroupRoles,
6468 List<UserGroupRole> previousUserGroupRoles)
6469 throws PortalException, SystemException {
6470
6471 if (userGroupRoles == null) {
6472 return;
6473 }
6474
6475 userGroupRoles = new ArrayList<UserGroupRole>(userGroupRoles);
6476
6477 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
6478 if (userGroupRoles.contains(userGroupRole)) {
6479 userGroupRoles.remove(userGroupRole);
6480 }
6481 else {
6482 userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
6483 }
6484 }
6485
6486 if (userGroupRoles.isEmpty()) {
6487 return;
6488 }
6489
6490 long[] validGroupIds = null;
6491
6492 if (groupIds != null) {
6493 validGroupIds = ArrayUtil.clone(groupIds);
6494 }
6495 else {
6496 validGroupIds = user.getGroupIds();
6497 }
6498
6499 if (organizationIds == null) {
6500 organizationIds = user.getOrganizationIds();
6501 }
6502
6503 long[] organizationGroupIds = new long[organizationIds.length];
6504
6505 for (int i = 0; i < organizationIds.length; i++) {
6506 long organizationId = organizationIds[i];
6507
6508 Organization organization =
6509 organizationPersistence.findByPrimaryKey(organizationId);
6510
6511 organizationGroupIds[i] = organization.getGroupId();
6512 }
6513
6514 validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
6515
6516 Arrays.sort(validGroupIds);
6517
6518 for (UserGroupRole userGroupRole : userGroupRoles) {
6519 if (Arrays.binarySearch(
6520 validGroupIds, userGroupRole.getGroupId()) >= 0) {
6521
6522 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
6523 }
6524 }
6525 }
6526
6527 protected void validate(
6528 long companyId, long userId, boolean autoPassword, String password1,
6529 String password2, boolean autoScreenName, String screenName,
6530 String emailAddress, String openId, String firstName,
6531 String middleName, String lastName, long[] organizationIds)
6532 throws PortalException, SystemException {
6533
6534 validateCompanyMaxUsers(companyId);
6535
6536 if (!autoScreenName) {
6537 validateScreenName(companyId, userId, screenName);
6538 }
6539
6540 if (!autoPassword) {
6541 PasswordPolicy passwordPolicy =
6542 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
6543
6544 PwdToolkitUtil.validate(
6545 companyId, 0, password1, password2, passwordPolicy);
6546 }
6547
6548 validateEmailAddress(companyId, emailAddress);
6549
6550 if (Validator.isNotNull(emailAddress)) {
6551 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
6552
6553 if ((user != null) && (user.getUserId() != userId)) {
6554 throw new DuplicateUserEmailAddressException(
6555 "{userId=" + userId + "}");
6556 }
6557 }
6558
6559 validateOpenId(companyId, userId, openId);
6560
6561 validateFullName(companyId, firstName, middleName, lastName);
6562
6563 if (organizationIds != null) {
6564 for (long organizationId : organizationIds) {
6565 Organization organization =
6566 organizationPersistence.fetchByPrimaryKey(organizationId);
6567
6568 if (organization == null) {
6569 throw new NoSuchOrganizationException(
6570 "{organizationId=" + organizationId + "}");
6571 }
6572 }
6573 }
6574 }
6575
6576 protected void validate(
6577 long userId, String screenName, String emailAddress, String openId,
6578 String firstName, String middleName, String lastName, String smsSn)
6579 throws PortalException, SystemException {
6580
6581 User user = userPersistence.findByPrimaryKey(userId);
6582
6583 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
6584 validateScreenName(user.getCompanyId(), userId, screenName);
6585 }
6586
6587 validateEmailAddress(user.getCompanyId(), emailAddress);
6588
6589 validateOpenId(user.getCompanyId(), userId, openId);
6590
6591 if (!user.isDefaultUser()) {
6592 if (Validator.isNotNull(emailAddress) &&
6593 !StringUtil.equalsIgnoreCase(
6594 user.getEmailAddress(), emailAddress)) {
6595
6596 if (userPersistence.fetchByC_EA(
6597 user.getCompanyId(), emailAddress) != null) {
6598
6599 throw new DuplicateUserEmailAddressException(
6600 "{userId=" + userId + "}");
6601 }
6602 }
6603
6604 validateFullName(
6605 user.getCompanyId(), firstName, middleName, lastName);
6606 }
6607
6608 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
6609 throw new UserSmsException();
6610 }
6611 }
6612
6613 protected void validateCompanyMaxUsers(long companyId)
6614 throws PortalException, SystemException {
6615
6616 Company company = companyPersistence.findByPrimaryKey(companyId);
6617
6618 if (company.isSystem() || (company.getMaxUsers() == 0)) {
6619 return;
6620 }
6621
6622 int userCount = searchCount(
6623 companyId, null, WorkflowConstants.STATUS_APPROVED, null);
6624
6625 if (userCount >= company.getMaxUsers()) {
6626 throw new CompanyMaxUsersException();
6627 }
6628 }
6629
6630 protected void validateEmailAddress(long companyId, String emailAddress)
6631 throws PortalException, SystemException {
6632
6633 if (Validator.isNull(emailAddress) &&
6634 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
6635
6636 return;
6637 }
6638
6639 EmailAddressValidator emailAddressValidator =
6640 EmailAddressValidatorFactory.getInstance();
6641
6642 if (!emailAddressValidator.validate(companyId, emailAddress)) {
6643 throw new UserEmailAddressException();
6644 }
6645
6646 String pop3User = PrefsPropsUtil.getString(
6647 PropsKeys.MAIL_SESSION_MAIL_POP3_USER,
6648 PropsValues.MAIL_SESSION_MAIL_POP3_USER);
6649
6650 if (StringUtil.equalsIgnoreCase(emailAddress, pop3User)) {
6651 throw new ReservedUserEmailAddressException();
6652 }
6653
6654 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
6655 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
6656 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
6657
6658 for (String reservedEmailAddress : reservedEmailAddresses) {
6659 if (StringUtil.equalsIgnoreCase(
6660 emailAddress, reservedEmailAddress)) {
6661
6662 throw new ReservedUserEmailAddressException();
6663 }
6664 }
6665 }
6666
6667 protected void validateEmailAddress(
6668 User user, String emailAddress1, String emailAddress2)
6669 throws PortalException, SystemException {
6670
6671 if (!emailAddress1.equals(emailAddress2)) {
6672 throw new UserEmailAddressException();
6673 }
6674
6675 validateEmailAddress(user.getCompanyId(), emailAddress1);
6676 validateEmailAddress(user.getCompanyId(), emailAddress2);
6677
6678 if (!StringUtil.equalsIgnoreCase(
6679 emailAddress1, user.getEmailAddress())) {
6680
6681 if (userPersistence.fetchByC_EA(
6682 user.getCompanyId(), emailAddress1) != null) {
6683
6684 throw new DuplicateUserEmailAddressException(
6685 "{userId=" + user.getUserId() + "}");
6686 }
6687 }
6688 }
6689
6690 protected void validateFullName(
6691 long companyId, String firstName, String middleName,
6692 String lastName)
6693 throws PortalException, SystemException {
6694
6695 if (Validator.isNull(firstName)) {
6696 throw new ContactFirstNameException();
6697 }
6698 else if (Validator.isNull(lastName) &&
6699 PrefsPropsUtil.getBoolean(
6700 companyId, PropsKeys.USERS_LAST_NAME_REQUIRED,
6701 PropsValues.USERS_LAST_NAME_REQUIRED)) {
6702
6703 throw new ContactLastNameException();
6704 }
6705
6706 FullNameValidator fullNameValidator =
6707 FullNameValidatorFactory.getInstance();
6708
6709 if (!fullNameValidator.validate(
6710 companyId, firstName, middleName, lastName)) {
6711
6712 throw new ContactFullNameException();
6713 }
6714 }
6715
6716 protected void validateOpenId(long companyId, long userId, String openId)
6717 throws PortalException, SystemException {
6718
6719 if (Validator.isNull(openId)) {
6720 return;
6721 }
6722
6723 User user = userPersistence.fetchByC_O(companyId, openId);
6724
6725 if ((user != null) && (user.getUserId() != userId)) {
6726 throw new DuplicateOpenIdException("{userId=" + userId + "}");
6727 }
6728 }
6729
6730 protected void validatePassword(
6731 long companyId, long userId, String password1, String password2)
6732 throws PortalException, SystemException {
6733
6734 if (Validator.isNull(password1) || Validator.isNull(password2)) {
6735 throw new UserPasswordException(
6736 UserPasswordException.PASSWORD_INVALID);
6737 }
6738
6739 if (!password1.equals(password2)) {
6740 throw new UserPasswordException(
6741 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
6742 }
6743
6744 PasswordPolicy passwordPolicy =
6745 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
6746
6747 PwdToolkitUtil.validate(
6748 companyId, userId, password1, password2, passwordPolicy);
6749 }
6750
6751 protected void validateReminderQuery(String question, String answer)
6752 throws PortalException {
6753
6754 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
6755 return;
6756 }
6757
6758 if (Validator.isNull(question)) {
6759 throw new UserReminderQueryException("Question is null");
6760 }
6761
6762 if (Validator.isNull(answer)) {
6763 throw new UserReminderQueryException("Answer is null");
6764 }
6765 }
6766
6767 protected void validateScreenName(
6768 long companyId, long userId, String screenName)
6769 throws PortalException, SystemException {
6770
6771 if (Validator.isNull(screenName)) {
6772 throw new UserScreenNameException();
6773 }
6774
6775 ScreenNameValidator screenNameValidator =
6776 ScreenNameValidatorFactory.getInstance();
6777
6778 if (!screenNameValidator.validate(companyId, screenName)) {
6779 throw new UserScreenNameException();
6780 }
6781
6782 if (Validator.isNumber(screenName)) {
6783 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
6784 throw new UserScreenNameException();
6785 }
6786
6787 if (!screenName.equals(String.valueOf(userId))) {
6788 Group group = groupPersistence.fetchByPrimaryKey(
6789 GetterUtil.getLong(screenName));
6790
6791 if (group != null) {
6792 throw new UserScreenNameException();
6793 }
6794 }
6795 }
6796
6797 for (char c : screenName.toCharArray()) {
6798 if (!Validator.isChar(c) && !Validator.isDigit(c) &&
6799 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
6800 (c != CharPool.UNDERLINE)) {
6801
6802 throw new UserScreenNameException();
6803 }
6804 }
6805
6806 String[] anonymousNames = BaseServiceImpl.ANONYMOUS_NAMES;
6807
6808 for (String anonymousName : anonymousNames) {
6809 if (StringUtil.equalsIgnoreCase(screenName, anonymousName)) {
6810 throw new UserScreenNameException();
6811 }
6812 }
6813
6814 User user = userPersistence.fetchByC_SN(companyId, screenName);
6815
6816 if ((user != null) && (user.getUserId() != userId)) {
6817 throw new DuplicateUserScreenNameException(
6818 "{userId=" + userId + "}");
6819 }
6820
6821 String friendlyURL = StringPool.SLASH + screenName;
6822
6823 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
6824
6825 if ((group != null) && (group.getClassPK() != userId)) {
6826 throw new GroupFriendlyURLException(
6827 GroupFriendlyURLException.DUPLICATE);
6828 }
6829
6830 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
6831
6832 if (exceptionType != -1) {
6833 throw new UserScreenNameException(
6834 new GroupFriendlyURLException(exceptionType));
6835 }
6836
6837 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
6838 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
6839 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
6840
6841 for (String reservedScreenName : reservedScreenNames) {
6842 if (StringUtil.equalsIgnoreCase(screenName, reservedScreenName)) {
6843 throw new ReservedUserScreenNameException();
6844 }
6845 }
6846 }
6847
6848 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
6849
6850 private Map<Long, User> _defaultUsers = new ConcurrentHashMap<Long, User>();
6851
6852 }