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
2040 @Override
2041 public User fetchUserByContactId(long contactId) throws SystemException {
2042 return userPersistence.fetchByContactId(contactId);
2043 }
2044
2045
2054 @Override
2055 public User fetchUserByEmailAddress(long companyId, String emailAddress)
2056 throws SystemException {
2057
2058 emailAddress = getLogin(emailAddress);
2059
2060 return userPersistence.fetchByC_EA(companyId, emailAddress);
2061 }
2062
2063
2072 @Override
2073 public User fetchUserByFacebookId(long companyId, long facebookId)
2074 throws SystemException {
2075
2076 return userPersistence.fetchByC_FID(companyId, facebookId);
2077 }
2078
2079
2087 @Override
2088 public User fetchUserById(long userId) throws SystemException {
2089 return userPersistence.fetchByPrimaryKey(userId);
2090 }
2091
2092
2101 @Override
2102 public User fetchUserByOpenId(long companyId, String openId)
2103 throws SystemException {
2104
2105 return userPersistence.fetchByC_O(companyId, openId);
2106 }
2107
2108
2117 @Override
2118 public User fetchUserByScreenName(long companyId, String screenName)
2119 throws SystemException {
2120
2121 screenName = getLogin(screenName);
2122
2123 return userPersistence.fetchByC_SN(companyId, screenName);
2124 }
2125
2126
2145 @Override
2146 public List<User> getCompanyUsers(long companyId, int start, int end)
2147 throws SystemException {
2148
2149 return userPersistence.findByCompanyId(companyId, start, end);
2150 }
2151
2152
2159 @Override
2160 public int getCompanyUsersCount(long companyId) throws SystemException {
2161 return userPersistence.countByCompanyId(companyId);
2162 }
2163
2164
2173 @Override
2174 @Skip
2175 public User getDefaultUser(long companyId)
2176 throws PortalException, SystemException {
2177
2178 User userModel = _defaultUsers.get(companyId);
2179
2180 if (userModel == null) {
2181 userModel = userLocalService.loadGetDefaultUser(companyId);
2182
2183 _defaultUsers.put(companyId, userModel);
2184 }
2185
2186 return userModel;
2187 }
2188
2189
2198 @Override
2199 @Skip
2200 public long getDefaultUserId(long companyId)
2201 throws PortalException, SystemException {
2202
2203 User user = getDefaultUser(companyId);
2204
2205 return user.getUserId();
2206 }
2207
2208
2215 @Override
2216 public long[] getGroupUserIds(long groupId) throws SystemException {
2217 return getUserIds(getGroupUsers(groupId));
2218 }
2219
2220
2230 @Override
2231 public int getGroupUsersCount(long groupId, int status)
2232 throws PortalException, SystemException {
2233
2234 Group group = groupPersistence.findByPrimaryKey(groupId);
2235
2236 LinkedHashMap<String, Object> params =
2237 new LinkedHashMap<String, Object>();
2238
2239 params.put("usersGroups", new Long(groupId));
2240
2241 return searchCount(group.getCompanyId(), null, status, params);
2242 }
2243
2244 @Override
2245 public List<User> getInheritedRoleUsers(
2246 long roleId, int start, int end, OrderByComparator obc)
2247 throws PortalException, SystemException {
2248
2249 Role role = rolePersistence.findByPrimaryKey(roleId);
2250
2251 LinkedHashMap<String, Object> params =
2252 new LinkedHashMap<String, Object>();
2253
2254 params.put("inherit", Boolean.TRUE);
2255 params.put("usersRoles", roleId);
2256
2257 return search(
2258 role.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2259 params, start, end, obc);
2260 }
2261
2262
2270 @Override
2271 public List<User> getNoAnnouncementsDeliveries(String type)
2272 throws SystemException {
2273
2274 return userFinder.findByNoAnnouncementsDeliveries(type);
2275 }
2276
2277
2283 @Override
2284 public List<User> getNoContacts() throws SystemException {
2285 return userFinder.findByNoContacts();
2286 }
2287
2288
2295 @Override
2296 public List<User> getNoGroups() throws SystemException {
2297 return userFinder.findByNoGroups();
2298 }
2299
2300
2307 @Override
2308 public long[] getOrganizationUserIds(long organizationId)
2309 throws SystemException {
2310
2311 return getUserIds(getOrganizationUsers(organizationId));
2312 }
2313
2314
2325 @Override
2326 public int getOrganizationUsersCount(long organizationId, int status)
2327 throws PortalException, SystemException {
2328
2329 Organization organization = organizationPersistence.findByPrimaryKey(
2330 organizationId);
2331
2332 LinkedHashMap<String, Object> params =
2333 new LinkedHashMap<String, Object>();
2334
2335 params.put("usersOrgs", new Long(organizationId));
2336
2337 return searchCount(organization.getCompanyId(), null, status, params);
2338 }
2339
2340
2347 @Override
2348 public long[] getRoleUserIds(long roleId) throws SystemException {
2349 return getUserIds(getRoleUsers(roleId));
2350 }
2351
2352
2362 @Override
2363 public int getRoleUsersCount(long roleId, int status)
2364 throws PortalException, SystemException {
2365
2366 Role role = rolePersistence.findByPrimaryKey(roleId);
2367
2368 LinkedHashMap<String, Object> params =
2369 new LinkedHashMap<String, Object>();
2370
2371 params.put("usersRoles", new Long(roleId));
2372
2373 return searchCount(role.getCompanyId(), null, status, params);
2374 }
2375
2376
2406 @Deprecated
2407 @Override
2408 public List<User> getSocialUsers(
2409 long userId, int socialRelationType, int start, int end,
2410 OrderByComparator obc)
2411 throws PortalException, SystemException {
2412
2413 return getSocialUsers(
2414 userId, socialRelationType, StringPool.EQUAL, start, end, obc);
2415 }
2416
2417
2444 @Deprecated
2445 @Override
2446 public List<User> getSocialUsers(
2447 long userId, int start, int end, OrderByComparator obc)
2448 throws PortalException, SystemException {
2449
2450 return getSocialUsers(
2451 userId, SocialRelationConstants.TYPE_UNI_ENEMY,
2452 StringPool.NOT_EQUAL, start, end, obc);
2453 }
2454
2455 @Override
2456 public List<User> getSocialUsers(
2457 long userId, int socialRelationType,
2458 String socialRelationTypeComparator, int start, int end,
2459 OrderByComparator obc)
2460 throws PortalException, SystemException {
2461
2462 if (!socialRelationTypeComparator.equals(StringPool.EQUAL) &&
2463 !socialRelationTypeComparator.equals(StringPool.NOT_EQUAL)) {
2464
2465 throw new IllegalArgumentException(
2466 "Invalid social relation type comparator " +
2467 socialRelationTypeComparator);
2468 }
2469
2470 if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS)) {
2471 List<SocialRelation> socialRelations =
2472 socialRelationPersistence.findByU1_T(
2473 userId, socialRelationType);
2474
2475 if (socialRelationTypeComparator.equals(StringPool.NOT_EQUAL)) {
2476 socialRelations = ListUtil.remove(
2477 socialRelationPersistence.findByUserId1(userId),
2478 socialRelations);
2479 }
2480
2481 List<User> users = new ArrayList<User>();
2482
2483 for (SocialRelation socialRelation : socialRelations) {
2484 User user = userPersistence.findByPrimaryKey(
2485 socialRelation.getUserId2());
2486
2487 if (user.isDefaultUser() ||
2488 (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {
2489
2490 continue;
2491 }
2492
2493 if (!users.contains(user)) {
2494 users.add(user);
2495 }
2496 }
2497
2498 if (obc != null) {
2499 users = ListUtil.sort(users, obc);
2500 }
2501
2502 return users;
2503 }
2504
2505 User user = userPersistence.findByPrimaryKey(userId);
2506
2507 return userFinder.findBySocialUsers(
2508 user.getCompanyId(), userId, socialRelationType,
2509 socialRelationTypeComparator, WorkflowConstants.STATUS_APPROVED,
2510 start, end, obc);
2511 }
2512
2513
2541 @Override
2542 public List<User> getSocialUsers(
2543 long userId1, long userId2, int socialRelationType, int start,
2544 int end, OrderByComparator obc)
2545 throws PortalException, SystemException {
2546
2547 User user1 = userPersistence.findByPrimaryKey(userId1);
2548
2549 LinkedHashMap<String, Object> params =
2550 new LinkedHashMap<String, Object>();
2551
2552 params.put(
2553 "socialMutualRelationType",
2554 new Long[] {userId1, new Long(socialRelationType), userId2,
2555 new Long(socialRelationType)});
2556
2557 return search(
2558 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2559 params, start, end, obc);
2560 }
2561
2562
2587 @Override
2588 public List<User> getSocialUsers(
2589 long userId1, long userId2, int start, int end,
2590 OrderByComparator obc)
2591 throws PortalException, SystemException {
2592
2593 User user1 = userPersistence.findByPrimaryKey(userId1);
2594
2595 LinkedHashMap<String, Object> params =
2596 new LinkedHashMap<String, Object>();
2597
2598 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2599
2600 return search(
2601 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2602 params, start, end, obc);
2603 }
2604
2605
2616 @Deprecated
2617 @Override
2618 public int getSocialUsersCount(long userId)
2619 throws PortalException, SystemException {
2620
2621 return getSocialUsersCount(
2622 userId, SocialRelationConstants.TYPE_UNI_ENEMY,
2623 StringPool.NOT_EQUAL);
2624 }
2625
2626
2642 @Deprecated
2643 @Override
2644 public int getSocialUsersCount(long userId, int socialRelationType)
2645 throws PortalException, SystemException {
2646
2647 return getSocialUsersCount(
2648 userId, socialRelationType, StringPool.EQUAL);
2649 }
2650
2651
2662 @Override
2663 public int getSocialUsersCount(
2664 long userId, int socialRelationType,
2665 String socialRelationTypeComparator)
2666 throws PortalException, SystemException {
2667
2668 User user = userPersistence.findByPrimaryKey(userId);
2669
2670 if (!socialRelationTypeComparator.equals(StringPool.EQUAL) &&
2671 !socialRelationTypeComparator.equals(StringPool.NOT_EQUAL)) {
2672
2673 throw new IllegalArgumentException(
2674 "Invalid social relation type comparator " +
2675 socialRelationTypeComparator);
2676 }
2677
2678 return userFinder.countBySocialUsers(
2679 user.getCompanyId(), user.getUserId(), socialRelationType,
2680 socialRelationTypeComparator, WorkflowConstants.STATUS_APPROVED);
2681 }
2682
2683
2693 @Override
2694 public int getSocialUsersCount(long userId1, long userId2)
2695 throws PortalException, SystemException {
2696
2697 User user1 = userPersistence.findByPrimaryKey(userId1);
2698
2699 LinkedHashMap<String, Object> params =
2700 new LinkedHashMap<String, Object>();
2701
2702 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2703
2704 return searchCount(
2705 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2706 params);
2707 }
2708
2709
2723 @Override
2724 public int getSocialUsersCount(
2725 long userId1, long userId2, int socialRelationType)
2726 throws PortalException, SystemException {
2727
2728 User user1 = userPersistence.findByPrimaryKey(userId1);
2729
2730 LinkedHashMap<String, Object> params =
2731 new LinkedHashMap<String, Object>();
2732
2733 params.put(
2734 "socialMutualRelationType",
2735 new Long[] {userId1, new Long(socialRelationType), userId2,
2736 new Long(socialRelationType)});
2737
2738 return searchCount(
2739 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2740 params);
2741 }
2742
2743
2751 @Override
2752 public User getUserByContactId(long contactId)
2753 throws PortalException, SystemException {
2754
2755 return userPersistence.findByContactId(contactId);
2756 }
2757
2758
2768 @Override
2769 public User getUserByEmailAddress(long companyId, String emailAddress)
2770 throws PortalException, SystemException {
2771
2772 emailAddress = getLogin(emailAddress);
2773
2774 return userPersistence.findByC_EA(companyId, emailAddress);
2775 }
2776
2777
2786 @Override
2787 public User getUserByFacebookId(long companyId, long facebookId)
2788 throws PortalException, SystemException {
2789
2790 return userPersistence.findByC_FID(companyId, facebookId);
2791 }
2792
2793
2801 @Override
2802 public User getUserById(long userId)
2803 throws PortalException, SystemException {
2804
2805 return userPersistence.findByPrimaryKey(userId);
2806 }
2807
2808
2818 @Override
2819 public User getUserById(long companyId, long userId)
2820 throws PortalException, SystemException {
2821
2822 return userPersistence.findByC_U(companyId, userId);
2823 }
2824
2825
2834 @Override
2835 public User getUserByOpenId(long companyId, String openId)
2836 throws PortalException, SystemException {
2837
2838 return userPersistence.findByC_O(companyId, openId);
2839 }
2840
2841
2849 @Override
2850 public User getUserByPortraitId(long portraitId)
2851 throws PortalException, SystemException {
2852
2853 return userPersistence.findByPortraitId(portraitId);
2854 }
2855
2856
2865 @Override
2866 public User getUserByScreenName(long companyId, String screenName)
2867 throws PortalException, SystemException {
2868
2869 screenName = getLogin(screenName);
2870
2871 return userPersistence.findByC_SN(companyId, screenName);
2872 }
2873
2874
2884 @Override
2885 public User getUserByUuid(String uuid)
2886 throws PortalException, SystemException {
2887
2888 List<User> users = userPersistence.findByUuid(uuid);
2889
2890 if (users.isEmpty()) {
2891 throw new NoSuchUserException("{uuid=" + uuid + "}");
2892 }
2893 else {
2894 return users.get(0);
2895 }
2896 }
2897
2898
2907 @Override
2908 public User getUserByUuidAndCompanyId(String uuid, long companyId)
2909 throws PortalException, SystemException {
2910
2911 List<User> users = userPersistence.findByUuid_C(uuid, companyId);
2912
2913 if (users.isEmpty()) {
2914 StringBundler sb = new StringBundler(5);
2915
2916 sb.append("{uuid=");
2917 sb.append(uuid);
2918 sb.append(", companyId=");
2919 sb.append(companyId);
2920 sb.append("}");
2921
2922 throw new NoSuchUserException(sb.toString());
2923 }
2924 else {
2925 return users.get(0);
2926 }
2927 }
2928
2929
2939 @Override
2940 public int getUserGroupUsersCount(long userGroupId, int status)
2941 throws PortalException, SystemException {
2942
2943 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
2944 userGroupId);
2945
2946 LinkedHashMap<String, Object> params =
2947 new LinkedHashMap<String, Object>();
2948
2949 params.put("usersUserGroups", new Long(userGroupId));
2950
2951 return searchCount(userGroup.getCompanyId(), null, status, params);
2952 }
2953
2954
2964 @Override
2965 public long getUserIdByEmailAddress(long companyId, String emailAddress)
2966 throws PortalException, SystemException {
2967
2968 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
2969
2970 User user = userPersistence.findByC_EA(companyId, emailAddress);
2971
2972 return user.getUserId();
2973 }
2974
2975
2984 @Override
2985 public long getUserIdByScreenName(long companyId, String screenName)
2986 throws PortalException, SystemException {
2987
2988 screenName = getLogin(screenName);
2989
2990 User user = userPersistence.findByC_SN(companyId, screenName);
2991
2992 return user.getUserId();
2993 }
2994
2995
3005 @Override
3006 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
3007 throws SystemException {
3008
3009 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
3010 passwordPolicyId, User.class.getName(), userId);
3011 }
3012
3013
3028 @Override
3029 public boolean hasRoleUser(
3030 long companyId, String name, long userId, boolean inherited)
3031 throws PortalException, SystemException {
3032
3033 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
3034 }
3035
3036
3046 @Override
3047 public boolean isPasswordExpired(User user)
3048 throws PortalException, SystemException {
3049
3050 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3051
3052 if ((passwordPolicy != null) && passwordPolicy.getExpireable()) {
3053 Date now = new Date();
3054
3055 if (user.getPasswordModifiedDate() == null) {
3056 user.setPasswordModifiedDate(now);
3057
3058 userLocalService.updateUser(user);
3059 }
3060
3061 long passwordStartTime = user.getPasswordModifiedDate().getTime();
3062 long elapsedTime = now.getTime() - passwordStartTime;
3063
3064 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
3065 return true;
3066 }
3067 else {
3068 return false;
3069 }
3070 }
3071
3072 return false;
3073 }
3074
3075
3087 @Override
3088 public boolean isPasswordExpiringSoon(User user)
3089 throws PortalException, SystemException {
3090
3091 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3092
3093 if ((passwordPolicy != null) && passwordPolicy.isExpireable() &&
3094 (passwordPolicy.getWarningTime() > 0)) {
3095
3096 Date now = new Date();
3097
3098 if (user.getPasswordModifiedDate() == null) {
3099 user.setPasswordModifiedDate(now);
3100
3101 userLocalService.updateUser(user);
3102 }
3103
3104 long timeModified = user.getPasswordModifiedDate().getTime();
3105 long passwordExpiresOn =
3106 (passwordPolicy.getMaxAge() * 1000) + timeModified;
3107
3108 long timeStartWarning =
3109 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
3110
3111 if (now.getTime() > timeStartWarning) {
3112 return true;
3113 }
3114 else {
3115 return false;
3116 }
3117 }
3118
3119 return false;
3120 }
3121
3122
3130 @Override
3131 public User loadGetDefaultUser(long companyId)
3132 throws PortalException, SystemException {
3133
3134 return userPersistence.findByC_DU(companyId, true);
3135 }
3136
3137
3169 @Override
3170 public List<User> search(
3171 long companyId, String keywords, int status,
3172 LinkedHashMap<String, Object> params, int start, int end,
3173 OrderByComparator obc)
3174 throws SystemException {
3175
3176 return userFinder.findByKeywords(
3177 companyId, keywords, status, params, start, end, obc);
3178 }
3179
3180
3211 @Override
3212 public Hits search(
3213 long companyId, String keywords, int status,
3214 LinkedHashMap<String, Object> params, int start, int end, Sort sort)
3215 throws SystemException {
3216
3217 String firstName = null;
3218 String middleName = null;
3219 String lastName = null;
3220 String fullName = null;
3221 String screenName = null;
3222 String emailAddress = null;
3223 String street = null;
3224 String city = null;
3225 String zip = null;
3226 String region = null;
3227 String country = null;
3228 boolean andOperator = false;
3229
3230 if (Validator.isNotNull(keywords)) {
3231 firstName = keywords;
3232 middleName = keywords;
3233 lastName = keywords;
3234 fullName = keywords;
3235 screenName = keywords;
3236 emailAddress = keywords;
3237 street = keywords;
3238 city = keywords;
3239 zip = keywords;
3240 region = keywords;
3241 country = keywords;
3242 }
3243 else {
3244 andOperator = true;
3245 }
3246
3247 if (params != null) {
3248 params.put("keywords", keywords);
3249 }
3250
3251 try {
3252 SearchContext searchContext = buildSearchContext(
3253 companyId, firstName, middleName, lastName, fullName,
3254 screenName, emailAddress, street, city, zip, region, country,
3255 status, params, andOperator, start, end, sort);
3256
3257 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3258 User.class);
3259
3260 return indexer.search(searchContext);
3261 }
3262 catch (Exception e) {
3263 throw new SystemException(e);
3264 }
3265 }
3266
3267
3307 @Override
3308 public List<User> search(
3309 long companyId, String firstName, String middleName,
3310 String lastName, String screenName, String emailAddress, int status,
3311 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3312 int end, OrderByComparator obc)
3313 throws SystemException {
3314
3315 return userFinder.findByC_FN_MN_LN_SN_EA_S(
3316 companyId, firstName, middleName, lastName, screenName,
3317 emailAddress, status, params, andSearch, start, end, obc);
3318 }
3319
3320
3359 @Override
3360 public Hits search(
3361 long companyId, String firstName, String middleName,
3362 String lastName, String screenName, String emailAddress, int status,
3363 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3364 int end, Sort sort)
3365 throws SystemException {
3366
3367 try {
3368 SearchContext searchContext = buildSearchContext(
3369 companyId, firstName, middleName, lastName, null, screenName,
3370 emailAddress, null, null, null, null, null, status, params,
3371 andSearch, start, end, sort);
3372
3373 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3374 User.class);
3375
3376 return indexer.search(searchContext);
3377 }
3378 catch (Exception e) {
3379 throw new SystemException(e);
3380 }
3381 }
3382
3383
3397 @Override
3398 public int searchCount(
3399 long companyId, String keywords, int status,
3400 LinkedHashMap<String, Object> params)
3401 throws SystemException {
3402
3403 if (!PropsValues.USERS_INDEXER_ENABLED ||
3404 !PropsValues.USERS_SEARCH_WITH_INDEX || isUseCustomSQL(params)) {
3405
3406 return userFinder.countByKeywords(
3407 companyId, keywords, status, params);
3408 }
3409
3410 try {
3411 String firstName = null;
3412 String middleName = null;
3413 String lastName = null;
3414 String fullName = null;
3415 String screenName = null;
3416 String emailAddress = null;
3417 String street = null;
3418 String city = null;
3419 String zip = null;
3420 String region = null;
3421 String country = null;
3422 boolean andOperator = false;
3423
3424 if (Validator.isNotNull(keywords)) {
3425 firstName = keywords;
3426 middleName = keywords;
3427 lastName = keywords;
3428 fullName = keywords;
3429 screenName = keywords;
3430 emailAddress = keywords;
3431 street = keywords;
3432 city = keywords;
3433 zip = keywords;
3434 region = keywords;
3435 country = keywords;
3436 }
3437 else {
3438 andOperator = true;
3439 }
3440
3441 if (params != null) {
3442 params.put("keywords", keywords);
3443 }
3444
3445 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3446 User.class);
3447
3448 SearchContext searchContext = buildSearchContext(
3449 companyId, firstName, middleName, lastName, fullName,
3450 screenName, emailAddress, street, city, zip, region, country,
3451 status, params, andOperator, QueryUtil.ALL_POS,
3452 QueryUtil.ALL_POS, null);
3453
3454 Hits hits = indexer.search(searchContext);
3455
3456 return hits.getLength();
3457 }
3458 catch (Exception e) {
3459 throw new SystemException(e);
3460 }
3461 }
3462
3463
3485 @Override
3486 public int searchCount(
3487 long companyId, String firstName, String middleName,
3488 String lastName, String screenName, String emailAddress, int status,
3489 LinkedHashMap<String, Object> params, boolean andSearch)
3490 throws SystemException {
3491
3492 if (!PropsValues.USERS_INDEXER_ENABLED ||
3493 !PropsValues.USERS_SEARCH_WITH_INDEX || isUseCustomSQL(params)) {
3494
3495 return userFinder.countByC_FN_MN_LN_SN_EA_S(
3496 companyId, firstName, middleName, lastName, screenName,
3497 emailAddress, status, params, andSearch);
3498 }
3499
3500 try {
3501 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3502 User.class);
3503
3504 FullNameGenerator fullNameGenerator =
3505 FullNameGeneratorFactory.getInstance();
3506
3507 String fullName = fullNameGenerator.getFullName(
3508 firstName, middleName, lastName);
3509
3510 SearchContext searchContext = buildSearchContext(
3511 companyId, firstName, middleName, lastName, fullName,
3512 screenName, emailAddress, null, null, null, null, null, status,
3513 params, true, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
3514
3515 Hits hits = indexer.search(searchContext);
3516
3517 return hits.getLength();
3518 }
3519 catch (Exception e) {
3520 throw new SystemException(e);
3521 }
3522 }
3523
3524
3535 @Override
3536 public void sendEmailAddressVerification(
3537 User user, String emailAddress, ServiceContext serviceContext)
3538 throws PortalException, SystemException {
3539
3540 if (user.isEmailAddressVerified() &&
3541 StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
3542
3543 return;
3544 }
3545
3546 Ticket ticket = ticketLocalService.addDistinctTicket(
3547 user.getCompanyId(), User.class.getName(), user.getUserId(),
3548 TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3549 serviceContext);
3550
3551 String verifyEmailAddressURL =
3552 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3553 "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3554
3555 long plid = serviceContext.getPlid();
3556
3557 if (plid > 0) {
3558 Layout layout = layoutLocalService.fetchLayout(plid);
3559
3560 if (layout != null) {
3561 Group group = layout.getGroup();
3562
3563 if (!layout.isPrivateLayout() && !group.isUser()) {
3564 verifyEmailAddressURL +=
3565 "&p_l_id=" + serviceContext.getPlid();
3566 }
3567 }
3568 }
3569
3570 String fromName = PrefsPropsUtil.getString(
3571 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3572 String fromAddress = PrefsPropsUtil.getString(
3573 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3574
3575 String toName = user.getFullName();
3576 String toAddress = emailAddress;
3577
3578 String subject = PrefsPropsUtil.getContent(
3579 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3580
3581 String body = PrefsPropsUtil.getContent(
3582 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3583
3584 SubscriptionSender subscriptionSender = new SubscriptionSender();
3585
3586 subscriptionSender.setBody(body);
3587 subscriptionSender.setCompanyId(user.getCompanyId());
3588 subscriptionSender.setContextAttributes(
3589 "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3590 "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3591 "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3592 "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_ID$]",
3593 user.getUserId(), "[$USER_SCREENNAME$]", user.getScreenName());
3594 subscriptionSender.setFrom(fromAddress, fromName);
3595 subscriptionSender.setHtmlFormat(true);
3596 subscriptionSender.setMailId("user", user.getUserId());
3597 subscriptionSender.setServiceContext(serviceContext);
3598 subscriptionSender.setSubject(subject);
3599 subscriptionSender.setUserId(user.getUserId());
3600
3601 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3602
3603 subscriptionSender.flushNotificationsAsync();
3604 }
3605
3606
3625 @Override
3626 public void sendPassword(
3627 long companyId, String emailAddress, String fromName,
3628 String fromAddress, String subject, String body,
3629 ServiceContext serviceContext)
3630 throws PortalException, SystemException {
3631
3632 Company company = companyPersistence.findByPrimaryKey(companyId);
3633
3634 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3635 return;
3636 }
3637
3638 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
3639
3640 if (Validator.isNull(emailAddress)) {
3641 throw new UserEmailAddressException();
3642 }
3643
3644 User user = userPersistence.findByC_EA(companyId, emailAddress);
3645
3646 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3647
3648 String newPassword = StringPool.BLANK;
3649 String passwordResetURL = StringPool.BLANK;
3650
3651 if (company.isSendPasswordResetLink()) {
3652 Date expirationDate = null;
3653
3654 if ((passwordPolicy != null) &&
3655 (passwordPolicy.getResetTicketMaxAge() > 0)) {
3656
3657 expirationDate = new Date(
3658 System.currentTimeMillis() +
3659 (passwordPolicy.getResetTicketMaxAge() * 1000));
3660 }
3661
3662 Ticket ticket = ticketLocalService.addDistinctTicket(
3663 companyId, User.class.getName(), user.getUserId(),
3664 TicketConstants.TYPE_PASSWORD, null, expirationDate,
3665 serviceContext);
3666
3667 passwordResetURL =
3668 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3669 "/portal/update_password?p_l_id="+
3670 serviceContext.getPlid() +
3671 "&ticketKey=" + ticket.getKey();
3672 }
3673 else {
3674 if (!PasswordEncryptorUtil.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
3675 PasswordEncryptorUtil.TYPE_NONE)) {
3676
3677 if (LDAPSettingsUtil.isPasswordPolicyEnabled(
3678 user.getCompanyId())) {
3679
3680 if (_log.isWarnEnabled()) {
3681 StringBundler sb = new StringBundler(5);
3682
3683 sb.append("When LDAP password policy is enabled, ");
3684 sb.append("it is possible that portal generated ");
3685 sb.append("passwords will not match the LDAP policy.");
3686 sb.append("Using RegExpToolkit to generate new ");
3687 sb.append("password.");
3688
3689 _log.warn(sb.toString());
3690 }
3691
3692 RegExpToolkit regExpToolkit = new RegExpToolkit();
3693
3694 newPassword = regExpToolkit.generate(null);
3695 }
3696 else {
3697 newPassword = PwdToolkitUtil.generate(passwordPolicy);
3698 }
3699
3700 boolean passwordReset = false;
3701
3702 if (passwordPolicy.getChangeable() &&
3703 passwordPolicy.getChangeRequired()) {
3704
3705 passwordReset = true;
3706 }
3707
3708 user.setPassword(PasswordEncryptorUtil.encrypt(newPassword));
3709 user.setPasswordUnencrypted(newPassword);
3710 user.setPasswordEncrypted(true);
3711 user.setPasswordReset(passwordReset);
3712 user.setPasswordModified(true);
3713 user.setPasswordModifiedDate(new Date());
3714
3715 userPersistence.update(user);
3716
3717 user.setPasswordModified(false);
3718 }
3719 else {
3720 newPassword = user.getPassword();
3721 }
3722 }
3723
3724 if (Validator.isNull(fromName)) {
3725 fromName = PrefsPropsUtil.getString(
3726 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3727 }
3728
3729 if (Validator.isNull(fromAddress)) {
3730 fromAddress = PrefsPropsUtil.getString(
3731 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3732 }
3733
3734 String toName = user.getFullName();
3735 String toAddress = user.getEmailAddress();
3736
3737 if (Validator.isNull(subject)) {
3738 if (company.isSendPasswordResetLink()) {
3739 subject = PrefsPropsUtil.getContent(
3740 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
3741 }
3742 else {
3743 subject = PrefsPropsUtil.getContent(
3744 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
3745 }
3746 }
3747
3748 if (Validator.isNull(body)) {
3749 if (company.isSendPasswordResetLink()) {
3750 body = PrefsPropsUtil.getContent(
3751 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
3752 }
3753 else {
3754 body = PrefsPropsUtil.getContent(
3755 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
3756 }
3757 }
3758
3759 SubscriptionSender subscriptionSender = new SubscriptionSender();
3760
3761 subscriptionSender.setBody(body);
3762 subscriptionSender.setCompanyId(companyId);
3763 subscriptionSender.setContextAttributes(
3764 "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
3765 serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
3766 serviceContext.getRemoteHost(), "[$USER_ID$]", user.getUserId(),
3767 "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
3768 user.getScreenName());
3769 subscriptionSender.setFrom(fromAddress, fromName);
3770 subscriptionSender.setHtmlFormat(true);
3771 subscriptionSender.setMailId("user", user.getUserId());
3772 subscriptionSender.setServiceContext(serviceContext);
3773 subscriptionSender.setSubject(subject);
3774 subscriptionSender.setUserId(user.getUserId());
3775
3776 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3777
3778 subscriptionSender.flushNotificationsAsync();
3779 }
3780
3781
3790 @Override
3791 public void setRoleUsers(long roleId, long[] userIds)
3792 throws PortalException, SystemException {
3793
3794 List<User> oldUsers = rolePersistence.getUsers(roleId);
3795
3796 long[] oldUserIds = new long[oldUsers.size()];
3797
3798 for (int i = 0; i < oldUsers.size(); i++) {
3799 User user = oldUsers.get(i);
3800
3801 oldUserIds[i] = user.getUserId();
3802 }
3803
3804 Set<Long> updatedUserIdsSet = SetUtil.symmetricDifference(
3805 userIds, oldUserIds);
3806
3807 long[] updateUserIds = ArrayUtil.toLongArray(updatedUserIdsSet);
3808
3809 rolePersistence.setUsers(roleId, userIds);
3810
3811 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3812
3813 indexer.reindex(updateUserIds);
3814
3815 PermissionCacheUtil.clearCache(updateUserIds);
3816 }
3817
3818
3827 @Override
3828 @SuppressWarnings("deprecation")
3829 public void setUserGroupUsers(long userGroupId, long[] userIds)
3830 throws PortalException, SystemException {
3831
3832 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3833 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3834 }
3835
3836 List<User> oldUsers = userGroupPersistence.getUsers(userGroupId);
3837
3838 long[] oldUserIds = new long[oldUsers.size()];
3839
3840 for (int i = 0; i < oldUsers.size(); i++) {
3841 User user = oldUsers.get(i);
3842
3843 oldUserIds[i] = user.getUserId();
3844 }
3845
3846 Set<Long> updatedUserIdsSet = SetUtil.symmetricDifference(
3847 userIds, oldUserIds);
3848
3849 long[] updateUserIds = ArrayUtil.toLongArray(updatedUserIdsSet);
3850
3851 userGroupPersistence.setUsers(userGroupId, userIds);
3852
3853 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3854
3855 indexer.reindex(updateUserIds);
3856
3857 PermissionCacheUtil.clearCache(updateUserIds);
3858 }
3859
3860
3868 @Override
3869 public void unsetGroupTeamsUsers(long groupId, long[] userIds)
3870 throws PortalException, SystemException {
3871
3872 List<Team> teams = teamPersistence.findByGroupId(groupId);
3873
3874 for (Team team : teams) {
3875 unsetTeamUsers(team.getTeamId(), userIds);
3876 }
3877
3878 PermissionCacheUtil.clearCache(userIds);
3879 }
3880
3881
3891 @Override
3892 public void unsetGroupUsers(
3893 final long groupId, final long[] userIds,
3894 ServiceContext serviceContext)
3895 throws PortalException, SystemException {
3896
3897 userGroupRoleLocalService.deleteUserGroupRoles(
3898 userIds, groupId, RoleConstants.TYPE_SITE);
3899
3900 userLocalService.unsetGroupTeamsUsers(groupId, userIds);
3901
3902 groupPersistence.removeUsers(groupId, userIds);
3903
3904 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3905
3906 indexer.reindex(userIds);
3907
3908 PermissionCacheUtil.clearCache(userIds);
3909
3910 Callable<Void> callable = new Callable<Void>() {
3911
3912 @Override
3913 public Void call() throws Exception {
3914 Message message = new Message();
3915
3916 message.put("groupId", groupId);
3917 message.put("userIds", userIds);
3918
3919 MessageBusUtil.sendMessage(
3920 DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
3921
3922 return null;
3923 }
3924
3925 };
3926
3927 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
3928 }
3929
3930
3938 @Override
3939 public void unsetOrganizationUsers(
3940 long organizationId, final long[] userIds)
3941 throws PortalException, SystemException {
3942
3943 Organization organization = organizationPersistence.findByPrimaryKey(
3944 organizationId);
3945
3946 final Group group = organization.getGroup();
3947
3948 userGroupRoleLocalService.deleteUserGroupRoles(
3949 userIds, group.getGroupId());
3950
3951 organizationPersistence.removeUsers(organizationId, userIds);
3952
3953 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3954
3955 indexer.reindex(userIds);
3956
3957 PermissionCacheUtil.clearCache(userIds);
3958
3959 Callable<Void> callable = new Callable<Void>() {
3960
3961 @Override
3962 public Void call() throws Exception {
3963 Message message = new Message();
3964
3965 message.put("groupId", group.getGroupId());
3966 message.put("userIds", userIds);
3967
3968 MessageBusUtil.sendMessage(
3969 DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
3970
3971 return null;
3972 }
3973
3974 };
3975
3976 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
3977 }
3978
3979
3986 @Override
3987 public void unsetPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
3988 throws SystemException {
3989
3990 passwordPolicyRelLocalService.deletePasswordPolicyRels(
3991 passwordPolicyId, User.class.getName(), userIds);
3992 }
3993
3994
4002 @Override
4003 public void unsetRoleUsers(long roleId, List<User> users)
4004 throws PortalException, SystemException {
4005
4006 Role role = rolePersistence.findByPrimaryKey(roleId);
4007
4008 String roleName = role.getName();
4009
4010 if ((roleName.equals(RoleConstants.ADMINISTRATOR) &&
4011 (getRoleUsersCount(role.getRoleId()) <= 1)) ||
4012 roleName.equals(RoleConstants.USER)) {
4013
4014 return;
4015 }
4016
4017 rolePersistence.removeUsers(roleId, users);
4018
4019 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
4020
4021 indexer.reindex(users);
4022
4023 long[] userIds = new long[users.size()];
4024
4025 for (int i = 0; i < users.size(); i++) {
4026 User user = users.get(i);
4027
4028 userIds[i] = user.getUserId();
4029 }
4030
4031 PermissionCacheUtil.clearCache(userIds);
4032 }
4033
4034
4042 @Override
4043 public void unsetRoleUsers(long roleId, long[] userIds)
4044 throws PortalException, SystemException {
4045
4046 Role role = rolePersistence.findByPrimaryKey(roleId);
4047
4048 String roleName = role.getName();
4049
4050 if (roleName.equals(RoleConstants.USER) ||
4051 (roleName.equals(RoleConstants.ADMINISTRATOR) &&
4052 getRoleUsersCount(role.getRoleId()) <= 1)) {
4053
4054 return;
4055 }
4056
4057 rolePersistence.removeUsers(roleId, userIds);
4058
4059 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
4060
4061 indexer.reindex(userIds);
4062
4063 PermissionCacheUtil.clearCache(userIds);
4064 }
4065
4066
4074 @Override
4075 public void unsetTeamUsers(long teamId, long[] userIds)
4076 throws PortalException, SystemException {
4077
4078 teamPersistence.removeUsers(teamId, userIds);
4079
4080 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
4081
4082 indexer.reindex(userIds);
4083
4084 PermissionCacheUtil.clearCache(userIds);
4085 }
4086
4087
4095 @Override
4096 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
4097 throws PortalException, SystemException {
4098
4099 userGroupPersistence.removeUsers(userGroupId, userIds);
4100
4101 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
4102
4103 indexer.reindex(userIds);
4104
4105 PermissionCacheUtil.clearCache(userIds);
4106 }
4107
4108
4118 @Override
4119 public User updateAgreedToTermsOfUse(
4120 long userId, boolean agreedToTermsOfUse)
4121 throws PortalException, SystemException {
4122
4123 User user = userPersistence.findByPrimaryKey(userId);
4124
4125 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
4126
4127 userPersistence.update(user);
4128
4129 return user;
4130 }
4131
4132
4143 @Override
4144 public void updateAsset(
4145 long userId, User user, long[] assetCategoryIds,
4146 String[] assetTagNames)
4147 throws PortalException, SystemException {
4148
4149 User owner = userPersistence.findByPrimaryKey(userId);
4150
4151 Company company = companyPersistence.findByPrimaryKey(
4152 owner.getCompanyId());
4153
4154 Group companyGroup = company.getGroup();
4155
4156 assetEntryLocalService.updateEntry(
4157 userId, companyGroup.getGroupId(), user.getCreateDate(),
4158 user.getModifiedDate(), User.class.getName(), user.getUserId(),
4159 user.getUuid(), 0, assetCategoryIds, assetTagNames, false, null,
4160 null, null, null, user.getFullName(), null, null, null, null, 0, 0,
4161 null, false);
4162 }
4163
4164
4173 @Override
4174 public User updateCreateDate(long userId, Date createDate)
4175 throws PortalException, SystemException {
4176
4177 User user = userPersistence.findByPrimaryKey(userId);
4178
4179 user.setCreateDate(createDate);
4180
4181 userPersistence.update(user);
4182
4183 return user;
4184 }
4185
4186
4197 @Override
4198 public User updateEmailAddress(
4199 long userId, String password, String emailAddress1,
4200 String emailAddress2)
4201 throws PortalException, SystemException {
4202
4203 emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
4204 emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
4205
4206 User user = userPersistence.findByPrimaryKey(userId);
4207
4208 validateEmailAddress(user, emailAddress1, emailAddress2);
4209
4210 setEmailAddress(
4211 user, password, user.getFirstName(), user.getMiddleName(),
4212 user.getLastName(), emailAddress1);
4213
4214 userPersistence.update(user);
4215
4216 Contact contact = user.getContact();
4217
4218 contact.setEmailAddress(user.getEmailAddress());
4219
4220 contactPersistence.update(contact);
4221
4222 return user;
4223 }
4224
4225
4239 @Override
4240 public User updateEmailAddress(
4241 long userId, String password, String emailAddress1,
4242 String emailAddress2, ServiceContext serviceContext)
4243 throws PortalException, SystemException {
4244
4245 emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
4246 emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
4247
4248 User user = userPersistence.findByPrimaryKey(userId);
4249
4250 validateEmailAddress(user, emailAddress1, emailAddress2);
4251
4252 Company company = companyPersistence.findByPrimaryKey(
4253 user.getCompanyId());
4254
4255 if (company.isStrangersVerify() &&
4256 !StringUtil.equalsIgnoreCase(
4257 emailAddress1, user.getEmailAddress())) {
4258
4259 sendEmailAddressVerification(user, emailAddress1, serviceContext);
4260 }
4261 else {
4262 setEmailAddress(
4263 user, password, user.getFirstName(), user.getMiddleName(),
4264 user.getLastName(), emailAddress1);
4265
4266 userPersistence.update(user);
4267
4268 Contact contact = user.getContact();
4269
4270 contact.setEmailAddress(user.getEmailAddress());
4271
4272 contactPersistence.update(contact);
4273 }
4274
4275 return user;
4276 }
4277
4278
4287 @Override
4288 public User updateEmailAddressVerified(
4289 long userId, boolean emailAddressVerified)
4290 throws PortalException, SystemException {
4291
4292 User user = userPersistence.findByPrimaryKey(userId);
4293
4294 user.setEmailAddressVerified(emailAddressVerified);
4295
4296 userPersistence.update(user);
4297
4298 return user;
4299 }
4300
4301
4310 @Override
4311 public User updateFacebookId(long userId, long facebookId)
4312 throws PortalException, SystemException {
4313
4314 User user = userPersistence.findByPrimaryKey(userId);
4315
4316 user.setFacebookId(facebookId);
4317
4318 userPersistence.update(user);
4319
4320 return user;
4321 }
4322
4323
4333 @Override
4334 public void updateGroups(
4335 long userId, long[] newGroupIds, ServiceContext serviceContext)
4336 throws PortalException, SystemException {
4337
4338 boolean indexingEnabled = true;
4339
4340 if (serviceContext != null) {
4341 indexingEnabled = serviceContext.isIndexingEnabled();
4342 }
4343
4344 updateGroups(userId, newGroupIds, serviceContext, indexingEnabled);
4345 }
4346
4347
4386 @Override
4387 public User updateIncompleteUser(
4388 long creatorUserId, long companyId, boolean autoPassword,
4389 String password1, String password2, boolean autoScreenName,
4390 String screenName, String emailAddress, long facebookId,
4391 String openId, Locale locale, String firstName, String middleName,
4392 String lastName, int prefixId, int suffixId, boolean male,
4393 int birthdayMonth, int birthdayDay, int birthdayYear,
4394 String jobTitle, boolean updateUserInformation, boolean sendEmail,
4395 ServiceContext serviceContext)
4396 throws PortalException, SystemException {
4397
4398 User user = getUserByEmailAddress(companyId, emailAddress);
4399
4400 if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
4401 throw new PortalException("Invalid user status");
4402 }
4403
4404 User defaultUser = getDefaultUser(companyId);
4405
4406 if (facebookId > 0) {
4407 autoPassword = false;
4408
4409 if ((password1 == null) || (password2 == null)) {
4410 password1 = PwdGenerator.getPassword();
4411 password2 = password1;
4412 }
4413
4414 sendEmail = false;
4415 }
4416
4417 if (updateUserInformation) {
4418 autoScreenName = false;
4419
4420 if (PrefsPropsUtil.getBoolean(
4421 companyId,
4422 PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
4423
4424 autoScreenName = true;
4425 }
4426
4427 validate(
4428 companyId, user.getUserId(), autoPassword, password1, password2,
4429 autoScreenName, screenName, emailAddress, openId, firstName,
4430 middleName, lastName, null);
4431
4432 if (!autoPassword) {
4433 if (Validator.isNull(password1) ||
4434 Validator.isNull(password2)) {
4435 throw new UserPasswordException(
4436 UserPasswordException.PASSWORD_INVALID);
4437 }
4438 }
4439
4440 if (autoScreenName) {
4441 ScreenNameGenerator screenNameGenerator =
4442 ScreenNameGeneratorFactory.getInstance();
4443
4444 try {
4445 screenName = screenNameGenerator.generate(
4446 companyId, user.getUserId(), emailAddress);
4447 }
4448 catch (Exception e) {
4449 throw new SystemException(e);
4450 }
4451 }
4452
4453 FullNameGenerator fullNameGenerator =
4454 FullNameGeneratorFactory.getInstance();
4455
4456 String fullName = fullNameGenerator.getFullName(
4457 firstName, middleName, lastName);
4458
4459 String greeting = LanguageUtil.format(
4460 locale, "welcome-x", " " + fullName, false);
4461
4462 if (Validator.isNotNull(password1)) {
4463 user.setPassword(PasswordEncryptorUtil.encrypt(password1));
4464 user.setPasswordUnencrypted(password1);
4465 }
4466
4467 user.setPasswordEncrypted(true);
4468
4469 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
4470
4471 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
4472 passwordPolicy.isChangeRequired()) {
4473
4474 user.setPasswordReset(true);
4475 }
4476 else {
4477 user.setPasswordReset(false);
4478 }
4479
4480 user.setScreenName(screenName);
4481 user.setFacebookId(facebookId);
4482 user.setOpenId(openId);
4483 user.setLanguageId(locale.toString());
4484 user.setTimeZoneId(defaultUser.getTimeZoneId());
4485 user.setGreeting(greeting);
4486 user.setFirstName(firstName);
4487 user.setMiddleName(middleName);
4488 user.setLastName(lastName);
4489 user.setJobTitle(jobTitle);
4490 user.setExpandoBridgeAttributes(serviceContext);
4491
4492 Date birthday = getBirthday(
4493 birthdayMonth, birthdayDay, birthdayYear);
4494
4495 Contact contact = user.getContact();
4496
4497 contact.setFirstName(firstName);
4498 contact.setMiddleName(middleName);
4499 contact.setLastName(lastName);
4500 contact.setPrefixId(prefixId);
4501 contact.setSuffixId(suffixId);
4502 contact.setMale(male);
4503 contact.setBirthday(birthday);
4504 contact.setJobTitle(jobTitle);
4505
4506 contactPersistence.update(contact, serviceContext);
4507
4508
4509
4510 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4511 User.class);
4512
4513 indexer.reindex(user);
4514 }
4515
4516 user.setStatus(WorkflowConstants.STATUS_DRAFT);
4517
4518 userPersistence.update(user, serviceContext);
4519
4520
4521
4522 long workflowUserId = creatorUserId;
4523
4524 if (workflowUserId == user.getUserId()) {
4525 workflowUserId = defaultUser.getUserId();
4526 }
4527
4528 ServiceContext workflowServiceContext = serviceContext;
4529
4530 if (workflowServiceContext == null) {
4531 workflowServiceContext = new ServiceContext();
4532 }
4533
4534 workflowServiceContext.setAttribute("autoPassword", autoPassword);
4535 workflowServiceContext.setAttribute("passwordUnencrypted", password1);
4536 workflowServiceContext.setAttribute("sendEmail", sendEmail);
4537
4538 WorkflowHandlerRegistryUtil.startWorkflowInstance(
4539 companyId, workflowUserId, User.class.getName(), user.getUserId(),
4540 user, workflowServiceContext);
4541
4542 return getUserByEmailAddress(companyId, emailAddress);
4543 }
4544
4545
4555 @Override
4556 public User updateJobTitle(long userId, String jobTitle)
4557 throws PortalException, SystemException {
4558
4559 User user = userPersistence.findByPrimaryKey(userId);
4560
4561 user.setJobTitle(jobTitle);
4562
4563 userPersistence.update(user);
4564
4565 Contact contact = contactPersistence.findByPrimaryKey(
4566 user.getContactId());
4567
4568 contact.setJobTitle(jobTitle);
4569
4570 contactPersistence.update(contact);
4571
4572 return user;
4573 }
4574
4575
4584 @Override
4585 public User updateLastLogin(long userId, String loginIP)
4586 throws PortalException, SystemException {
4587
4588 User user = userPersistence.findByPrimaryKey(userId);
4589
4590 Date lastLoginDate = user.getLoginDate();
4591
4592 if (lastLoginDate == null) {
4593 lastLoginDate = new Date();
4594 }
4595
4596 user.setLoginDate(new Date());
4597 user.setLoginIP(loginIP);
4598 user.setLastLoginDate(lastLoginDate);
4599 user.setLastLoginIP(user.getLoginIP());
4600
4601 resetFailedLoginAttempts(user, true);
4602
4603 return user;
4604 }
4605
4606
4615 @Override
4616 public User updateLockout(User user, boolean lockout)
4617 throws PortalException, SystemException {
4618
4619 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
4620
4621 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
4622 return user;
4623 }
4624
4625 Date lockoutDate = null;
4626
4627 if (lockout) {
4628 lockoutDate = new Date();
4629 }
4630
4631 user.setLockout(lockout);
4632 user.setLockoutDate(lockoutDate);
4633
4634 if (!lockout) {
4635 user.setLastFailedLoginDate(lockoutDate);
4636 user.setFailedLoginAttempts(0);
4637 }
4638
4639 userPersistence.update(user);
4640
4641 return user;
4642 }
4643
4644
4655 @Override
4656 public User updateLockoutByEmailAddress(
4657 long companyId, String emailAddress, boolean lockout)
4658 throws PortalException, SystemException {
4659
4660 User user = getUserByEmailAddress(companyId, emailAddress);
4661
4662 return updateLockout(user, lockout);
4663 }
4664
4665
4674 @Override
4675 public User updateLockoutById(long userId, boolean lockout)
4676 throws PortalException, SystemException {
4677
4678 User user = userPersistence.findByPrimaryKey(userId);
4679
4680 return updateLockout(user, lockout);
4681 }
4682
4683
4693 @Override
4694 public User updateLockoutByScreenName(
4695 long companyId, String screenName, boolean lockout)
4696 throws PortalException, SystemException {
4697
4698 User user = getUserByScreenName(companyId, screenName);
4699
4700 return updateLockout(user, lockout);
4701 }
4702
4703
4712 @Override
4713 public User updateModifiedDate(long userId, Date modifiedDate)
4714 throws PortalException, SystemException {
4715
4716 User user = userPersistence.findByPrimaryKey(userId);
4717
4718 user.setModifiedDate(modifiedDate);
4719
4720 userPersistence.update(user);
4721
4722 return user;
4723 }
4724
4725
4734 @Override
4735 public User updateOpenId(long userId, String openId)
4736 throws PortalException, SystemException {
4737
4738 openId = openId.trim();
4739
4740 User user = userPersistence.findByPrimaryKey(userId);
4741
4742 user.setOpenId(openId);
4743
4744 userPersistence.update(user);
4745
4746 return user;
4747 }
4748
4749
4760 @Override
4761 public void updateOrganizations(
4762 long userId, long[] newOrganizationIds,
4763 ServiceContext serviceContext)
4764 throws PortalException, SystemException {
4765
4766 updateOrganizations(
4767 userId, newOrganizationIds, serviceContext.isIndexingEnabled());
4768 }
4769
4770
4782 @Override
4783 public User updatePassword(
4784 long userId, String password1, String password2,
4785 boolean passwordReset)
4786 throws PortalException, SystemException {
4787
4788 return updatePassword(
4789 userId, password1, password2, passwordReset, false);
4790 }
4791
4792
4807 @Override
4808 public User updatePassword(
4809 long userId, String password1, String password2,
4810 boolean passwordReset, boolean silentUpdate)
4811 throws PortalException, SystemException {
4812
4813 User user = userPersistence.findByPrimaryKey(userId);
4814
4815 if (!silentUpdate) {
4816 validatePassword(user.getCompanyId(), userId, password1, password2);
4817 }
4818
4819 String oldEncPwd = user.getPassword();
4820
4821 if (!user.isPasswordEncrypted()) {
4822 oldEncPwd = PasswordEncryptorUtil.encrypt(user.getPassword());
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 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
4871 }
4872
4873 return user;
4874 }
4875
4876
4890 @Override
4891 public User updatePasswordManually(
4892 long userId, String password, boolean passwordEncrypted,
4893 boolean passwordReset, Date passwordModifiedDate)
4894 throws PortalException, SystemException {
4895
4896
4897
4898 User user = userPersistence.findByPrimaryKey(userId);
4899
4900 user.setPassword(password);
4901 user.setPasswordEncrypted(passwordEncrypted);
4902 user.setPasswordReset(passwordReset);
4903 user.setPasswordModifiedDate(passwordModifiedDate);
4904 user.setDigest(StringPool.BLANK);
4905
4906 userPersistence.update(user);
4907
4908 return user;
4909 }
4910
4911
4922 @Override
4923 public User updatePasswordReset(long userId, boolean passwordReset)
4924 throws PortalException, SystemException {
4925
4926 User user = userPersistence.findByPrimaryKey(userId);
4927
4928 user.setPasswordReset(passwordReset);
4929
4930 userPersistence.update(user);
4931
4932 return user;
4933 }
4934
4935
4945 @Override
4946 public User updatePortrait(long userId, byte[] bytes)
4947 throws PortalException, SystemException {
4948
4949 User user = userPersistence.findByPrimaryKey(userId);
4950
4951 long imageMaxSize = PrefsPropsUtil.getLong(
4952 PropsKeys.USERS_IMAGE_MAX_SIZE);
4953
4954 if ((imageMaxSize > 0) &&
4955 ((bytes == null) || (bytes.length > imageMaxSize))) {
4956
4957 throw new UserPortraitSizeException();
4958 }
4959
4960 long portraitId = user.getPortraitId();
4961
4962 if (portraitId <= 0) {
4963 portraitId = counterLocalService.increment();
4964
4965 user.setPortraitId(portraitId);
4966 }
4967
4968 try {
4969 ImageBag imageBag = ImageToolUtil.read(bytes);
4970
4971 RenderedImage renderedImage = imageBag.getRenderedImage();
4972
4973 if (renderedImage == null) {
4974 throw new UserPortraitTypeException();
4975 }
4976
4977 renderedImage = ImageToolUtil.scale(
4978 renderedImage, PropsValues.USERS_IMAGE_MAX_HEIGHT,
4979 PropsValues.USERS_IMAGE_MAX_WIDTH);
4980
4981 String contentType = imageBag.getType();
4982
4983 imageLocalService.updateImage(
4984 portraitId,
4985 ImageToolUtil.getBytes(renderedImage, contentType));
4986 }
4987 catch (IOException ioe) {
4988 throw new ImageSizeException(ioe);
4989 }
4990
4991 userPersistence.update(user);
4992
4993 return user;
4994 }
4995
4996
5007 @Override
5008 public User updateReminderQuery(long userId, String question, String answer)
5009 throws PortalException, SystemException {
5010
5011 validateReminderQuery(question, answer);
5012
5013 User user = userPersistence.findByPrimaryKey(userId);
5014
5015 user.setReminderQueryQuestion(question);
5016 user.setReminderQueryAnswer(answer);
5017
5018 userPersistence.update(user);
5019
5020 return user;
5021 }
5022
5023
5033 @Override
5034 public User updateScreenName(long userId, String screenName)
5035 throws PortalException, SystemException {
5036
5037
5038
5039 User user = userPersistence.findByPrimaryKey(userId);
5040
5041 screenName = getLogin(screenName);
5042
5043 validateScreenName(user.getCompanyId(), userId, screenName);
5044
5045 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
5046 user.setDigest(StringPool.BLANK);
5047 }
5048
5049 user.setScreenName(screenName);
5050
5051 userPersistence.update(user);
5052
5053
5054
5055 Group group = groupLocalService.getUserGroup(
5056 user.getCompanyId(), userId);
5057
5058 group.setFriendlyURL(StringPool.SLASH + screenName);
5059
5060 groupPersistence.update(group);
5061
5062 return user;
5063 }
5064
5065
5077 @Deprecated
5078 @Override
5079 public User updateStatus(long userId, int status)
5080 throws PortalException, SystemException {
5081
5082 return updateStatus(userId, status, new ServiceContext());
5083 }
5084
5085
5097 @Override
5098 public User updateStatus(
5099 long userId, int status, ServiceContext serviceContext)
5100 throws PortalException, SystemException {
5101
5102 User user = userPersistence.findByPrimaryKey(userId);
5103
5104 if ((status == WorkflowConstants.STATUS_APPROVED) &&
5105 (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {
5106
5107 validateCompanyMaxUsers(user.getCompanyId());
5108 }
5109
5110 String passwordUnencrypted = (String)serviceContext.getAttribute(
5111 "passwordUnencrypted");
5112
5113 if (Validator.isNotNull(passwordUnencrypted)) {
5114 user.setPasswordUnencrypted(passwordUnencrypted);
5115 }
5116
5117 user.setStatus(status);
5118
5119 userPersistence.update(user);
5120
5121 reindex(user);
5122
5123 return user;
5124 }
5125
5126
5182 @Override
5183 @SuppressWarnings("deprecation")
5184 public User updateUser(
5185 long userId, String oldPassword, String newPassword1,
5186 String newPassword2, boolean passwordReset,
5187 String reminderQueryQuestion, String reminderQueryAnswer,
5188 String screenName, String emailAddress, long facebookId,
5189 String openId, String languageId, String timeZoneId,
5190 String greeting, String comments, String firstName,
5191 String middleName, String lastName, int prefixId, int suffixId,
5192 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
5193 String smsSn, String aimSn, String facebookSn, String icqSn,
5194 String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
5195 String twitterSn, String ymSn, String jobTitle, long[] groupIds,
5196 long[] organizationIds, long[] roleIds,
5197 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
5198 ServiceContext serviceContext)
5199 throws PortalException, SystemException {
5200
5201
5202
5203 User user = userPersistence.findByPrimaryKey(userId);
5204 Company company = companyPersistence.findByPrimaryKey(
5205 user.getCompanyId());
5206 String password = oldPassword;
5207 screenName = getLogin(screenName);
5208 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
5209 openId = openId.trim();
5210 String oldFullName = user.getFullName();
5211 aimSn = StringUtil.toLowerCase(aimSn.trim());
5212 facebookSn = StringUtil.toLowerCase(facebookSn.trim());
5213 icqSn = StringUtil.toLowerCase(icqSn.trim());
5214 jabberSn = StringUtil.toLowerCase(jabberSn.trim());
5215 msnSn = StringUtil.toLowerCase(msnSn.trim());
5216 mySpaceSn = StringUtil.toLowerCase(mySpaceSn.trim());
5217 skypeSn = StringUtil.toLowerCase(skypeSn.trim());
5218 twitterSn = StringUtil.toLowerCase(twitterSn.trim());
5219 ymSn = StringUtil.toLowerCase(ymSn.trim());
5220 Date now = new Date();
5221
5222 EmailAddressGenerator emailAddressGenerator =
5223 EmailAddressGeneratorFactory.getInstance();
5224
5225 if (emailAddressGenerator.isGenerated(emailAddress)) {
5226 emailAddress = StringPool.BLANK;
5227 }
5228
5229 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
5230 Validator.isNull(emailAddress)) {
5231
5232 emailAddress = emailAddressGenerator.generate(
5233 user.getCompanyId(), userId);
5234 }
5235
5236 validate(
5237 userId, screenName, emailAddress, openId, firstName, middleName,
5238 lastName, smsSn);
5239
5240 if (Validator.isNotNull(newPassword1) ||
5241 Validator.isNotNull(newPassword2)) {
5242
5243 user = updatePassword(
5244 userId, newPassword1, newPassword2, passwordReset);
5245
5246 password = newPassword1;
5247
5248 user.setDigest(StringPool.BLANK);
5249 }
5250
5251 user.setModifiedDate(now);
5252
5253 if (user.getContactId() <= 0) {
5254 user.setContactId(counterLocalService.increment());
5255 }
5256
5257 user.setPasswordReset(passwordReset);
5258
5259 if (Validator.isNotNull(reminderQueryQuestion) &&
5260 Validator.isNotNull(reminderQueryAnswer)) {
5261
5262 user.setReminderQueryQuestion(reminderQueryQuestion);
5263 user.setReminderQueryAnswer(reminderQueryAnswer);
5264 }
5265
5266 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
5267 user.setScreenName(screenName);
5268
5269 user.setDigest(StringPool.BLANK);
5270 }
5271
5272 boolean sendEmailAddressVerification = false;
5273
5274 if (company.isStrangersVerify() &&
5275 !StringUtil.equalsIgnoreCase(
5276 emailAddress, user.getEmailAddress())) {
5277
5278 sendEmailAddressVerification = true;
5279 }
5280 else {
5281 setEmailAddress(
5282 user, password, firstName, middleName, lastName, emailAddress);
5283 }
5284
5285 if (serviceContext != null) {
5286 String uuid = serviceContext.getUuid();
5287
5288 if (Validator.isNotNull(uuid)) {
5289 user.setUuid(uuid);
5290 }
5291 }
5292
5293 user.setFacebookId(facebookId);
5294
5295 Long ldapServerId = null;
5296
5297 if (serviceContext != null) {
5298 ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
5299 }
5300
5301 if (ldapServerId != null) {
5302 user.setLdapServerId(ldapServerId);
5303 }
5304
5305 user.setOpenId(openId);
5306 user.setLanguageId(languageId);
5307 user.setTimeZoneId(timeZoneId);
5308 user.setGreeting(greeting);
5309 user.setComments(comments);
5310 user.setFirstName(firstName);
5311 user.setMiddleName(middleName);
5312 user.setLastName(lastName);
5313 user.setJobTitle(jobTitle);
5314 user.setExpandoBridgeAttributes(serviceContext);
5315
5316 userPersistence.update(user, serviceContext);
5317
5318
5319
5320 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
5321
5322 long contactId = user.getContactId();
5323
5324 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
5325
5326 if (contact == null) {
5327 contact = contactPersistence.create(contactId);
5328
5329 contact.setCompanyId(user.getCompanyId());
5330 contact.setUserName(StringPool.BLANK);
5331 contact.setCreateDate(now);
5332 contact.setClassName(User.class.getName());
5333 contact.setClassPK(user.getUserId());
5334 contact.setAccountId(company.getAccountId());
5335 contact.setParentContactId(
5336 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
5337 }
5338
5339 contact.setModifiedDate(now);
5340 contact.setEmailAddress(user.getEmailAddress());
5341 contact.setFirstName(firstName);
5342 contact.setMiddleName(middleName);
5343 contact.setLastName(lastName);
5344 contact.setPrefixId(prefixId);
5345 contact.setSuffixId(suffixId);
5346 contact.setMale(male);
5347 contact.setBirthday(birthday);
5348 contact.setSmsSn(smsSn);
5349 contact.setAimSn(aimSn);
5350 contact.setFacebookSn(facebookSn);
5351 contact.setIcqSn(icqSn);
5352 contact.setJabberSn(jabberSn);
5353 contact.setMsnSn(msnSn);
5354 contact.setMySpaceSn(mySpaceSn);
5355 contact.setSkypeSn(skypeSn);
5356 contact.setTwitterSn(twitterSn);
5357 contact.setYmSn(ymSn);
5358 contact.setJobTitle(jobTitle);
5359
5360 contactPersistence.update(contact, serviceContext);
5361
5362
5363
5364 Group group = groupLocalService.getUserGroup(
5365 user.getCompanyId(), userId);
5366
5367 group.setFriendlyURL(StringPool.SLASH + screenName);
5368
5369 groupPersistence.update(group);
5370
5371
5372
5373
5374
5375
5376
5377 List<UserGroupRole> previousUserGroupRoles =
5378 userGroupRolePersistence.findByUserId(userId);
5379
5380 updateGroups(userId, groupIds, serviceContext, false);
5381 updateOrganizations(userId, organizationIds, false);
5382
5383
5384
5385 if (roleIds != null) {
5386 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
5387
5388 userPersistence.setRoles(userId, roleIds);
5389 }
5390
5391
5392
5393 updateUserGroupRoles(
5394 user, groupIds, organizationIds, userGroupRoles,
5395 previousUserGroupRoles);
5396
5397
5398
5399 if (userGroupIds != null) {
5400 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
5401 userGroupLocalService.copyUserGroupLayouts(
5402 userGroupIds, userId);
5403 }
5404
5405 userPersistence.setUserGroups(userId, userGroupIds);
5406 }
5407
5408 if (!hasManageLayoutsRolePermission(user) &&
5409 !hasManageLayoutsOrgPermission(organizationIds, user) &&
5410 !hasManageLayoutsSitePermission(groupIds, user)) {
5411
5412 unsetToggleControlsPreference(userId);
5413 }
5414
5415
5416
5417 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
5418
5419
5420
5421 if (serviceContext != null) {
5422 updateAsset(
5423 userId, user, serviceContext.getAssetCategoryIds(),
5424 serviceContext.getAssetTagNames());
5425 }
5426
5427
5428
5429 if (GetterUtil.getBoolean(
5430 PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
5431 !oldFullName.equals(user.getFullName())) {
5432
5433 mbMessageLocalService.updateUserName(userId, user.getFullName());
5434 }
5435
5436
5437
5438 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
5439 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5440 User.class);
5441
5442 indexer.reindex(user);
5443 }
5444
5445
5446
5447 if ((serviceContext != null) && sendEmailAddressVerification) {
5448 sendEmailAddressVerification(user, emailAddress, serviceContext);
5449 }
5450
5451
5452
5453 PermissionCacheUtil.clearCache(userId);
5454
5455 return user;
5456 }
5457
5458
5467 @Override
5468 public void verifyEmailAddress(String ticketKey)
5469 throws PortalException, SystemException {
5470
5471 Ticket ticket = ticketLocalService.getTicket(ticketKey);
5472
5473 if (ticket.isExpired() ||
5474 (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
5475
5476 throw new NoSuchTicketException("{ticketKey=" + ticketKey + "}");
5477 }
5478
5479 User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
5480
5481 String emailAddress = ticket.getExtraInfo();
5482
5483 emailAddress = StringUtil.toLowerCase(emailAddress).trim();
5484
5485 if (!emailAddress.equals(user.getEmailAddress())) {
5486 if (userPersistence.fetchByC_EA(
5487 user.getCompanyId(), emailAddress) != null) {
5488
5489 throw new DuplicateUserEmailAddressException(
5490 "{userId=" + user.getUserId() + "}");
5491 }
5492
5493 setEmailAddress(
5494 user, StringPool.BLANK, user.getFirstName(),
5495 user.getMiddleName(), user.getLastName(), emailAddress);
5496
5497 Contact contact = user.getContact();
5498
5499 contact.setEmailAddress(user.getEmailAddress());
5500
5501 contactPersistence.update(contact);
5502 }
5503
5504 user.setEmailAddressVerified(true);
5505
5506 userPersistence.update(user);
5507
5508 ticketLocalService.deleteTicket(ticket);
5509 }
5510
5511 protected void addDefaultRolesAndTeams(long groupId, long[] userIds)
5512 throws PortalException, SystemException {
5513
5514 List<Role> defaultSiteRoles = new ArrayList<Role>();
5515
5516 Group group = groupLocalService.getGroup(groupId);
5517
5518 UnicodeProperties typeSettingsProperties =
5519 group.getTypeSettingsProperties();
5520
5521 long[] defaultSiteRoleIds = StringUtil.split(
5522 typeSettingsProperties.getProperty("defaultSiteRoleIds"), 0L);
5523
5524 for (long defaultSiteRoleId : defaultSiteRoleIds) {
5525 Role defaultSiteRole = rolePersistence.fetchByPrimaryKey(
5526 defaultSiteRoleId);
5527
5528 if (defaultSiteRole == null) {
5529 if (_log.isWarnEnabled()) {
5530 _log.warn("Unable to find role " + defaultSiteRoleId);
5531 }
5532
5533 continue;
5534 }
5535
5536 defaultSiteRoles.add(defaultSiteRole);
5537 }
5538
5539 List<Team> defaultTeams = new ArrayList<Team>();
5540
5541 long[] defaultTeamIds = StringUtil.split(
5542 typeSettingsProperties.getProperty("defaultTeamIds"), 0L);
5543
5544 for (long defaultTeamId : defaultTeamIds) {
5545 Team defaultTeam = teamPersistence.findByPrimaryKey(defaultTeamId);
5546
5547 if (defaultTeam == null) {
5548 if (_log.isWarnEnabled()) {
5549 _log.warn("Unable to find team " + defaultTeamId);
5550 }
5551
5552 continue;
5553 }
5554
5555 defaultTeams.add(defaultTeam);
5556 }
5557
5558 for (long userId : userIds) {
5559 Set<Long> userRoleIdsSet = new HashSet<Long>();
5560
5561 for (Role role : defaultSiteRoles) {
5562 if (!userPersistence.containsRole(userId, role.getRoleId())) {
5563 userRoleIdsSet.add(role.getRoleId());
5564 }
5565 }
5566
5567 long[] userRoleIds = ArrayUtil.toArray(
5568 userRoleIdsSet.toArray(new Long[userRoleIdsSet.size()]));
5569
5570 userGroupRoleLocalService.addUserGroupRoles(
5571 userId, groupId, userRoleIds);
5572
5573 Set<Long> userTeamIdsSet = new HashSet<Long>();
5574
5575 for (Team team : defaultTeams) {
5576 if (!userPersistence.containsTeam(userId, team.getTeamId())) {
5577 userTeamIdsSet.add(team.getTeamId());
5578 }
5579 }
5580
5581 long[] userTeamIds = ArrayUtil.toArray(
5582 userTeamIdsSet.toArray(new Long[userTeamIdsSet.size()]));
5583
5584 userPersistence.addTeams(userId, userTeamIds);
5585 }
5586 }
5587
5588
5634 protected int authenticate(
5635 long companyId, String login, String password, String authType,
5636 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
5637 Map<String, Object> resultsMap)
5638 throws PortalException, SystemException {
5639
5640 if (PropsValues.AUTH_LOGIN_DISABLED) {
5641 return Authenticator.FAILURE;
5642 }
5643
5644 login = StringUtil.toLowerCase(login.trim());
5645
5646 long userId = GetterUtil.getLong(login);
5647
5648
5649
5650 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5651 if (Validator.isNull(login)) {
5652 throw new UserEmailAddressException();
5653 }
5654 }
5655 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5656 if (Validator.isNull(login)) {
5657 throw new UserScreenNameException();
5658 }
5659 }
5660 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5661 if (Validator.isNull(login)) {
5662 throw new UserIdException();
5663 }
5664 }
5665
5666 if (Validator.isNull(password)) {
5667 throw new UserPasswordException(
5668 UserPasswordException.PASSWORD_INVALID);
5669 }
5670
5671 int authResult = Authenticator.FAILURE;
5672
5673
5674
5675 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5676 authResult = AuthPipeline.authenticateByEmailAddress(
5677 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5678 headerMap, parameterMap);
5679 }
5680 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5681 authResult = AuthPipeline.authenticateByScreenName(
5682 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5683 headerMap, parameterMap);
5684 }
5685 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5686 authResult = AuthPipeline.authenticateByUserId(
5687 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
5688 headerMap, parameterMap);
5689 }
5690
5691
5692
5693 User user = null;
5694
5695 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5696 user = fetchUserByEmailAddress(companyId, login);
5697 }
5698 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5699 user = fetchUserByScreenName(companyId, login);
5700 }
5701 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5702 user = userPersistence.fetchByPrimaryKey(GetterUtil.getLong(login));
5703 }
5704
5705 if (user == null) {
5706 return Authenticator.DNE;
5707 }
5708
5709 if (!isUserAllowedToAuthenticate(user)) {
5710 return Authenticator.FAILURE;
5711 }
5712
5713 if (!user.isPasswordEncrypted()) {
5714 user.setPassword(PasswordEncryptorUtil.encrypt(user.getPassword()));
5715 user.setPasswordEncrypted(true);
5716
5717 userPersistence.update(user);
5718 }
5719
5720
5721
5722 boolean skipLiferayCheck = false;
5723
5724 if (authResult == Authenticator.SKIP_LIFERAY_CHECK) {
5725 authResult = Authenticator.SUCCESS;
5726
5727 skipLiferayCheck = true;
5728 }
5729 else if ((authResult == Authenticator.SUCCESS) &&
5730 PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5731
5732 boolean authenticated = PwdAuthenticator.authenticate(
5733 login, password, user.getPassword());
5734
5735 if (authenticated) {
5736 authResult = Authenticator.SUCCESS;
5737 }
5738 else {
5739 authResult = Authenticator.FAILURE;
5740 }
5741 }
5742
5743
5744
5745 if (authResult == Authenticator.SUCCESS) {
5746 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5747 authResult = AuthPipeline.authenticateByEmailAddress(
5748 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5749 headerMap, parameterMap);
5750 }
5751 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5752 authResult = AuthPipeline.authenticateByScreenName(
5753 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5754 headerMap, parameterMap);
5755 }
5756 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5757 authResult = AuthPipeline.authenticateByUserId(
5758 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5759 headerMap, parameterMap);
5760 }
5761 }
5762
5763 if (resultsMap != null) {
5764 resultsMap.put("userId", user.getUserId());
5765 }
5766
5767 if (authResult == Authenticator.SUCCESS) {
5768
5769
5770
5771 if (skipLiferayCheck ||
5772 !PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK ||
5773 Validator.isNull(user.getDigest())) {
5774
5775 String digest = user.getDigest(password);
5776
5777 user.setDigest(digest);
5778
5779 userPersistence.update(user);
5780 }
5781 }
5782
5783
5784
5785 if (authResult == Authenticator.FAILURE) {
5786 authResult = handleAuthenticationFailure(
5787 login, authType, user, headerMap, parameterMap);
5788 }
5789 else {
5790 resetFailedLoginAttempts(user);
5791 }
5792
5793
5794
5795 return authResult;
5796 }
5797
5798 protected SearchContext buildSearchContext(
5799 long companyId, String firstName, String middleName, String lastName,
5800 String fullName, String screenName, String emailAddress, String street,
5801 String city, String zip, String region, String country, int status,
5802 LinkedHashMap<String, Object> params, boolean andSearch, int start,
5803 int end, Sort sort) {
5804
5805 SearchContext searchContext = new SearchContext();
5806
5807 searchContext.setAndSearch(andSearch);
5808
5809 Map<String, Serializable> attributes =
5810 new HashMap<String, Serializable>();
5811
5812 attributes.put("city", city);
5813 attributes.put("country", country);
5814 attributes.put("emailAddress", emailAddress);
5815 attributes.put("firstName", firstName);
5816 attributes.put("fullName", fullName);
5817 attributes.put("lastName", lastName);
5818 attributes.put("middleName", middleName);
5819 attributes.put("params", params);
5820 attributes.put("region", region);
5821 attributes.put("screenName", screenName);
5822 attributes.put("street", street);
5823 attributes.put("status", status);
5824 attributes.put("zip", zip);
5825
5826 searchContext.setAttributes(attributes);
5827
5828 searchContext.setCompanyId(companyId);
5829 searchContext.setEnd(end);
5830
5831 if (params != null) {
5832 String keywords = (String)params.remove("keywords");
5833
5834 if (Validator.isNotNull(keywords)) {
5835 searchContext.setKeywords(keywords);
5836 }
5837 }
5838
5839 QueryConfig queryConfig = new QueryConfig();
5840
5841 queryConfig.setHighlightEnabled(false);
5842 queryConfig.setScoreEnabled(false);
5843
5844 searchContext.setQueryConfig(queryConfig);
5845
5846 if (sort != null) {
5847 searchContext.setSorts(sort);
5848 }
5849
5850 searchContext.setStart(start);
5851
5852 return searchContext;
5853 }
5854
5855 protected Date getBirthday(
5856 int birthdayMonth, int birthdayDay, int birthdayYear)
5857 throws PortalException {
5858
5859 Date birthday = PortalUtil.getDate(
5860 birthdayMonth, birthdayDay, birthdayYear,
5861 ContactBirthdayException.class);
5862
5863 Date now = new Date();
5864
5865 if (birthday.after(now)) {
5866 throw new ContactBirthdayException();
5867 }
5868
5869 return birthday;
5870 }
5871
5872 protected String getLogin(String login) {
5873 return StringUtil.lowerCase(StringUtil.trim(login));
5874 }
5875
5876 protected long[] getUserIds(List<User> users) {
5877 long[] userIds = new long[users.size()];
5878
5879 for (int i = 0; i < users.size(); i++) {
5880 User user = users.get(i);
5881
5882 userIds[i] = user.getUserId();
5883 }
5884
5885 return userIds;
5886 }
5887
5888 protected int handleAuthenticationFailure(
5889 String login, String authType, User user,
5890 Map<String, String[]> headerMap, Map<String, String[]> parameterMap) {
5891
5892 if (user == null) {
5893 return Authenticator.DNE;
5894 }
5895
5896 try {
5897 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5898 AuthPipeline.onFailureByEmailAddress(
5899 PropsKeys.AUTH_FAILURE, user.getCompanyId(), login,
5900 headerMap, parameterMap);
5901 }
5902 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5903 AuthPipeline.onFailureByScreenName(
5904 PropsKeys.AUTH_FAILURE, user.getCompanyId(), login,
5905 headerMap, parameterMap);
5906 }
5907 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5908 AuthPipeline.onFailureByUserId(
5909 PropsKeys.AUTH_FAILURE, user.getCompanyId(),
5910 user.getUserId(), headerMap, parameterMap);
5911 }
5912
5913 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5914
5915 if (user == null) {
5916 return Authenticator.DNE;
5917 }
5918
5919
5920
5921 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5922 user.getCompanyId())) {
5923
5924 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5925
5926 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5927
5928 int failedLoginAttempts = user.getFailedLoginAttempts();
5929 int maxFailures = passwordPolicy.getMaxFailure();
5930
5931 if ((failedLoginAttempts >= maxFailures) &&
5932 (maxFailures != 0)) {
5933
5934 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5935 AuthPipeline.onMaxFailuresByEmailAddress(
5936 PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
5937 login, headerMap, parameterMap);
5938 }
5939 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5940 AuthPipeline.onMaxFailuresByScreenName(
5941 PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
5942 login, headerMap, parameterMap);
5943 }
5944 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5945 AuthPipeline.onMaxFailuresByUserId(
5946 PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
5947 user.getUserId(), headerMap, parameterMap);
5948 }
5949 }
5950 }
5951 }
5952 catch (Exception e) {
5953 _log.error(e, e);
5954 }
5955
5956 return Authenticator.FAILURE;
5957 }
5958
5959 protected boolean hasManageLayoutsPermission(
5960 long groupId, PermissionChecker permissionChecker)
5961 throws PortalException, SystemException {
5962
5963 return GroupPermissionUtil.contains(
5964 permissionChecker, groupId, ActionKeys.MANAGE_LAYOUTS);
5965 }
5966
5967 protected boolean hasManageLayoutsOrgPermission(
5968 long[] organizationIds, User user)
5969 throws PortalException, SystemException {
5970
5971 if (ArrayUtil.isEmpty(organizationIds)) {
5972 return false;
5973 }
5974
5975 try {
5976 PermissionChecker permissionChecker =
5977 PermissionCheckerFactoryUtil.create(user);
5978
5979 long organizationClassId =
5980 ClassNameLocalServiceUtil.fetchClassNameId(
5981 Organization.class.getName());
5982
5983 for (long organizationId : organizationIds) {
5984 Group group = groupPersistence.fetchByC_C_C(
5985 user.getCompanyId(), organizationClassId, organizationId);
5986
5987 if (hasManageLayoutsPermission(
5988 group.getGroupId(), permissionChecker)) {
5989
5990 return true;
5991 }
5992 }
5993 }
5994 catch (Exception e) {
5995 }
5996
5997 return false;
5998 }
5999
6000 protected boolean hasManageLayoutsRolePermission(User user)
6001 throws PortalException, SystemException {
6002
6003 try {
6004 PermissionChecker permissionChecker =
6005 PermissionCheckerFactoryUtil.create(user);
6006
6007 return GroupPermissionUtil.contains(
6008 permissionChecker, ActionKeys.MANAGE_LAYOUTS);
6009 }
6010 catch (Exception e) {
6011 }
6012
6013 return false;
6014 }
6015
6016 protected boolean hasManageLayoutsSitePermission(long[] groupIds, User user)
6017 throws PortalException, SystemException {
6018
6019 if (ArrayUtil.isEmpty(groupIds)) {
6020 return false;
6021 }
6022
6023 try {
6024 PermissionChecker permissionChecker =
6025 PermissionCheckerFactoryUtil.create(user);
6026
6027 for (long groupId : groupIds) {
6028 if (hasManageLayoutsPermission(groupId, permissionChecker)) {
6029 return true;
6030 }
6031 }
6032 }
6033 catch (Exception e) {
6034 }
6035
6036 return false;
6037 }
6038
6039 protected boolean isUserAllowedToAuthenticate(User user)
6040 throws PortalException, SystemException {
6041
6042 if (user.isDefaultUser()) {
6043 if (_log.isInfoEnabled()) {
6044 _log.info("Authentication is disabled for the default user");
6045 }
6046
6047 return false;
6048 }
6049 else if (!user.isActive()) {
6050 if (_log.isInfoEnabled()) {
6051 _log.info(
6052 "Authentication is disabled for inactive user " +
6053 user.getUserId());
6054 }
6055
6056 return false;
6057 }
6058
6059
6060
6061
6062 checkLockout(user);
6063
6064 checkPasswordExpired(user);
6065
6066 return true;
6067 }
6068
6069 protected boolean isUseCustomSQL(LinkedHashMap<String, Object> params) {
6070 if ((params == null) || params.isEmpty()) {
6071 return false;
6072 }
6073
6074 for (String key : params.keySet()) {
6075 if (!key.equals("inherit") &&
6076 !key.equals("usersGroups") &&
6077 !key.equals("usersOrgs") &&
6078 !key.equals("usersOrgsCount") &&
6079 !key.equals("usersRoles") &&
6080 !key.equals("usersTeams") &&
6081 !key.equals("usersUserGroups")) {
6082
6083 return true;
6084 }
6085 }
6086
6087 Boolean inherit = (Boolean)params.get("inherit");
6088
6089 if ((inherit != null) && inherit) {
6090 return true;
6091 }
6092
6093 return false;
6094 }
6095
6096 protected void reindex(final User user) {
6097 final Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6098 User.class);
6099
6100 Callable<Void> callable = new ShardCallable<Void>(
6101 user.getCompanyId()) {
6102
6103 @Override
6104 protected Void doCall() throws Exception {
6105 indexer.reindex(user);
6106
6107 return null;
6108 }
6109
6110 };
6111
6112 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
6113 }
6114
6115 protected void resetFailedLoginAttempts(User user) throws SystemException {
6116 resetFailedLoginAttempts(user, false);
6117 }
6118
6119 protected void resetFailedLoginAttempts(User user, boolean forceUpdate)
6120 throws SystemException {
6121
6122 if (forceUpdate || (user.getFailedLoginAttempts() > 0)) {
6123 user.setFailedLoginAttempts(0);
6124
6125 userPersistence.update(user);
6126 }
6127 }
6128
6129 protected Hits search(
6130 long companyId, String firstName, String middleName,
6131 String lastName, String fullName, String screenName,
6132 String emailAddress, String street, String city, String zip,
6133 String region, String country, int status,
6134 LinkedHashMap<String, Object> params, boolean andSearch, int start,
6135 int end, Sort sort)
6136 throws SystemException {
6137
6138 try {
6139 SearchContext searchContext = new SearchContext();
6140
6141 searchContext.setAndSearch(andSearch);
6142
6143 Map<String, Serializable> attributes =
6144 new HashMap<String, Serializable>();
6145
6146 attributes.put("city", city);
6147 attributes.put("country", country);
6148 attributes.put("emailAddress", emailAddress);
6149 attributes.put("firstName", firstName);
6150 attributes.put("fullName", fullName);
6151 attributes.put("lastName", lastName);
6152 attributes.put("middleName", middleName);
6153 attributes.put("params", params);
6154 attributes.put("region", region);
6155 attributes.put("screenName", screenName);
6156 attributes.put("street", street);
6157 attributes.put("status", status);
6158 attributes.put("zip", zip);
6159
6160 searchContext.setAttributes(attributes);
6161
6162 searchContext.setCompanyId(companyId);
6163 searchContext.setEnd(end);
6164
6165 if (params != null) {
6166 String keywords = (String)params.remove("keywords");
6167
6168 if (Validator.isNotNull(keywords)) {
6169 searchContext.setKeywords(keywords);
6170 }
6171 }
6172
6173 QueryConfig queryConfig = new QueryConfig();
6174
6175 queryConfig.setHighlightEnabled(false);
6176 queryConfig.setScoreEnabled(false);
6177
6178 searchContext.setQueryConfig(queryConfig);
6179
6180 if (sort != null) {
6181 searchContext.setSorts(sort);
6182 }
6183
6184 searchContext.setStart(start);
6185
6186 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6187 User.class);
6188
6189 return indexer.search(searchContext);
6190 }
6191 catch (Exception e) {
6192 throw new SystemException(e);
6193 }
6194 }
6195
6196 protected void sendEmail(
6197 User user, String password, ServiceContext serviceContext)
6198 throws SystemException {
6199
6200 if (!PrefsPropsUtil.getBoolean(
6201 user.getCompanyId(),
6202 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
6203
6204 return;
6205 }
6206
6207 String fromName = PrefsPropsUtil.getString(
6208 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
6209 String fromAddress = PrefsPropsUtil.getString(
6210 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
6211
6212 String toName = user.getFullName();
6213 String toAddress = user.getEmailAddress();
6214
6215 String subject = PrefsPropsUtil.getContent(
6216 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
6217
6218 String body = null;
6219
6220 if (Validator.isNotNull(password)) {
6221 body = PrefsPropsUtil.getContent(
6222 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
6223 }
6224 else {
6225 body = PrefsPropsUtil.getContent(
6226 user.getCompanyId(),
6227 PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
6228 }
6229
6230 SubscriptionSender subscriptionSender = new SubscriptionSender();
6231
6232 subscriptionSender.setBody(body);
6233 subscriptionSender.setCompanyId(user.getCompanyId());
6234 subscriptionSender.setContextAttributes(
6235 "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
6236 "[$USER_SCREENNAME$]", user.getScreenName());
6237 subscriptionSender.setFrom(fromAddress, fromName);
6238 subscriptionSender.setHtmlFormat(true);
6239 subscriptionSender.setMailId("user", user.getUserId());
6240 subscriptionSender.setServiceContext(serviceContext);
6241 subscriptionSender.setSubject(subject);
6242 subscriptionSender.setUserId(user.getUserId());
6243
6244 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
6245
6246 subscriptionSender.flushNotificationsAsync();
6247 }
6248
6249 protected void setEmailAddress(
6250 User user, String password, String firstName, String middleName,
6251 String lastName, String emailAddress)
6252 throws PortalException, SystemException {
6253
6254 if (StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
6255 return;
6256 }
6257
6258 long userId = user.getUserId();
6259
6260
6261
6262 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
6263 Validator.isNotNull(password)) {
6264
6265 mailService.addUser(
6266 user.getCompanyId(), userId, password, firstName, middleName,
6267 lastName, emailAddress);
6268 }
6269
6270
6271
6272 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
6273 mailService.updateEmailAddress(
6274 user.getCompanyId(), userId, emailAddress);
6275 }
6276
6277
6278
6279 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
6280 mailService.deleteEmailAddress(user.getCompanyId(), userId);
6281 }
6282
6283 user.setEmailAddress(emailAddress);
6284 user.setDigest(StringPool.BLANK);
6285 }
6286
6287 protected void unsetToggleControlsPreference(long userId)
6288 throws PortalException, SystemException {
6289
6290 PortletPreferencesFactoryImpl portletPreferencesFactory =
6291 new PortletPreferencesFactoryImpl();
6292
6293 PortalPreferences portalPreferences =
6294 portletPreferencesFactory.getPortalPreferences(userId, false);
6295
6296 String toggleControls = portalPreferences.getValue(
6297 SessionClicks.class.getName(),"liferay_toggle_controls", null);
6298
6299 if (Validator.isNotNull(toggleControls) &&
6300 !toggleControls.equals("visible")) {
6301
6302 portalPreferences.setValue(
6303 SessionClicks.class.getName(),"liferay_toggle_controls",
6304 "visible");
6305
6306 String xml = portletPreferencesFactory.toXML(portalPreferences);
6307
6308 PortalPreferencesLocalServiceUtil.updatePreferences(
6309 userId, PortletKeys.PREFS_OWNER_TYPE_USER, xml);
6310 }
6311 }
6312
6313 protected void updateGroups(
6314 long userId, long[] newGroupIds, ServiceContext serviceContext,
6315 boolean indexingEnabled)
6316 throws PortalException, SystemException {
6317
6318 if (newGroupIds == null) {
6319 return;
6320 }
6321
6322 List<Group> oldGroups = userPersistence.getGroups(userId);
6323
6324 Set<Long> oldGroupIds = new HashSet<Long>(oldGroups.size());
6325
6326 for (Group oldGroup : oldGroups) {
6327 long oldGroupId = oldGroup.getGroupId();
6328
6329 oldGroupIds.add(oldGroupId);
6330
6331 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
6332 unsetGroupUsers(
6333 oldGroupId, new long[] {userId}, serviceContext);
6334 }
6335 }
6336
6337 for (long newGroupId : newGroupIds) {
6338 if (!oldGroupIds.contains(newGroupId)) {
6339 addGroupUsers(newGroupId, new long[] {userId});
6340 }
6341 }
6342
6343 if (indexingEnabled) {
6344 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6345 User.class);
6346
6347 indexer.reindex(new long[] {userId});
6348 }
6349
6350 PermissionCacheUtil.clearCache(userId);
6351 }
6352
6353 protected void updateOrganizations(
6354 long userId, long[] newOrganizationIds, boolean indexingEnabled)
6355 throws PortalException, SystemException {
6356
6357 if (newOrganizationIds == null) {
6358 return;
6359 }
6360
6361 List<Organization> oldOrganizations = userPersistence.getOrganizations(
6362 userId);
6363
6364 Set<Long> oldOrganizationIds = new HashSet<Long>(
6365 oldOrganizations.size());
6366
6367 for (Organization oldOrganization : oldOrganizations) {
6368 long oldOrganizationId = oldOrganization.getOrganizationId();
6369
6370 oldOrganizationIds.add(oldOrganizationId);
6371
6372 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
6373 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
6374 }
6375 }
6376
6377 for (long newOrganizationId : newOrganizationIds) {
6378 if (!oldOrganizationIds.contains(newOrganizationId)) {
6379 addOrganizationUsers(newOrganizationId, new long[] {userId});
6380 }
6381 }
6382
6383 if (indexingEnabled) {
6384 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6385 User.class);
6386
6387 indexer.reindex(new long[] {userId});
6388 }
6389
6390 PermissionCacheUtil.clearCache(userId);
6391 }
6392
6393 protected void updateUserGroupRoles(
6394 User user, long[] groupIds, long[] organizationIds,
6395 List<UserGroupRole> userGroupRoles,
6396 List<UserGroupRole> previousUserGroupRoles)
6397 throws PortalException, SystemException {
6398
6399 if (userGroupRoles == null) {
6400 return;
6401 }
6402
6403 userGroupRoles = new ArrayList<UserGroupRole>(userGroupRoles);
6404
6405 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
6406 if (userGroupRoles.contains(userGroupRole)) {
6407 userGroupRoles.remove(userGroupRole);
6408 }
6409 else {
6410 userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
6411 }
6412 }
6413
6414 if (userGroupRoles.isEmpty()) {
6415 return;
6416 }
6417
6418 long[] validGroupIds = null;
6419
6420 if (groupIds != null) {
6421 validGroupIds = ArrayUtil.clone(groupIds);
6422 }
6423 else {
6424 validGroupIds = user.getGroupIds();
6425 }
6426
6427 if (organizationIds == null) {
6428 organizationIds = user.getOrganizationIds();
6429 }
6430
6431 long[] organizationGroupIds = new long[organizationIds.length];
6432
6433 for (int i = 0; i < organizationIds.length; i++) {
6434 long organizationId = organizationIds[i];
6435
6436 Organization organization =
6437 organizationPersistence.findByPrimaryKey(organizationId);
6438
6439 organizationGroupIds[i] = organization.getGroupId();
6440 }
6441
6442 validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
6443
6444 Arrays.sort(validGroupIds);
6445
6446 for (UserGroupRole userGroupRole : userGroupRoles) {
6447 if (Arrays.binarySearch(
6448 validGroupIds, userGroupRole.getGroupId()) >= 0) {
6449
6450 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
6451 }
6452 }
6453 }
6454
6455 protected void validate(
6456 long companyId, long userId, boolean autoPassword, String password1,
6457 String password2, boolean autoScreenName, String screenName,
6458 String emailAddress, String openId, String firstName,
6459 String middleName, String lastName, long[] organizationIds)
6460 throws PortalException, SystemException {
6461
6462 validateCompanyMaxUsers(companyId);
6463
6464 if (!autoScreenName) {
6465 validateScreenName(companyId, userId, screenName);
6466 }
6467
6468 if (!autoPassword) {
6469 PasswordPolicy passwordPolicy =
6470 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
6471
6472 PwdToolkitUtil.validate(
6473 companyId, 0, password1, password2, passwordPolicy);
6474 }
6475
6476 validateEmailAddress(companyId, emailAddress);
6477
6478 if (Validator.isNotNull(emailAddress)) {
6479 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
6480
6481 if ((user != null) && (user.getUserId() != userId)) {
6482 throw new DuplicateUserEmailAddressException(
6483 "{userId=" + userId + "}");
6484 }
6485 }
6486
6487 validateOpenId(companyId, userId, openId);
6488
6489 validateFullName(companyId, firstName, middleName, lastName);
6490
6491 if (organizationIds != null) {
6492 for (long organizationId : organizationIds) {
6493 Organization organization =
6494 organizationPersistence.fetchByPrimaryKey(organizationId);
6495
6496 if (organization == null) {
6497 throw new NoSuchOrganizationException(
6498 "{organizationId=" + organizationId + "}");
6499 }
6500 }
6501 }
6502 }
6503
6504 protected void validate(
6505 long userId, String screenName, String emailAddress, String openId,
6506 String firstName, String middleName, String lastName, String smsSn)
6507 throws PortalException, SystemException {
6508
6509 User user = userPersistence.findByPrimaryKey(userId);
6510
6511 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
6512 validateScreenName(user.getCompanyId(), userId, screenName);
6513 }
6514
6515 validateEmailAddress(user.getCompanyId(), emailAddress);
6516
6517 validateOpenId(user.getCompanyId(), userId, openId);
6518
6519 if (!user.isDefaultUser()) {
6520 if (Validator.isNotNull(emailAddress) &&
6521 !StringUtil.equalsIgnoreCase(
6522 user.getEmailAddress(), emailAddress)) {
6523
6524 if (userPersistence.fetchByC_EA(
6525 user.getCompanyId(), emailAddress) != null) {
6526
6527 throw new DuplicateUserEmailAddressException(
6528 "{userId=" + userId + "}");
6529 }
6530 }
6531
6532 validateFullName(
6533 user.getCompanyId(), firstName, middleName, lastName);
6534 }
6535
6536 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
6537 throw new UserSmsException();
6538 }
6539 }
6540
6541 protected void validateCompanyMaxUsers(long companyId)
6542 throws PortalException, SystemException {
6543
6544 Company company = companyPersistence.findByPrimaryKey(companyId);
6545
6546 if (company.isSystem() || (company.getMaxUsers() == 0)) {
6547 return;
6548 }
6549
6550 int userCount = searchCount(
6551 companyId, null, WorkflowConstants.STATUS_APPROVED, null);
6552
6553 if (userCount >= company.getMaxUsers()) {
6554 throw new CompanyMaxUsersException();
6555 }
6556 }
6557
6558 protected void validateEmailAddress(long companyId, String emailAddress)
6559 throws PortalException, SystemException {
6560
6561 if (Validator.isNull(emailAddress) &&
6562 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
6563
6564 return;
6565 }
6566
6567 EmailAddressValidator emailAddressValidator =
6568 EmailAddressValidatorFactory.getInstance();
6569
6570 if (!emailAddressValidator.validate(companyId, emailAddress)) {
6571 throw new UserEmailAddressException();
6572 }
6573
6574 String pop3User = PrefsPropsUtil.getString(
6575 PropsKeys.MAIL_SESSION_MAIL_POP3_USER,
6576 PropsValues.MAIL_SESSION_MAIL_POP3_USER);
6577
6578 if (StringUtil.equalsIgnoreCase(emailAddress, pop3User)) {
6579 throw new ReservedUserEmailAddressException();
6580 }
6581
6582 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
6583 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
6584 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
6585
6586 for (String reservedEmailAddress : reservedEmailAddresses) {
6587 if (StringUtil.equalsIgnoreCase(
6588 emailAddress, reservedEmailAddress)) {
6589
6590 throw new ReservedUserEmailAddressException();
6591 }
6592 }
6593 }
6594
6595 protected void validateEmailAddress(
6596 User user, String emailAddress1, String emailAddress2)
6597 throws PortalException, SystemException {
6598
6599 if (!emailAddress1.equals(emailAddress2)) {
6600 throw new UserEmailAddressException();
6601 }
6602
6603 validateEmailAddress(user.getCompanyId(), emailAddress1);
6604 validateEmailAddress(user.getCompanyId(), emailAddress2);
6605
6606 if (!StringUtil.equalsIgnoreCase(
6607 emailAddress1, user.getEmailAddress())) {
6608
6609 if (userPersistence.fetchByC_EA(
6610 user.getCompanyId(), emailAddress1) != null) {
6611
6612 throw new DuplicateUserEmailAddressException(
6613 "{userId=" + user.getUserId() + "}");
6614 }
6615 }
6616 }
6617
6618 protected void validateFullName(
6619 long companyId, String firstName, String middleName,
6620 String lastName)
6621 throws PortalException, SystemException {
6622
6623 if (Validator.isNull(firstName)) {
6624 throw new ContactFirstNameException();
6625 }
6626 else if (Validator.isNull(lastName) &&
6627 PrefsPropsUtil.getBoolean(
6628 companyId, PropsKeys.USERS_LAST_NAME_REQUIRED,
6629 PropsValues.USERS_LAST_NAME_REQUIRED)) {
6630
6631 throw new ContactLastNameException();
6632 }
6633
6634 FullNameValidator fullNameValidator =
6635 FullNameValidatorFactory.getInstance();
6636
6637 if (!fullNameValidator.validate(
6638 companyId, firstName, middleName, lastName)) {
6639
6640 throw new ContactFullNameException();
6641 }
6642 }
6643
6644 protected void validateOpenId(long companyId, long userId, String openId)
6645 throws PortalException, SystemException {
6646
6647 if (Validator.isNull(openId)) {
6648 return;
6649 }
6650
6651 User user = userPersistence.fetchByC_O(companyId, openId);
6652
6653 if ((user != null) && (user.getUserId() != userId)) {
6654 throw new DuplicateOpenIdException("{userId=" + userId + "}");
6655 }
6656 }
6657
6658 protected void validatePassword(
6659 long companyId, long userId, String password1, String password2)
6660 throws PortalException, SystemException {
6661
6662 if (Validator.isNull(password1) || Validator.isNull(password2)) {
6663 throw new UserPasswordException(
6664 UserPasswordException.PASSWORD_INVALID);
6665 }
6666
6667 if (!password1.equals(password2)) {
6668 throw new UserPasswordException(
6669 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
6670 }
6671
6672 PasswordPolicy passwordPolicy =
6673 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
6674
6675 PwdToolkitUtil.validate(
6676 companyId, userId, password1, password2, passwordPolicy);
6677 }
6678
6679 protected void validateReminderQuery(String question, String answer)
6680 throws PortalException {
6681
6682 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
6683 return;
6684 }
6685
6686 if (Validator.isNull(question)) {
6687 throw new UserReminderQueryException("Question is null");
6688 }
6689
6690 if (Validator.isNull(answer)) {
6691 throw new UserReminderQueryException("Answer is null");
6692 }
6693 }
6694
6695 protected void validateScreenName(
6696 long companyId, long userId, String screenName)
6697 throws PortalException, SystemException {
6698
6699 if (Validator.isNull(screenName)) {
6700 throw new UserScreenNameException();
6701 }
6702
6703 ScreenNameValidator screenNameValidator =
6704 ScreenNameValidatorFactory.getInstance();
6705
6706 if (!screenNameValidator.validate(companyId, screenName)) {
6707 throw new UserScreenNameException();
6708 }
6709
6710 if (Validator.isNumber(screenName)) {
6711 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
6712 throw new UserScreenNameException();
6713 }
6714
6715 if (!screenName.equals(String.valueOf(userId))) {
6716 Group group = groupPersistence.fetchByPrimaryKey(
6717 GetterUtil.getLong(screenName));
6718
6719 if (group != null) {
6720 throw new UserScreenNameException();
6721 }
6722 }
6723 }
6724
6725 for (char c : screenName.toCharArray()) {
6726 if (!Validator.isChar(c) && !Validator.isDigit(c) &&
6727 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
6728 (c != CharPool.UNDERLINE)) {
6729
6730 throw new UserScreenNameException();
6731 }
6732 }
6733
6734 String[] anonymousNames = BaseServiceImpl.ANONYMOUS_NAMES;
6735
6736 for (String anonymousName : anonymousNames) {
6737 if (StringUtil.equalsIgnoreCase(screenName, anonymousName)) {
6738 throw new UserScreenNameException();
6739 }
6740 }
6741
6742 User user = userPersistence.fetchByC_SN(companyId, screenName);
6743
6744 if ((user != null) && (user.getUserId() != userId)) {
6745 throw new DuplicateUserScreenNameException(
6746 "{userId=" + userId + "}");
6747 }
6748
6749 String friendlyURL = StringPool.SLASH + screenName;
6750
6751 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
6752
6753 if ((group != null) && (group.getClassPK() != userId)) {
6754 throw new GroupFriendlyURLException(
6755 GroupFriendlyURLException.DUPLICATE);
6756 }
6757
6758 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
6759
6760 if (exceptionType != -1) {
6761 throw new UserScreenNameException(
6762 new GroupFriendlyURLException(exceptionType));
6763 }
6764
6765 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
6766 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
6767 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
6768
6769 for (String reservedScreenName : reservedScreenNames) {
6770 if (StringUtil.equalsIgnoreCase(screenName, reservedScreenName)) {
6771 throw new ReservedUserScreenNameException();
6772 }
6773 }
6774 }
6775
6776 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
6777
6778 private Map<Long, User> _defaultUsers = new ConcurrentHashMap<Long, User>();
6779
6780 }