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.LocaleUtil;
079 import com.liferay.portal.kernel.util.OrderByComparator;
080 import com.liferay.portal.kernel.util.ParamUtil;
081 import com.liferay.portal.kernel.util.PropsKeys;
082 import com.liferay.portal.kernel.util.SetUtil;
083 import com.liferay.portal.kernel.util.StringBundler;
084 import com.liferay.portal.kernel.util.StringPool;
085 import com.liferay.portal.kernel.util.StringUtil;
086 import com.liferay.portal.kernel.util.UnicodeProperties;
087 import com.liferay.portal.kernel.util.Validator;
088 import com.liferay.portal.kernel.workflow.WorkflowConstants;
089 import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil;
090 import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
091 import com.liferay.portal.model.Account;
092 import com.liferay.portal.model.Company;
093 import com.liferay.portal.model.CompanyConstants;
094 import com.liferay.portal.model.Contact;
095 import com.liferay.portal.model.ContactConstants;
096 import com.liferay.portal.model.Group;
097 import com.liferay.portal.model.GroupConstants;
098 import com.liferay.portal.model.Layout;
099 import com.liferay.portal.model.Organization;
100 import com.liferay.portal.model.PasswordPolicy;
101 import com.liferay.portal.model.ResourceConstants;
102 import com.liferay.portal.model.Role;
103 import com.liferay.portal.model.RoleConstants;
104 import com.liferay.portal.model.Team;
105 import com.liferay.portal.model.Ticket;
106 import com.liferay.portal.model.TicketConstants;
107 import com.liferay.portal.model.User;
108 import com.liferay.portal.model.UserGroup;
109 import com.liferay.portal.model.UserGroupRole;
110 import com.liferay.portal.model.impl.LayoutImpl;
111 import com.liferay.portal.model.impl.UserCacheModel;
112 import com.liferay.portal.model.impl.UserImpl;
113 import com.liferay.portal.security.auth.AuthPipeline;
114 import com.liferay.portal.security.auth.Authenticator;
115 import com.liferay.portal.security.auth.EmailAddressGenerator;
116 import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
117 import com.liferay.portal.security.auth.EmailAddressValidator;
118 import com.liferay.portal.security.auth.EmailAddressValidatorFactory;
119 import com.liferay.portal.security.auth.FullNameGenerator;
120 import com.liferay.portal.security.auth.FullNameGeneratorFactory;
121 import com.liferay.portal.security.auth.FullNameValidator;
122 import com.liferay.portal.security.auth.FullNameValidatorFactory;
123 import com.liferay.portal.security.auth.PrincipalException;
124 import com.liferay.portal.security.auth.ScreenNameGenerator;
125 import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
126 import com.liferay.portal.security.auth.ScreenNameValidator;
127 import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
128 import com.liferay.portal.security.ldap.LDAPSettingsUtil;
129 import com.liferay.portal.security.permission.ActionKeys;
130 import com.liferay.portal.security.permission.PermissionCacheUtil;
131 import com.liferay.portal.security.permission.PermissionChecker;
132 import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil;
133 import com.liferay.portal.security.pwd.PasswordEncryptorUtil;
134 import com.liferay.portal.security.pwd.PwdAuthenticator;
135 import com.liferay.portal.security.pwd.PwdToolkitUtil;
136 import com.liferay.portal.security.pwd.RegExpToolkit;
137 import com.liferay.portal.service.BaseServiceImpl;
138 import com.liferay.portal.service.ClassNameLocalServiceUtil;
139 import com.liferay.portal.service.PortalPreferencesLocalServiceUtil;
140 import com.liferay.portal.service.ServiceContext;
141 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
142 import com.liferay.portal.service.permission.GroupPermissionUtil;
143 import com.liferay.portal.util.PortalUtil;
144 import com.liferay.portal.util.PortletKeys;
145 import com.liferay.portal.util.PrefsPropsUtil;
146 import com.liferay.portal.util.PropsValues;
147 import com.liferay.portal.util.SessionClicks;
148 import com.liferay.portal.util.SubscriptionSender;
149 import com.liferay.portlet.PortalPreferences;
150 import com.liferay.portlet.PortletPreferencesFactoryImpl;
151 import com.liferay.portlet.documentlibrary.ImageSizeException;
152 import com.liferay.portlet.messageboards.model.MBMessage;
153 import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
154 import com.liferay.util.Encryptor;
155 import com.liferay.util.EncryptorException;
156 import com.liferay.util.PwdGenerator;
157
158 import java.awt.image.RenderedImage;
159
160 import java.io.IOException;
161 import java.io.Serializable;
162
163 import java.util.ArrayList;
164 import java.util.Arrays;
165 import java.util.Calendar;
166 import java.util.Collections;
167 import java.util.Date;
168 import java.util.HashMap;
169 import java.util.HashSet;
170 import java.util.LinkedHashMap;
171 import java.util.List;
172 import java.util.Locale;
173 import java.util.Map;
174 import java.util.Set;
175 import java.util.concurrent.Callable;
176 import java.util.concurrent.ConcurrentHashMap;
177
178
190 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
191
192
206 @Override
207 public User addDefaultAdminUser(
208 long companyId, String screenName, String emailAddress,
209 Locale locale, String firstName, String middleName, String lastName)
210 throws PortalException, SystemException {
211
212 long creatorUserId = 0;
213 boolean autoPassword = false;
214 String password1 = PropsValues.DEFAULT_ADMIN_PASSWORD;
215 String password2 = password1;
216 boolean autoScreenName = false;
217
218 screenName = getLogin(screenName);
219
220 for (int i = 1;; i++) {
221 User screenNameUser = userPersistence.fetchByC_SN(
222 companyId, screenName);
223
224 if (screenNameUser == null) {
225 break;
226 }
227
228 screenName = screenName + i;
229 }
230
231 long facebookId = 0;
232 String openId = StringPool.BLANK;
233 int prefixId = 0;
234 int suffixId = 0;
235 boolean male = true;
236 int birthdayMonth = Calendar.JANUARY;
237 int birthdayDay = 1;
238 int birthdayYear = 1970;
239 String jobTitle = StringPool.BLANK;
240
241 Group guestGroup = groupLocalService.getGroup(
242 companyId, GroupConstants.GUEST);
243
244 long[] groupIds = {guestGroup.getGroupId()};
245
246 long[] organizationIds = null;
247
248 Role adminRole = roleLocalService.getRole(
249 companyId, RoleConstants.ADMINISTRATOR);
250
251 Role powerUserRole = roleLocalService.getRole(
252 companyId, RoleConstants.POWER_USER);
253
254 long[] roleIds = {adminRole.getRoleId(), powerUserRole.getRoleId()};
255
256 long[] userGroupIds = null;
257 boolean sendEmail = false;
258 ServiceContext serviceContext = new ServiceContext();
259
260 User defaultAdminUser = addUser(
261 creatorUserId, companyId, autoPassword, password1, password2,
262 autoScreenName, screenName, emailAddress, facebookId, openId,
263 locale, firstName, middleName, lastName, prefixId, suffixId, male,
264 birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
265 organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
266
267 updateEmailAddressVerified(defaultAdminUser.getUserId(), true);
268
269 updateLastLogin(
270 defaultAdminUser.getUserId(), defaultAdminUser.getLoginIP());
271
272 updatePasswordReset(defaultAdminUser.getUserId(), false);
273
274 return defaultAdminUser;
275 }
276
277
287 @Override
288 public void addDefaultGroups(long userId)
289 throws PortalException, SystemException {
290
291 User user = userPersistence.findByPrimaryKey(userId);
292
293 Set<Long> groupIdsSet = new HashSet<Long>();
294
295 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
296 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
297 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
298
299 for (String defaultGroupName : defaultGroupNames) {
300 Company company = companyPersistence.findByPrimaryKey(
301 user.getCompanyId());
302
303 Account account = company.getAccount();
304
305 if (StringUtil.equalsIgnoreCase(
306 defaultGroupName, account.getName())) {
307
308 defaultGroupName = GroupConstants.GUEST;
309 }
310
311 Group group = groupPersistence.fetchByC_N(
312 user.getCompanyId(), defaultGroupName);
313
314 if ((group != null) &&
315 !userPersistence.containsGroup(
316 userId, group.getGroupId())) {
317
318 groupIdsSet.add(group.getGroupId());
319 }
320 }
321
322 String[] defaultOrganizationGroupNames = PrefsPropsUtil.getStringArray(
323 user.getCompanyId(),
324 PropsKeys.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES,
325 StringPool.NEW_LINE,
326 PropsValues.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES);
327
328 for (String defaultOrganizationGroupName :
329 defaultOrganizationGroupNames) {
330
331 defaultOrganizationGroupName +=
332 GroupLocalServiceImpl.ORGANIZATION_NAME_SUFFIX;
333
334 Group group = groupPersistence.fetchByC_N(
335 user.getCompanyId(), defaultOrganizationGroupName);
336
337 if ((group != null) &&
338 !userPersistence.containsGroup(
339 userId, group.getGroupId())) {
340
341 groupIdsSet.add(group.getGroupId());
342 }
343 }
344
345 long[] groupIds = ArrayUtil.toArray(
346 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
347
348 groupLocalService.addUserGroups(userId, groupIds);
349 }
350
351
361 @Override
362 public void addDefaultRoles(long userId)
363 throws PortalException, SystemException {
364
365 User user = userPersistence.findByPrimaryKey(userId);
366
367 Set<Long> roleIdSet = new HashSet<Long>();
368
369 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
370 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
371 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
372
373 for (String defaultRoleName : defaultRoleNames) {
374 try {
375 Role role = rolePersistence.findByC_N(
376 user.getCompanyId(), defaultRoleName);
377
378 if (!userPersistence.containsRole(userId, role.getRoleId())) {
379 roleIdSet.add(role.getRoleId());
380 }
381 }
382 catch (NoSuchRoleException nsre) {
383 }
384 }
385
386 long[] roleIds = ArrayUtil.toArray(
387 roleIdSet.toArray(new Long[roleIdSet.size()]));
388
389 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
390
391 userPersistence.addRoles(userId, roleIds);
392 }
393
394
404 @Override
405 @SuppressWarnings("deprecation")
406 public void addDefaultUserGroups(long userId)
407 throws PortalException, SystemException {
408
409 User user = userPersistence.findByPrimaryKey(userId);
410
411 Set<Long> userGroupIdSet = new HashSet<Long>();
412
413 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
414 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
415 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
416
417 for (String defaultUserGroupName : defaultUserGroupNames) {
418 try {
419 UserGroup userGroup = userGroupPersistence.findByC_N(
420 user.getCompanyId(), defaultUserGroupName);
421
422 if (!userPersistence.containsUserGroup(
423 userId, userGroup.getUserGroupId())) {
424
425 userGroupIdSet.add(userGroup.getUserGroupId());
426 }
427 }
428 catch (NoSuchUserGroupException nsuge) {
429 }
430 }
431
432 long[] userGroupIds = ArrayUtil.toArray(
433 userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
434
435 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
436 for (long userGroupId : userGroupIds) {
437 userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
438 }
439 }
440
441 userPersistence.addUserGroups(userId, userGroupIds);
442 }
443
444
453 @Override
454 public void addGroupUsers(long groupId, long[] userIds)
455 throws PortalException, SystemException {
456
457 groupPersistence.addUsers(groupId, userIds);
458
459 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
460
461 indexer.reindex(userIds);
462
463 PermissionCacheUtil.clearCache(userIds);
464
465 addDefaultRolesAndTeams(groupId, userIds);
466 }
467
468
477 @Override
478 public void addOrganizationUsers(long organizationId, long[] userIds)
479 throws PortalException, SystemException {
480
481 organizationPersistence.addUsers(organizationId, userIds);
482
483 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
484
485 indexer.reindex(userIds);
486
487 PermissionCacheUtil.clearCache(userIds);
488 }
489
490
498 @Override
499 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
500 throws SystemException {
501
502 passwordPolicyRelLocalService.addPasswordPolicyRels(
503 passwordPolicyId, User.class.getName(), userIds);
504 }
505
506
515 @Override
516 public void addRoleUsers(long roleId, long[] userIds)
517 throws PortalException, SystemException {
518
519 rolePersistence.addUsers(roleId, userIds);
520
521 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
522
523 indexer.reindex(userIds);
524
525 PermissionCacheUtil.clearCache(userIds);
526 }
527
528
537 @Override
538 public void addTeamUsers(long teamId, long[] userIds)
539 throws PortalException, SystemException {
540
541 teamPersistence.addUsers(teamId, userIds);
542
543 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
544
545 indexer.reindex(userIds);
546
547 PermissionCacheUtil.clearCache(userIds);
548 }
549
550
598 @Override
599 public User addUser(
600 long creatorUserId, long companyId, boolean autoPassword,
601 String password1, String password2, boolean autoScreenName,
602 String screenName, String emailAddress, long facebookId,
603 String openId, Locale locale, String firstName, String middleName,
604 String lastName, int prefixId, int suffixId, boolean male,
605 int birthdayMonth, int birthdayDay, int birthdayYear,
606 String jobTitle, long[] groupIds, long[] organizationIds,
607 long[] roleIds, long[] userGroupIds, boolean sendEmail,
608 ServiceContext serviceContext)
609 throws PortalException, SystemException {
610
611 boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
612
613 try {
614 WorkflowThreadLocal.setEnabled(false);
615
616 if (serviceContext == null) {
617 serviceContext = new ServiceContext();
618 }
619
620 if (serviceContext.getWorkflowAction() !=
621 WorkflowConstants.ACTION_PUBLISH) {
622
623 serviceContext.setWorkflowAction(
624 WorkflowConstants.ACTION_PUBLISH);
625 }
626
627 return addUserWithWorkflow(
628 creatorUserId, companyId, autoPassword, password1, password2,
629 autoScreenName, screenName, emailAddress, facebookId, openId,
630 locale, firstName, middleName, lastName, prefixId, suffixId,
631 male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
632 groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
633 serviceContext);
634 }
635 finally {
636 WorkflowThreadLocal.setEnabled(workflowEnabled);
637 }
638 }
639
640
649 @Override
650 @SuppressWarnings("deprecation")
651 public void addUserGroupUsers(long userGroupId, long[] userIds)
652 throws PortalException, SystemException {
653
654 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
655 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
656 }
657
658 userGroupPersistence.addUsers(userGroupId, userIds);
659
660 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
661
662 indexer.reindex(userIds);
663
664 PermissionCacheUtil.clearCache(userIds);
665 }
666
667
715 @Override
716 @SuppressWarnings("deprecation")
717 public User addUserWithWorkflow(
718 long creatorUserId, long companyId, boolean autoPassword,
719 String password1, String password2, boolean autoScreenName,
720 String screenName, String emailAddress, long facebookId,
721 String openId, Locale locale, String firstName, String middleName,
722 String lastName, int prefixId, int suffixId, boolean male,
723 int birthdayMonth, int birthdayDay, int birthdayYear,
724 String jobTitle, long[] groupIds, long[] organizationIds,
725 long[] roleIds, long[] userGroupIds, boolean sendEmail,
726 ServiceContext serviceContext)
727 throws PortalException, SystemException {
728
729
730
731 Company company = companyPersistence.findByPrimaryKey(companyId);
732 screenName = getLogin(screenName);
733 openId = StringUtil.trim(openId);
734 Date now = new Date();
735
736 if (PrefsPropsUtil.getBoolean(
737 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
738
739 autoScreenName = true;
740 }
741
742
743
744 long userId = counterLocalService.increment();
745
746 EmailAddressGenerator emailAddressGenerator =
747 EmailAddressGeneratorFactory.getInstance();
748
749 if ((emailAddress == null) ||
750 emailAddressGenerator.isGenerated(emailAddress)) {
751
752 emailAddress = StringPool.BLANK;
753 }
754 else {
755 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
756 }
757
758 if (!PrefsPropsUtil.getBoolean(
759 companyId, PropsKeys.USERS_EMAIL_ADDRESS_REQUIRED) &&
760 Validator.isNull(emailAddress)) {
761
762 emailAddress = emailAddressGenerator.generate(companyId, userId);
763 }
764
765 validate(
766 companyId, userId, autoPassword, password1, password2,
767 autoScreenName, screenName, emailAddress, openId, firstName,
768 middleName, lastName, organizationIds);
769
770 if (!autoPassword) {
771 if (Validator.isNull(password1) || Validator.isNull(password2)) {
772 throw new UserPasswordException(
773 UserPasswordException.PASSWORD_INVALID);
774 }
775 }
776
777 if (autoScreenName) {
778 ScreenNameGenerator screenNameGenerator =
779 ScreenNameGeneratorFactory.getInstance();
780
781 try {
782 screenName = screenNameGenerator.generate(
783 companyId, userId, emailAddress);
784 }
785 catch (Exception e) {
786 throw new SystemException(e);
787 }
788 }
789
790 User defaultUser = getDefaultUser(companyId);
791
792 FullNameGenerator fullNameGenerator =
793 FullNameGeneratorFactory.getInstance();
794
795 String fullName = fullNameGenerator.getFullName(
796 firstName, middleName, lastName);
797
798 String greeting = LanguageUtil.format(
799 locale, "welcome-x", " " + fullName, false);
800
801 User user = userPersistence.create(userId);
802
803 if (serviceContext != null) {
804 String uuid = serviceContext.getUuid();
805
806 if (Validator.isNotNull(uuid)) {
807 user.setUuid(uuid);
808 }
809 }
810
811 user.setCompanyId(companyId);
812 user.setCreateDate(now);
813 user.setModifiedDate(now);
814 user.setDefaultUser(false);
815 user.setContactId(counterLocalService.increment());
816
817 if (Validator.isNotNull(password1)) {
818 user.setPassword(PasswordEncryptorUtil.encrypt(password1));
819 user.setPasswordUnencrypted(password1);
820 }
821
822 user.setPasswordEncrypted(true);
823
824 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
825
826 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
827 passwordPolicy.isChangeRequired()) {
828
829 user.setPasswordReset(true);
830 }
831 else {
832 user.setPasswordReset(false);
833 }
834
835 user.setDigest(StringPool.BLANK);
836 user.setScreenName(screenName);
837 user.setEmailAddress(emailAddress);
838 user.setFacebookId(facebookId);
839
840 Long ldapServerId = null;
841
842 if (serviceContext != null) {
843 ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
844 }
845
846 if (ldapServerId != null) {
847 user.setLdapServerId(ldapServerId);
848 }
849 else {
850 user.setLdapServerId(-1);
851 }
852
853 user.setOpenId(openId);
854 user.setLanguageId(LocaleUtil.toLanguageId(locale));
855 user.setTimeZoneId(defaultUser.getTimeZoneId());
856 user.setGreeting(greeting);
857 user.setFirstName(firstName);
858 user.setMiddleName(middleName);
859 user.setLastName(lastName);
860 user.setJobTitle(jobTitle);
861 user.setStatus(WorkflowConstants.STATUS_DRAFT);
862 user.setExpandoBridgeAttributes(serviceContext);
863
864 userPersistence.update(user, serviceContext);
865
866
867
868 String creatorUserName = StringPool.BLANK;
869
870 if (creatorUserId <= 0) {
871 creatorUserId = user.getUserId();
872
873
874
875
876
877 }
878 else {
879 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
880
881 creatorUserName = creatorUser.getFullName();
882 }
883
884 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
885
886 Contact contact = contactPersistence.create(user.getContactId());
887
888 contact.setCompanyId(user.getCompanyId());
889 contact.setUserId(creatorUserId);
890 contact.setUserName(creatorUserName);
891 contact.setCreateDate(now);
892 contact.setModifiedDate(now);
893 contact.setClassName(User.class.getName());
894 contact.setClassPK(user.getUserId());
895 contact.setAccountId(company.getAccountId());
896 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
897 contact.setEmailAddress(user.getEmailAddress());
898 contact.setFirstName(firstName);
899 contact.setMiddleName(middleName);
900 contact.setLastName(lastName);
901 contact.setPrefixId(prefixId);
902 contact.setSuffixId(suffixId);
903 contact.setMale(male);
904 contact.setBirthday(birthday);
905 contact.setJobTitle(jobTitle);
906
907 contactPersistence.update(contact, serviceContext);
908
909
910
911 groupLocalService.addGroup(
912 user.getUserId(), GroupConstants.DEFAULT_PARENT_GROUP_ID,
913 User.class.getName(), user.getUserId(), null, null, 0,
914 StringPool.SLASH + screenName, false, true, null);
915
916
917
918 if (groupIds != null) {
919 List<Group> groups = new ArrayList<Group>();
920
921 for (long groupId : groupIds) {
922 Group group = groupLocalService.fetchGroup(groupId);
923
924 if (group != null) {
925 groups.add(group);
926 }
927 else {
928 if (_log.isWarnEnabled()) {
929 _log.warn("Group " + groupId + " does not exist");
930 }
931 }
932 }
933
934 groupLocalService.addUserGroups(userId, groups);
935 }
936
937 addDefaultGroups(userId);
938
939
940
941 updateOrganizations(userId, organizationIds, false);
942
943
944
945 if (roleIds != null) {
946 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
947
948 userPersistence.setRoles(userId, roleIds);
949 }
950
951 addDefaultRoles(userId);
952
953
954
955 if (userGroupIds != null) {
956 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
957 for (long userGroupId : userGroupIds) {
958 userGroupLocalService.copyUserGroupLayouts(
959 userGroupId, new long[] {userId});
960 }
961 }
962
963 userPersistence.setUserGroups(userId, userGroupIds);
964 }
965
966 addDefaultUserGroups(userId);
967
968
969
970 resourceLocalService.addResources(
971 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
972 false, false, false);
973
974
975
976 if (serviceContext != null) {
977 updateAsset(
978 creatorUserId, user, serviceContext.getAssetCategoryIds(),
979 serviceContext.getAssetTagNames());
980 }
981
982
983
984 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
985 reindex(user);
986 }
987
988
989
990 long workflowUserId = creatorUserId;
991
992 if (workflowUserId == userId) {
993 workflowUserId = defaultUser.getUserId();
994 }
995
996 ServiceContext workflowServiceContext = serviceContext;
997
998 if (workflowServiceContext == null) {
999 workflowServiceContext = new ServiceContext();
1000 }
1001
1002 workflowServiceContext.setAttribute("autoPassword", autoPassword);
1003 workflowServiceContext.setAttribute("passwordUnencrypted", password1);
1004 workflowServiceContext.setAttribute("sendEmail", sendEmail);
1005
1006 WorkflowHandlerRegistryUtil.startWorkflowInstance(
1007 companyId, workflowUserId, User.class.getName(), userId, user,
1008 workflowServiceContext);
1009
1010 if (serviceContext != null) {
1011 String passwordUnencrypted = (String)serviceContext.getAttribute(
1012 "passwordUnencrypted");
1013
1014 if (Validator.isNotNull(passwordUnencrypted)) {
1015 user.setPasswordUnencrypted(passwordUnencrypted);
1016 }
1017 }
1018
1019 return user;
1020 }
1021
1022 @Override
1023 public void afterPropertiesSet() {
1024 super.afterPropertiesSet();
1025
1026 PortalCache<Serializable, Serializable> portalCache =
1027 EntityCacheUtil.getPortalCache(UserImpl.class);
1028
1029 PortalCacheMapSynchronizeUtil.synchronize(
1030 portalCache, _defaultUsers,
1031 new Synchronizer<Serializable, Serializable>() {
1032
1033 @Override
1034 public void onSynchronize(
1035 Map<? extends Serializable, ? extends Serializable> map,
1036 Serializable key, Serializable value) {
1037
1038 if (!(value instanceof UserCacheModel)) {
1039 return;
1040 }
1041
1042 UserCacheModel userCacheModel = (UserCacheModel)value;
1043
1044 if (userCacheModel.defaultUser) {
1045 _defaultUsers.remove(userCacheModel.companyId);
1046 }
1047 }
1048
1049 });
1050 }
1051
1052
1076 @Override
1077 public int authenticateByEmailAddress(
1078 long companyId, String emailAddress, String password,
1079 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1080 Map<String, Object> resultsMap)
1081 throws PortalException, SystemException {
1082
1083 return authenticate(
1084 companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
1085 headerMap, parameterMap, resultsMap);
1086 }
1087
1088
1112 @Override
1113 public int authenticateByScreenName(
1114 long companyId, String screenName, String password,
1115 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1116 Map<String, Object> resultsMap)
1117 throws PortalException, SystemException {
1118
1119 return authenticate(
1120 companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
1121 headerMap, parameterMap, resultsMap);
1122 }
1123
1124
1148 @Override
1149 public int authenticateByUserId(
1150 long companyId, long userId, String password,
1151 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1152 Map<String, Object> resultsMap)
1153 throws PortalException, SystemException {
1154
1155 return authenticate(
1156 companyId, String.valueOf(userId), password,
1157 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap, resultsMap);
1158 }
1159
1160
1200 @Override
1201 @Transactional(propagation = Propagation.SUPPORTS)
1202 public long authenticateForBasic(
1203 long companyId, String authType, String login, String password)
1204 throws PortalException, SystemException {
1205
1206 if (PropsValues.AUTH_LOGIN_DISABLED) {
1207 return 0;
1208 }
1209
1210 User user = null;
1211
1212 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1213 user = fetchUserByEmailAddress(companyId, login);
1214 }
1215 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1216 user = fetchUserByScreenName(companyId, login);
1217 }
1218 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1219 user = userPersistence.fetchByPrimaryKey(GetterUtil.getLong(login));
1220 }
1221
1222 if (user == null) {
1223 return 0;
1224 }
1225
1226 if (!isUserAllowedToAuthenticate(user)) {
1227 return 0;
1228 }
1229
1230 if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
1231 return user.getUserId();
1232 }
1233
1234 String userPassword = user.getPassword();
1235
1236 if (!user.isPasswordEncrypted()) {
1237 userPassword = PasswordEncryptorUtil.encrypt(userPassword);
1238 }
1239
1240 String encPassword = PasswordEncryptorUtil.encrypt(
1241 password, userPassword);
1242
1243 if (userPassword.equals(password) || userPassword.equals(encPassword)) {
1244 resetFailedLoginAttempts(user);
1245
1246 return user.getUserId();
1247 }
1248
1249 handleAuthenticationFailure(
1250 login, authType, user, Collections.<String, String[]>emptyMap(),
1251 Collections.<String, String[]>emptyMap());
1252
1253 return 0;
1254 }
1255
1256
1274 @Override
1275 @Transactional(propagation = Propagation.SUPPORTS)
1276 public long authenticateForDigest(
1277 long companyId, String username, String realm, String nonce,
1278 String method, String uri, String response)
1279 throws PortalException, SystemException {
1280
1281 if (PropsValues.AUTH_LOGIN_DISABLED) {
1282 return 0;
1283 }
1284
1285
1286
1287 User user = fetchUserByEmailAddress(companyId, username);
1288
1289 if (user == null) {
1290 user = fetchUserByScreenName(companyId, username);
1291 }
1292
1293 if (user == null) {
1294 user = userPersistence.fetchByPrimaryKey(
1295 GetterUtil.getLong(username));
1296 }
1297
1298 if (user == null) {
1299 return 0;
1300 }
1301
1302 if (!isUserAllowedToAuthenticate(user)) {
1303 return 0;
1304 }
1305
1306
1307
1308 String digest = user.getDigest();
1309
1310 if (Validator.isNull(digest)) {
1311 _log.error(
1312 "User must first login through the portal " + user.getUserId());
1313
1314 return 0;
1315 }
1316
1317 String[] digestArray = StringUtil.split(user.getDigest());
1318
1319 for (String ha1 : digestArray) {
1320 String ha2 = DigesterUtil.digestHex(Digester.MD5, method, uri);
1321
1322 String curResponse = DigesterUtil.digestHex(
1323 Digester.MD5, ha1, nonce, ha2);
1324
1325 if (response.equals(curResponse)) {
1326 resetFailedLoginAttempts(user);
1327
1328 return user.getUserId();
1329 }
1330 }
1331
1332 Company company = companyPersistence.findByPrimaryKey(companyId);
1333
1334 handleAuthenticationFailure(
1335 username, company.getAuthType(), user,
1336 new HashMap<String, String[]>(), new HashMap<String, String[]>());
1337
1338 return 0;
1339 }
1340
1341
1350 @Override
1351 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1352 public boolean authenticateForJAAS(long userId, String encPassword) {
1353 if (PropsValues.AUTH_LOGIN_DISABLED) {
1354 return false;
1355 }
1356
1357 try {
1358 User user = userPersistence.findByPrimaryKey(userId);
1359
1360 if (user.isDefaultUser()) {
1361 if (_log.isInfoEnabled()) {
1362 _log.info(
1363 "JAAS authentication is disabled for the default user");
1364 }
1365
1366 return false;
1367 }
1368 else if (!user.isActive()) {
1369 if (_log.isInfoEnabled()) {
1370 _log.info(
1371 "JAAS authentication is disabled for inactive user " +
1372 userId);
1373 }
1374
1375 return false;
1376 }
1377
1378 String userPassword = user.getPassword();
1379
1380 if (user.isPasswordEncrypted()) {
1381 if (userPassword.equals(encPassword)) {
1382 return true;
1383 }
1384
1385 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1386 encPassword = PasswordEncryptorUtil.encrypt(
1387 encPassword, userPassword);
1388
1389 if (userPassword.equals(encPassword)) {
1390 return true;
1391 }
1392 }
1393 }
1394 else {
1395 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1396 if (userPassword.equals(encPassword)) {
1397 return true;
1398 }
1399 }
1400
1401 userPassword = PasswordEncryptorUtil.encrypt(
1402 userPassword, encPassword);
1403
1404 if (userPassword.equals(encPassword)) {
1405 return true;
1406 }
1407 }
1408 }
1409 catch (Exception e) {
1410 _log.error(e);
1411 }
1412
1413 return false;
1414 }
1415
1416
1424 @Override
1425 public void checkLockout(User user)
1426 throws PortalException, SystemException {
1427
1428 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1429 return;
1430 }
1431
1432 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1433
1434 if (!passwordPolicy.isLockout()) {
1435 return;
1436 }
1437
1438
1439
1440 Date now = new Date();
1441 int failedLoginAttempts = user.getFailedLoginAttempts();
1442
1443 if (failedLoginAttempts > 0) {
1444 long failedLoginTime = user.getLastFailedLoginDate().getTime();
1445 long elapsedTime = now.getTime() - failedLoginTime;
1446 long requiredElapsedTime =
1447 passwordPolicy.getResetFailureCount() * 1000;
1448
1449 if ((requiredElapsedTime != 0) &&
1450 (elapsedTime > requiredElapsedTime)) {
1451
1452 user.setFailedLoginAttempts(0);
1453
1454 userPersistence.update(user);
1455 }
1456 }
1457
1458
1459
1460 if (user.isLockout()) {
1461 long lockoutTime = user.getLockoutDate().getTime();
1462 long elapsedTime = now.getTime() - lockoutTime;
1463 long requiredElapsedTime =
1464 passwordPolicy.getLockoutDuration() * 1000;
1465
1466 if ((requiredElapsedTime != 0) &&
1467 (elapsedTime > requiredElapsedTime)) {
1468
1469 user.setLockout(false);
1470 user.setLockoutDate(null);
1471
1472 userPersistence.update(user);
1473 }
1474 }
1475
1476 if (user.isLockout()) {
1477 throw new UserLockoutException();
1478 }
1479 }
1480
1481
1488 @Override
1489 public void checkLoginFailure(User user) throws SystemException {
1490 Date now = new Date();
1491
1492 int failedLoginAttempts = user.getFailedLoginAttempts();
1493
1494 user.setLastFailedLoginDate(now);
1495 user.setFailedLoginAttempts(++failedLoginAttempts);
1496
1497 userPersistence.update(user);
1498 }
1499
1500
1510 @Override
1511 public void checkLoginFailureByEmailAddress(
1512 long companyId, String emailAddress)
1513 throws PortalException, SystemException {
1514
1515 User user = getUserByEmailAddress(companyId, emailAddress);
1516
1517 checkLoginFailure(user);
1518 }
1519
1520
1528 @Override
1529 public void checkLoginFailureById(long userId)
1530 throws PortalException, SystemException {
1531
1532 User user = userPersistence.findByPrimaryKey(userId);
1533
1534 checkLoginFailure(user);
1535 }
1536
1537
1546 @Override
1547 public void checkLoginFailureByScreenName(long companyId, String screenName)
1548 throws PortalException, SystemException {
1549
1550 User user = getUserByScreenName(companyId, screenName);
1551
1552 checkLoginFailure(user);
1553 }
1554
1555
1565 @Override
1566 public void checkPasswordExpired(User user)
1567 throws PortalException, SystemException {
1568
1569 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1570 return;
1571 }
1572
1573 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1574
1575
1576
1577 if (isPasswordExpired(user)) {
1578 int graceLoginCount = user.getGraceLoginCount();
1579
1580 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
1581 user.setGraceLoginCount(++graceLoginCount);
1582
1583 userPersistence.update(user);
1584 }
1585 else {
1586 user.setDigest(StringPool.BLANK);
1587
1588 userPersistence.update(user);
1589
1590 throw new PasswordExpiredException();
1591 }
1592 }
1593
1594
1595
1596 if (passwordPolicy.isChangeable() &&
1597 passwordPolicy.isChangeRequired()) {
1598
1599 if (user.getLastLoginDate() == null) {
1600 user.setPasswordReset(true);
1601
1602 userPersistence.update(user);
1603 }
1604 }
1605 }
1606
1607
1613 @Override
1614 public void clearOrganizationUsers(long organizationId)
1615 throws SystemException {
1616
1617 organizationPersistence.clearUsers(organizationId);
1618
1619 PermissionCacheUtil.clearCache();
1620 }
1621
1622
1628 @Override
1629 public void clearUserGroupUsers(long userGroupId) throws SystemException {
1630 userGroupPersistence.clearUsers(userGroupId);
1631
1632 PermissionCacheUtil.clearCache();
1633 }
1634
1635
1650 @Override
1651 public void completeUserRegistration(
1652 User user, ServiceContext serviceContext)
1653 throws PortalException, SystemException {
1654
1655 boolean autoPassword = ParamUtil.getBoolean(
1656 serviceContext, "autoPassword");
1657
1658 String password = (String)serviceContext.getAttribute(
1659 "passwordUnencrypted");
1660
1661 if (autoPassword) {
1662 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1663 if (_log.isWarnEnabled()) {
1664 StringBundler sb = new StringBundler(4);
1665
1666 sb.append("When LDAP password policy is enabled, it is ");
1667 sb.append("possible that portal generated passwords will ");
1668 sb.append("not match the LDAP policy. Using ");
1669 sb.append("RegExpToolkit to generate new password.");
1670
1671 _log.warn(sb.toString());
1672 }
1673
1674 RegExpToolkit regExpToolkit = new RegExpToolkit();
1675
1676 password = regExpToolkit.generate(null);
1677 }
1678 else {
1679 PasswordPolicy passwordPolicy =
1680 passwordPolicyLocalService.getPasswordPolicy(
1681 user.getCompanyId(), user.getOrganizationIds());
1682
1683 password = PwdToolkitUtil.generate(passwordPolicy);
1684 }
1685
1686 serviceContext.setAttribute("passwordUnencrypted", password);
1687
1688 user.setPassword(PasswordEncryptorUtil.encrypt(password));
1689 user.setPasswordUnencrypted(password);
1690 user.setPasswordEncrypted(true);
1691 user.setPasswordModified(true);
1692 user.setPasswordModifiedDate(new Date());
1693
1694 userPersistence.update(user);
1695
1696 user.setPasswordModified(false);
1697 }
1698
1699 if (user.hasCompanyMx()) {
1700 mailService.addUser(
1701 user.getCompanyId(), user.getUserId(), password,
1702 user.getFirstName(), user.getMiddleName(), user.getLastName(),
1703 user.getEmailAddress());
1704 }
1705
1706 boolean sendEmail = ParamUtil.getBoolean(serviceContext, "sendEmail");
1707
1708 if (sendEmail) {
1709 sendEmail(user, password, serviceContext);
1710 }
1711
1712 Company company = companyPersistence.findByPrimaryKey(
1713 user.getCompanyId());
1714
1715 if (company.isStrangersVerify()) {
1716 sendEmailAddressVerification(
1717 user, user.getEmailAddress(), serviceContext);
1718 }
1719 }
1720
1721
1734 @Override
1735 public KeyValuePair decryptUserId(
1736 long companyId, String name, String password)
1737 throws PortalException, SystemException {
1738
1739 Company company = companyPersistence.findByPrimaryKey(companyId);
1740
1741 try {
1742 name = Encryptor.decrypt(company.getKeyObj(), name);
1743 }
1744 catch (EncryptorException ee) {
1745 throw new SystemException(ee);
1746 }
1747
1748 long userId = GetterUtil.getLong(name);
1749
1750 User user = userPersistence.findByPrimaryKey(userId);
1751
1752 try {
1753 password = Encryptor.decrypt(company.getKeyObj(), password);
1754 }
1755 catch (EncryptorException ee) {
1756 throw new SystemException(ee);
1757 }
1758
1759 String userPassword = user.getPassword();
1760 String encPassword = PasswordEncryptorUtil.encrypt(
1761 password, userPassword);
1762
1763 if (userPassword.equals(encPassword)) {
1764 if (isPasswordExpired(user)) {
1765 user.setPasswordReset(true);
1766
1767 userPersistence.update(user);
1768 }
1769
1770 return new KeyValuePair(name, password);
1771 }
1772 else {
1773 throw new PrincipalException();
1774 }
1775 }
1776
1777
1785 @Override
1786 public void deletePortrait(long userId)
1787 throws PortalException, SystemException {
1788
1789 User user = userPersistence.findByPrimaryKey(userId);
1790
1791 long portraitId = user.getPortraitId();
1792
1793 if (portraitId > 0) {
1794 user.setPortraitId(0);
1795
1796 userPersistence.update(user);
1797
1798 imageLocalService.deleteImage(portraitId);
1799 }
1800 }
1801
1802
1811 @Override
1812 public void deleteRoleUser(long roleId, long userId)
1813 throws PortalException, SystemException {
1814
1815 rolePersistence.removeUser(roleId, userId);
1816
1817 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1818
1819 indexer.reindex(userId);
1820
1821 PermissionCacheUtil.clearCache(userId);
1822 }
1823
1824
1832 @Override
1833 public User deleteUser(long userId)
1834 throws PortalException, SystemException {
1835
1836 User user = userPersistence.findByPrimaryKey(userId);
1837
1838 return deleteUser(user);
1839 }
1840
1841
1849 @Override
1850 public User deleteUser(User user) throws PortalException, SystemException {
1851 if (!PropsValues.USERS_DELETE) {
1852 throw new RequiredUserException();
1853 }
1854
1855
1856
1857 browserTrackerLocalService.deleteUserBrowserTracker(user.getUserId());
1858
1859
1860
1861 Group group = null;
1862
1863 if (!user.isDefaultUser()) {
1864 group = user.getGroup();
1865 }
1866
1867 if (group != null) {
1868 groupLocalService.deleteGroup(group);
1869 }
1870
1871
1872
1873 try {
1874 imageLocalService.deleteImage(user.getPortraitId());
1875 }
1876 catch (NoSuchImageException nsie) {
1877 if (_log.isWarnEnabled()) {
1878 _log.warn("Unable to delete image " + user.getPortraitId());
1879 }
1880 }
1881
1882
1883
1884 passwordPolicyRelLocalService.deletePasswordPolicyRel(
1885 User.class.getName(), user.getUserId());
1886
1887
1888
1889 passwordTrackerLocalService.deletePasswordTrackers(user.getUserId());
1890
1891
1892
1893 subscriptionLocalService.deleteSubscriptions(user.getUserId());
1894
1895
1896
1897 userIdMapperLocalService.deleteUserIdMappers(user.getUserId());
1898
1899
1900
1901 announcementsDeliveryLocalService.deleteDeliveries(user.getUserId());
1902
1903
1904
1905 assetEntryLocalService.deleteEntry(
1906 User.class.getName(), user.getUserId());
1907
1908
1909
1910 blogsStatsUserLocalService.deleteStatsUserByUserId(user.getUserId());
1911
1912
1913
1914 dlFileRankLocalService.deleteFileRanksByUserId(user.getUserId());
1915
1916
1917
1918 expandoRowLocalService.deleteRows(user.getUserId());
1919
1920
1921
1922 mbBanLocalService.deleteBansByBanUserId(user.getUserId());
1923 mbStatsUserLocalService.deleteStatsUsersByUserId(user.getUserId());
1924 mbThreadFlagLocalService.deleteThreadFlagsByUserId(user.getUserId());
1925
1926
1927
1928 membershipRequestLocalService.deleteMembershipRequestsByUserId(
1929 user.getUserId());
1930
1931
1932
1933 shoppingCartLocalService.deleteUserCarts(user.getUserId());
1934
1935
1936
1937 socialActivityLocalService.deleteUserActivities(user.getUserId());
1938 socialRequestLocalService.deleteReceiverUserRequests(user.getUserId());
1939 socialRequestLocalService.deleteUserRequests(user.getUserId());
1940
1941
1942
1943 mailService.deleteUser(user.getCompanyId(), user.getUserId());
1944
1945
1946
1947 Contact contact = contactLocalService.fetchContact(user.getContactId());
1948
1949 if (contact != null) {
1950 contactLocalService.deleteContact(contact);
1951 }
1952
1953
1954
1955 userGroupRoleLocalService.deleteUserGroupRolesByUserId(
1956 user.getUserId());
1957
1958
1959
1960 resourceLocalService.deleteResource(
1961 user.getCompanyId(), User.class.getName(),
1962 ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
1963
1964
1965
1966 userPersistence.remove(user);
1967
1968
1969
1970 PermissionCacheUtil.clearCache(user.getUserId());
1971
1972
1973
1974 workflowInstanceLinkLocalService.deleteWorkflowInstanceLinks(
1975 user.getCompanyId(), 0, User.class.getName(), user.getUserId());
1976
1977 return user;
1978 }
1979
1980
1988 @Override
1989 public void deleteUserGroupUser(long userGroupId, long userId)
1990 throws PortalException, SystemException {
1991
1992 userGroupPersistence.removeUser(userGroupId, userId);
1993
1994 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
1995
1996 indexer.reindex(userId);
1997
1998 PermissionCacheUtil.clearCache(userId);
1999 }
2000
2001
2010 @Override
2011 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
2012 public String encryptUserId(String name)
2013 throws PortalException, SystemException {
2014
2015 long userId = GetterUtil.getLong(name);
2016
2017 User user = userPersistence.findByPrimaryKey(userId);
2018
2019 Company company = companyPersistence.findByPrimaryKey(
2020 user.getCompanyId());
2021
2022 try {
2023 return Encryptor.encrypt(company.getKeyObj(), name);
2024 }
2025 catch (EncryptorException ee) {
2026 throw new SystemException(ee);
2027 }
2028 }
2029
2030
2037 @Override
2038 public User fetchUserByContactId(long contactId) throws SystemException {
2039 return userPersistence.fetchByContactId(contactId);
2040 }
2041
2042
2051 @Override
2052 public User fetchUserByEmailAddress(long companyId, String emailAddress)
2053 throws SystemException {
2054
2055 emailAddress = getLogin(emailAddress);
2056
2057 return userPersistence.fetchByC_EA(companyId, emailAddress);
2058 }
2059
2060
2069 @Override
2070 public User fetchUserByFacebookId(long companyId, long facebookId)
2071 throws SystemException {
2072
2073 return userPersistence.fetchByC_FID(companyId, facebookId);
2074 }
2075
2076
2084 @Override
2085 public User fetchUserById(long userId) throws SystemException {
2086 return userPersistence.fetchByPrimaryKey(userId);
2087 }
2088
2089
2098 @Override
2099 public User fetchUserByOpenId(long companyId, String openId)
2100 throws SystemException {
2101
2102 return userPersistence.fetchByC_O(companyId, openId);
2103 }
2104
2105
2114 @Override
2115 public User fetchUserByScreenName(long companyId, String screenName)
2116 throws SystemException {
2117
2118 screenName = getLogin(screenName);
2119
2120 return userPersistence.fetchByC_SN(companyId, screenName);
2121 }
2122
2123
2142 @Override
2143 public List<User> getCompanyUsers(long companyId, int start, int end)
2144 throws SystemException {
2145
2146 return userPersistence.findByCompanyId(companyId, start, end);
2147 }
2148
2149
2156 @Override
2157 public int getCompanyUsersCount(long companyId) throws SystemException {
2158 return userPersistence.countByCompanyId(companyId);
2159 }
2160
2161
2170 @Override
2171 @Skip
2172 public User getDefaultUser(long companyId)
2173 throws PortalException, SystemException {
2174
2175 User userModel = _defaultUsers.get(companyId);
2176
2177 if (userModel == null) {
2178 userModel = userLocalService.loadGetDefaultUser(companyId);
2179
2180 _defaultUsers.put(companyId, userModel);
2181 }
2182
2183 return userModel;
2184 }
2185
2186
2195 @Override
2196 @Skip
2197 public long getDefaultUserId(long companyId)
2198 throws PortalException, SystemException {
2199
2200 User user = getDefaultUser(companyId);
2201
2202 return user.getUserId();
2203 }
2204
2205
2212 @Override
2213 public long[] getGroupUserIds(long groupId) throws SystemException {
2214 return getUserIds(getGroupUsers(groupId));
2215 }
2216
2217
2227 @Override
2228 public int getGroupUsersCount(long groupId, int status)
2229 throws PortalException, SystemException {
2230
2231 Group group = groupPersistence.findByPrimaryKey(groupId);
2232
2233 LinkedHashMap<String, Object> params =
2234 new LinkedHashMap<String, Object>();
2235
2236 params.put("usersGroups", new Long(groupId));
2237
2238 return searchCount(group.getCompanyId(), null, status, params);
2239 }
2240
2241 @Override
2242 public List<User> getInheritedRoleUsers(
2243 long roleId, int start, int end, OrderByComparator obc)
2244 throws PortalException, SystemException {
2245
2246 Role role = rolePersistence.findByPrimaryKey(roleId);
2247
2248 LinkedHashMap<String, Object> params =
2249 new LinkedHashMap<String, Object>();
2250
2251 params.put("inherit", Boolean.TRUE);
2252 params.put("usersRoles", roleId);
2253
2254 return search(
2255 role.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2256 params, start, end, obc);
2257 }
2258
2259
2267 @Override
2268 public List<User> getNoAnnouncementsDeliveries(String type)
2269 throws SystemException {
2270
2271 return userFinder.findByNoAnnouncementsDeliveries(type);
2272 }
2273
2274
2280 @Override
2281 public List<User> getNoContacts() throws SystemException {
2282 return userFinder.findByNoContacts();
2283 }
2284
2285
2292 @Override
2293 public List<User> getNoGroups() throws SystemException {
2294 return userFinder.findByNoGroups();
2295 }
2296
2297
2304 @Override
2305 public long[] getOrganizationUserIds(long organizationId)
2306 throws SystemException {
2307
2308 return getUserIds(getOrganizationUsers(organizationId));
2309 }
2310
2311
2322 @Override
2323 public int getOrganizationUsersCount(long organizationId, int status)
2324 throws PortalException, SystemException {
2325
2326 Organization organization = organizationPersistence.findByPrimaryKey(
2327 organizationId);
2328
2329 LinkedHashMap<String, Object> params =
2330 new LinkedHashMap<String, Object>();
2331
2332 params.put("usersOrgs", new Long(organizationId));
2333
2334 return searchCount(organization.getCompanyId(), null, status, params);
2335 }
2336
2337
2344 @Override
2345 public long[] getRoleUserIds(long roleId) throws SystemException {
2346 return getUserIds(getRoleUsers(roleId));
2347 }
2348
2349
2359 @Override
2360 public int getRoleUsersCount(long roleId, int status)
2361 throws PortalException, SystemException {
2362
2363 Role role = rolePersistence.findByPrimaryKey(roleId);
2364
2365 LinkedHashMap<String, Object> params =
2366 new LinkedHashMap<String, Object>();
2367
2368 params.put("usersRoles", new Long(roleId));
2369
2370 return searchCount(role.getCompanyId(), null, status, params);
2371 }
2372
2373
2400 @Override
2401 public List<User> getSocialUsers(
2402 long userId, int type, int start, int end, OrderByComparator obc)
2403 throws PortalException, SystemException {
2404
2405 User user = userPersistence.findByPrimaryKey(userId);
2406
2407 LinkedHashMap<String, Object> params =
2408 new LinkedHashMap<String, Object>();
2409
2410 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2411
2412 return search(
2413 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2414 params, start, end, obc);
2415 }
2416
2417
2440 @Override
2441 public List<User> getSocialUsers(
2442 long userId, int start, int end, OrderByComparator obc)
2443 throws PortalException, SystemException {
2444
2445 User user = userPersistence.findByPrimaryKey(userId);
2446
2447 LinkedHashMap<String, Object> params =
2448 new LinkedHashMap<String, Object>();
2449
2450 params.put("socialRelation", new Long[] {userId});
2451
2452 return search(
2453 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2454 params, start, end, obc);
2455 }
2456
2457
2485 @Override
2486 public List<User> getSocialUsers(
2487 long userId1, long userId2, int type, int start, int end,
2488 OrderByComparator obc)
2489 throws PortalException, SystemException {
2490
2491 User user1 = userPersistence.findByPrimaryKey(userId1);
2492
2493 LinkedHashMap<String, Object> params =
2494 new LinkedHashMap<String, Object>();
2495
2496 params.put(
2497 "socialMutualRelationType",
2498 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2499
2500 return search(
2501 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2502 params, start, end, obc);
2503 }
2504
2505
2530 @Override
2531 public List<User> getSocialUsers(
2532 long userId1, long userId2, int start, int end,
2533 OrderByComparator obc)
2534 throws PortalException, SystemException {
2535
2536 User user1 = userPersistence.findByPrimaryKey(userId1);
2537
2538 LinkedHashMap<String, Object> params =
2539 new LinkedHashMap<String, Object>();
2540
2541 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2542
2543 return search(
2544 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2545 params, start, end, obc);
2546 }
2547
2548
2556 @Override
2557 public int getSocialUsersCount(long userId)
2558 throws PortalException, SystemException {
2559
2560 User user = userPersistence.findByPrimaryKey(userId);
2561
2562 LinkedHashMap<String, Object> params =
2563 new LinkedHashMap<String, Object>();
2564
2565 params.put("socialRelation", new Long[] {userId});
2566
2567 return searchCount(
2568 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2569 params);
2570 }
2571
2572
2585 @Override
2586 public int getSocialUsersCount(long userId, int type)
2587 throws PortalException, SystemException {
2588
2589 User user = userPersistence.findByPrimaryKey(userId);
2590
2591 LinkedHashMap<String, Object> params =
2592 new LinkedHashMap<String, Object>();
2593
2594 params.put("socialRelationType", new Long[] {userId, new Long(type)});
2595
2596 return searchCount(
2597 user.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2598 params);
2599 }
2600
2601
2611 @Override
2612 public int getSocialUsersCount(long userId1, long userId2)
2613 throws PortalException, SystemException {
2614
2615 User user1 = userPersistence.findByPrimaryKey(userId1);
2616
2617 LinkedHashMap<String, Object> params =
2618 new LinkedHashMap<String, Object>();
2619
2620 params.put("socialMutualRelation", new Long[] {userId1, userId2});
2621
2622 return searchCount(
2623 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2624 params);
2625 }
2626
2627
2641 @Override
2642 public int getSocialUsersCount(long userId1, long userId2, int type)
2643 throws PortalException, SystemException {
2644
2645 User user1 = userPersistence.findByPrimaryKey(userId1);
2646
2647 LinkedHashMap<String, Object> params =
2648 new LinkedHashMap<String, Object>();
2649
2650 params.put(
2651 "socialMutualRelationType",
2652 new Long[] {userId1, new Long(type), userId2, new Long(type)});
2653
2654 return searchCount(
2655 user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2656 params);
2657 }
2658
2659
2667 @Override
2668 public User getUserByContactId(long contactId)
2669 throws PortalException, SystemException {
2670
2671 return userPersistence.findByContactId(contactId);
2672 }
2673
2674
2684 @Override
2685 public User getUserByEmailAddress(long companyId, String emailAddress)
2686 throws PortalException, SystemException {
2687
2688 emailAddress = getLogin(emailAddress);
2689
2690 return userPersistence.findByC_EA(companyId, emailAddress);
2691 }
2692
2693
2702 @Override
2703 public User getUserByFacebookId(long companyId, long facebookId)
2704 throws PortalException, SystemException {
2705
2706 return userPersistence.findByC_FID(companyId, facebookId);
2707 }
2708
2709
2717 @Override
2718 public User getUserById(long userId)
2719 throws PortalException, SystemException {
2720
2721 return userPersistence.findByPrimaryKey(userId);
2722 }
2723
2724
2734 @Override
2735 public User getUserById(long companyId, long userId)
2736 throws PortalException, SystemException {
2737
2738 return userPersistence.findByC_U(companyId, userId);
2739 }
2740
2741
2750 @Override
2751 public User getUserByOpenId(long companyId, String openId)
2752 throws PortalException, SystemException {
2753
2754 return userPersistence.findByC_O(companyId, openId);
2755 }
2756
2757
2765 @Override
2766 public User getUserByPortraitId(long portraitId)
2767 throws PortalException, SystemException {
2768
2769 return userPersistence.findByPortraitId(portraitId);
2770 }
2771
2772
2781 @Override
2782 public User getUserByScreenName(long companyId, String screenName)
2783 throws PortalException, SystemException {
2784
2785 screenName = getLogin(screenName);
2786
2787 return userPersistence.findByC_SN(companyId, screenName);
2788 }
2789
2790
2800 @Override
2801 public User getUserByUuid(String uuid)
2802 throws PortalException, SystemException {
2803
2804 List<User> users = userPersistence.findByUuid(uuid);
2805
2806 if (users.isEmpty()) {
2807 throw new NoSuchUserException("{uuid=" + uuid + "}");
2808 }
2809 else {
2810 return users.get(0);
2811 }
2812 }
2813
2814
2823 @Override
2824 public User getUserByUuidAndCompanyId(String uuid, long companyId)
2825 throws PortalException, SystemException {
2826
2827 List<User> users = userPersistence.findByUuid_C(uuid, companyId);
2828
2829 if (users.isEmpty()) {
2830 StringBundler sb = new StringBundler(5);
2831
2832 sb.append("{uuid=");
2833 sb.append(uuid);
2834 sb.append(", companyId=");
2835 sb.append(companyId);
2836 sb.append("}");
2837
2838 throw new NoSuchUserException(sb.toString());
2839 }
2840 else {
2841 return users.get(0);
2842 }
2843 }
2844
2845
2855 @Override
2856 public int getUserGroupUsersCount(long userGroupId, int status)
2857 throws PortalException, SystemException {
2858
2859 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
2860 userGroupId);
2861
2862 LinkedHashMap<String, Object> params =
2863 new LinkedHashMap<String, Object>();
2864
2865 params.put("usersUserGroups", new Long(userGroupId));
2866
2867 return searchCount(userGroup.getCompanyId(), null, status, params);
2868 }
2869
2870
2880 @Override
2881 public long getUserIdByEmailAddress(long companyId, String emailAddress)
2882 throws PortalException, SystemException {
2883
2884 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
2885
2886 User user = userPersistence.findByC_EA(companyId, emailAddress);
2887
2888 return user.getUserId();
2889 }
2890
2891
2900 @Override
2901 public long getUserIdByScreenName(long companyId, String screenName)
2902 throws PortalException, SystemException {
2903
2904 screenName = getLogin(screenName);
2905
2906 User user = userPersistence.findByC_SN(companyId, screenName);
2907
2908 return user.getUserId();
2909 }
2910
2911
2921 @Override
2922 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
2923 throws SystemException {
2924
2925 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
2926 passwordPolicyId, User.class.getName(), userId);
2927 }
2928
2929
2944 @Override
2945 public boolean hasRoleUser(
2946 long companyId, String name, long userId, boolean inherited)
2947 throws PortalException, SystemException {
2948
2949 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
2950 }
2951
2952
2962 @Override
2963 public boolean isPasswordExpired(User user)
2964 throws PortalException, SystemException {
2965
2966 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2967
2968 if ((passwordPolicy != null) && passwordPolicy.getExpireable()) {
2969 Date now = new Date();
2970
2971 if (user.getPasswordModifiedDate() == null) {
2972 user.setPasswordModifiedDate(now);
2973
2974 userLocalService.updateUser(user);
2975 }
2976
2977 long passwordStartTime = user.getPasswordModifiedDate().getTime();
2978 long elapsedTime = now.getTime() - passwordStartTime;
2979
2980 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
2981 return true;
2982 }
2983 else {
2984 return false;
2985 }
2986 }
2987
2988 return false;
2989 }
2990
2991
3003 @Override
3004 public boolean isPasswordExpiringSoon(User user)
3005 throws PortalException, SystemException {
3006
3007 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3008
3009 if ((passwordPolicy != null) && passwordPolicy.isExpireable() &&
3010 (passwordPolicy.getWarningTime() > 0)) {
3011
3012 Date now = new Date();
3013
3014 if (user.getPasswordModifiedDate() == null) {
3015 user.setPasswordModifiedDate(now);
3016
3017 userLocalService.updateUser(user);
3018 }
3019
3020 long timeModified = user.getPasswordModifiedDate().getTime();
3021 long passwordExpiresOn =
3022 (passwordPolicy.getMaxAge() * 1000) + timeModified;
3023
3024 long timeStartWarning =
3025 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
3026
3027 if (now.getTime() > timeStartWarning) {
3028 return true;
3029 }
3030 else {
3031 return false;
3032 }
3033 }
3034
3035 return false;
3036 }
3037
3038
3046 @Override
3047 public User loadGetDefaultUser(long companyId)
3048 throws PortalException, SystemException {
3049
3050 return userPersistence.findByC_DU(companyId, true);
3051 }
3052
3053
3085 @Override
3086 public List<User> search(
3087 long companyId, String keywords, int status,
3088 LinkedHashMap<String, Object> params, int start, int end,
3089 OrderByComparator obc)
3090 throws SystemException {
3091
3092 return userFinder.findByKeywords(
3093 companyId, keywords, status, params, start, end, obc);
3094 }
3095
3096
3127 @Override
3128 public Hits search(
3129 long companyId, String keywords, int status,
3130 LinkedHashMap<String, Object> params, int start, int end, Sort sort)
3131 throws SystemException {
3132
3133 String firstName = null;
3134 String middleName = null;
3135 String lastName = null;
3136 String fullName = null;
3137 String screenName = null;
3138 String emailAddress = null;
3139 String street = null;
3140 String city = null;
3141 String zip = null;
3142 String region = null;
3143 String country = null;
3144 boolean andOperator = false;
3145
3146 if (Validator.isNotNull(keywords)) {
3147 firstName = keywords;
3148 middleName = keywords;
3149 lastName = keywords;
3150 fullName = keywords;
3151 screenName = keywords;
3152 emailAddress = keywords;
3153 street = keywords;
3154 city = keywords;
3155 zip = keywords;
3156 region = keywords;
3157 country = keywords;
3158 }
3159 else {
3160 andOperator = true;
3161 }
3162
3163 if (params != null) {
3164 params.put("keywords", keywords);
3165 }
3166
3167 try {
3168 SearchContext searchContext = buildSearchContext(
3169 companyId, firstName, middleName, lastName, fullName,
3170 screenName, emailAddress, street, city, zip, region, country,
3171 status, params, andOperator, start, end, sort);
3172
3173 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3174 User.class);
3175
3176 return indexer.search(searchContext);
3177 }
3178 catch (Exception e) {
3179 throw new SystemException(e);
3180 }
3181 }
3182
3183
3223 @Override
3224 public List<User> search(
3225 long companyId, String firstName, String middleName,
3226 String lastName, String screenName, String emailAddress, int status,
3227 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3228 int end, OrderByComparator obc)
3229 throws SystemException {
3230
3231 return userFinder.findByC_FN_MN_LN_SN_EA_S(
3232 companyId, firstName, middleName, lastName, screenName,
3233 emailAddress, status, params, andSearch, start, end, obc);
3234 }
3235
3236
3275 @Override
3276 public Hits search(
3277 long companyId, String firstName, String middleName,
3278 String lastName, String screenName, String emailAddress, int status,
3279 LinkedHashMap<String, Object> params, boolean andSearch, int start,
3280 int end, Sort sort)
3281 throws SystemException {
3282
3283 try {
3284 SearchContext searchContext = buildSearchContext(
3285 companyId, firstName, middleName, lastName, null, screenName,
3286 emailAddress, null, null, null, null, null, status, params,
3287 andSearch, start, end, sort);
3288
3289 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3290 User.class);
3291
3292 return indexer.search(searchContext);
3293 }
3294 catch (Exception e) {
3295 throw new SystemException(e);
3296 }
3297 }
3298
3299
3313 @Override
3314 public int searchCount(
3315 long companyId, String keywords, int status,
3316 LinkedHashMap<String, Object> params)
3317 throws SystemException {
3318
3319 if (!PropsValues.USERS_INDEXER_ENABLED ||
3320 !PropsValues.USERS_SEARCH_WITH_INDEX || isUseCustomSQL(params)) {
3321
3322 return userFinder.countByKeywords(
3323 companyId, keywords, status, params);
3324 }
3325
3326 try {
3327 String firstName = null;
3328 String middleName = null;
3329 String lastName = null;
3330 String fullName = null;
3331 String screenName = null;
3332 String emailAddress = null;
3333 String street = null;
3334 String city = null;
3335 String zip = null;
3336 String region = null;
3337 String country = null;
3338 boolean andOperator = false;
3339
3340 if (Validator.isNotNull(keywords)) {
3341 firstName = keywords;
3342 middleName = keywords;
3343 lastName = keywords;
3344 fullName = keywords;
3345 screenName = keywords;
3346 emailAddress = keywords;
3347 street = keywords;
3348 city = keywords;
3349 zip = keywords;
3350 region = keywords;
3351 country = keywords;
3352 }
3353 else {
3354 andOperator = true;
3355 }
3356
3357 if (params != null) {
3358 params.put("keywords", keywords);
3359 }
3360
3361 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3362 User.class);
3363
3364 SearchContext searchContext = buildSearchContext(
3365 companyId, firstName, middleName, lastName, fullName,
3366 screenName, emailAddress, street, city, zip, region, country,
3367 status, params, andOperator, QueryUtil.ALL_POS,
3368 QueryUtil.ALL_POS, null);
3369
3370 Hits hits = indexer.search(searchContext);
3371
3372 return hits.getLength();
3373 }
3374 catch (Exception e) {
3375 throw new SystemException(e);
3376 }
3377 }
3378
3379
3401 @Override
3402 public int searchCount(
3403 long companyId, String firstName, String middleName,
3404 String lastName, String screenName, String emailAddress, int status,
3405 LinkedHashMap<String, Object> params, boolean andSearch)
3406 throws SystemException {
3407
3408 if (!PropsValues.USERS_INDEXER_ENABLED ||
3409 !PropsValues.USERS_SEARCH_WITH_INDEX || isUseCustomSQL(params)) {
3410
3411 return userFinder.countByC_FN_MN_LN_SN_EA_S(
3412 companyId, firstName, middleName, lastName, screenName,
3413 emailAddress, status, params, andSearch);
3414 }
3415
3416 try {
3417 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3418 User.class);
3419
3420 FullNameGenerator fullNameGenerator =
3421 FullNameGeneratorFactory.getInstance();
3422
3423 String fullName = fullNameGenerator.getFullName(
3424 firstName, middleName, lastName);
3425
3426 SearchContext searchContext = buildSearchContext(
3427 companyId, firstName, middleName, lastName, fullName,
3428 screenName, emailAddress, null, null, null, null, null, status,
3429 params, true, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
3430
3431 Hits hits = indexer.search(searchContext);
3432
3433 return hits.getLength();
3434 }
3435 catch (Exception e) {
3436 throw new SystemException(e);
3437 }
3438 }
3439
3440
3451 @Override
3452 public void sendEmailAddressVerification(
3453 User user, String emailAddress, ServiceContext serviceContext)
3454 throws PortalException, SystemException {
3455
3456 if (user.isEmailAddressVerified() &&
3457 StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
3458
3459 return;
3460 }
3461
3462 Ticket ticket = ticketLocalService.addDistinctTicket(
3463 user.getCompanyId(), User.class.getName(), user.getUserId(),
3464 TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3465 serviceContext);
3466
3467 String verifyEmailAddressURL =
3468 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3469 "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3470
3471 long plid = serviceContext.getPlid();
3472
3473 if (plid > 0) {
3474 Layout layout = layoutLocalService.fetchLayout(plid);
3475
3476 if (layout != null) {
3477 Group group = layout.getGroup();
3478
3479 if (!layout.isPrivateLayout() && !group.isUser()) {
3480 verifyEmailAddressURL +=
3481 "&p_l_id=" + serviceContext.getPlid();
3482 }
3483 }
3484 }
3485
3486 String fromName = PrefsPropsUtil.getString(
3487 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3488 String fromAddress = PrefsPropsUtil.getString(
3489 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3490
3491 String toName = user.getFullName();
3492 String toAddress = emailAddress;
3493
3494 String subject = PrefsPropsUtil.getContent(
3495 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3496
3497 String body = PrefsPropsUtil.getContent(
3498 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3499
3500 SubscriptionSender subscriptionSender = new SubscriptionSender();
3501
3502 subscriptionSender.setBody(body);
3503 subscriptionSender.setCompanyId(user.getCompanyId());
3504 subscriptionSender.setContextAttributes(
3505 "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3506 "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3507 "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3508 "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_ID$]",
3509 user.getUserId(), "[$USER_SCREENNAME$]", user.getScreenName());
3510 subscriptionSender.setFrom(fromAddress, fromName);
3511 subscriptionSender.setHtmlFormat(true);
3512 subscriptionSender.setMailId("user", user.getUserId());
3513 subscriptionSender.setServiceContext(serviceContext);
3514 subscriptionSender.setSubject(subject);
3515 subscriptionSender.setUserId(user.getUserId());
3516
3517 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3518
3519 subscriptionSender.flushNotificationsAsync();
3520 }
3521
3522
3541 @Override
3542 public void sendPassword(
3543 long companyId, String emailAddress, String fromName,
3544 String fromAddress, String subject, String body,
3545 ServiceContext serviceContext)
3546 throws PortalException, SystemException {
3547
3548 Company company = companyPersistence.findByPrimaryKey(companyId);
3549
3550 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3551 return;
3552 }
3553
3554 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
3555
3556 if (Validator.isNull(emailAddress)) {
3557 throw new UserEmailAddressException();
3558 }
3559
3560 User user = userPersistence.findByC_EA(companyId, emailAddress);
3561
3562 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3563
3564 String newPassword = StringPool.BLANK;
3565 String passwordResetURL = StringPool.BLANK;
3566
3567 if (company.isSendPasswordResetLink()) {
3568 Date expirationDate = null;
3569
3570 if ((passwordPolicy != null) &&
3571 (passwordPolicy.getResetTicketMaxAge() > 0)) {
3572
3573 expirationDate = new Date(
3574 System.currentTimeMillis() +
3575 (passwordPolicy.getResetTicketMaxAge() * 1000));
3576 }
3577
3578 Ticket ticket = ticketLocalService.addDistinctTicket(
3579 companyId, User.class.getName(), user.getUserId(),
3580 TicketConstants.TYPE_PASSWORD, null, expirationDate,
3581 serviceContext);
3582
3583 passwordResetURL =
3584 serviceContext.getPortalURL() + serviceContext.getPathMain() +
3585 "/portal/update_password?p_l_id="+
3586 serviceContext.getPlid() +
3587 "&ticketKey=" + ticket.getKey();
3588 }
3589 else {
3590 if (!PasswordEncryptorUtil.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
3591 PasswordEncryptorUtil.TYPE_NONE)) {
3592
3593 if (LDAPSettingsUtil.isPasswordPolicyEnabled(
3594 user.getCompanyId())) {
3595
3596 if (_log.isWarnEnabled()) {
3597 StringBundler sb = new StringBundler(5);
3598
3599 sb.append("When LDAP password policy is enabled, ");
3600 sb.append("it is possible that portal generated ");
3601 sb.append("passwords will not match the LDAP policy.");
3602 sb.append("Using RegExpToolkit to generate new ");
3603 sb.append("password.");
3604
3605 _log.warn(sb.toString());
3606 }
3607
3608 RegExpToolkit regExpToolkit = new RegExpToolkit();
3609
3610 newPassword = regExpToolkit.generate(null);
3611 }
3612 else {
3613 newPassword = PwdToolkitUtil.generate(passwordPolicy);
3614 }
3615
3616 boolean passwordReset = false;
3617
3618 if (passwordPolicy.getChangeable() &&
3619 passwordPolicy.getChangeRequired()) {
3620
3621 passwordReset = true;
3622 }
3623
3624 user.setPassword(PasswordEncryptorUtil.encrypt(newPassword));
3625 user.setPasswordUnencrypted(newPassword);
3626 user.setPasswordEncrypted(true);
3627 user.setPasswordReset(passwordReset);
3628 user.setPasswordModified(true);
3629 user.setPasswordModifiedDate(new Date());
3630
3631 userPersistence.update(user);
3632
3633 user.setPasswordModified(false);
3634 }
3635 else {
3636 newPassword = user.getPassword();
3637 }
3638 }
3639
3640 if (Validator.isNull(fromName)) {
3641 fromName = PrefsPropsUtil.getString(
3642 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3643 }
3644
3645 if (Validator.isNull(fromAddress)) {
3646 fromAddress = PrefsPropsUtil.getString(
3647 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3648 }
3649
3650 String toName = user.getFullName();
3651 String toAddress = user.getEmailAddress();
3652
3653 if (Validator.isNull(subject)) {
3654 if (company.isSendPasswordResetLink()) {
3655 subject = PrefsPropsUtil.getContent(
3656 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
3657 }
3658 else {
3659 subject = PrefsPropsUtil.getContent(
3660 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
3661 }
3662 }
3663
3664 if (Validator.isNull(body)) {
3665 if (company.isSendPasswordResetLink()) {
3666 body = PrefsPropsUtil.getContent(
3667 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
3668 }
3669 else {
3670 body = PrefsPropsUtil.getContent(
3671 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
3672 }
3673 }
3674
3675 SubscriptionSender subscriptionSender = new SubscriptionSender();
3676
3677 subscriptionSender.setBody(body);
3678 subscriptionSender.setCompanyId(companyId);
3679 subscriptionSender.setContextAttributes(
3680 "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
3681 serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
3682 serviceContext.getRemoteHost(), "[$USER_ID$]", user.getUserId(),
3683 "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
3684 user.getScreenName());
3685 subscriptionSender.setFrom(fromAddress, fromName);
3686 subscriptionSender.setHtmlFormat(true);
3687 subscriptionSender.setMailId("user", user.getUserId());
3688 subscriptionSender.setServiceContext(serviceContext);
3689 subscriptionSender.setSubject(subject);
3690 subscriptionSender.setUserId(user.getUserId());
3691
3692 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3693
3694 subscriptionSender.flushNotificationsAsync();
3695 }
3696
3697
3706 @Override
3707 public void setRoleUsers(long roleId, long[] userIds)
3708 throws PortalException, SystemException {
3709
3710 List<User> oldUsers = rolePersistence.getUsers(roleId);
3711
3712 long[] oldUserIds = new long[oldUsers.size()];
3713
3714 for (int i = 0; i < oldUsers.size(); i++) {
3715 User user = oldUsers.get(i);
3716
3717 oldUserIds[i] = user.getUserId();
3718 }
3719
3720 Set<Long> updatedUserIdsSet = SetUtil.symmetricDifference(
3721 userIds, oldUserIds);
3722
3723 long[] updateUserIds = ArrayUtil.toLongArray(updatedUserIdsSet);
3724
3725 rolePersistence.setUsers(roleId, userIds);
3726
3727 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3728
3729 indexer.reindex(updateUserIds);
3730
3731 PermissionCacheUtil.clearCache(updateUserIds);
3732 }
3733
3734
3743 @Override
3744 @SuppressWarnings("deprecation")
3745 public void setUserGroupUsers(long userGroupId, long[] userIds)
3746 throws PortalException, SystemException {
3747
3748 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3749 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3750 }
3751
3752 List<User> oldUsers = userGroupPersistence.getUsers(userGroupId);
3753
3754 long[] oldUserIds = new long[oldUsers.size()];
3755
3756 for (int i = 0; i < oldUsers.size(); i++) {
3757 User user = oldUsers.get(i);
3758
3759 oldUserIds[i] = user.getUserId();
3760 }
3761
3762 Set<Long> updatedUserIdsSet = SetUtil.symmetricDifference(
3763 userIds, oldUserIds);
3764
3765 long[] updateUserIds = ArrayUtil.toLongArray(updatedUserIdsSet);
3766
3767 userGroupPersistence.setUsers(userGroupId, userIds);
3768
3769 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3770
3771 indexer.reindex(updateUserIds);
3772
3773 PermissionCacheUtil.clearCache(updateUserIds);
3774 }
3775
3776
3784 @Override
3785 public void unsetGroupTeamsUsers(long groupId, long[] userIds)
3786 throws PortalException, SystemException {
3787
3788 List<Team> teams = teamPersistence.findByGroupId(groupId);
3789
3790 for (Team team : teams) {
3791 unsetTeamUsers(team.getTeamId(), userIds);
3792 }
3793
3794 PermissionCacheUtil.clearCache(userIds);
3795 }
3796
3797
3807 @Override
3808 public void unsetGroupUsers(
3809 final long groupId, final long[] userIds,
3810 ServiceContext serviceContext)
3811 throws PortalException, SystemException {
3812
3813 userGroupRoleLocalService.deleteUserGroupRoles(
3814 userIds, groupId, RoleConstants.TYPE_SITE);
3815
3816 userLocalService.unsetGroupTeamsUsers(groupId, userIds);
3817
3818 groupPersistence.removeUsers(groupId, userIds);
3819
3820 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3821
3822 indexer.reindex(userIds);
3823
3824 PermissionCacheUtil.clearCache(userIds);
3825
3826 Callable<Void> callable = new Callable<Void>() {
3827
3828 @Override
3829 public Void call() throws Exception {
3830 Message message = new Message();
3831
3832 message.put("groupId", groupId);
3833 message.put("userIds", userIds);
3834
3835 MessageBusUtil.sendMessage(
3836 DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
3837
3838 return null;
3839 }
3840
3841 };
3842
3843 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
3844 }
3845
3846
3854 @Override
3855 public void unsetOrganizationUsers(
3856 long organizationId, final long[] userIds)
3857 throws PortalException, SystemException {
3858
3859 Organization organization = organizationPersistence.findByPrimaryKey(
3860 organizationId);
3861
3862 final Group group = organization.getGroup();
3863
3864 userGroupRoleLocalService.deleteUserGroupRoles(
3865 userIds, group.getGroupId());
3866
3867 organizationPersistence.removeUsers(organizationId, userIds);
3868
3869 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3870
3871 indexer.reindex(userIds);
3872
3873 PermissionCacheUtil.clearCache(userIds);
3874
3875 Callable<Void> callable = new Callable<Void>() {
3876
3877 @Override
3878 public Void call() throws Exception {
3879 Message message = new Message();
3880
3881 message.put("groupId", group.getGroupId());
3882 message.put("userIds", userIds);
3883
3884 MessageBusUtil.sendMessage(
3885 DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
3886
3887 return null;
3888 }
3889
3890 };
3891
3892 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
3893 }
3894
3895
3902 @Override
3903 public void unsetPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
3904 throws SystemException {
3905
3906 passwordPolicyRelLocalService.deletePasswordPolicyRels(
3907 passwordPolicyId, User.class.getName(), userIds);
3908 }
3909
3910
3918 @Override
3919 public void unsetRoleUsers(long roleId, List<User> users)
3920 throws PortalException, SystemException {
3921
3922 Role role = rolePersistence.findByPrimaryKey(roleId);
3923
3924 String roleName = role.getName();
3925
3926 if ((roleName.equals(RoleConstants.ADMINISTRATOR) &&
3927 (getRoleUsersCount(role.getRoleId()) <= 1)) ||
3928 roleName.equals(RoleConstants.USER)) {
3929
3930 return;
3931 }
3932
3933 rolePersistence.removeUsers(roleId, users);
3934
3935 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3936
3937 indexer.reindex(users);
3938
3939 long[] userIds = new long[users.size()];
3940
3941 for (int i = 0; i < users.size(); i++) {
3942 User user = users.get(i);
3943
3944 userIds[i] = user.getUserId();
3945 }
3946
3947 PermissionCacheUtil.clearCache(userIds);
3948 }
3949
3950
3958 @Override
3959 public void unsetRoleUsers(long roleId, long[] userIds)
3960 throws PortalException, SystemException {
3961
3962 Role role = rolePersistence.findByPrimaryKey(roleId);
3963
3964 String roleName = role.getName();
3965
3966 if (roleName.equals(RoleConstants.USER) ||
3967 (roleName.equals(RoleConstants.ADMINISTRATOR) &&
3968 getRoleUsersCount(role.getRoleId()) <= 1)) {
3969
3970 return;
3971 }
3972
3973 rolePersistence.removeUsers(roleId, userIds);
3974
3975 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3976
3977 indexer.reindex(userIds);
3978
3979 PermissionCacheUtil.clearCache(userIds);
3980 }
3981
3982
3990 @Override
3991 public void unsetTeamUsers(long teamId, long[] userIds)
3992 throws PortalException, SystemException {
3993
3994 teamPersistence.removeUsers(teamId, userIds);
3995
3996 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3997
3998 indexer.reindex(userIds);
3999
4000 PermissionCacheUtil.clearCache(userIds);
4001 }
4002
4003
4011 @Override
4012 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
4013 throws PortalException, SystemException {
4014
4015 userGroupPersistence.removeUsers(userGroupId, userIds);
4016
4017 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
4018
4019 indexer.reindex(userIds);
4020
4021 PermissionCacheUtil.clearCache(userIds);
4022 }
4023
4024
4034 @Override
4035 public User updateAgreedToTermsOfUse(
4036 long userId, boolean agreedToTermsOfUse)
4037 throws PortalException, SystemException {
4038
4039 User user = userPersistence.findByPrimaryKey(userId);
4040
4041 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
4042
4043 userPersistence.update(user);
4044
4045 return user;
4046 }
4047
4048
4059 @Override
4060 public void updateAsset(
4061 long userId, User user, long[] assetCategoryIds,
4062 String[] assetTagNames)
4063 throws PortalException, SystemException {
4064
4065 User owner = userPersistence.findByPrimaryKey(userId);
4066
4067 Company company = companyPersistence.findByPrimaryKey(
4068 owner.getCompanyId());
4069
4070 Group companyGroup = company.getGroup();
4071
4072 assetEntryLocalService.updateEntry(
4073 userId, companyGroup.getGroupId(), user.getCreateDate(),
4074 user.getModifiedDate(), User.class.getName(), user.getUserId(),
4075 user.getUuid(), 0, assetCategoryIds, assetTagNames, false, null,
4076 null, null, null, user.getFullName(), null, null, null, null, 0, 0,
4077 null, false);
4078 }
4079
4080
4089 @Override
4090 public User updateCreateDate(long userId, Date createDate)
4091 throws PortalException, SystemException {
4092
4093 User user = userPersistence.findByPrimaryKey(userId);
4094
4095 user.setCreateDate(createDate);
4096
4097 userPersistence.update(user);
4098
4099 return user;
4100 }
4101
4102
4113 @Override
4114 public User updateEmailAddress(
4115 long userId, String password, String emailAddress1,
4116 String emailAddress2)
4117 throws PortalException, SystemException {
4118
4119 emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
4120 emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
4121
4122 User user = userPersistence.findByPrimaryKey(userId);
4123
4124 validateEmailAddress(user, emailAddress1, emailAddress2);
4125
4126 setEmailAddress(
4127 user, password, user.getFirstName(), user.getMiddleName(),
4128 user.getLastName(), emailAddress1);
4129
4130 userPersistence.update(user);
4131
4132 Contact contact = user.getContact();
4133
4134 contact.setEmailAddress(user.getEmailAddress());
4135
4136 contactPersistence.update(contact);
4137
4138 return user;
4139 }
4140
4141
4155 @Override
4156 public User updateEmailAddress(
4157 long userId, String password, String emailAddress1,
4158 String emailAddress2, ServiceContext serviceContext)
4159 throws PortalException, SystemException {
4160
4161 emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
4162 emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
4163
4164 User user = userPersistence.findByPrimaryKey(userId);
4165
4166 validateEmailAddress(user, emailAddress1, emailAddress2);
4167
4168 Company company = companyPersistence.findByPrimaryKey(
4169 user.getCompanyId());
4170
4171 if (company.isStrangersVerify() &&
4172 !StringUtil.equalsIgnoreCase(
4173 emailAddress1, user.getEmailAddress())) {
4174
4175 sendEmailAddressVerification(user, emailAddress1, serviceContext);
4176 }
4177 else {
4178 setEmailAddress(
4179 user, password, user.getFirstName(), user.getMiddleName(),
4180 user.getLastName(), emailAddress1);
4181
4182 userPersistence.update(user);
4183
4184 Contact contact = user.getContact();
4185
4186 contact.setEmailAddress(user.getEmailAddress());
4187
4188 contactPersistence.update(contact);
4189 }
4190
4191 return user;
4192 }
4193
4194
4203 @Override
4204 public User updateEmailAddressVerified(
4205 long userId, boolean emailAddressVerified)
4206 throws PortalException, SystemException {
4207
4208 User user = userPersistence.findByPrimaryKey(userId);
4209
4210 user.setEmailAddressVerified(emailAddressVerified);
4211
4212 userPersistence.update(user);
4213
4214 return user;
4215 }
4216
4217
4226 @Override
4227 public User updateFacebookId(long userId, long facebookId)
4228 throws PortalException, SystemException {
4229
4230 User user = userPersistence.findByPrimaryKey(userId);
4231
4232 user.setFacebookId(facebookId);
4233
4234 userPersistence.update(user);
4235
4236 return user;
4237 }
4238
4239
4249 @Override
4250 public void updateGroups(
4251 long userId, long[] newGroupIds, ServiceContext serviceContext)
4252 throws PortalException, SystemException {
4253
4254 boolean indexingEnabled = true;
4255
4256 if (serviceContext != null) {
4257 indexingEnabled = serviceContext.isIndexingEnabled();
4258 }
4259
4260 updateGroups(userId, newGroupIds, serviceContext, indexingEnabled);
4261 }
4262
4263
4302 @Override
4303 public User updateIncompleteUser(
4304 long creatorUserId, long companyId, boolean autoPassword,
4305 String password1, String password2, boolean autoScreenName,
4306 String screenName, String emailAddress, long facebookId,
4307 String openId, Locale locale, String firstName, String middleName,
4308 String lastName, int prefixId, int suffixId, boolean male,
4309 int birthdayMonth, int birthdayDay, int birthdayYear,
4310 String jobTitle, boolean updateUserInformation, boolean sendEmail,
4311 ServiceContext serviceContext)
4312 throws PortalException, SystemException {
4313
4314 User user = getUserByEmailAddress(companyId, emailAddress);
4315
4316 if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
4317 throw new PortalException("Invalid user status");
4318 }
4319
4320 User defaultUser = getDefaultUser(companyId);
4321
4322 if (facebookId > 0) {
4323 autoPassword = false;
4324
4325 if ((password1 == null) || (password2 == null)) {
4326 password1 = PwdGenerator.getPassword();
4327 password2 = password1;
4328 }
4329
4330 sendEmail = false;
4331 }
4332
4333 if (updateUserInformation) {
4334 autoScreenName = false;
4335
4336 if (PrefsPropsUtil.getBoolean(
4337 companyId,
4338 PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
4339
4340 autoScreenName = true;
4341 }
4342
4343 validate(
4344 companyId, user.getUserId(), autoPassword, password1, password2,
4345 autoScreenName, screenName, emailAddress, openId, firstName,
4346 middleName, lastName, null);
4347
4348 if (!autoPassword) {
4349 if (Validator.isNull(password1) ||
4350 Validator.isNull(password2)) {
4351 throw new UserPasswordException(
4352 UserPasswordException.PASSWORD_INVALID);
4353 }
4354 }
4355
4356 if (autoScreenName) {
4357 ScreenNameGenerator screenNameGenerator =
4358 ScreenNameGeneratorFactory.getInstance();
4359
4360 try {
4361 screenName = screenNameGenerator.generate(
4362 companyId, user.getUserId(), emailAddress);
4363 }
4364 catch (Exception e) {
4365 throw new SystemException(e);
4366 }
4367 }
4368
4369 FullNameGenerator fullNameGenerator =
4370 FullNameGeneratorFactory.getInstance();
4371
4372 String fullName = fullNameGenerator.getFullName(
4373 firstName, middleName, lastName);
4374
4375 String greeting = LanguageUtil.format(
4376 locale, "welcome-x", " " + fullName, false);
4377
4378 if (Validator.isNotNull(password1)) {
4379 user.setPassword(PasswordEncryptorUtil.encrypt(password1));
4380 user.setPasswordUnencrypted(password1);
4381 }
4382
4383 user.setPasswordEncrypted(true);
4384
4385 PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
4386
4387 if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
4388 passwordPolicy.isChangeRequired()) {
4389
4390 user.setPasswordReset(true);
4391 }
4392 else {
4393 user.setPasswordReset(false);
4394 }
4395
4396 user.setScreenName(screenName);
4397 user.setFacebookId(facebookId);
4398 user.setOpenId(openId);
4399 user.setLanguageId(locale.toString());
4400 user.setTimeZoneId(defaultUser.getTimeZoneId());
4401 user.setGreeting(greeting);
4402 user.setFirstName(firstName);
4403 user.setMiddleName(middleName);
4404 user.setLastName(lastName);
4405 user.setJobTitle(jobTitle);
4406 user.setExpandoBridgeAttributes(serviceContext);
4407
4408 Date birthday = getBirthday(
4409 birthdayMonth, birthdayDay, birthdayYear);
4410
4411 Contact contact = user.getContact();
4412
4413 contact.setFirstName(firstName);
4414 contact.setMiddleName(middleName);
4415 contact.setLastName(lastName);
4416 contact.setPrefixId(prefixId);
4417 contact.setSuffixId(suffixId);
4418 contact.setMale(male);
4419 contact.setBirthday(birthday);
4420 contact.setJobTitle(jobTitle);
4421
4422 contactPersistence.update(contact, serviceContext);
4423
4424
4425
4426 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4427 User.class);
4428
4429 indexer.reindex(user);
4430 }
4431
4432 user.setStatus(WorkflowConstants.STATUS_DRAFT);
4433
4434 userPersistence.update(user, serviceContext);
4435
4436
4437
4438 long workflowUserId = creatorUserId;
4439
4440 if (workflowUserId == user.getUserId()) {
4441 workflowUserId = defaultUser.getUserId();
4442 }
4443
4444 ServiceContext workflowServiceContext = serviceContext;
4445
4446 if (workflowServiceContext == null) {
4447 workflowServiceContext = new ServiceContext();
4448 }
4449
4450 workflowServiceContext.setAttribute("autoPassword", autoPassword);
4451 workflowServiceContext.setAttribute("passwordUnencrypted", password1);
4452 workflowServiceContext.setAttribute("sendEmail", sendEmail);
4453
4454 WorkflowHandlerRegistryUtil.startWorkflowInstance(
4455 companyId, workflowUserId, User.class.getName(), user.getUserId(),
4456 user, workflowServiceContext);
4457
4458 return getUserByEmailAddress(companyId, emailAddress);
4459 }
4460
4461
4471 @Override
4472 public User updateJobTitle(long userId, String jobTitle)
4473 throws PortalException, SystemException {
4474
4475 User user = userPersistence.findByPrimaryKey(userId);
4476
4477 user.setJobTitle(jobTitle);
4478
4479 userPersistence.update(user);
4480
4481 Contact contact = contactPersistence.findByPrimaryKey(
4482 user.getContactId());
4483
4484 contact.setJobTitle(jobTitle);
4485
4486 contactPersistence.update(contact);
4487
4488 return user;
4489 }
4490
4491
4500 @Override
4501 public User updateLastLogin(long userId, String loginIP)
4502 throws PortalException, SystemException {
4503
4504 User user = userPersistence.findByPrimaryKey(userId);
4505
4506 Date lastLoginDate = user.getLoginDate();
4507
4508 if (lastLoginDate == null) {
4509 lastLoginDate = new Date();
4510 }
4511
4512 user.setLoginDate(new Date());
4513 user.setLoginIP(loginIP);
4514 user.setLastLoginDate(lastLoginDate);
4515 user.setLastLoginIP(user.getLoginIP());
4516
4517 resetFailedLoginAttempts(user, true);
4518
4519 return user;
4520 }
4521
4522
4531 @Override
4532 public User updateLockout(User user, boolean lockout)
4533 throws PortalException, SystemException {
4534
4535 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
4536
4537 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
4538 return user;
4539 }
4540
4541 Date lockoutDate = null;
4542
4543 if (lockout) {
4544 lockoutDate = new Date();
4545 }
4546
4547 user.setLockout(lockout);
4548 user.setLockoutDate(lockoutDate);
4549
4550 if (!lockout) {
4551 user.setLastFailedLoginDate(lockoutDate);
4552 user.setFailedLoginAttempts(0);
4553 }
4554
4555 userPersistence.update(user);
4556
4557 return user;
4558 }
4559
4560
4571 @Override
4572 public User updateLockoutByEmailAddress(
4573 long companyId, String emailAddress, boolean lockout)
4574 throws PortalException, SystemException {
4575
4576 User user = getUserByEmailAddress(companyId, emailAddress);
4577
4578 return updateLockout(user, lockout);
4579 }
4580
4581
4590 @Override
4591 public User updateLockoutById(long userId, boolean lockout)
4592 throws PortalException, SystemException {
4593
4594 User user = userPersistence.findByPrimaryKey(userId);
4595
4596 return updateLockout(user, lockout);
4597 }
4598
4599
4609 @Override
4610 public User updateLockoutByScreenName(
4611 long companyId, String screenName, boolean lockout)
4612 throws PortalException, SystemException {
4613
4614 User user = getUserByScreenName(companyId, screenName);
4615
4616 return updateLockout(user, lockout);
4617 }
4618
4619
4628 @Override
4629 public User updateModifiedDate(long userId, Date modifiedDate)
4630 throws PortalException, SystemException {
4631
4632 User user = userPersistence.findByPrimaryKey(userId);
4633
4634 user.setModifiedDate(modifiedDate);
4635
4636 userPersistence.update(user);
4637
4638 return user;
4639 }
4640
4641
4650 @Override
4651 public User updateOpenId(long userId, String openId)
4652 throws PortalException, SystemException {
4653
4654 openId = openId.trim();
4655
4656 User user = userPersistence.findByPrimaryKey(userId);
4657
4658 user.setOpenId(openId);
4659
4660 userPersistence.update(user);
4661
4662 return user;
4663 }
4664
4665
4676 @Override
4677 public void updateOrganizations(
4678 long userId, long[] newOrganizationIds,
4679 ServiceContext serviceContext)
4680 throws PortalException, SystemException {
4681
4682 updateOrganizations(
4683 userId, newOrganizationIds, serviceContext.isIndexingEnabled());
4684 }
4685
4686
4698 @Override
4699 public User updatePassword(
4700 long userId, String password1, String password2,
4701 boolean passwordReset)
4702 throws PortalException, SystemException {
4703
4704 return updatePassword(
4705 userId, password1, password2, passwordReset, false);
4706 }
4707
4708
4723 @Override
4724 public User updatePassword(
4725 long userId, String password1, String password2,
4726 boolean passwordReset, boolean silentUpdate)
4727 throws PortalException, SystemException {
4728
4729 User user = userPersistence.findByPrimaryKey(userId);
4730
4731 if (!silentUpdate) {
4732 validatePassword(user.getCompanyId(), userId, password1, password2);
4733 }
4734
4735 String oldEncPwd = user.getPassword();
4736
4737 if (!user.isPasswordEncrypted()) {
4738 oldEncPwd = PasswordEncryptorUtil.encrypt(user.getPassword());
4739 }
4740
4741 String newEncPwd = PasswordEncryptorUtil.encrypt(password1);
4742
4743 if (user.hasCompanyMx()) {
4744 mailService.updatePassword(user.getCompanyId(), userId, password1);
4745 }
4746
4747 user.setPassword(newEncPwd);
4748 user.setPasswordUnencrypted(password1);
4749 user.setPasswordEncrypted(true);
4750 user.setPasswordReset(passwordReset);
4751
4752 if (!silentUpdate || (user.getPasswordModifiedDate() == null)) {
4753 user.setPasswordModifiedDate(new Date());
4754 }
4755
4756 user.setDigest(StringPool.BLANK);
4757 user.setGraceLoginCount(0);
4758
4759 if (!silentUpdate) {
4760 user.setPasswordModified(true);
4761 }
4762
4763 try {
4764 userPersistence.update(user);
4765 }
4766 catch (ModelListenerException mle) {
4767 String msg = GetterUtil.getString(mle.getCause().getMessage());
4768
4769 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
4770 String passwordHistory = PrefsPropsUtil.getString(
4771 user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
4772
4773 if (msg.contains(passwordHistory)) {
4774 throw new UserPasswordException(
4775 UserPasswordException.PASSWORD_ALREADY_USED);
4776 }
4777 }
4778
4779 throw new UserPasswordException(
4780 UserPasswordException.PASSWORD_INVALID);
4781 }
4782
4783 if (!silentUpdate) {
4784 user.setPasswordModified(false);
4785
4786 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
4787 }
4788
4789 return user;
4790 }
4791
4792
4806 @Override
4807 public User updatePasswordManually(
4808 long userId, String password, boolean passwordEncrypted,
4809 boolean passwordReset, Date passwordModifiedDate)
4810 throws PortalException, SystemException {
4811
4812
4813
4814 User user = userPersistence.findByPrimaryKey(userId);
4815
4816 user.setPassword(password);
4817 user.setPasswordEncrypted(passwordEncrypted);
4818 user.setPasswordReset(passwordReset);
4819 user.setPasswordModifiedDate(passwordModifiedDate);
4820 user.setDigest(StringPool.BLANK);
4821
4822 userPersistence.update(user);
4823
4824 return user;
4825 }
4826
4827
4838 @Override
4839 public User updatePasswordReset(long userId, boolean passwordReset)
4840 throws PortalException, SystemException {
4841
4842 User user = userPersistence.findByPrimaryKey(userId);
4843
4844 user.setPasswordReset(passwordReset);
4845
4846 userPersistence.update(user);
4847
4848 return user;
4849 }
4850
4851
4861 @Override
4862 public User updatePortrait(long userId, byte[] bytes)
4863 throws PortalException, SystemException {
4864
4865 User user = userPersistence.findByPrimaryKey(userId);
4866
4867 long imageMaxSize = PrefsPropsUtil.getLong(
4868 PropsKeys.USERS_IMAGE_MAX_SIZE);
4869
4870 if ((imageMaxSize > 0) &&
4871 ((bytes == null) || (bytes.length > imageMaxSize))) {
4872
4873 throw new UserPortraitSizeException();
4874 }
4875
4876 long portraitId = user.getPortraitId();
4877
4878 if (portraitId <= 0) {
4879 portraitId = counterLocalService.increment();
4880
4881 user.setPortraitId(portraitId);
4882 }
4883
4884 try {
4885 ImageBag imageBag = ImageToolUtil.read(bytes);
4886
4887 RenderedImage renderedImage = imageBag.getRenderedImage();
4888
4889 if (renderedImage == null) {
4890 throw new UserPortraitTypeException();
4891 }
4892
4893 renderedImage = ImageToolUtil.scale(
4894 renderedImage, PropsValues.USERS_IMAGE_MAX_HEIGHT,
4895 PropsValues.USERS_IMAGE_MAX_WIDTH);
4896
4897 String contentType = imageBag.getType();
4898
4899 imageLocalService.updateImage(
4900 portraitId,
4901 ImageToolUtil.getBytes(renderedImage, contentType));
4902 }
4903 catch (IOException ioe) {
4904 throw new ImageSizeException(ioe);
4905 }
4906
4907 userPersistence.update(user);
4908
4909 return user;
4910 }
4911
4912
4923 @Override
4924 public User updateReminderQuery(long userId, String question, String answer)
4925 throws PortalException, SystemException {
4926
4927 validateReminderQuery(question, answer);
4928
4929 User user = userPersistence.findByPrimaryKey(userId);
4930
4931 user.setReminderQueryQuestion(question);
4932 user.setReminderQueryAnswer(answer);
4933
4934 userPersistence.update(user);
4935
4936 return user;
4937 }
4938
4939
4949 @Override
4950 public User updateScreenName(long userId, String screenName)
4951 throws PortalException, SystemException {
4952
4953
4954
4955 User user = userPersistence.findByPrimaryKey(userId);
4956
4957 screenName = getLogin(screenName);
4958
4959 validateScreenName(user.getCompanyId(), userId, screenName);
4960
4961 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
4962 user.setDigest(StringPool.BLANK);
4963 }
4964
4965 user.setScreenName(screenName);
4966
4967 userPersistence.update(user);
4968
4969
4970
4971 Group group = groupLocalService.getUserGroup(
4972 user.getCompanyId(), userId);
4973
4974 group.setFriendlyURL(StringPool.SLASH + screenName);
4975
4976 groupPersistence.update(group);
4977
4978 return user;
4979 }
4980
4981
4993 @Deprecated
4994 @Override
4995 public User updateStatus(long userId, int status)
4996 throws PortalException, SystemException {
4997
4998 return updateStatus(userId, status, new ServiceContext());
4999 }
5000
5001
5013 @Override
5014 public User updateStatus(
5015 long userId, int status, ServiceContext serviceContext)
5016 throws PortalException, SystemException {
5017
5018 User user = userPersistence.findByPrimaryKey(userId);
5019
5020 if ((status == WorkflowConstants.STATUS_APPROVED) &&
5021 (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {
5022
5023 validateCompanyMaxUsers(user.getCompanyId());
5024 }
5025
5026 String passwordUnencrypted = (String)serviceContext.getAttribute(
5027 "passwordUnencrypted");
5028
5029 if (Validator.isNotNull(passwordUnencrypted)) {
5030 user.setPasswordUnencrypted(passwordUnencrypted);
5031 }
5032
5033 user.setStatus(status);
5034
5035 userPersistence.update(user);
5036
5037 reindex(user);
5038
5039 return user;
5040 }
5041
5042
5098 @Override
5099 @SuppressWarnings("deprecation")
5100 public User updateUser(
5101 long userId, String oldPassword, String newPassword1,
5102 String newPassword2, boolean passwordReset,
5103 String reminderQueryQuestion, String reminderQueryAnswer,
5104 String screenName, String emailAddress, long facebookId,
5105 String openId, String languageId, String timeZoneId,
5106 String greeting, String comments, String firstName,
5107 String middleName, String lastName, int prefixId, int suffixId,
5108 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
5109 String smsSn, String aimSn, String facebookSn, String icqSn,
5110 String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
5111 String twitterSn, String ymSn, String jobTitle, long[] groupIds,
5112 long[] organizationIds, long[] roleIds,
5113 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
5114 ServiceContext serviceContext)
5115 throws PortalException, SystemException {
5116
5117
5118
5119 User user = userPersistence.findByPrimaryKey(userId);
5120 Company company = companyPersistence.findByPrimaryKey(
5121 user.getCompanyId());
5122 String password = oldPassword;
5123 screenName = getLogin(screenName);
5124 emailAddress = StringUtil.toLowerCase(emailAddress.trim());
5125 openId = openId.trim();
5126 String oldFullName = user.getFullName();
5127 aimSn = StringUtil.toLowerCase(aimSn.trim());
5128 facebookSn = StringUtil.toLowerCase(facebookSn.trim());
5129 icqSn = StringUtil.toLowerCase(icqSn.trim());
5130 jabberSn = StringUtil.toLowerCase(jabberSn.trim());
5131 msnSn = StringUtil.toLowerCase(msnSn.trim());
5132 mySpaceSn = StringUtil.toLowerCase(mySpaceSn.trim());
5133 skypeSn = StringUtil.toLowerCase(skypeSn.trim());
5134 twitterSn = StringUtil.toLowerCase(twitterSn.trim());
5135 ymSn = StringUtil.toLowerCase(ymSn.trim());
5136 Date now = new Date();
5137
5138 EmailAddressGenerator emailAddressGenerator =
5139 EmailAddressGeneratorFactory.getInstance();
5140
5141 if (emailAddressGenerator.isGenerated(emailAddress)) {
5142 emailAddress = StringPool.BLANK;
5143 }
5144
5145 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
5146 Validator.isNull(emailAddress)) {
5147
5148 emailAddress = emailAddressGenerator.generate(
5149 user.getCompanyId(), userId);
5150 }
5151
5152 validate(
5153 userId, screenName, emailAddress, openId, firstName, middleName,
5154 lastName, smsSn);
5155
5156 if (Validator.isNotNull(newPassword1) ||
5157 Validator.isNotNull(newPassword2)) {
5158
5159 user = updatePassword(
5160 userId, newPassword1, newPassword2, passwordReset);
5161
5162 password = newPassword1;
5163
5164 user.setDigest(StringPool.BLANK);
5165 }
5166
5167 user.setModifiedDate(now);
5168
5169 if (user.getContactId() <= 0) {
5170 user.setContactId(counterLocalService.increment());
5171 }
5172
5173 user.setPasswordReset(passwordReset);
5174
5175 if (Validator.isNotNull(reminderQueryQuestion) &&
5176 Validator.isNotNull(reminderQueryAnswer)) {
5177
5178 user.setReminderQueryQuestion(reminderQueryQuestion);
5179 user.setReminderQueryAnswer(reminderQueryAnswer);
5180 }
5181
5182 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
5183 user.setScreenName(screenName);
5184
5185 user.setDigest(StringPool.BLANK);
5186 }
5187
5188 boolean sendEmailAddressVerification = false;
5189
5190 if (company.isStrangersVerify() &&
5191 !StringUtil.equalsIgnoreCase(
5192 emailAddress, user.getEmailAddress())) {
5193
5194 sendEmailAddressVerification = true;
5195 }
5196 else {
5197 setEmailAddress(
5198 user, password, firstName, middleName, lastName, emailAddress);
5199 }
5200
5201 if (serviceContext != null) {
5202 String uuid = serviceContext.getUuid();
5203
5204 if (Validator.isNotNull(uuid)) {
5205 user.setUuid(uuid);
5206 }
5207 }
5208
5209 user.setFacebookId(facebookId);
5210
5211 Long ldapServerId = null;
5212
5213 if (serviceContext != null) {
5214 ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
5215 }
5216
5217 if (ldapServerId != null) {
5218 user.setLdapServerId(ldapServerId);
5219 }
5220
5221 user.setOpenId(openId);
5222 user.setLanguageId(languageId);
5223 user.setTimeZoneId(timeZoneId);
5224 user.setGreeting(greeting);
5225 user.setComments(comments);
5226 user.setFirstName(firstName);
5227 user.setMiddleName(middleName);
5228 user.setLastName(lastName);
5229 user.setJobTitle(jobTitle);
5230 user.setExpandoBridgeAttributes(serviceContext);
5231
5232 userPersistence.update(user, serviceContext);
5233
5234
5235
5236 Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
5237
5238 long contactId = user.getContactId();
5239
5240 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
5241
5242 if (contact == null) {
5243 contact = contactPersistence.create(contactId);
5244
5245 contact.setCompanyId(user.getCompanyId());
5246 contact.setUserName(StringPool.BLANK);
5247 contact.setCreateDate(now);
5248 contact.setClassName(User.class.getName());
5249 contact.setClassPK(user.getUserId());
5250 contact.setAccountId(company.getAccountId());
5251 contact.setParentContactId(
5252 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
5253 }
5254
5255 contact.setModifiedDate(now);
5256 contact.setEmailAddress(user.getEmailAddress());
5257 contact.setFirstName(firstName);
5258 contact.setMiddleName(middleName);
5259 contact.setLastName(lastName);
5260 contact.setPrefixId(prefixId);
5261 contact.setSuffixId(suffixId);
5262 contact.setMale(male);
5263 contact.setBirthday(birthday);
5264 contact.setSmsSn(smsSn);
5265 contact.setAimSn(aimSn);
5266 contact.setFacebookSn(facebookSn);
5267 contact.setIcqSn(icqSn);
5268 contact.setJabberSn(jabberSn);
5269 contact.setMsnSn(msnSn);
5270 contact.setMySpaceSn(mySpaceSn);
5271 contact.setSkypeSn(skypeSn);
5272 contact.setTwitterSn(twitterSn);
5273 contact.setYmSn(ymSn);
5274 contact.setJobTitle(jobTitle);
5275
5276 contactPersistence.update(contact, serviceContext);
5277
5278
5279
5280 Group group = groupLocalService.getUserGroup(
5281 user.getCompanyId(), userId);
5282
5283 group.setFriendlyURL(StringPool.SLASH + screenName);
5284
5285 groupPersistence.update(group);
5286
5287
5288
5289
5290
5291
5292
5293 List<UserGroupRole> previousUserGroupRoles =
5294 userGroupRolePersistence.findByUserId(userId);
5295
5296 updateGroups(userId, groupIds, serviceContext, false);
5297 updateOrganizations(userId, organizationIds, false);
5298
5299
5300
5301 if (roleIds != null) {
5302 roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
5303
5304 userPersistence.setRoles(userId, roleIds);
5305 }
5306
5307
5308
5309 updateUserGroupRoles(
5310 user, groupIds, organizationIds, userGroupRoles,
5311 previousUserGroupRoles);
5312
5313
5314
5315 if (userGroupIds != null) {
5316 if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
5317 userGroupLocalService.copyUserGroupLayouts(
5318 userGroupIds, userId);
5319 }
5320
5321 userPersistence.setUserGroups(userId, userGroupIds);
5322 }
5323
5324 if (!hasManageLayoutsRolePermission(user) &&
5325 !hasManageLayoutsOrgPermission(organizationIds, user) &&
5326 !hasManageLayoutsSitePermission(groupIds, user)) {
5327
5328 unsetToggleControlsPreference(userId);
5329 }
5330
5331
5332
5333 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
5334
5335
5336
5337 if (serviceContext != null) {
5338 updateAsset(
5339 userId, user, serviceContext.getAssetCategoryIds(),
5340 serviceContext.getAssetTagNames());
5341 }
5342
5343
5344
5345 if (GetterUtil.getBoolean(
5346 PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
5347 !oldFullName.equals(user.getFullName())) {
5348
5349 mbMessageLocalService.updateUserName(userId, user.getFullName());
5350 }
5351
5352
5353
5354 if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
5355 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5356 User.class);
5357
5358 indexer.reindex(user);
5359 }
5360
5361
5362
5363 if ((serviceContext != null) && sendEmailAddressVerification) {
5364 sendEmailAddressVerification(user, emailAddress, serviceContext);
5365 }
5366
5367
5368
5369 PermissionCacheUtil.clearCache(userId);
5370
5371 return user;
5372 }
5373
5374
5383 @Override
5384 public void verifyEmailAddress(String ticketKey)
5385 throws PortalException, SystemException {
5386
5387 Ticket ticket = ticketLocalService.getTicket(ticketKey);
5388
5389 if (ticket.isExpired() ||
5390 (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
5391
5392 throw new NoSuchTicketException("{ticketKey=" + ticketKey + "}");
5393 }
5394
5395 User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
5396
5397 String emailAddress = ticket.getExtraInfo();
5398
5399 emailAddress = StringUtil.toLowerCase(emailAddress).trim();
5400
5401 if (!emailAddress.equals(user.getEmailAddress())) {
5402 if (userPersistence.fetchByC_EA(
5403 user.getCompanyId(), emailAddress) != null) {
5404
5405 throw new DuplicateUserEmailAddressException(
5406 "{userId=" + user.getUserId() + "}");
5407 }
5408
5409 setEmailAddress(
5410 user, StringPool.BLANK, user.getFirstName(),
5411 user.getMiddleName(), user.getLastName(), emailAddress);
5412
5413 Contact contact = user.getContact();
5414
5415 contact.setEmailAddress(user.getEmailAddress());
5416
5417 contactPersistence.update(contact);
5418 }
5419
5420 user.setEmailAddressVerified(true);
5421
5422 userPersistence.update(user);
5423
5424 ticketLocalService.deleteTicket(ticket);
5425 }
5426
5427 protected void addDefaultRolesAndTeams(long groupId, long[] userIds)
5428 throws PortalException, SystemException {
5429
5430 List<Role> defaultSiteRoles = new ArrayList<Role>();
5431
5432 Group group = groupLocalService.getGroup(groupId);
5433
5434 UnicodeProperties typeSettingsProperties =
5435 group.getTypeSettingsProperties();
5436
5437 long[] defaultSiteRoleIds = StringUtil.split(
5438 typeSettingsProperties.getProperty("defaultSiteRoleIds"), 0L);
5439
5440 for (long defaultSiteRoleId : defaultSiteRoleIds) {
5441 Role defaultSiteRole = rolePersistence.fetchByPrimaryKey(
5442 defaultSiteRoleId);
5443
5444 if (defaultSiteRole == null) {
5445 if (_log.isWarnEnabled()) {
5446 _log.warn("Unable to find role " + defaultSiteRoleId);
5447 }
5448
5449 continue;
5450 }
5451
5452 defaultSiteRoles.add(defaultSiteRole);
5453 }
5454
5455 List<Team> defaultTeams = new ArrayList<Team>();
5456
5457 long[] defaultTeamIds = StringUtil.split(
5458 typeSettingsProperties.getProperty("defaultTeamIds"), 0L);
5459
5460 for (long defaultTeamId : defaultTeamIds) {
5461 Team defaultTeam = teamPersistence.findByPrimaryKey(defaultTeamId);
5462
5463 if (defaultTeam == null) {
5464 if (_log.isWarnEnabled()) {
5465 _log.warn("Unable to find team " + defaultTeamId);
5466 }
5467
5468 continue;
5469 }
5470
5471 defaultTeams.add(defaultTeam);
5472 }
5473
5474 for (long userId : userIds) {
5475 Set<Long> userRoleIdsSet = new HashSet<Long>();
5476
5477 for (Role role : defaultSiteRoles) {
5478 if (!userPersistence.containsRole(userId, role.getRoleId())) {
5479 userRoleIdsSet.add(role.getRoleId());
5480 }
5481 }
5482
5483 long[] userRoleIds = ArrayUtil.toArray(
5484 userRoleIdsSet.toArray(new Long[userRoleIdsSet.size()]));
5485
5486 userGroupRoleLocalService.addUserGroupRoles(
5487 userId, groupId, userRoleIds);
5488
5489 Set<Long> userTeamIdsSet = new HashSet<Long>();
5490
5491 for (Team team : defaultTeams) {
5492 if (!userPersistence.containsTeam(userId, team.getTeamId())) {
5493 userTeamIdsSet.add(team.getTeamId());
5494 }
5495 }
5496
5497 long[] userTeamIds = ArrayUtil.toArray(
5498 userTeamIdsSet.toArray(new Long[userTeamIdsSet.size()]));
5499
5500 userPersistence.addTeams(userId, userTeamIds);
5501 }
5502 }
5503
5504
5550 protected int authenticate(
5551 long companyId, String login, String password, String authType,
5552 Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
5553 Map<String, Object> resultsMap)
5554 throws PortalException, SystemException {
5555
5556 if (PropsValues.AUTH_LOGIN_DISABLED) {
5557 return Authenticator.FAILURE;
5558 }
5559
5560 login = StringUtil.toLowerCase(login.trim());
5561
5562 long userId = GetterUtil.getLong(login);
5563
5564
5565
5566 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5567 if (Validator.isNull(login)) {
5568 throw new UserEmailAddressException();
5569 }
5570 }
5571 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5572 if (Validator.isNull(login)) {
5573 throw new UserScreenNameException();
5574 }
5575 }
5576 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5577 if (Validator.isNull(login)) {
5578 throw new UserIdException();
5579 }
5580 }
5581
5582 if (Validator.isNull(password)) {
5583 throw new UserPasswordException(
5584 UserPasswordException.PASSWORD_INVALID);
5585 }
5586
5587 int authResult = Authenticator.FAILURE;
5588
5589
5590
5591 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5592 authResult = AuthPipeline.authenticateByEmailAddress(
5593 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5594 headerMap, parameterMap);
5595 }
5596 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5597 authResult = AuthPipeline.authenticateByScreenName(
5598 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5599 headerMap, parameterMap);
5600 }
5601 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5602 authResult = AuthPipeline.authenticateByUserId(
5603 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
5604 headerMap, parameterMap);
5605 }
5606
5607
5608
5609 User user = null;
5610
5611 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5612 user = fetchUserByEmailAddress(companyId, login);
5613 }
5614 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5615 user = fetchUserByScreenName(companyId, login);
5616 }
5617 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5618 user = userPersistence.fetchByPrimaryKey(GetterUtil.getLong(login));
5619 }
5620
5621 if (user == null) {
5622 return Authenticator.DNE;
5623 }
5624
5625 if (!isUserAllowedToAuthenticate(user)) {
5626 return Authenticator.FAILURE;
5627 }
5628
5629 if (!user.isPasswordEncrypted()) {
5630 user.setPassword(PasswordEncryptorUtil.encrypt(user.getPassword()));
5631 user.setPasswordEncrypted(true);
5632
5633 userPersistence.update(user);
5634 }
5635
5636
5637
5638 boolean skipLiferayCheck = false;
5639
5640 if (authResult == Authenticator.SKIP_LIFERAY_CHECK) {
5641 authResult = Authenticator.SUCCESS;
5642
5643 skipLiferayCheck = true;
5644 }
5645 else if ((authResult == Authenticator.SUCCESS) &&
5646 PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5647
5648 boolean authenticated = PwdAuthenticator.authenticate(
5649 login, password, user.getPassword());
5650
5651 if (authenticated) {
5652 authResult = Authenticator.SUCCESS;
5653 }
5654 else {
5655 authResult = Authenticator.FAILURE;
5656 }
5657 }
5658
5659
5660
5661 if (authResult == Authenticator.SUCCESS) {
5662 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5663 authResult = AuthPipeline.authenticateByEmailAddress(
5664 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5665 headerMap, parameterMap);
5666 }
5667 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5668 authResult = AuthPipeline.authenticateByScreenName(
5669 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5670 headerMap, parameterMap);
5671 }
5672 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5673 authResult = AuthPipeline.authenticateByUserId(
5674 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5675 headerMap, parameterMap);
5676 }
5677 }
5678
5679 if (resultsMap != null) {
5680 resultsMap.put("userId", user.getUserId());
5681 }
5682
5683 if (authResult == Authenticator.SUCCESS) {
5684
5685
5686
5687 if (skipLiferayCheck ||
5688 !PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK ||
5689 Validator.isNull(user.getDigest())) {
5690
5691 String digest = user.getDigest(password);
5692
5693 user.setDigest(digest);
5694
5695 userPersistence.update(user);
5696 }
5697 }
5698
5699
5700
5701 if (authResult == Authenticator.FAILURE) {
5702 authResult = handleAuthenticationFailure(
5703 login, authType, user, headerMap, parameterMap);
5704 }
5705 else {
5706 resetFailedLoginAttempts(user);
5707 }
5708
5709
5710
5711 return authResult;
5712 }
5713
5714 protected SearchContext buildSearchContext(
5715 long companyId, String firstName, String middleName, String lastName,
5716 String fullName, String screenName, String emailAddress, String street,
5717 String city, String zip, String region, String country, int status,
5718 LinkedHashMap<String, Object> params, boolean andSearch, int start,
5719 int end, Sort sort) {
5720
5721 SearchContext searchContext = new SearchContext();
5722
5723 searchContext.setAndSearch(andSearch);
5724
5725 Map<String, Serializable> attributes =
5726 new HashMap<String, Serializable>();
5727
5728 attributes.put("city", city);
5729 attributes.put("country", country);
5730 attributes.put("emailAddress", emailAddress);
5731 attributes.put("firstName", firstName);
5732 attributes.put("fullName", fullName);
5733 attributes.put("lastName", lastName);
5734 attributes.put("middleName", middleName);
5735 attributes.put("params", params);
5736 attributes.put("region", region);
5737 attributes.put("screenName", screenName);
5738 attributes.put("street", street);
5739 attributes.put("status", status);
5740 attributes.put("zip", zip);
5741
5742 searchContext.setAttributes(attributes);
5743
5744 searchContext.setCompanyId(companyId);
5745 searchContext.setEnd(end);
5746
5747 if (params != null) {
5748 String keywords = (String)params.remove("keywords");
5749
5750 if (Validator.isNotNull(keywords)) {
5751 searchContext.setKeywords(keywords);
5752 }
5753 }
5754
5755 QueryConfig queryConfig = new QueryConfig();
5756
5757 queryConfig.setHighlightEnabled(false);
5758 queryConfig.setScoreEnabled(false);
5759
5760 searchContext.setQueryConfig(queryConfig);
5761
5762 if (sort != null) {
5763 searchContext.setSorts(sort);
5764 }
5765
5766 searchContext.setStart(start);
5767
5768 return searchContext;
5769 }
5770
5771 protected Date getBirthday(
5772 int birthdayMonth, int birthdayDay, int birthdayYear)
5773 throws PortalException {
5774
5775 Date birthday = PortalUtil.getDate(
5776 birthdayMonth, birthdayDay, birthdayYear,
5777 ContactBirthdayException.class);
5778
5779 Date now = new Date();
5780
5781 if (birthday.after(now)) {
5782 throw new ContactBirthdayException();
5783 }
5784
5785 return birthday;
5786 }
5787
5788 protected String getLogin(String login) {
5789 return StringUtil.lowerCase(StringUtil.trim(login));
5790 }
5791
5792 protected long[] getUserIds(List<User> users) {
5793 long[] userIds = new long[users.size()];
5794
5795 for (int i = 0; i < users.size(); i++) {
5796 User user = users.get(i);
5797
5798 userIds[i] = user.getUserId();
5799 }
5800
5801 return userIds;
5802 }
5803
5804 protected int handleAuthenticationFailure(
5805 String login, String authType, User user,
5806 Map<String, String[]> headerMap, Map<String, String[]> parameterMap) {
5807
5808 if (user == null) {
5809 return Authenticator.DNE;
5810 }
5811
5812 try {
5813 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5814 AuthPipeline.onFailureByEmailAddress(
5815 PropsKeys.AUTH_FAILURE, user.getCompanyId(), login,
5816 headerMap, parameterMap);
5817 }
5818 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5819 AuthPipeline.onFailureByScreenName(
5820 PropsKeys.AUTH_FAILURE, user.getCompanyId(), login,
5821 headerMap, parameterMap);
5822 }
5823 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5824 AuthPipeline.onFailureByUserId(
5825 PropsKeys.AUTH_FAILURE, user.getCompanyId(),
5826 user.getUserId(), headerMap, parameterMap);
5827 }
5828
5829 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5830
5831 if (user == null) {
5832 return Authenticator.DNE;
5833 }
5834
5835
5836
5837 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5838 user.getCompanyId())) {
5839
5840 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5841
5842 user = userPersistence.fetchByPrimaryKey(user.getUserId());
5843
5844 int failedLoginAttempts = user.getFailedLoginAttempts();
5845 int maxFailures = passwordPolicy.getMaxFailure();
5846
5847 if ((failedLoginAttempts >= maxFailures) &&
5848 (maxFailures != 0)) {
5849
5850 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5851 AuthPipeline.onMaxFailuresByEmailAddress(
5852 PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
5853 login, headerMap, parameterMap);
5854 }
5855 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5856 AuthPipeline.onMaxFailuresByScreenName(
5857 PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
5858 login, headerMap, parameterMap);
5859 }
5860 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5861 AuthPipeline.onMaxFailuresByUserId(
5862 PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
5863 user.getUserId(), headerMap, parameterMap);
5864 }
5865 }
5866 }
5867 }
5868 catch (Exception e) {
5869 _log.error(e, e);
5870 }
5871
5872 return Authenticator.FAILURE;
5873 }
5874
5875 protected boolean hasManageLayoutsPermission(
5876 long groupId, PermissionChecker permissionChecker)
5877 throws PortalException, SystemException {
5878
5879 return GroupPermissionUtil.contains(
5880 permissionChecker, groupId, ActionKeys.MANAGE_LAYOUTS);
5881 }
5882
5883 protected boolean hasManageLayoutsOrgPermission(
5884 long[] organizationIds, User user)
5885 throws PortalException, SystemException {
5886
5887 if (ArrayUtil.isEmpty(organizationIds)) {
5888 return false;
5889 }
5890
5891 try {
5892 PermissionChecker permissionChecker =
5893 PermissionCheckerFactoryUtil.create(user);
5894
5895 long organizationClassId =
5896 ClassNameLocalServiceUtil.fetchClassNameId(
5897 Organization.class.getName());
5898
5899 for (long organizationId : organizationIds) {
5900 Group group = groupPersistence.fetchByC_C_C(
5901 user.getCompanyId(), organizationClassId, organizationId);
5902
5903 if (hasManageLayoutsPermission(
5904 group.getGroupId(), permissionChecker)) {
5905
5906 return true;
5907 }
5908 }
5909 }
5910 catch (Exception e) {
5911 }
5912
5913 return false;
5914 }
5915
5916 protected boolean hasManageLayoutsRolePermission(User user)
5917 throws PortalException, SystemException {
5918
5919 try {
5920 PermissionChecker permissionChecker =
5921 PermissionCheckerFactoryUtil.create(user);
5922
5923 return GroupPermissionUtil.contains(
5924 permissionChecker, ActionKeys.MANAGE_LAYOUTS);
5925 }
5926 catch (Exception e) {
5927 }
5928
5929 return false;
5930 }
5931
5932 protected boolean hasManageLayoutsSitePermission(long[] groupIds, User user)
5933 throws PortalException, SystemException {
5934
5935 if (ArrayUtil.isEmpty(groupIds)) {
5936 return false;
5937 }
5938
5939 try {
5940 PermissionChecker permissionChecker =
5941 PermissionCheckerFactoryUtil.create(user);
5942
5943 for (long groupId : groupIds) {
5944 if (hasManageLayoutsPermission(groupId, permissionChecker)) {
5945 return true;
5946 }
5947 }
5948 }
5949 catch (Exception e) {
5950 }
5951
5952 return false;
5953 }
5954
5955 protected boolean isUserAllowedToAuthenticate(User user)
5956 throws PortalException, SystemException {
5957
5958 if (user.isDefaultUser()) {
5959 if (_log.isInfoEnabled()) {
5960 _log.info("Authentication is disabled for the default user");
5961 }
5962
5963 return false;
5964 }
5965 else if (!user.isActive()) {
5966 if (_log.isInfoEnabled()) {
5967 _log.info(
5968 "Authentication is disabled for inactive user " +
5969 user.getUserId());
5970 }
5971
5972 return false;
5973 }
5974
5975
5976
5977
5978 checkLockout(user);
5979
5980 checkPasswordExpired(user);
5981
5982 return true;
5983 }
5984
5985 protected boolean isUseCustomSQL(LinkedHashMap<String, Object> params) {
5986 if ((params == null) || params.isEmpty()) {
5987 return false;
5988 }
5989
5990 for (String key : params.keySet()) {
5991 if (!key.equals("inherit") &&
5992 !key.equals("usersGroups") &&
5993 !key.equals("usersOrgs") &&
5994 !key.equals("usersOrgsCount") &&
5995 !key.equals("usersRoles") &&
5996 !key.equals("usersTeams") &&
5997 !key.equals("usersUserGroups")) {
5998
5999 return true;
6000 }
6001 }
6002
6003 Boolean inherit = (Boolean)params.get("inherit");
6004
6005 if ((inherit != null) && inherit) {
6006 return true;
6007 }
6008
6009 return false;
6010 }
6011
6012 protected void reindex(final User user) {
6013 final Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6014 User.class);
6015
6016 Callable<Void> callable = new ShardCallable<Void>(
6017 user.getCompanyId()) {
6018
6019 @Override
6020 protected Void doCall() throws Exception {
6021 indexer.reindex(user);
6022
6023 return null;
6024 }
6025
6026 };
6027
6028 TransactionCommitCallbackRegistryUtil.registerCallback(callable);
6029 }
6030
6031 protected void resetFailedLoginAttempts(User user) throws SystemException {
6032 resetFailedLoginAttempts(user, false);
6033 }
6034
6035 protected void resetFailedLoginAttempts(User user, boolean forceUpdate)
6036 throws SystemException {
6037
6038 if (forceUpdate || (user.getFailedLoginAttempts() > 0)) {
6039 user.setFailedLoginAttempts(0);
6040
6041 userPersistence.update(user);
6042 }
6043 }
6044
6045 protected Hits search(
6046 long companyId, String firstName, String middleName,
6047 String lastName, String fullName, String screenName,
6048 String emailAddress, String street, String city, String zip,
6049 String region, String country, int status,
6050 LinkedHashMap<String, Object> params, boolean andSearch, int start,
6051 int end, Sort sort)
6052 throws SystemException {
6053
6054 try {
6055 SearchContext searchContext = new SearchContext();
6056
6057 searchContext.setAndSearch(andSearch);
6058
6059 Map<String, Serializable> attributes =
6060 new HashMap<String, Serializable>();
6061
6062 attributes.put("city", city);
6063 attributes.put("country", country);
6064 attributes.put("emailAddress", emailAddress);
6065 attributes.put("firstName", firstName);
6066 attributes.put("fullName", fullName);
6067 attributes.put("lastName", lastName);
6068 attributes.put("middleName", middleName);
6069 attributes.put("params", params);
6070 attributes.put("region", region);
6071 attributes.put("screenName", screenName);
6072 attributes.put("street", street);
6073 attributes.put("status", status);
6074 attributes.put("zip", zip);
6075
6076 searchContext.setAttributes(attributes);
6077
6078 searchContext.setCompanyId(companyId);
6079 searchContext.setEnd(end);
6080
6081 if (params != null) {
6082 String keywords = (String)params.remove("keywords");
6083
6084 if (Validator.isNotNull(keywords)) {
6085 searchContext.setKeywords(keywords);
6086 }
6087 }
6088
6089 QueryConfig queryConfig = new QueryConfig();
6090
6091 queryConfig.setHighlightEnabled(false);
6092 queryConfig.setScoreEnabled(false);
6093
6094 searchContext.setQueryConfig(queryConfig);
6095
6096 if (sort != null) {
6097 searchContext.setSorts(sort);
6098 }
6099
6100 searchContext.setStart(start);
6101
6102 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6103 User.class);
6104
6105 return indexer.search(searchContext);
6106 }
6107 catch (Exception e) {
6108 throw new SystemException(e);
6109 }
6110 }
6111
6112 protected void sendEmail(
6113 User user, String password, ServiceContext serviceContext)
6114 throws SystemException {
6115
6116 if (!PrefsPropsUtil.getBoolean(
6117 user.getCompanyId(),
6118 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
6119
6120 return;
6121 }
6122
6123 String fromName = PrefsPropsUtil.getString(
6124 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
6125 String fromAddress = PrefsPropsUtil.getString(
6126 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
6127
6128 String toName = user.getFullName();
6129 String toAddress = user.getEmailAddress();
6130
6131 String subject = PrefsPropsUtil.getContent(
6132 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
6133
6134 String body = null;
6135
6136 if (Validator.isNotNull(password)) {
6137 body = PrefsPropsUtil.getContent(
6138 user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
6139 }
6140 else {
6141 body = PrefsPropsUtil.getContent(
6142 user.getCompanyId(),
6143 PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
6144 }
6145
6146 SubscriptionSender subscriptionSender = new SubscriptionSender();
6147
6148 subscriptionSender.setBody(body);
6149 subscriptionSender.setCompanyId(user.getCompanyId());
6150 subscriptionSender.setContextAttributes(
6151 "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
6152 "[$USER_SCREENNAME$]", user.getScreenName());
6153 subscriptionSender.setFrom(fromAddress, fromName);
6154 subscriptionSender.setHtmlFormat(true);
6155 subscriptionSender.setMailId("user", user.getUserId());
6156 subscriptionSender.setServiceContext(serviceContext);
6157 subscriptionSender.setSubject(subject);
6158 subscriptionSender.setUserId(user.getUserId());
6159
6160 subscriptionSender.addRuntimeSubscribers(toAddress, toName);
6161
6162 subscriptionSender.flushNotificationsAsync();
6163 }
6164
6165 protected void setEmailAddress(
6166 User user, String password, String firstName, String middleName,
6167 String lastName, String emailAddress)
6168 throws PortalException, SystemException {
6169
6170 if (StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
6171 return;
6172 }
6173
6174 long userId = user.getUserId();
6175
6176
6177
6178 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
6179 Validator.isNotNull(password)) {
6180
6181 mailService.addUser(
6182 user.getCompanyId(), userId, password, firstName, middleName,
6183 lastName, emailAddress);
6184 }
6185
6186
6187
6188 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
6189 mailService.updateEmailAddress(
6190 user.getCompanyId(), userId, emailAddress);
6191 }
6192
6193
6194
6195 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
6196 mailService.deleteEmailAddress(user.getCompanyId(), userId);
6197 }
6198
6199 user.setEmailAddress(emailAddress);
6200 user.setDigest(StringPool.BLANK);
6201 }
6202
6203 protected void unsetToggleControlsPreference(long userId)
6204 throws PortalException, SystemException {
6205
6206 PortletPreferencesFactoryImpl portletPreferencesFactory =
6207 new PortletPreferencesFactoryImpl();
6208
6209 PortalPreferences portalPreferences =
6210 portletPreferencesFactory.getPortalPreferences(userId, false);
6211
6212 String toggleControls = portalPreferences.getValue(
6213 SessionClicks.class.getName(),"liferay_toggle_controls", null);
6214
6215 if (Validator.isNotNull(toggleControls) &&
6216 !toggleControls.equals("visible")) {
6217
6218 portalPreferences.setValue(
6219 SessionClicks.class.getName(),"liferay_toggle_controls",
6220 "visible");
6221
6222 String xml = portletPreferencesFactory.toXML(portalPreferences);
6223
6224 PortalPreferencesLocalServiceUtil.updatePreferences(
6225 userId, PortletKeys.PREFS_OWNER_TYPE_USER, xml);
6226 }
6227 }
6228
6229 protected void updateGroups(
6230 long userId, long[] newGroupIds, ServiceContext serviceContext,
6231 boolean indexingEnabled)
6232 throws PortalException, SystemException {
6233
6234 if (newGroupIds == null) {
6235 return;
6236 }
6237
6238 List<Group> oldGroups = userPersistence.getGroups(userId);
6239
6240 Set<Long> oldGroupIds = new HashSet<Long>(oldGroups.size());
6241
6242 for (Group oldGroup : oldGroups) {
6243 long oldGroupId = oldGroup.getGroupId();
6244
6245 oldGroupIds.add(oldGroupId);
6246
6247 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
6248 unsetGroupUsers(
6249 oldGroupId, new long[] {userId}, serviceContext);
6250 }
6251 }
6252
6253 for (long newGroupId : newGroupIds) {
6254 if (!oldGroupIds.contains(newGroupId)) {
6255 addGroupUsers(newGroupId, new long[] {userId});
6256 }
6257 }
6258
6259 if (indexingEnabled) {
6260 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6261 User.class);
6262
6263 indexer.reindex(new long[] {userId});
6264 }
6265
6266 PermissionCacheUtil.clearCache(userId);
6267 }
6268
6269 protected void updateOrganizations(
6270 long userId, long[] newOrganizationIds, boolean indexingEnabled)
6271 throws PortalException, SystemException {
6272
6273 if (newOrganizationIds == null) {
6274 return;
6275 }
6276
6277 List<Organization> oldOrganizations = userPersistence.getOrganizations(
6278 userId);
6279
6280 Set<Long> oldOrganizationIds = new HashSet<Long>(
6281 oldOrganizations.size());
6282
6283 for (Organization oldOrganization : oldOrganizations) {
6284 long oldOrganizationId = oldOrganization.getOrganizationId();
6285
6286 oldOrganizationIds.add(oldOrganizationId);
6287
6288 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
6289 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
6290 }
6291 }
6292
6293 for (long newOrganizationId : newOrganizationIds) {
6294 if (!oldOrganizationIds.contains(newOrganizationId)) {
6295 addOrganizationUsers(newOrganizationId, new long[] {userId});
6296 }
6297 }
6298
6299 if (indexingEnabled) {
6300 Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6301 User.class);
6302
6303 indexer.reindex(new long[] {userId});
6304 }
6305
6306 PermissionCacheUtil.clearCache(userId);
6307 }
6308
6309 protected void updateUserGroupRoles(
6310 User user, long[] groupIds, long[] organizationIds,
6311 List<UserGroupRole> userGroupRoles,
6312 List<UserGroupRole> previousUserGroupRoles)
6313 throws PortalException, SystemException {
6314
6315 if (userGroupRoles == null) {
6316 return;
6317 }
6318
6319 userGroupRoles = new ArrayList<UserGroupRole>(userGroupRoles);
6320
6321 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
6322 if (userGroupRoles.contains(userGroupRole)) {
6323 userGroupRoles.remove(userGroupRole);
6324 }
6325 else {
6326 userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
6327 }
6328 }
6329
6330 if (userGroupRoles.isEmpty()) {
6331 return;
6332 }
6333
6334 long[] validGroupIds = null;
6335
6336 if (groupIds != null) {
6337 validGroupIds = ArrayUtil.clone(groupIds);
6338 }
6339 else {
6340 validGroupIds = user.getGroupIds();
6341 }
6342
6343 if (organizationIds == null) {
6344 organizationIds = user.getOrganizationIds();
6345 }
6346
6347 long[] organizationGroupIds = new long[organizationIds.length];
6348
6349 for (int i = 0; i < organizationIds.length; i++) {
6350 long organizationId = organizationIds[i];
6351
6352 Organization organization =
6353 organizationPersistence.findByPrimaryKey(organizationId);
6354
6355 organizationGroupIds[i] = organization.getGroupId();
6356 }
6357
6358 validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
6359
6360 Arrays.sort(validGroupIds);
6361
6362 for (UserGroupRole userGroupRole : userGroupRoles) {
6363 if (Arrays.binarySearch(
6364 validGroupIds, userGroupRole.getGroupId()) >= 0) {
6365
6366 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
6367 }
6368 }
6369 }
6370
6371 protected void validate(
6372 long companyId, long userId, boolean autoPassword, String password1,
6373 String password2, boolean autoScreenName, String screenName,
6374 String emailAddress, String openId, String firstName,
6375 String middleName, String lastName, long[] organizationIds)
6376 throws PortalException, SystemException {
6377
6378 validateCompanyMaxUsers(companyId);
6379
6380 if (!autoScreenName) {
6381 validateScreenName(companyId, userId, screenName);
6382 }
6383
6384 if (!autoPassword) {
6385 PasswordPolicy passwordPolicy =
6386 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
6387
6388 PwdToolkitUtil.validate(
6389 companyId, 0, password1, password2, passwordPolicy);
6390 }
6391
6392 validateEmailAddress(companyId, emailAddress);
6393
6394 if (Validator.isNotNull(emailAddress)) {
6395 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
6396
6397 if ((user != null) && (user.getUserId() != userId)) {
6398 throw new DuplicateUserEmailAddressException(
6399 "{userId=" + userId + "}");
6400 }
6401 }
6402
6403 validateOpenId(companyId, userId, openId);
6404
6405 validateFullName(companyId, firstName, middleName, lastName);
6406
6407 if (organizationIds != null) {
6408 for (long organizationId : organizationIds) {
6409 Organization organization =
6410 organizationPersistence.fetchByPrimaryKey(organizationId);
6411
6412 if (organization == null) {
6413 throw new NoSuchOrganizationException(
6414 "{organizationId=" + organizationId + "}");
6415 }
6416 }
6417 }
6418 }
6419
6420 protected void validate(
6421 long userId, String screenName, String emailAddress, String openId,
6422 String firstName, String middleName, String lastName, String smsSn)
6423 throws PortalException, SystemException {
6424
6425 User user = userPersistence.findByPrimaryKey(userId);
6426
6427 if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
6428 validateScreenName(user.getCompanyId(), userId, screenName);
6429 }
6430
6431 validateEmailAddress(user.getCompanyId(), emailAddress);
6432
6433 validateOpenId(user.getCompanyId(), userId, openId);
6434
6435 if (!user.isDefaultUser()) {
6436 if (Validator.isNotNull(emailAddress) &&
6437 !StringUtil.equalsIgnoreCase(
6438 user.getEmailAddress(), emailAddress)) {
6439
6440 if (userPersistence.fetchByC_EA(
6441 user.getCompanyId(), emailAddress) != null) {
6442
6443 throw new DuplicateUserEmailAddressException(
6444 "{userId=" + userId + "}");
6445 }
6446 }
6447
6448 validateFullName(
6449 user.getCompanyId(), firstName, middleName, lastName);
6450 }
6451
6452 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
6453 throw new UserSmsException();
6454 }
6455 }
6456
6457 protected void validateCompanyMaxUsers(long companyId)
6458 throws PortalException, SystemException {
6459
6460 Company company = companyPersistence.findByPrimaryKey(companyId);
6461
6462 if (company.isSystem() || (company.getMaxUsers() == 0)) {
6463 return;
6464 }
6465
6466 int userCount = searchCount(
6467 companyId, null, WorkflowConstants.STATUS_APPROVED, null);
6468
6469 if (userCount >= company.getMaxUsers()) {
6470 throw new CompanyMaxUsersException();
6471 }
6472 }
6473
6474 protected void validateEmailAddress(long companyId, String emailAddress)
6475 throws PortalException, SystemException {
6476
6477 if (Validator.isNull(emailAddress) &&
6478 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
6479
6480 return;
6481 }
6482
6483 EmailAddressValidator emailAddressValidator =
6484 EmailAddressValidatorFactory.getInstance();
6485
6486 if (!emailAddressValidator.validate(companyId, emailAddress)) {
6487 throw new UserEmailAddressException();
6488 }
6489
6490 String pop3User = PrefsPropsUtil.getString(
6491 PropsKeys.MAIL_SESSION_MAIL_POP3_USER,
6492 PropsValues.MAIL_SESSION_MAIL_POP3_USER);
6493
6494 if (StringUtil.equalsIgnoreCase(emailAddress, pop3User)) {
6495 throw new ReservedUserEmailAddressException();
6496 }
6497
6498 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
6499 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
6500 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
6501
6502 for (String reservedEmailAddress : reservedEmailAddresses) {
6503 if (StringUtil.equalsIgnoreCase(
6504 emailAddress, reservedEmailAddress)) {
6505
6506 throw new ReservedUserEmailAddressException();
6507 }
6508 }
6509 }
6510
6511 protected void validateEmailAddress(
6512 User user, String emailAddress1, String emailAddress2)
6513 throws PortalException, SystemException {
6514
6515 if (!emailAddress1.equals(emailAddress2)) {
6516 throw new UserEmailAddressException();
6517 }
6518
6519 validateEmailAddress(user.getCompanyId(), emailAddress1);
6520 validateEmailAddress(user.getCompanyId(), emailAddress2);
6521
6522 if (!StringUtil.equalsIgnoreCase(
6523 emailAddress1, user.getEmailAddress())) {
6524
6525 if (userPersistence.fetchByC_EA(
6526 user.getCompanyId(), emailAddress1) != null) {
6527
6528 throw new DuplicateUserEmailAddressException(
6529 "{userId=" + user.getUserId() + "}");
6530 }
6531 }
6532 }
6533
6534 protected void validateFullName(
6535 long companyId, String firstName, String middleName,
6536 String lastName)
6537 throws PortalException, SystemException {
6538
6539 if (Validator.isNull(firstName)) {
6540 throw new ContactFirstNameException();
6541 }
6542 else if (Validator.isNull(lastName) &&
6543 PrefsPropsUtil.getBoolean(
6544 companyId, PropsKeys.USERS_LAST_NAME_REQUIRED,
6545 PropsValues.USERS_LAST_NAME_REQUIRED)) {
6546
6547 throw new ContactLastNameException();
6548 }
6549
6550 FullNameValidator fullNameValidator =
6551 FullNameValidatorFactory.getInstance();
6552
6553 if (!fullNameValidator.validate(
6554 companyId, firstName, middleName, lastName)) {
6555
6556 throw new ContactFullNameException();
6557 }
6558 }
6559
6560 protected void validateOpenId(long companyId, long userId, String openId)
6561 throws PortalException, SystemException {
6562
6563 if (Validator.isNull(openId)) {
6564 return;
6565 }
6566
6567 User user = userPersistence.fetchByC_O(companyId, openId);
6568
6569 if ((user != null) && (user.getUserId() != userId)) {
6570 throw new DuplicateOpenIdException("{userId=" + userId + "}");
6571 }
6572 }
6573
6574 protected void validatePassword(
6575 long companyId, long userId, String password1, String password2)
6576 throws PortalException, SystemException {
6577
6578 if (Validator.isNull(password1) || Validator.isNull(password2)) {
6579 throw new UserPasswordException(
6580 UserPasswordException.PASSWORD_INVALID);
6581 }
6582
6583 if (!password1.equals(password2)) {
6584 throw new UserPasswordException(
6585 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
6586 }
6587
6588 PasswordPolicy passwordPolicy =
6589 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
6590
6591 PwdToolkitUtil.validate(
6592 companyId, userId, password1, password2, passwordPolicy);
6593 }
6594
6595 protected void validateReminderQuery(String question, String answer)
6596 throws PortalException {
6597
6598 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
6599 return;
6600 }
6601
6602 if (Validator.isNull(question)) {
6603 throw new UserReminderQueryException("Question is null");
6604 }
6605
6606 if (Validator.isNull(answer)) {
6607 throw new UserReminderQueryException("Answer is null");
6608 }
6609 }
6610
6611 protected void validateScreenName(
6612 long companyId, long userId, String screenName)
6613 throws PortalException, SystemException {
6614
6615 if (Validator.isNull(screenName)) {
6616 throw new UserScreenNameException();
6617 }
6618
6619 ScreenNameValidator screenNameValidator =
6620 ScreenNameValidatorFactory.getInstance();
6621
6622 if (!screenNameValidator.validate(companyId, screenName)) {
6623 throw new UserScreenNameException();
6624 }
6625
6626 if (Validator.isNumber(screenName)) {
6627 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
6628 throw new UserScreenNameException();
6629 }
6630
6631 if (!screenName.equals(String.valueOf(userId))) {
6632 Group group = groupPersistence.fetchByPrimaryKey(
6633 GetterUtil.getLong(screenName));
6634
6635 if (group != null) {
6636 throw new UserScreenNameException();
6637 }
6638 }
6639 }
6640
6641 for (char c : screenName.toCharArray()) {
6642 if (!Validator.isChar(c) && !Validator.isDigit(c) &&
6643 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
6644 (c != CharPool.UNDERLINE)) {
6645
6646 throw new UserScreenNameException();
6647 }
6648 }
6649
6650 String[] anonymousNames = BaseServiceImpl.ANONYMOUS_NAMES;
6651
6652 for (String anonymousName : anonymousNames) {
6653 if (StringUtil.equalsIgnoreCase(screenName, anonymousName)) {
6654 throw new UserScreenNameException();
6655 }
6656 }
6657
6658 User user = userPersistence.fetchByC_SN(companyId, screenName);
6659
6660 if ((user != null) && (user.getUserId() != userId)) {
6661 throw new DuplicateUserScreenNameException(
6662 "{userId=" + userId + "}");
6663 }
6664
6665 String friendlyURL = StringPool.SLASH + screenName;
6666
6667 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
6668
6669 if ((group != null) && (group.getClassPK() != userId)) {
6670 throw new GroupFriendlyURLException(
6671 GroupFriendlyURLException.DUPLICATE);
6672 }
6673
6674 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
6675
6676 if (exceptionType != -1) {
6677 throw new UserScreenNameException(
6678 new GroupFriendlyURLException(exceptionType));
6679 }
6680
6681 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
6682 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
6683 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
6684
6685 for (String reservedScreenName : reservedScreenNames) {
6686 if (StringUtil.equalsIgnoreCase(screenName, reservedScreenName)) {
6687 throw new ReservedUserScreenNameException();
6688 }
6689 }
6690 }
6691
6692 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
6693
6694 private Map<Long, User> _defaultUsers = new ConcurrentHashMap<Long, User>();
6695
6696 }