1
14
15 package com.liferay.portal.service.impl;
16
17 import com.liferay.portal.ContactBirthdayException;
18 import com.liferay.portal.ContactFirstNameException;
19 import com.liferay.portal.ContactFullNameException;
20 import com.liferay.portal.ContactLastNameException;
21 import com.liferay.portal.DuplicateUserEmailAddressException;
22 import com.liferay.portal.DuplicateUserScreenNameException;
23 import com.liferay.portal.GroupFriendlyURLException;
24 import com.liferay.portal.ModelListenerException;
25 import com.liferay.portal.NoSuchContactException;
26 import com.liferay.portal.NoSuchGroupException;
27 import com.liferay.portal.NoSuchRoleException;
28 import com.liferay.portal.NoSuchUserException;
29 import com.liferay.portal.NoSuchUserGroupException;
30 import com.liferay.portal.PasswordExpiredException;
31 import com.liferay.portal.PortalException;
32 import com.liferay.portal.RequiredUserException;
33 import com.liferay.portal.ReservedUserEmailAddressException;
34 import com.liferay.portal.ReservedUserScreenNameException;
35 import com.liferay.portal.SystemException;
36 import com.liferay.portal.UserEmailAddressException;
37 import com.liferay.portal.UserIdException;
38 import com.liferay.portal.UserLockoutException;
39 import com.liferay.portal.UserPasswordException;
40 import com.liferay.portal.UserPortraitSizeException;
41 import com.liferay.portal.UserPortraitTypeException;
42 import com.liferay.portal.UserReminderQueryException;
43 import com.liferay.portal.UserScreenNameException;
44 import com.liferay.portal.UserSmsException;
45 import com.liferay.portal.kernel.annotation.Propagation;
46 import com.liferay.portal.kernel.annotation.Transactional;
47 import com.liferay.portal.kernel.image.ImageBag;
48 import com.liferay.portal.kernel.image.ImageProcessorUtil;
49 import com.liferay.portal.kernel.language.LanguageUtil;
50 import com.liferay.portal.kernel.log.Log;
51 import com.liferay.portal.kernel.log.LogFactoryUtil;
52 import com.liferay.portal.kernel.mail.MailMessage;
53 import com.liferay.portal.kernel.search.BooleanClauseOccur;
54 import com.liferay.portal.kernel.search.BooleanQuery;
55 import com.liferay.portal.kernel.search.BooleanQueryFactoryUtil;
56 import com.liferay.portal.kernel.search.Field;
57 import com.liferay.portal.kernel.search.Hits;
58 import com.liferay.portal.kernel.search.ParseException;
59 import com.liferay.portal.kernel.search.SearchEngineUtil;
60 import com.liferay.portal.kernel.search.SearchException;
61 import com.liferay.portal.kernel.search.Sort;
62 import com.liferay.portal.kernel.util.ArrayUtil;
63 import com.liferay.portal.kernel.util.Base64;
64 import com.liferay.portal.kernel.util.CharPool;
65 import com.liferay.portal.kernel.util.GetterUtil;
66 import com.liferay.portal.kernel.util.HtmlUtil;
67 import com.liferay.portal.kernel.util.KeyValuePair;
68 import com.liferay.portal.kernel.util.ListUtil;
69 import com.liferay.portal.kernel.util.OrderByComparator;
70 import com.liferay.portal.kernel.util.PropsKeys;
71 import com.liferay.portal.kernel.util.SetUtil;
72 import com.liferay.portal.kernel.util.StringPool;
73 import com.liferay.portal.kernel.util.StringUtil;
74 import com.liferay.portal.kernel.util.UnicodeProperties;
75 import com.liferay.portal.kernel.util.Validator;
76 import com.liferay.portal.model.Company;
77 import com.liferay.portal.model.CompanyConstants;
78 import com.liferay.portal.model.Contact;
79 import com.liferay.portal.model.ContactConstants;
80 import com.liferay.portal.model.Group;
81 import com.liferay.portal.model.Organization;
82 import com.liferay.portal.model.PasswordPolicy;
83 import com.liferay.portal.model.ResourceConstants;
84 import com.liferay.portal.model.Role;
85 import com.liferay.portal.model.RoleConstants;
86 import com.liferay.portal.model.User;
87 import com.liferay.portal.model.UserGroup;
88 import com.liferay.portal.model.UserGroupRole;
89 import com.liferay.portal.model.impl.LayoutImpl;
90 import com.liferay.portal.security.auth.AuthPipeline;
91 import com.liferay.portal.security.auth.Authenticator;
92 import com.liferay.portal.security.auth.EmailAddressGenerator;
93 import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
94 import com.liferay.portal.security.auth.FullNameValidator;
95 import com.liferay.portal.security.auth.FullNameValidatorFactory;
96 import com.liferay.portal.security.auth.PrincipalException;
97 import com.liferay.portal.security.auth.ScreenNameGenerator;
98 import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
99 import com.liferay.portal.security.auth.ScreenNameValidator;
100 import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
101 import com.liferay.portal.security.ldap.LDAPSettingsUtil;
102 import com.liferay.portal.security.permission.PermissionCacheUtil;
103 import com.liferay.portal.security.pwd.PwdEncryptor;
104 import com.liferay.portal.security.pwd.PwdToolkitUtil;
105 import com.liferay.portal.service.ServiceContext;
106 import com.liferay.portal.service.base.PrincipalBean;
107 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
108 import com.liferay.portal.util.PortalUtil;
109 import com.liferay.portal.util.PrefsPropsUtil;
110 import com.liferay.portal.util.PropsUtil;
111 import com.liferay.portal.util.PropsValues;
112 import com.liferay.portlet.enterpriseadmin.util.EnterpriseAdminUtil;
113 import com.liferay.portlet.enterpriseadmin.util.UserIndexer;
114 import com.liferay.portlet.expando.model.ExpandoBridge;
115 import com.liferay.portlet.expando.model.ExpandoColumnConstants;
116 import com.liferay.portlet.expando.util.ExpandoBridgeFactoryUtil;
117 import com.liferay.portlet.expando.util.ExpandoBridgeIndexer;
118 import com.liferay.portlet.imagegallery.ImageSizeException;
119 import com.liferay.util.Encryptor;
120 import com.liferay.util.EncryptorException;
121
122 import java.awt.image.RenderedImage;
123
124 import java.io.IOException;
125 import java.io.UnsupportedEncodingException;
126
127 import java.security.MessageDigest;
128 import java.security.NoSuchAlgorithmException;
129
130 import java.util.ArrayList;
131 import java.util.Arrays;
132 import java.util.Date;
133 import java.util.HashSet;
134 import java.util.LinkedHashMap;
135 import java.util.List;
136 import java.util.Locale;
137 import java.util.Map;
138 import java.util.Set;
139 import java.util.concurrent.ConcurrentHashMap;
140
141 import javax.mail.internet.InternetAddress;
142
143
154 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
155
156 public void addDefaultGroups(long userId)
157 throws PortalException, SystemException {
158
159 User user = userPersistence.findByPrimaryKey(userId);
160
161 Set<Long> groupIdsSet = new HashSet<Long>();
162
163 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
164 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
165 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
166
167 for (String defaultGroupName : defaultGroupNames) {
168 try {
169 Group group = groupPersistence.findByC_N(
170 user.getCompanyId(), defaultGroupName);
171
172 if (!userPersistence.containsGroup(
173 userId, group.getGroupId())) {
174
175 groupIdsSet.add(group.getGroupId());
176 }
177 }
178 catch (NoSuchGroupException nsge) {
179 }
180 }
181
182 long[] groupIds = ArrayUtil.toArray(
183 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
184
185 groupLocalService.addUserGroups(userId, groupIds);
186 }
187
188 public void addDefaultRoles(long userId)
189 throws PortalException, SystemException {
190
191 User user = userPersistence.findByPrimaryKey(userId);
192
193 Set<Long> roleIdSet = new HashSet<Long>();
194
195 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
196 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
197 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
198
199 for (String defaultRoleName : defaultRoleNames) {
200 try {
201 Role role = rolePersistence.findByC_N(
202 user.getCompanyId(), defaultRoleName);
203
204 if (!userPersistence.containsRole(
205 userId, role.getRoleId())) {
206
207 roleIdSet.add(role.getRoleId());
208 }
209 }
210 catch (NoSuchRoleException nsre) {
211 }
212 }
213
214 long[] roleIds = ArrayUtil.toArray(
215 roleIdSet.toArray(new Long[roleIdSet.size()]));
216
217 roleIds = EnterpriseAdminUtil.addRequiredRoles(user, roleIds);
218
219 userPersistence.addRoles(userId, roleIds);
220 }
221
222 public void addDefaultUserGroups(long userId)
223 throws PortalException, SystemException {
224
225 User user = userPersistence.findByPrimaryKey(userId);
226
227 Set<Long> userGroupIdSet = new HashSet<Long>();
228
229 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
230 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
231 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
232
233 for (String defaultUserGroupName : defaultUserGroupNames) {
234 try {
235 UserGroup userGroup = userGroupPersistence.findByC_N(
236 user.getCompanyId(), defaultUserGroupName);
237
238 if (!userPersistence.containsUserGroup(
239 userId, userGroup.getUserGroupId())) {
240
241 userGroupIdSet.add(userGroup.getUserGroupId());
242 }
243 }
244 catch (NoSuchUserGroupException nsuge) {
245 }
246 }
247
248 long[] userGroupIds = ArrayUtil.toArray(
249 userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
250
251 for (long userGroupId : userGroupIds) {
252 userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
253 }
254
255 userPersistence.addUserGroups(userId, userGroupIds);
256 }
257
258 public void addGroupUsers(long groupId, long[] userIds)
259 throws SystemException {
260
261 groupPersistence.addUsers(groupId, userIds);
262
263 try {
264 UserIndexer.updateUsers(userIds);
265 }
266 catch (SearchException se) {
267 _log.error("Indexing " + StringUtil.merge(userIds), se);
268 }
269
270 PermissionCacheUtil.clearCache();
271 }
272
273 public void addOrganizationUsers(long organizationId, long[] userIds)
274 throws SystemException {
275
276 organizationPersistence.addUsers(organizationId, userIds);
277
278 try {
279 UserIndexer.updateUsers(userIds);
280 }
281 catch (SearchException se) {
282 _log.error("Indexing " + StringUtil.merge(userIds), se);
283 }
284
285 PermissionCacheUtil.clearCache();
286 }
287
288 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
289 throws SystemException {
290
291 passwordPolicyRelLocalService.addPasswordPolicyRels(
292 passwordPolicyId, User.class.getName(), userIds);
293 }
294
295 public void addRoleUsers(long roleId, long[] userIds)
296 throws SystemException {
297
298 rolePersistence.addUsers(roleId, userIds);
299
300 try {
301 UserIndexer.updateUsers(userIds);
302 }
303 catch (SearchException se) {
304 _log.error("Indexing " + StringUtil.merge(userIds), se);
305 }
306
307 PermissionCacheUtil.clearCache();
308 }
309
310 public void addUserGroupUsers(long userGroupId, long[] userIds)
311 throws PortalException, SystemException {
312
313 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
314
315 userGroupPersistence.addUsers(userGroupId, userIds);
316
317 try {
318 UserIndexer.updateUsers(userIds);
319 }
320 catch (SearchException se) {
321 _log.error("Indexing " + StringUtil.merge(userIds), se);
322 }
323
324 PermissionCacheUtil.clearCache();
325 }
326
327 public User addUser(
328 long creatorUserId, long companyId, boolean autoPassword,
329 String password1, String password2, boolean autoScreenName,
330 String screenName, String emailAddress, String openId,
331 Locale locale, String firstName, String middleName, String lastName,
332 int prefixId, int suffixId, boolean male, int birthdayMonth,
333 int birthdayDay, int birthdayYear, String jobTitle, long[] groupIds,
334 long[] organizationIds, long[] roleIds, long[] userGroupIds,
335 boolean sendEmail, ServiceContext serviceContext)
336 throws PortalException, SystemException {
337
338
340 Company company = companyPersistence.findByPrimaryKey(companyId);
341 screenName = getScreenName(screenName);
342 emailAddress = emailAddress.trim().toLowerCase();
343 openId = openId.trim();
344 Date now = new Date();
345
346 if (PrefsPropsUtil.getBoolean(
347 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
348
349 autoScreenName = true;
350 }
351
352 long userId = counterLocalService.increment();
353
354 EmailAddressGenerator emailAddressGenerator =
355 EmailAddressGeneratorFactory.getInstance();
356
357 if (emailAddressGenerator.isGenerated(emailAddress)) {
358 emailAddress = StringPool.BLANK;
359 }
360
361 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
362 Validator.isNull(emailAddress)) {
363
364 emailAddress = emailAddressGenerator.generate(companyId, userId);
365 }
366
367 validate(
368 companyId, userId, autoPassword, password1, password2,
369 autoScreenName, screenName, emailAddress, firstName, middleName,
370 lastName, organizationIds);
371
372 if (autoPassword) {
373 password1 = PwdToolkitUtil.generate();
374 }
375 else {
376 if (Validator.isNull(password1) || Validator.isNull(password2)) {
377 throw new UserPasswordException(
378 UserPasswordException.PASSWORD_INVALID);
379 }
380 }
381
382 if (autoScreenName) {
383 ScreenNameGenerator screenNameGenerator =
384 ScreenNameGeneratorFactory.getInstance();
385
386 try {
387 screenName = screenNameGenerator.generate(
388 companyId, userId, emailAddress);
389 }
390 catch (Exception e) {
391 throw new SystemException(e);
392 }
393 }
394
395 User defaultUser = getDefaultUser(companyId);
396
397 String fullName = ContactConstants.getFullName(
398 firstName, middleName, lastName);
399
400 String greeting = LanguageUtil.format(
401 locale, "welcome-x", " " + fullName, false);
402
403 User user = userPersistence.create(userId);
404
405 user.setCompanyId(companyId);
406 user.setCreateDate(now);
407 user.setModifiedDate(now);
408 user.setDefaultUser(false);
409 user.setContactId(counterLocalService.increment());
410 user.setPassword(PwdEncryptor.encrypt(password1));
411 user.setPasswordUnencrypted(password1);
412 user.setPasswordEncrypted(true);
413 user.setPasswordReset(false);
414 user.setScreenName(screenName);
415 user.setEmailAddress(emailAddress);
416 user.setOpenId(openId);
417 user.setLanguageId(locale.toString());
418 user.setTimeZoneId(defaultUser.getTimeZoneId());
419 user.setGreeting(greeting);
420 user.setFirstName(firstName);
421 user.setMiddleName(middleName);
422 user.setLastName(lastName);
423 user.setJobTitle(jobTitle);
424 user.setActive(true);
425
426 userPersistence.update(user, false);
427
428
430 String creatorUserName = StringPool.BLANK;
431
432 if (creatorUserId <= 0) {
433 creatorUserId = user.getUserId();
434
435
438 }
440 else {
441 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
442
443 creatorUserName = creatorUser.getFullName();
444 }
445
446 resourceLocalService.addResources(
447 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
448 false, false, false);
449
450
452 user.setExpandoBridgeAttributes(serviceContext);
453
454
456 if (user.hasCompanyMx()) {
457 mailService.addUser(
458 companyId, userId, password1, firstName, middleName, lastName,
459 emailAddress);
460 }
461
462
464 Date birthday = PortalUtil.getDate(
465 birthdayMonth, birthdayDay, birthdayYear,
466 new ContactBirthdayException());
467
468 Contact contact = contactPersistence.create(user.getContactId());
469
470 contact.setCompanyId(user.getCompanyId());
471 contact.setUserId(creatorUserId);
472 contact.setUserName(creatorUserName);
473 contact.setCreateDate(now);
474 contact.setModifiedDate(now);
475 contact.setAccountId(company.getAccountId());
476 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
477 contact.setFirstName(firstName);
478 contact.setMiddleName(middleName);
479 contact.setLastName(lastName);
480 contact.setPrefixId(prefixId);
481 contact.setSuffixId(suffixId);
482 contact.setMale(male);
483 contact.setBirthday(birthday);
484 contact.setJobTitle(jobTitle);
485
486 contactPersistence.update(contact, false);
487
488
490 groupLocalService.addGroup(
491 user.getUserId(), User.class.getName(), user.getUserId(), null,
492 null, 0, StringPool.SLASH + screenName, true, null);
493
494
496 if (groupIds != null) {
497 groupLocalService.addUserGroups(userId, groupIds);
498 }
499
500 addDefaultGroups(userId);
501
502
504 updateOrganizations(userId, organizationIds);
505
506
508 if (roleIds != null) {
509 roleIds = EnterpriseAdminUtil.addRequiredRoles(user, roleIds);
510
511 userPersistence.setRoles(userId, roleIds);
512 }
513
514 addDefaultRoles(userId);
515
516
518 if (userGroupIds != null) {
519 for (long userGroupId : userGroupIds) {
520 userGroupLocalService.copyUserGroupLayouts(
521 userGroupId, new long[] {userId});
522 }
523
524 userPersistence.setUserGroups(userId, userGroupIds);
525 }
526
527 addDefaultUserGroups(userId);
528
529
531 if (sendEmail) {
532 try {
533 sendEmail(user, password1);
534 }
535 catch (IOException ioe) {
536 throw new SystemException(ioe);
537 }
538 }
539
540
542 if (serviceContext != null) {
543 updateTagsAsset(
544 creatorUserId, user, serviceContext.getTagsEntries());
545 }
546
547
549 try {
550 UserIndexer.updateUser(user);
551 }
552 catch (SearchException se) {
553 _log.error("Indexing " + userId, se);
554 }
555
556 return user;
557 }
558
559 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
560 public int authenticateByEmailAddress(
561 long companyId, String emailAddress, String password,
562 Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
563 throws PortalException, SystemException {
564
565 return authenticate(
566 companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
567 headerMap, parameterMap);
568 }
569
570 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
571 public int authenticateByScreenName(
572 long companyId, String screenName, String password,
573 Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
574 throws PortalException, SystemException {
575
576 return authenticate(
577 companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
578 headerMap, parameterMap);
579 }
580
581 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
582 public int authenticateByUserId(
583 long companyId, long userId, String password,
584 Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
585 throws PortalException, SystemException {
586
587 return authenticate(
588 companyId, String.valueOf(userId), password,
589 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap);
590 }
591
592 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
593 public long authenticateForBasic(
594 long companyId, String authType, String login, String password)
595 throws PortalException, SystemException {
596
597 try {
598 User user = null;
599
600 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
601 user = getUserByEmailAddress(companyId, login);
602 }
603 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
604 user = getUserByScreenName(companyId, login);
605 }
606 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
607 user = getUserById(companyId, GetterUtil.getLong(login));
608 }
609
610 if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
611 return user.getUserId();
612 }
613
614 String userPassword = user.getPassword();
615
616 if (!user.isPasswordEncrypted()) {
617 userPassword = PwdEncryptor.encrypt(userPassword);
618 }
619
620 String encPassword = PwdEncryptor.encrypt(password);
621
622 if (userPassword.equals(password) ||
623 userPassword.equals(encPassword)) {
624
625 return user.getUserId();
626 }
627 }
628 catch (NoSuchUserException nsue) {
629 }
630
631 return 0;
632 }
633
634 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
635 public boolean authenticateForJAAS(long userId, String encPassword) {
636 try {
637 User user = userPersistence.findByPrimaryKey(userId);
638
639 if (user.isDefaultUser()) {
640 _log.error(
641 "The default user should never be allowed to authenticate");
642
643 return false;
644 }
645
646 String password = user.getPassword();
647
648 if (user.isPasswordEncrypted()) {
649 if (password.equals(encPassword)) {
650 return true;
651 }
652
653 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
654 encPassword = PwdEncryptor.encrypt(encPassword, password);
655
656 if (password.equals(encPassword)) {
657 return true;
658 }
659 }
660 }
661 else {
662 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
663 if (password.equals(encPassword)) {
664 return true;
665 }
666 }
667
668 password = PwdEncryptor.encrypt(password);
669
670 if (password.equals(encPassword)) {
671 return true;
672 }
673 }
674 }
675 catch (Exception e) {
676 _log.error(e);
677 }
678
679 return false;
680 }
681
682 public void checkLockout(User user)
683 throws PortalException, SystemException {
684
685 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
686 return;
687 }
688
689 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
690
691 if (passwordPolicy.isLockout()) {
692
693
695 Date now = new Date();
696 int failedLoginAttempts = user.getFailedLoginAttempts();
697
698 if (failedLoginAttempts > 0) {
699 long failedLoginTime = user.getLastFailedLoginDate().getTime();
700 long elapsedTime = now.getTime() - failedLoginTime;
701 long requiredElapsedTime =
702 passwordPolicy.getResetFailureCount() * 1000;
703
704 if ((requiredElapsedTime != 0) &&
705 (elapsedTime > requiredElapsedTime)) {
706
707 user.setLastFailedLoginDate(null);
708 user.setFailedLoginAttempts(0);
709 }
710 }
711
712
714 if (user.isLockout()) {
715 long lockoutTime = user.getLockoutDate().getTime();
716 long elapsedTime = now.getTime() - lockoutTime;
717 long requiredElapsedTime =
718 passwordPolicy.getLockoutDuration() * 1000;
719
720 if ((requiredElapsedTime != 0) &&
721 (elapsedTime > requiredElapsedTime)) {
722
723 user.setLockout(false);
724 user.setLockoutDate(null);
725 }
726 }
727
728 if (user.isLockout()) {
729 throw new UserLockoutException();
730 }
731 }
732 }
733
734 public void checkLoginFailure(User user) throws SystemException {
735 Date now = new Date();
736
737 int failedLoginAttempts = user.getFailedLoginAttempts();
738
739 user.setLastFailedLoginDate(now);
740 user.setFailedLoginAttempts(++failedLoginAttempts);
741
742 userPersistence.update(user, false);
743 }
744
745 public void checkLoginFailureByEmailAddress(
746 long companyId, String emailAddress)
747 throws PortalException, SystemException {
748
749 User user = getUserByEmailAddress(companyId, emailAddress);
750
751 checkLoginFailure(user);
752 }
753
754 public void checkLoginFailureById(long userId)
755 throws PortalException, SystemException {
756
757 User user = userPersistence.findByPrimaryKey(userId);
758
759 checkLoginFailure(user);
760 }
761
762 public void checkLoginFailureByScreenName(long companyId, String screenName)
763 throws PortalException, SystemException {
764
765 User user = getUserByScreenName(companyId, screenName);
766
767 checkLoginFailure(user);
768 }
769
770 public void checkPasswordExpired(User user)
771 throws PortalException, SystemException {
772
773 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
774 return;
775 }
776
777 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
778
779
781 if (isPasswordExpired(user)) {
782 int graceLoginCount = user.getGraceLoginCount();
783
784 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
785 user.setGraceLoginCount(++graceLoginCount);
786
787 userPersistence.update(user, false);
788 }
789 else {
790 throw new PasswordExpiredException();
791 }
792 }
793
794
796 if (isPasswordExpiringSoon(user)) {
797 user.setPasswordReset(true);
798
799 userPersistence.update(user, false);
800 }
801
802
804 if (passwordPolicy.isChangeable() &&
805 passwordPolicy.isChangeRequired()) {
806
807 if (user.getLastLoginDate() == null) {
808 boolean passwordReset = false;
809
810 if (passwordPolicy.isChangeable() &&
811 passwordPolicy.isChangeRequired()) {
812
813 passwordReset = true;
814 }
815
816 user.setPasswordReset(passwordReset);
817
818 userPersistence.update(user, false);
819 }
820 }
821 }
822
823 public void clearOrganizationUsers(long organizationId)
824 throws SystemException {
825
826 organizationPersistence.clearUsers(organizationId);
827
828 PermissionCacheUtil.clearCache();
829 }
830
831 public void clearUserGroupUsers(long userGroupId) throws SystemException {
832 userGroupPersistence.clearUsers(userGroupId);
833
834 PermissionCacheUtil.clearCache();
835 }
836
837 public KeyValuePair decryptUserId(
838 long companyId, String name, String password)
839 throws PortalException, SystemException {
840
841 Company company = companyPersistence.findByPrimaryKey(companyId);
842
843 try {
844 name = Encryptor.decrypt(company.getKeyObj(), name);
845 }
846 catch (EncryptorException ee) {
847 throw new SystemException(ee);
848 }
849
850 long userId = GetterUtil.getLong(name);
851
852 User user = userPersistence.findByPrimaryKey(userId);
853
854 try {
855 password = Encryptor.decrypt(company.getKeyObj(), password);
856 }
857 catch (EncryptorException ee) {
858 throw new SystemException(ee);
859 }
860
861 String encPassword = PwdEncryptor.encrypt(password);
862
863 if (user.getPassword().equals(encPassword)) {
864 if (isPasswordExpired(user)) {
865 user.setPasswordReset(true);
866
867 userPersistence.update(user, false);
868 }
869
870 return new KeyValuePair(name, password);
871 }
872 else {
873 throw new PrincipalException();
874 }
875 }
876
877 public void deletePasswordPolicyUser(long passwordPolicyId, long userId)
878 throws SystemException {
879
880 passwordPolicyRelLocalService.deletePasswordPolicyRel(
881 passwordPolicyId, User.class.getName(), userId);
882 }
883
884 public void deletePortrait(long userId)
885 throws PortalException, SystemException {
886
887 User user = userPersistence.findByPrimaryKey(userId);
888
889 long portraitId = user.getPortraitId();
890
891 if (portraitId > 0) {
892 user.setPortraitId(0);
893
894 userPersistence.update(user, false);
895
896 imageLocalService.deleteImage(portraitId);
897 }
898 }
899
900 public void deleteRoleUser(long roleId, long userId)
901 throws SystemException {
902
903 rolePersistence.removeUser(roleId, userId);
904
905 PermissionCacheUtil.clearCache();
906 }
907
908 public void deleteUser(long userId)
909 throws PortalException, SystemException {
910
911 if (!PropsValues.USERS_DELETE) {
912 throw new RequiredUserException();
913 }
914
915 User user = userPersistence.findByPrimaryKey(userId);
916
917
919 try {
920 UserIndexer.deleteUser(user.getCompanyId(), user.getUserId());
921 }
922 catch (SearchException se) {
923 _log.error("Indexing " + userId, se);
924 }
925
926
928 browserTrackerLocalService.deleteUserBrowserTracker(userId);
929
930
932 Group group = user.getGroup();
933
934 if (group != null) {
935 groupLocalService.deleteGroup(group.getGroupId());
936 }
937
938
940 imageLocalService.deleteImage(user.getPortraitId());
941
942
944 passwordPolicyRelLocalService.deletePasswordPolicyRel(
945 User.class.getName(), userId);
946
947
949 passwordTrackerLocalService.deletePasswordTrackers(userId);
950
951
953 subscriptionLocalService.deleteSubscriptions(userId);
954
955
957 userIdMapperLocalService.deleteUserIdMappers(userId);
958
959
961 announcementsDeliveryLocalService.deleteDeliveries(userId);
962
963
965 blogsStatsUserLocalService.deleteStatsUserByUserId(userId);
966
967
969 dlFileRankLocalService.deleteFileRanks(userId);
970
971
973 expandoValueLocalService.deleteValues(User.class.getName(), userId);
974
975
977 mbBanLocalService.deleteBansByBanUserId(userId);
978 mbMessageFlagLocalService.deleteFlags(userId);
979 mbStatsUserLocalService.deleteStatsUsersByUserId(userId);
980
981
983 shoppingCartLocalService.deleteUserCarts(userId);
984
985
987 socialActivityLocalService.deleteUserActivities(userId);
988 socialRequestLocalService.deleteReceiverUserRequests(userId);
989 socialRequestLocalService.deleteUserRequests(userId);
990
991
993 tagsAssetLocalService.deleteAsset(User.class.getName(), userId);
994
995
997 mailService.deleteUser(user.getCompanyId(), userId);
998
999
1001 try {
1002 contactLocalService.deleteContact(user.getContactId());
1003 }
1004 catch (NoSuchContactException nsce) {
1005 }
1006
1007
1009 resourceLocalService.deleteResource(
1010 user.getCompanyId(), User.class.getName(),
1011 ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
1012
1013
1015 userGroupRoleLocalService.deleteUserGroupRolesByUserId(userId);
1016
1017
1019 userPersistence.remove(userId);
1020
1021
1023 PermissionCacheUtil.clearCache();
1024 }
1025
1026 public String encryptUserId(String name)
1027 throws PortalException, SystemException {
1028
1029 long userId = GetterUtil.getLong(name);
1030
1031 User user = userPersistence.findByPrimaryKey(userId);
1032
1033 Company company = companyPersistence.findByPrimaryKey(
1034 user.getCompanyId());
1035
1036 try {
1037 return Encryptor.encrypt(company.getKeyObj(), name);
1038 }
1039 catch (EncryptorException ee) {
1040 throw new SystemException(ee);
1041 }
1042 }
1043
1044 public User getDefaultUser(long companyId)
1045 throws PortalException, SystemException {
1046
1047 User userModel = _defaultUsers.get(companyId);
1048
1049 if (userModel == null) {
1050 userModel = userPersistence.findByC_DU(companyId, true);
1051
1052 _defaultUsers.put(companyId, userModel);
1053 }
1054
1055 return userModel;
1056 }
1057
1058 public long getDefaultUserId(long companyId)
1059 throws PortalException, SystemException {
1060
1061 User user = getDefaultUser(companyId);
1062
1063 return user.getUserId();
1064 }
1065
1066 public long[] getGroupUserIds(long groupId) throws SystemException {
1067 return getUserIds(getGroupUsers(groupId));
1068 }
1069
1070 public List<User> getGroupUsers(long groupId) throws SystemException {
1071 return groupPersistence.getUsers(groupId);
1072 }
1073
1074 public int getGroupUsersCount(long groupId) throws SystemException {
1075 return groupPersistence.getUsersSize(groupId);
1076 }
1077
1078 public int getGroupUsersCount(long groupId, boolean active)
1079 throws PortalException, SystemException {
1080
1081 Group group = groupPersistence.findByPrimaryKey(groupId);
1082
1083 LinkedHashMap<String, Object> params =
1084 new LinkedHashMap<String, Object>();
1085
1086 params.put("usersGroups", new Long(groupId));
1087
1088 return searchCount(group.getCompanyId(), null, active, params);
1089 }
1090
1091 public List<User> getNoAnnouncementsDeliveries(String type)
1092 throws SystemException {
1093
1094 return userFinder.findByNoAnnouncementsDeliveries(type);
1095 }
1096
1097 public List<User> getNoContacts() throws SystemException {
1098 return userFinder.findByNoContacts();
1099 }
1100
1101 public List<User> getNoGroups() throws SystemException {
1102 return userFinder.findByNoGroups();
1103 }
1104
1105 public long[] getOrganizationUserIds(long organizationId)
1106 throws SystemException {
1107
1108 return getUserIds(getOrganizationUsers(organizationId));
1109 }
1110
1111 public List<User> getOrganizationUsers(long organizationId)
1112 throws SystemException {
1113
1114 return organizationPersistence.getUsers(organizationId);
1115 }
1116
1117 public int getOrganizationUsersCount(long organizationId)
1118 throws SystemException {
1119
1120 return organizationPersistence.getUsersSize(organizationId);
1121 }
1122
1123 public int getOrganizationUsersCount(long organizationId, boolean active)
1124 throws PortalException, SystemException {
1125
1126 Organization organization = organizationPersistence.findByPrimaryKey(
1127 organizationId);
1128
1129 LinkedHashMap<String, Object> params =
1130 new LinkedHashMap<String, Object>();
1131
1132 params.put("usersOrgs", new Long(organizationId));
1133
1134 return searchCount(organization.getCompanyId(), null, active, params);
1135 }
1136
1137 public long[] getRoleUserIds(long roleId) throws SystemException {
1138 return getUserIds(getRoleUsers(roleId));
1139 }
1140
1141 public List<User> getRoleUsers(long roleId) throws SystemException {
1142 return rolePersistence.getUsers(roleId);
1143 }
1144
1145 public List<User> getRoleUsers(long roleId, int start, int end)
1146 throws SystemException {
1147
1148 return rolePersistence.getUsers(roleId, start, end);
1149 }
1150
1151 public int getRoleUsersCount(long roleId) throws SystemException {
1152 return rolePersistence.getUsersSize(roleId);
1153 }
1154
1155 public int getRoleUsersCount(long roleId, boolean active)
1156 throws PortalException, SystemException {
1157
1158 Role role = rolePersistence.findByPrimaryKey(
1159 roleId);
1160
1161 LinkedHashMap<String, Object> params =
1162 new LinkedHashMap<String, Object>();
1163
1164 params.put("usersRoles", new Long(roleId));
1165
1166 return searchCount(role.getCompanyId(), null, active, params);
1167 }
1168
1169 public List<User> getSocialUsers(
1170 long userId, int start, int end, OrderByComparator obc)
1171 throws PortalException, SystemException {
1172
1173 User user = userPersistence.findByPrimaryKey(userId);
1174
1175 LinkedHashMap<String, Object> params =
1176 new LinkedHashMap<String, Object>();
1177
1178 params.put("socialRelation", new Long[] {userId});
1179
1180 return search(
1181 user.getCompanyId(), null, true, params, start, end, obc);
1182 }
1183
1184 public List<User> getSocialUsers(
1185 long userId, int type, int start, int end, OrderByComparator obc)
1186 throws PortalException, SystemException {
1187
1188 User user = userPersistence.findByPrimaryKey(userId);
1189
1190 LinkedHashMap<String, Object> params =
1191 new LinkedHashMap<String, Object>();
1192
1193 params.put("socialRelationType", new Long[] {userId, new Long(type)});
1194
1195 return search(user.getCompanyId(), null, true, params, start, end, obc);
1196 }
1197
1198 public List<User> getSocialUsers(
1199 long userId1, long userId2, int start, int end,
1200 OrderByComparator obc)
1201 throws PortalException, SystemException {
1202
1203 User user1 = userPersistence.findByPrimaryKey(userId1);
1204
1205 LinkedHashMap<String, Object> params =
1206 new LinkedHashMap<String, Object>();
1207
1208 params.put("socialMutualRelation", new Long[] {userId1, userId2});
1209
1210 return search(
1211 user1.getCompanyId(), null, true, params, start, end, obc);
1212 }
1213
1214 public List<User> getSocialUsers(
1215 long userId1, long userId2, int type, int start, int end,
1216 OrderByComparator obc)
1217 throws PortalException, SystemException {
1218
1219 User user1 = userPersistence.findByPrimaryKey(userId1);
1220
1221 LinkedHashMap<String, Object> params =
1222 new LinkedHashMap<String, Object>();
1223
1224 params.put(
1225 "socialMutualRelationType",
1226 new Long[] {userId1, new Long(type), userId2, new Long(type)});
1227
1228 return search(
1229 user1.getCompanyId(), null, true, params, start, end, obc);
1230 }
1231
1232 public int getSocialUsersCount(long userId)
1233 throws PortalException, SystemException {
1234
1235 User user = userPersistence.findByPrimaryKey(userId);
1236
1237 LinkedHashMap<String, Object> params =
1238 new LinkedHashMap<String, Object>();
1239
1240 params.put("socialRelation", new Long[] {userId});
1241
1242 return searchCount(user.getCompanyId(), null, true, params);
1243 }
1244
1245 public int getSocialUsersCount(long userId, int type)
1246 throws PortalException, SystemException {
1247
1248 User user = userPersistence.findByPrimaryKey(userId);
1249
1250 LinkedHashMap<String, Object> params =
1251 new LinkedHashMap<String, Object>();
1252
1253 params.put("socialRelationType", new Long[] {userId, new Long(type)});
1254
1255 return searchCount(user.getCompanyId(), null, true, params);
1256 }
1257
1258 public int getSocialUsersCount(long userId1, long userId2)
1259 throws PortalException, SystemException {
1260
1261 User user1 = userPersistence.findByPrimaryKey(userId1);
1262
1263 LinkedHashMap<String, Object> params =
1264 new LinkedHashMap<String, Object>();
1265
1266 params.put("socialMutualRelation", new Long[] {userId1, userId2});
1267
1268 return searchCount(user1.getCompanyId(), null, true, params);
1269 }
1270
1271 public int getSocialUsersCount(long userId1, long userId2, int type)
1272 throws PortalException, SystemException {
1273
1274 User user1 = userPersistence.findByPrimaryKey(userId1);
1275
1276 LinkedHashMap<String, Object> params =
1277 new LinkedHashMap<String, Object>();
1278
1279 params.put(
1280 "socialMutualRelationType",
1281 new Long[] {userId1, new Long(type), userId2, new Long(type)});
1282
1283 return searchCount(user1.getCompanyId(), null, true, params);
1284 }
1285
1286 public List<User> getUserGroupUsers(long userGroupId)
1287 throws SystemException {
1288
1289 return userGroupPersistence.getUsers(userGroupId);
1290 }
1291
1292 public int getUserGroupUsersCount(long userGroupId) throws SystemException {
1293 return userGroupPersistence.getUsersSize(userGroupId);
1294 }
1295
1296 public int getUserGroupUsersCount(long userGroupId, boolean active)
1297 throws PortalException, SystemException {
1298
1299 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
1300 userGroupId);
1301
1302 LinkedHashMap<String, Object> params =
1303 new LinkedHashMap<String, Object>();
1304
1305 params.put("usersUserGroups", new Long(userGroupId));
1306
1307 return searchCount(userGroup.getCompanyId(), null, active, params);
1308 }
1309
1310 public User getUserByContactId(long contactId)
1311 throws PortalException, SystemException {
1312
1313 return userPersistence.findByContactId(contactId);
1314 }
1315
1316 public User getUserByEmailAddress(long companyId, String emailAddress)
1317 throws PortalException, SystemException {
1318
1319 emailAddress = emailAddress.trim().toLowerCase();
1320
1321 return userPersistence.findByC_EA(companyId, emailAddress);
1322 }
1323
1324 public User getUserById(long userId)
1325 throws PortalException, SystemException {
1326
1327 return userPersistence.findByPrimaryKey(userId);
1328 }
1329
1330 public User getUserById(long companyId, long userId)
1331 throws PortalException, SystemException {
1332
1333 return userPersistence.findByC_U(companyId, userId);
1334 }
1335
1336 public User getUserByOpenId(String openId)
1337 throws PortalException, SystemException {
1338
1339 return userPersistence.findByOpenId(openId);
1340 }
1341
1342 public User getUserByPortraitId(long portraitId)
1343 throws PortalException, SystemException {
1344
1345 return userPersistence.findByPortraitId(portraitId);
1346 }
1347
1348 public User getUserByScreenName(long companyId, String screenName)
1349 throws PortalException, SystemException {
1350
1351 screenName = getScreenName(screenName);
1352
1353 return userPersistence.findByC_SN(companyId, screenName);
1354 }
1355
1356 public User getUserByUuid(String uuid)
1357 throws PortalException, SystemException {
1358
1359 List<User> users = userPersistence.findByUuid(uuid);
1360
1361 if (users.isEmpty()) {
1362 throw new NoSuchUserException();
1363 }
1364 else {
1365 return users.get(0);
1366 }
1367 }
1368
1369 public long getUserIdByEmailAddress(long companyId, String emailAddress)
1370 throws PortalException, SystemException {
1371
1372 emailAddress = emailAddress.trim().toLowerCase();
1373
1374 User user = userPersistence.findByC_EA(companyId, emailAddress);
1375
1376 return user.getUserId();
1377 }
1378
1379 public long getUserIdByScreenName(long companyId, String screenName)
1380 throws PortalException, SystemException {
1381
1382 screenName = getScreenName(screenName);
1383
1384 User user = userPersistence.findByC_SN(companyId, screenName);
1385
1386 return user.getUserId();
1387 }
1388
1389 public boolean hasGroupUser(long groupId, long userId)
1390 throws SystemException {
1391
1392 return groupPersistence.containsUser(groupId, userId);
1393 }
1394
1395 public boolean hasOrganizationUser(long organizationId, long userId)
1396 throws SystemException {
1397
1398 return organizationPersistence.containsUser(organizationId, userId);
1399 }
1400
1401 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
1402 throws SystemException {
1403
1404 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
1405 passwordPolicyId, User.class.getName(), userId);
1406 }
1407
1408 public boolean hasRoleUser(long roleId, long userId)
1409 throws SystemException {
1410
1411 return rolePersistence.containsUser(roleId, userId);
1412 }
1413
1414
1419 public boolean hasRoleUser(
1420 long companyId, String name, long userId, boolean inherited)
1421 throws PortalException, SystemException {
1422
1423 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
1424 }
1425
1426 public boolean hasUserGroupUser(long userGroupId, long userId)
1427 throws SystemException {
1428
1429 return userGroupPersistence.containsUser(userGroupId, userId);
1430 }
1431
1432 public boolean isPasswordExpired(User user)
1433 throws PortalException, SystemException {
1434
1435 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1436
1437 if (passwordPolicy.getExpireable()) {
1438 Date now = new Date();
1439
1440 if (user.getPasswordModifiedDate() == null) {
1441 user.setPasswordModifiedDate(now);
1442
1443 userLocalService.updateUser(user, false);
1444 }
1445
1446 long passwordStartTime = user.getPasswordModifiedDate().getTime();
1447 long elapsedTime = now.getTime() - passwordStartTime;
1448
1449 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
1450 return true;
1451 }
1452 else {
1453 return false;
1454 }
1455 }
1456
1457 return false;
1458 }
1459
1460 public boolean isPasswordExpiringSoon(User user)
1461 throws PortalException, SystemException {
1462
1463 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1464
1465 if (passwordPolicy.isExpireable()) {
1466 Date now = new Date();
1467
1468 if (user.getPasswordModifiedDate() == null) {
1469 user.setPasswordModifiedDate(now);
1470
1471 userLocalService.updateUser(user, false);
1472 }
1473
1474 long timeModified = user.getPasswordModifiedDate().getTime();
1475 long passwordExpiresOn =
1476 (passwordPolicy.getMaxAge() * 1000) + timeModified;
1477
1478 long timeStartWarning =
1479 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
1480
1481 if (now.getTime() > timeStartWarning) {
1482 return true;
1483 }
1484 else {
1485 return false;
1486 }
1487 }
1488
1489 return false;
1490 }
1491
1492 public void reIndex(long userId) throws SystemException {
1493 if (SearchEngineUtil.isIndexReadOnly()) {
1494 return;
1495 }
1496
1497 try {
1498 UserIndexer.updateUsers(new long[] {userId});
1499 }
1500 catch (SearchException se) {
1501 throw new SystemException(se);
1502 }
1503 }
1504
1505 public void reIndex(String[] ids) throws SystemException {
1506 if (SearchEngineUtil.isIndexReadOnly()) {
1507 return;
1508 }
1509
1510 long companyId = GetterUtil.getLong(ids[0]);
1511
1512 try {
1513 reIndexUsers(companyId);
1514 }
1515 catch (SystemException se) {
1516 throw se;
1517 }
1518 catch (Exception e) {
1519 throw new SystemException(e);
1520 }
1521 }
1522
1523 public Hits search(
1524 long companyId, String keywords, Boolean active,
1525 LinkedHashMap<String, Object> params, int start, int end, Sort sort)
1526 throws SystemException {
1527
1528 String firstName = null;
1529 String middleName = null;
1530 String lastName = null;
1531 String screenName = null;
1532 String emailAddress = null;
1533 boolean andOperator = false;
1534
1535 if (Validator.isNotNull(keywords)) {
1536 firstName = keywords;
1537 middleName = keywords;
1538 lastName = keywords;
1539 screenName = keywords;
1540 emailAddress = keywords;
1541 }
1542 else {
1543 andOperator = true;
1544 }
1545
1546 return search(
1547 companyId, firstName, middleName, lastName, screenName,
1548 emailAddress, active, params, andOperator, start, end, sort);
1549 }
1550
1551 public Hits search(
1552 long companyId, String firstName, String middleName,
1553 String lastName, String screenName, String emailAddress,
1554 Boolean active, LinkedHashMap<String, Object> params,
1555 boolean andSearch, int start, int end, Sort sort)
1556 throws SystemException {
1557
1558 try {
1559 BooleanQuery contextQuery = BooleanQueryFactoryUtil.create();
1560
1561 contextQuery.addRequiredTerm(
1562 Field.PORTLET_ID, UserIndexer.PORTLET_ID);
1563
1564 if (active != null) {
1565 contextQuery.addRequiredTerm("active", active);
1566 }
1567
1568 BooleanQuery searchQuery = BooleanQueryFactoryUtil.create();
1569
1570 if (Validator.isNotNull(firstName)) {
1571 if (andSearch) {
1572 searchQuery.addRequiredTerm("firstName", firstName, true);
1573 }
1574 else {
1575 searchQuery.addTerm("firstName", firstName, true);
1576 }
1577 }
1578
1579 if (Validator.isNotNull(middleName)) {
1580 if (andSearch) {
1581 searchQuery.addRequiredTerm("middleName", middleName, true);
1582 }
1583 else {
1584 searchQuery.addTerm("middleName", middleName, true);
1585 }
1586 }
1587
1588 if (Validator.isNotNull(lastName)) {
1589 if (andSearch) {
1590 searchQuery.addRequiredTerm("lastName", lastName, true);
1591 }
1592 else {
1593 searchQuery.addTerm("lastName", lastName, true);
1594 }
1595 }
1596
1597 if (Validator.isNotNull(screenName)) {
1598 if (andSearch) {
1599 searchQuery.addRequiredTerm("screenName", screenName, true);
1600 }
1601 else {
1602 searchQuery.addTerm("screenName", screenName, true);
1603 }
1604 }
1605
1606 if (Validator.isNotNull(emailAddress)) {
1607 if (andSearch) {
1608 searchQuery.addRequiredTerm(
1609 "emailAddress", emailAddress, true);
1610 }
1611 else {
1612 searchQuery.addTerm("emailAddress", emailAddress, true);
1613 }
1614 }
1615
1616 populateQuery(contextQuery, searchQuery, params, andSearch);
1617
1618 BooleanQuery fullQuery = BooleanQueryFactoryUtil.create();
1619
1620 fullQuery.add(contextQuery, BooleanClauseOccur.MUST);
1621
1622 if (searchQuery.clauses().size() > 0) {
1623 fullQuery.add(searchQuery, BooleanClauseOccur.MUST);
1624 }
1625
1626 return SearchEngineUtil.search(
1627 companyId, fullQuery, sort, start, end);
1628 }
1629 catch (Exception e) {
1630 throw new SystemException(e);
1631 }
1632 }
1633
1634 public List<User> search(
1635 long companyId, String keywords, Boolean active,
1636 LinkedHashMap<String, Object> params, int start, int end,
1637 OrderByComparator obc)
1638 throws SystemException {
1639
1640 return userFinder.findByKeywords(
1641 companyId, keywords, active, params, start, end, obc);
1642 }
1643
1644 public List<User> search(
1645 long companyId, String firstName, String middleName,
1646 String lastName, String screenName, String emailAddress,
1647 Boolean active, LinkedHashMap<String, Object> params,
1648 boolean andSearch, int start, int end, OrderByComparator obc)
1649 throws SystemException {
1650
1651 return userFinder.findByC_FN_MN_LN_SN_EA_A(
1652 companyId, firstName, middleName, lastName, screenName,
1653 emailAddress, active, params, andSearch, start, end, obc);
1654 }
1655
1656 public int searchCount(
1657 long companyId, String keywords, Boolean active,
1658 LinkedHashMap<String, Object> params)
1659 throws SystemException {
1660
1661 return userFinder.countByKeywords(companyId, keywords, active, params);
1662 }
1663
1664 public int searchCount(
1665 long companyId, String firstName, String middleName,
1666 String lastName, String screenName, String emailAddress,
1667 Boolean active, LinkedHashMap<String, Object> params,
1668 boolean andSearch)
1669 throws SystemException {
1670
1671 return userFinder.countByC_FN_MN_LN_SN_EA_A(
1672 companyId, firstName, middleName, lastName, screenName,
1673 emailAddress, active, params, andSearch);
1674 }
1675
1676 public void sendPassword(
1677 long companyId, String emailAddress, String remoteAddr,
1678 String remoteHost, String userAgent, String fromName,
1679 String fromAddress, String subject, String body)
1680 throws PortalException, SystemException {
1681
1682 try {
1683 doSendPassword(
1684 companyId, emailAddress, remoteAddr, remoteHost, userAgent,
1685 fromName, fromAddress, subject, body);
1686 }
1687 catch (IOException ioe) {
1688 throw new SystemException(ioe);
1689 }
1690 }
1691
1692 public void setRoleUsers(long roleId, long[] userIds)
1693 throws SystemException {
1694
1695 rolePersistence.setUsers(roleId, userIds);
1696
1697 try {
1698 UserIndexer.updateUsers(userIds);
1699 }
1700 catch (SearchException se) {
1701 _log.error("Indexing " + StringUtil.merge(userIds), se);
1702 }
1703
1704 PermissionCacheUtil.clearCache();
1705 }
1706
1707 public void setUserGroupUsers(long userGroupId, long[] userIds)
1708 throws PortalException, SystemException {
1709
1710 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
1711
1712 userGroupPersistence.setUsers(userGroupId, userIds);
1713
1714 try {
1715 UserIndexer.updateUsers(userIds);
1716 }
1717 catch (SearchException se) {
1718 _log.error("Indexing " + StringUtil.merge(userIds), se);
1719 }
1720
1721 PermissionCacheUtil.clearCache();
1722 }
1723
1724 public void unsetGroupUsers(long groupId, long[] userIds)
1725 throws SystemException {
1726
1727 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
1728
1729 groupPersistence.removeUsers(groupId, userIds);
1730
1731 try {
1732 UserIndexer.updateUsers(userIds);
1733 }
1734 catch (SearchException se) {
1735 _log.error("Indexing " + StringUtil.merge(userIds), se);
1736 }
1737
1738 PermissionCacheUtil.clearCache();
1739 }
1740
1741 public void unsetOrganizationUsers(long organizationId, long[] userIds)
1742 throws PortalException, SystemException {
1743
1744 Organization organization = organizationPersistence.findByPrimaryKey(
1745 organizationId);
1746
1747 Group group = organization.getGroup();
1748
1749 long groupId = group.getGroupId();
1750
1751 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
1752
1753 organizationPersistence.removeUsers(organizationId, userIds);
1754
1755 try {
1756 UserIndexer.updateUsers(userIds);
1757 }
1758 catch (SearchException se) {
1759 _log.error("Indexing " + StringUtil.merge(userIds), se);
1760 }
1761
1762 PermissionCacheUtil.clearCache();
1763 }
1764
1765 public void unsetPasswordPolicyUsers(
1766 long passwordPolicyId, long[] userIds)
1767 throws SystemException {
1768
1769 passwordPolicyRelLocalService.deletePasswordPolicyRels(
1770 passwordPolicyId, User.class.getName(), userIds);
1771 }
1772
1773 public void unsetRoleUsers(long roleId, long[] userIds)
1774 throws PortalException, SystemException {
1775
1776 Role role = rolePersistence.findByPrimaryKey(roleId);
1777
1778 if (role.getName().equals(RoleConstants.USER)) {
1779 return;
1780 }
1781
1782 rolePersistence.removeUsers(roleId, userIds);
1783
1784 try {
1785 UserIndexer.updateUsers(userIds);
1786 }
1787 catch (SearchException se) {
1788 _log.error("Indexing " + StringUtil.merge(userIds), se);
1789 }
1790
1791 PermissionCacheUtil.clearCache();
1792 }
1793
1794 public void unsetRoleUsers(long roleId, List<User> users)
1795 throws PortalException, SystemException {
1796
1797 Role role = rolePersistence.findByPrimaryKey(roleId);
1798
1799 if (role.getName().equals(RoleConstants.USER)) {
1800 return;
1801 }
1802
1803 rolePersistence.removeUsers(roleId, users);
1804
1805 try {
1806 UserIndexer.updateUsers(users);
1807 }
1808 catch (SearchException se) {
1809 _log.error("Indexing " + ListUtil.toString(users, "userId"), se);
1810 }
1811
1812 PermissionCacheUtil.clearCache();
1813 }
1814
1815 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
1816 throws SystemException {
1817
1818 userGroupPersistence.removeUsers(userGroupId, userIds);
1819
1820 try {
1821 UserIndexer.updateUsers(userIds);
1822 }
1823 catch (SearchException se) {
1824 _log.error("Indexing " + StringUtil.merge(userIds), se);
1825 }
1826
1827 PermissionCacheUtil.clearCache();
1828 }
1829
1830 public User updateActive(long userId, boolean active)
1831 throws PortalException, SystemException {
1832
1833 User user = userPersistence.findByPrimaryKey(userId);
1834
1835 user.setActive(active);
1836
1837 userPersistence.update(user, false);
1838
1839 try {
1840 UserIndexer.updateUsers(new long[] {userId});
1841 }
1842 catch (SearchException se) {
1843 _log.error("Indexing " + userId, se);
1844 }
1845
1846 return user;
1847 }
1848
1849 public User updateAgreedToTermsOfUse(
1850 long userId, boolean agreedToTermsOfUse)
1851 throws PortalException, SystemException {
1852
1853 User user = userPersistence.findByPrimaryKey(userId);
1854
1855 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
1856
1857 userPersistence.update(user, false);
1858
1859 return user;
1860 }
1861
1862 public User updateCreateDate(long userId, Date createDate)
1863 throws PortalException, SystemException {
1864
1865 User user = userPersistence.findByPrimaryKey(userId);
1866
1867 user.setCreateDate(createDate);
1868
1869 userPersistence.update(user, false);
1870
1871 return user;
1872 }
1873
1874 public User updateEmailAddress(
1875 long userId, String password, String emailAddress1,
1876 String emailAddress2)
1877 throws PortalException, SystemException {
1878
1879 emailAddress1 = emailAddress1.trim().toLowerCase();
1880 emailAddress2 = emailAddress2.trim().toLowerCase();
1881
1882 if (!emailAddress1.equals(emailAddress2)) {
1883 throw new UserEmailAddressException();
1884 }
1885
1886 User user = userPersistence.findByPrimaryKey(userId);
1887
1888 validateEmailAddress(user.getCompanyId(), emailAddress1);
1889 validateEmailAddress(user.getCompanyId(), emailAddress2);
1890
1891 if (!user.getEmailAddress().equalsIgnoreCase(emailAddress1)) {
1892 if (userPersistence.fetchByC_EA(
1893 user.getCompanyId(), emailAddress1) != null) {
1894
1895 throw new DuplicateUserEmailAddressException();
1896 }
1897 }
1898
1899 setEmailAddress(
1900 user, password, user.getFirstName(), user.getMiddleName(),
1901 user.getLastName(), emailAddress1);
1902
1903 userPersistence.update(user, false);
1904
1905 return user;
1906 }
1907
1908 public void updateGroups(long userId, long[] newGroupIds)
1909 throws SystemException {
1910
1911 if (newGroupIds == null) {
1912 return;
1913 }
1914
1915 List<Group> oldGroups = userPersistence.getGroups(userId);
1916
1917 List<Long> oldGroupIds = new ArrayList<Long>(oldGroups.size());
1918
1919 for (Group oldGroup : oldGroups) {
1920 long oldGroupId = oldGroup.getGroupId();
1921
1922 oldGroupIds.add(oldGroupId);
1923
1924 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
1925 unsetGroupUsers(oldGroupId, new long[] {userId});
1926 }
1927 }
1928
1929 for (long newGroupId : newGroupIds) {
1930 if (!oldGroupIds.contains(newGroupId)) {
1931 addGroupUsers(newGroupId, new long[] {userId});
1932 }
1933 }
1934
1935 try {
1936 UserIndexer.updateUsers(new long[] {userId});
1937 }
1938 catch (SearchException se) {
1939 _log.error("Indexing " + userId, se);
1940 }
1941
1942 PermissionCacheUtil.clearCache();
1943 }
1944
1945 public User updateLastLogin(long userId, String loginIP)
1946 throws PortalException, SystemException {
1947
1948 User user = userPersistence.findByPrimaryKey(userId);
1949
1950 Date lastLoginDate = user.getLoginDate();
1951
1952 if (lastLoginDate == null) {
1953 lastLoginDate = new Date();
1954 }
1955
1956 user.setLoginDate(new Date());
1957 user.setLoginIP(loginIP);
1958 user.setLastLoginDate(lastLoginDate);
1959 user.setLastLoginIP(user.getLoginIP());
1960 user.setLastFailedLoginDate(null);
1961 user.setFailedLoginAttempts(0);
1962
1963 userPersistence.update(user, false);
1964
1965 return user;
1966 }
1967
1968 public User updateLockout(User user, boolean lockout)
1969 throws PortalException, SystemException {
1970
1971 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1972
1973 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
1974 return user;
1975 }
1976
1977 Date lockoutDate = null;
1978
1979 if (lockout) {
1980 lockoutDate = new Date();
1981 }
1982
1983 user.setLockout(lockout);
1984 user.setLockoutDate(lockoutDate);
1985
1986 if (!lockout) {
1987 user.setLastFailedLoginDate(lockoutDate);
1988 user.setFailedLoginAttempts(0);
1989 }
1990
1991 userPersistence.update(user, false);
1992
1993 return user;
1994 }
1995
1996 public User updateLockoutByEmailAddress(
1997 long companyId, String emailAddress, boolean lockout)
1998 throws PortalException, SystemException {
1999
2000 User user = getUserByEmailAddress(companyId, emailAddress);
2001
2002 return updateLockout(user, lockout);
2003 }
2004
2005 public User updateLockoutById(long userId, boolean lockout)
2006 throws PortalException, SystemException {
2007
2008 User user = userPersistence.findByPrimaryKey(userId);
2009
2010 return updateLockout(user, lockout);
2011 }
2012
2013 public User updateLockoutByScreenName(
2014 long companyId, String screenName, boolean lockout)
2015 throws PortalException, SystemException {
2016
2017 User user = getUserByScreenName(companyId, screenName);
2018
2019 return updateLockout(user, lockout);
2020 }
2021
2022 public User updateModifiedDate(long userId, Date modifiedDate)
2023 throws PortalException, SystemException {
2024
2025 User user = userPersistence.findByPrimaryKey(userId);
2026
2027 user.setModifiedDate(modifiedDate);
2028
2029 userPersistence.update(user, false);
2030
2031 return user;
2032 }
2033
2034 public void updateOpenId(long userId, String openId)
2035 throws PortalException, SystemException {
2036
2037 openId = openId.trim();
2038
2039 User user = userPersistence.findByPrimaryKey(userId);
2040
2041 user.setOpenId(openId);
2042
2043 userPersistence.update(user, false);
2044 }
2045
2046 public void updateOrganizations(long userId, long[] newOrganizationIds)
2047 throws PortalException, SystemException {
2048
2049 if (newOrganizationIds == null) {
2050 return;
2051 }
2052
2053 List<Organization> oldOrganizations = userPersistence.getOrganizations(
2054 userId);
2055
2056 List<Long> oldOrganizationIds = new ArrayList<Long>(
2057 oldOrganizations.size());
2058
2059 for (Organization oldOrganization : oldOrganizations) {
2060 long oldOrganizationId = oldOrganization.getOrganizationId();
2061
2062 oldOrganizationIds.add(oldOrganizationId);
2063
2064 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
2065 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
2066 }
2067 }
2068
2069 for (long newOrganizationId : newOrganizationIds) {
2070 if (!oldOrganizationIds.contains(newOrganizationId)) {
2071 addOrganizationUsers(newOrganizationId, new long[] {userId});
2072 }
2073 }
2074
2075 try {
2076 UserIndexer.updateUsers(new long[] {userId});
2077 }
2078 catch (SearchException se) {
2079 _log.error("Indexing " + userId, se);
2080 }
2081
2082 PermissionCacheUtil.clearCache();
2083 }
2084
2085 public User updatePassword(
2086 long userId, String password1, String password2,
2087 boolean passwordReset)
2088 throws PortalException, SystemException {
2089
2090 return updatePassword(
2091 userId, password1, password2, passwordReset, false);
2092 }
2093
2094 public User updatePassword(
2095 long userId, String password1, String password2,
2096 boolean passwordReset, boolean silentUpdate)
2097 throws PortalException, SystemException {
2098
2099 User user = userPersistence.findByPrimaryKey(userId);
2100
2101
2104 if (!silentUpdate) {
2105 validatePassword(user.getCompanyId(), userId, password1, password2);
2106 }
2107
2108 String oldEncPwd = user.getPassword();
2109
2110 if (!user.isPasswordEncrypted()) {
2111 oldEncPwd = PwdEncryptor.encrypt(user.getPassword());
2112 }
2113
2114 String newEncPwd = PwdEncryptor.encrypt(password1);
2115
2116 if (user.hasCompanyMx()) {
2117 mailService.updatePassword(user.getCompanyId(), userId, password1);
2118 }
2119
2120 user.setPassword(newEncPwd);
2121 user.setPasswordUnencrypted(password1);
2122 user.setPasswordEncrypted(true);
2123 user.setPasswordReset(passwordReset);
2124 user.setPasswordModifiedDate(new Date());
2125 user.setGraceLoginCount(0);
2126
2127 if (!silentUpdate) {
2128 user.setPasswordModified(true);
2129 }
2130
2131 try {
2132 userPersistence.update(user, false);
2133 }
2134 catch (ModelListenerException mle) {
2135 String msg = GetterUtil.getString(mle.getCause().getMessage());
2136
2137 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
2138 String passwordHistory = PrefsPropsUtil.getString(
2139 user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
2140
2141 if (msg.indexOf(passwordHistory) != -1) {
2142 throw new UserPasswordException(
2143 UserPasswordException.PASSWORD_ALREADY_USED);
2144 }
2145 }
2146
2147 throw new UserPasswordException(
2148 UserPasswordException.PASSWORD_INVALID);
2149 }
2150
2151 if (!silentUpdate) {
2152 user.setPasswordModified(false);
2153
2154 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
2155 }
2156
2157 return user;
2158 }
2159
2160 public User updatePasswordManually(
2161 long userId, String password, boolean passwordEncrypted,
2162 boolean passwordReset, Date passwordModifiedDate)
2163 throws PortalException, SystemException {
2164
2165
2167 User user = userPersistence.findByPrimaryKey(userId);
2168
2169 user.setPassword(password);
2170 user.setPasswordEncrypted(passwordEncrypted);
2171 user.setPasswordReset(passwordReset);
2172 user.setPasswordModifiedDate(passwordModifiedDate);
2173
2174 userPersistence.update(user, false);
2175
2176 return user;
2177 }
2178
2179 public void updatePasswordReset(long userId, boolean passwordReset)
2180 throws PortalException, SystemException {
2181
2182 User user = userPersistence.findByPrimaryKey(userId);
2183
2184 user.setPasswordReset(passwordReset);
2185
2186 userPersistence.update(user, false);
2187 }
2188
2189 public void updatePortrait(long userId, byte[] bytes)
2190 throws PortalException, SystemException {
2191
2192 User user = userPersistence.findByPrimaryKey(userId);
2193
2194 long imageMaxSize = PrefsPropsUtil.getLong(
2195 PropsKeys.USERS_IMAGE_MAX_SIZE);
2196
2197 if ((imageMaxSize > 0) &&
2198 ((bytes == null) || (bytes.length > imageMaxSize))) {
2199
2200 throw new UserPortraitSizeException();
2201 }
2202
2203 long portraitId = user.getPortraitId();
2204
2205 if (portraitId <= 0) {
2206 portraitId = counterLocalService.increment();
2207
2208 user.setPortraitId(portraitId);
2209
2210 userPersistence.update(user, false);
2211 }
2212
2213 try {
2214 ImageBag imageBag = ImageProcessorUtil.read(bytes);
2215
2216 RenderedImage renderedImage = imageBag.getRenderedImage();
2217
2218 if (renderedImage == null) {
2219 throw new UserPortraitTypeException();
2220 }
2221
2222 renderedImage = ImageProcessorUtil.scale(
2223 renderedImage, PropsValues.USERS_IMAGE_MAX_HEIGHT,
2224 PropsValues.USERS_IMAGE_MAX_WIDTH);
2225
2226 String contentType = imageBag.getType();
2227
2228 imageLocalService.updateImage(
2229 portraitId,
2230 ImageProcessorUtil.getBytes(renderedImage, contentType));
2231 }
2232 catch (IOException ioe) {
2233 throw new ImageSizeException(ioe);
2234 }
2235 }
2236
2237 public void updateReminderQuery(long userId, String question, String answer)
2238 throws PortalException, SystemException {
2239
2240 validateReminderQuery(question, answer) ;
2241
2242 User user = userPersistence.findByPrimaryKey(userId);
2243
2244 user.setReminderQueryQuestion(question);
2245 user.setReminderQueryAnswer(answer);
2246
2247 userPersistence.update(user, false);
2248 }
2249
2250 public void updateScreenName(long userId, String screenName)
2251 throws PortalException, SystemException {
2252
2253
2255 User user = userPersistence.findByPrimaryKey(userId);
2256
2257 screenName = getScreenName(screenName);
2258
2259 validateScreenName(user.getCompanyId(), userId, screenName);
2260
2261 user.setScreenName(screenName);
2262
2263 userPersistence.update(user, false);
2264
2265
2267 Group group = groupLocalService.getUserGroup(
2268 user.getCompanyId(), userId);
2269
2270 group.setFriendlyURL(StringPool.SLASH + screenName);
2271
2272 groupPersistence.update(group, false);
2273 }
2274
2275 public User updateUser(
2276 long userId, String oldPassword, String newPassword1,
2277 String newPassword2, boolean passwordReset,
2278 String reminderQueryQuestion, String reminderQueryAnswer,
2279 String screenName, String emailAddress, String openId,
2280 String languageId, String timeZoneId, String greeting,
2281 String comments, String firstName, String middleName,
2282 String lastName, int prefixId, int suffixId, boolean male,
2283 int birthdayMonth, int birthdayDay, int birthdayYear, String smsSn,
2284 String aimSn, String facebookSn, String icqSn, String jabberSn,
2285 String msnSn, String mySpaceSn, String skypeSn, String twitterSn,
2286 String ymSn, String jobTitle, long[] groupIds,
2287 long[] organizationIds, long[] roleIds,
2288 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
2289 ServiceContext serviceContext)
2290 throws PortalException, SystemException {
2291
2292
2294 User user = userPersistence.findByPrimaryKey(userId);
2295 Company company = companyPersistence.findByPrimaryKey(
2296 user.getCompanyId());
2297 String password = oldPassword;
2298 screenName = getScreenName(screenName);
2299 emailAddress = emailAddress.trim().toLowerCase();
2300 openId = openId.trim();
2301 aimSn = aimSn.trim().toLowerCase();
2302 facebookSn = facebookSn.trim().toLowerCase();
2303 icqSn = icqSn.trim().toLowerCase();
2304 jabberSn = jabberSn.trim().toLowerCase();
2305 msnSn = msnSn.trim().toLowerCase();
2306 mySpaceSn = mySpaceSn.trim().toLowerCase();
2307 skypeSn = skypeSn.trim().toLowerCase();
2308 twitterSn = twitterSn.trim().toLowerCase();
2309 ymSn = ymSn.trim().toLowerCase();
2310 Date now = new Date();
2311
2312 EmailAddressGenerator emailAddressGenerator =
2313 EmailAddressGeneratorFactory.getInstance();
2314
2315 if (emailAddressGenerator.isGenerated(emailAddress)) {
2316 emailAddress = StringPool.BLANK;
2317 }
2318
2319 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
2320 Validator.isNull(emailAddress)) {
2321
2322 emailAddress = emailAddressGenerator.generate(
2323 user.getCompanyId(), userId);
2324 }
2325
2326 validate(
2327 userId, screenName, emailAddress, firstName, middleName, lastName,
2328 smsSn);
2329
2330 if (Validator.isNotNull(newPassword1) ||
2331 Validator.isNotNull(newPassword2)) {
2332
2333 user = updatePassword(
2334 userId, newPassword1, newPassword2, passwordReset);
2335
2336 password = newPassword1;
2337 }
2338
2339 user.setModifiedDate(now);
2340
2341 if (user.getContactId() <= 0) {
2342 user.setContactId(counterLocalService.increment());
2343 }
2344
2345 user.setPasswordReset(passwordReset);
2346
2347 if (Validator.isNotNull(reminderQueryQuestion) &&
2348 Validator.isNotNull(reminderQueryAnswer)) {
2349
2350 user.setReminderQueryQuestion(reminderQueryQuestion);
2351 user.setReminderQueryAnswer(reminderQueryAnswer);
2352 }
2353
2354 user.setScreenName(screenName);
2355
2356 setEmailAddress(
2357 user, password, firstName, middleName, lastName, emailAddress);
2358
2359 user.setOpenId(openId);
2360 user.setLanguageId(languageId);
2361 user.setTimeZoneId(timeZoneId);
2362 user.setGreeting(greeting);
2363 user.setComments(comments);
2364 user.setFirstName(firstName);
2365 user.setMiddleName(middleName);
2366 user.setLastName(lastName);
2367 user.setJobTitle(jobTitle);
2368
2369 userPersistence.update(user, false);
2370
2371
2373 user.setExpandoBridgeAttributes(serviceContext);
2374
2375
2377 Date birthday = PortalUtil.getDate(
2378 birthdayMonth, birthdayDay, birthdayYear,
2379 new ContactBirthdayException());
2380
2381 long contactId = user.getContactId();
2382
2383 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
2384
2385 if (contact == null) {
2386 contact = contactPersistence.create(contactId);
2387
2388 contact.setCompanyId(user.getCompanyId());
2389 contact.setUserName(StringPool.BLANK);
2390 contact.setCreateDate(now);
2391 contact.setAccountId(company.getAccountId());
2392 contact.setParentContactId(
2393 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
2394 }
2395
2396 contact.setModifiedDate(now);
2397 contact.setFirstName(firstName);
2398 contact.setMiddleName(middleName);
2399 contact.setLastName(lastName);
2400 contact.setPrefixId(prefixId);
2401 contact.setSuffixId(suffixId);
2402 contact.setMale(male);
2403 contact.setBirthday(birthday);
2404 contact.setSmsSn(smsSn);
2405 contact.setAimSn(aimSn);
2406 contact.setFacebookSn(facebookSn);
2407 contact.setIcqSn(icqSn);
2408 contact.setJabberSn(jabberSn);
2409 contact.setMsnSn(msnSn);
2410 contact.setMySpaceSn(mySpaceSn);
2411 contact.setSkypeSn(skypeSn);
2412 contact.setTwitterSn(twitterSn);
2413 contact.setYmSn(ymSn);
2414 contact.setJobTitle(jobTitle);
2415
2416 contactPersistence.update(contact, false);
2417
2418
2420 Group group = groupLocalService.getUserGroup(
2421 user.getCompanyId(), userId);
2422
2423 group.setFriendlyURL(StringPool.SLASH + screenName);
2424
2425 groupPersistence.update(group, false);
2426
2427
2429 updateGroups(userId, groupIds);
2430
2431
2433 updateOrganizations(userId, organizationIds);
2434
2435
2437 if (roleIds != null) {
2438 roleIds = EnterpriseAdminUtil.addRequiredRoles(user, roleIds);
2439
2440 userPersistence.setRoles(userId, roleIds);
2441 }
2442
2443
2445 updateUserGroupRoles(user, groupIds, organizationIds, userGroupRoles);
2446
2447
2449 if (userGroupIds != null) {
2450 userGroupLocalService.copyUserGroupLayouts(userGroupIds, userId);
2451
2452 userPersistence.setUserGroups(userId, userGroupIds);
2453 }
2454
2455
2457 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
2458
2459
2461 if (serviceContext != null) {
2462 updateTagsAsset(userId, user, serviceContext.getTagsEntries());
2463 }
2464
2465
2467 try {
2468 UserIndexer.updateUser(user);
2469 }
2470 catch (SearchException se) {
2471 _log.error("Indexing " + userId, se);
2472 }
2473
2474
2476 PermissionCacheUtil.clearCache();
2477
2478 return user;
2479 }
2480
2481 public void updateTagsAsset(long userId, User user, String[] tagsEntries)
2482 throws PortalException, SystemException {
2483
2484 tagsAssetLocalService.updateAsset(
2485 userId, 0, User.class.getName(), user.getUserId(), null,
2486 tagsEntries, true, null, null, null, null, null, user.getFullName(),
2487 null, null, null, 0, 0, null, false);
2488 }
2489
2490 protected int authenticate(
2491 long companyId, String login, String password, String authType,
2492 Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
2493 throws PortalException, SystemException {
2494
2495 login = login.trim().toLowerCase();
2496
2497 long userId = GetterUtil.getLong(login);
2498
2499
2501 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2502 if (!Validator.isEmailAddress(login)) {
2503 throw new UserEmailAddressException();
2504 }
2505 }
2506 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2507 if (Validator.isNull(login)) {
2508 throw new UserScreenNameException();
2509 }
2510 }
2511 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2512 if (Validator.isNull(login)) {
2513 throw new UserIdException();
2514 }
2515 }
2516
2517 if (Validator.isNull(password)) {
2518 throw new UserPasswordException(
2519 UserPasswordException.PASSWORD_INVALID);
2520 }
2521
2522 int authResult = Authenticator.FAILURE;
2523
2524
2526 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2527 authResult = AuthPipeline.authenticateByEmailAddress(
2528 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
2529 headerMap, parameterMap);
2530 }
2531 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2532 authResult = AuthPipeline.authenticateByScreenName(
2533 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
2534 headerMap, parameterMap);
2535 }
2536 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2537 authResult = AuthPipeline.authenticateByUserId(
2538 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
2539 headerMap, parameterMap);
2540 }
2541
2542
2544 User user = null;
2545
2546 try {
2547 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2548 user = userPersistence.findByC_EA(companyId, login);
2549 }
2550 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2551 user = userPersistence.findByC_SN(companyId, login);
2552 }
2553 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2554 user = userPersistence.findByC_U(
2555 companyId, GetterUtil.getLong(login));
2556 }
2557 }
2558 catch (NoSuchUserException nsue) {
2559 return Authenticator.DNE;
2560 }
2561
2562 if (user.isDefaultUser()) {
2563 _log.error(
2564 "The default user should never be allowed to authenticate");
2565
2566 return Authenticator.DNE;
2567 }
2568
2569 if (!user.isPasswordEncrypted()) {
2570 user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
2571 user.setPasswordEncrypted(true);
2572
2573 userPersistence.update(user, false);
2574 }
2575
2576
2579 checkLockout(user);
2580
2581 checkPasswordExpired(user);
2582
2583
2585 if (authResult == Authenticator.SUCCESS) {
2586 if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
2587 String encPassword = PwdEncryptor.encrypt(
2588 password, user.getPassword());
2589
2590 if (user.getPassword().equals(encPassword)) {
2591 authResult = Authenticator.SUCCESS;
2592 }
2593 else if (GetterUtil.getBoolean(PropsUtil.get(
2594 PropsKeys.AUTH_MAC_ALLOW))) {
2595
2596 try {
2597 MessageDigest digester = MessageDigest.getInstance(
2598 PropsUtil.get(PropsKeys.AUTH_MAC_ALGORITHM));
2599
2600 digester.update(login.getBytes("UTF8"));
2601
2602 String shardKey =
2603 PropsUtil.get(PropsKeys.AUTH_MAC_SHARED_KEY);
2604
2605 encPassword = Base64.encode(
2606 digester.digest(shardKey.getBytes("UTF8")));
2607
2608 if (password.equals(encPassword)) {
2609 authResult = Authenticator.SUCCESS;
2610 }
2611 else {
2612 authResult = Authenticator.FAILURE;
2613 }
2614 }
2615 catch (NoSuchAlgorithmException nsae) {
2616 throw new SystemException(nsae);
2617 }
2618 catch (UnsupportedEncodingException uee) {
2619 throw new SystemException(uee);
2620 }
2621 }
2622 else {
2623 authResult = Authenticator.FAILURE;
2624 }
2625 }
2626 }
2627
2628
2630 if (authResult == Authenticator.SUCCESS) {
2631 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2632 authResult = AuthPipeline.authenticateByEmailAddress(
2633 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
2634 headerMap, parameterMap);
2635 }
2636 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2637 authResult = AuthPipeline.authenticateByScreenName(
2638 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
2639 headerMap, parameterMap);
2640 }
2641 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2642 authResult = AuthPipeline.authenticateByUserId(
2643 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
2644 headerMap, parameterMap);
2645 }
2646 }
2647
2648
2650 if (authResult == Authenticator.FAILURE) {
2651 try {
2652 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2653 AuthPipeline.onFailureByEmailAddress(
2654 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
2655 parameterMap);
2656 }
2657 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2658 AuthPipeline.onFailureByScreenName(
2659 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
2660 parameterMap);
2661 }
2662 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2663 AuthPipeline.onFailureByUserId(
2664 PropsKeys.AUTH_FAILURE, companyId, userId, headerMap,
2665 parameterMap);
2666 }
2667
2668
2670 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
2671 user.getCompanyId())) {
2672
2673 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2674
2675 int failedLoginAttempts = user.getFailedLoginAttempts();
2676 int maxFailures = passwordPolicy.getMaxFailure();
2677
2678 if ((failedLoginAttempts >= maxFailures) &&
2679 (maxFailures != 0)) {
2680
2681 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2682 AuthPipeline.onMaxFailuresByEmailAddress(
2683 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
2684 headerMap, parameterMap);
2685 }
2686 else if (authType.equals(
2687 CompanyConstants.AUTH_TYPE_SN)) {
2688
2689 AuthPipeline.onMaxFailuresByScreenName(
2690 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
2691 headerMap, parameterMap);
2692 }
2693 else if (authType.equals(
2694 CompanyConstants.AUTH_TYPE_ID)) {
2695
2696 AuthPipeline.onMaxFailuresByUserId(
2697 PropsKeys.AUTH_MAX_FAILURES, companyId, userId,
2698 headerMap, parameterMap);
2699 }
2700 }
2701 }
2702 }
2703 catch (Exception e) {
2704 _log.error(e, e);
2705 }
2706 }
2707
2708 return authResult;
2709 }
2710
2711 protected void doSendPassword(
2712 long companyId, String emailAddress, String remoteAddr,
2713 String remoteHost, String userAgent, String fromName,
2714 String fromAddress, String subject, String body)
2715 throws IOException, PortalException, SystemException {
2716
2717 if (!PrefsPropsUtil.getBoolean(
2718 companyId, PropsKeys.COMPANY_SECURITY_SEND_PASSWORD) ||
2719 !PrefsPropsUtil.getBoolean(
2720 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_ENABLED)) {
2721
2722 return;
2723 }
2724
2725 emailAddress = emailAddress.trim().toLowerCase();
2726
2727 if (!Validator.isEmailAddress(emailAddress)) {
2728 throw new UserEmailAddressException();
2729 }
2730
2731 Company company = companyPersistence.findByPrimaryKey(companyId);
2732
2733 User user = userPersistence.findByC_EA(companyId, emailAddress);
2734
2735 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2736
2737
2740
2741 String newPassword = null;
2742
2743 if (!PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
2744 PwdEncryptor.TYPE_NONE)) {
2745
2746 newPassword = PwdToolkitUtil.generate();
2747
2748 boolean passwordReset = false;
2749
2750 if (passwordPolicy.getChangeable() &&
2751 passwordPolicy.getChangeRequired()) {
2752
2753 passwordReset = true;
2754 }
2755
2756 user.setPassword(PwdEncryptor.encrypt(newPassword));
2757 user.setPasswordUnencrypted(newPassword);
2758 user.setPasswordEncrypted(true);
2759 user.setPasswordReset(passwordReset);
2760 user.setPasswordModified(true);
2761 user.setPasswordModifiedDate(new Date());
2762
2763 userPersistence.update(user, false);
2764
2765 user.setPasswordModified(false);
2766 }
2767 else {
2768 newPassword = user.getPassword();
2769 }
2770
2771 if (Validator.isNull(fromName)) {
2772 fromName = PrefsPropsUtil.getString(
2773 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
2774 }
2775
2776 if (Validator.isNull(fromAddress)) {
2777 fromAddress = PrefsPropsUtil.getString(
2778 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
2779 }
2780
2781 String toName = user.getFullName();
2782 String toAddress = user.getEmailAddress();
2783
2784 if (Validator.isNull(subject)) {
2785 subject = PrefsPropsUtil.getContent(
2786 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
2787 }
2788
2789 if (Validator.isNull(body)) {
2790 body = PrefsPropsUtil.getContent(
2791 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
2792 }
2793
2794 subject = StringUtil.replace(
2795 subject,
2796 new String[] {
2797 "[$FROM_ADDRESS$]",
2798 "[$FROM_NAME$]",
2799 "[$PORTAL_URL$]",
2800 "[$REMOTE_ADDRESS$]",
2801 "[$REMOTE_HOST$]",
2802 "[$TO_ADDRESS$]",
2803 "[$TO_NAME$]",
2804 "[$USER_AGENT$]",
2805 "[$USER_ID$]",
2806 "[$USER_PASSWORD$]",
2807 "[$USER_SCREENNAME$]"
2808 },
2809 new String[] {
2810 fromAddress,
2811 fromName,
2812 company.getVirtualHost(),
2813 remoteAddr,
2814 remoteHost,
2815 toAddress,
2816 toName,
2817 HtmlUtil.escape(userAgent),
2818 String.valueOf(user.getUserId()),
2819 newPassword,
2820 user.getScreenName()
2821 });
2822
2823 body = StringUtil.replace(
2824 body,
2825 new String[] {
2826 "[$FROM_ADDRESS$]",
2827 "[$FROM_NAME$]",
2828 "[$PORTAL_URL$]",
2829 "[$REMOTE_ADDRESS$]",
2830 "[$REMOTE_HOST$]",
2831 "[$TO_ADDRESS$]",
2832 "[$TO_NAME$]",
2833 "[$USER_AGENT$]",
2834 "[$USER_ID$]",
2835 "[$USER_PASSWORD$]",
2836 "[$USER_SCREENNAME$]"
2837 },
2838 new String[] {
2839 fromAddress,
2840 fromName,
2841 company.getVirtualHost(),
2842 remoteAddr,
2843 remoteHost,
2844 toAddress,
2845 toName,
2846 HtmlUtil.escape(userAgent),
2847 String.valueOf(user.getUserId()),
2848 newPassword,
2849 user.getScreenName()
2850 });
2851
2852 InternetAddress from = new InternetAddress(fromAddress, fromName);
2853
2854 InternetAddress to = new InternetAddress(toAddress, toName);
2855
2856 MailMessage message = new MailMessage(from, to, subject, body, true);
2857
2858 mailService.sendEmail(message);
2859 }
2860
2861 protected String getScreenName(String screenName) {
2862 return StringUtil.lowerCase(StringUtil.trim(screenName));
2863 }
2864
2865 protected long[] getUserIds(List<User> users) {
2866 long[] userIds = new long[users.size()];
2867
2868 for (int i = 0; i < users.size(); i++) {
2869 User user = users.get(i);
2870
2871 userIds[i] = user.getUserId();
2872 }
2873
2874 return userIds;
2875 }
2876
2877 protected void populateQuery(
2878 BooleanQuery contextQuery, BooleanQuery searchQuery,
2879 LinkedHashMap<String, Object> params, boolean andSearch)
2880 throws ParseException {
2881
2882 if (params == null) {
2883 return;
2884 }
2885
2886 ExpandoBridge expandoBridge = ExpandoBridgeFactoryUtil.getExpandoBridge(
2887 User.class.getName());
2888
2889 Set<String> attributeNames = SetUtil.fromEnumeration(
2890 expandoBridge.getAttributeNames());
2891
2892 for (Map.Entry<String, Object> entry : params.entrySet()) {
2893 String key = entry.getKey();
2894 Object value = entry.getValue();
2895
2896 if (value == null) {
2897 continue;
2898 }
2899
2900 populateQuery(
2901 contextQuery, searchQuery, expandoBridge, attributeNames,
2902 key, value, andSearch);
2903 }
2904 }
2905
2906 protected void populateQuery(
2907 BooleanQuery contextQuery, BooleanQuery searchQuery,
2908 ExpandoBridge expandoBridge, Set<String> attributeNames,
2909 String key, Object value, boolean andSearch)
2910 throws ParseException {
2911
2912 if (key.equals("usersOrgs")) {
2913 if (value instanceof Long[]) {
2914 Long[] values = (Long[])value;
2915
2916 BooleanQuery usersOrgsQuery = BooleanQueryFactoryUtil.create();
2917
2918 for (long organizationId : values) {
2919 usersOrgsQuery.addTerm("organizationIds", organizationId);
2920 usersOrgsQuery.addTerm(
2921 "ancestorOrganizationIds", organizationId);
2922 }
2923
2924 contextQuery.add(usersOrgsQuery, BooleanClauseOccur.MUST);
2925 }
2926 else {
2927 contextQuery.addRequiredTerm(
2928 "organizationIds", String.valueOf(value));
2929 }
2930 }
2931 else if (key.equals("usersRoles")) {
2932 contextQuery.addRequiredTerm("roleIds", String.valueOf(value));
2933 }
2934 else if (key.equals("usersUserGroups")) {
2935 contextQuery.addRequiredTerm("userGroupIds", String.valueOf(value));
2936 }
2937 else if (attributeNames.contains(key)) {
2938 UnicodeProperties properties = expandoBridge.getAttributeProperties(
2939 key);
2940
2941 if (GetterUtil.getBoolean(
2942 properties.getProperty(ExpandoBridgeIndexer.INDEXABLE))) {
2943
2944 int type = expandoBridge.getAttributeType(key);
2945
2946 if ((type == ExpandoColumnConstants.STRING) &&
2947 (Validator.isNotNull((String)value))) {
2948
2949 if (andSearch) {
2950 searchQuery.addRequiredTerm(key, (String)value, true);
2951 }
2952 else {
2953 searchQuery.addTerm(key, (String)value, true);
2954 }
2955 }
2956 }
2957 }
2958 else if (Validator.isNotNull(key) && Validator.isNotNull(value)) {
2959 if (andSearch) {
2960 searchQuery.addRequiredTerm(key, String.valueOf(value));
2961 }
2962 else {
2963 searchQuery.addTerm(key, String.valueOf(value));
2964 }
2965 }
2966 }
2967
2968 protected void reIndexUsers(long companyId) throws SystemException {
2969 int count = userPersistence.countByCompanyId(companyId);
2970
2971 int pages = count / UserIndexer.DEFAULT_INTERVAL;
2972
2973 for (int i = 0; i <= pages; i++) {
2974 int start = (i * UserIndexer.DEFAULT_INTERVAL);
2975 int end = start + UserIndexer.DEFAULT_INTERVAL;
2976
2977 reIndexUsers(companyId, start, end);
2978 }
2979 }
2980
2981 protected void reIndexUsers(long companyId, int start, int end)
2982 throws SystemException {
2983
2984 List<User> users = userPersistence.findByCompanyId(
2985 companyId, start, end);
2986
2987 for (User user : users) {
2988 try {
2989 UserIndexer.updateUser(user);
2990 }
2991 catch (SearchException se) {
2992 _log.error("Reindexing " + user.getUserId(), se);
2993 }
2994 }
2995 }
2996
2997 protected void sendEmail(User user, String password)
2998 throws IOException, PortalException, SystemException {
2999
3000 if (!PrefsPropsUtil.getBoolean(
3001 user.getCompanyId(),
3002 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
3003
3004 return;
3005 }
3006
3007 long companyId = user.getCompanyId();
3008
3009 Company company = companyPersistence.findByPrimaryKey(companyId);
3010
3011 String fromName = PrefsPropsUtil.getString(
3012 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3013 String fromAddress = PrefsPropsUtil.getString(
3014 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3015
3016 String toName = user.getFullName();
3017 String toAddress = user.getEmailAddress();
3018
3019 String subject = PrefsPropsUtil.getContent(
3020 companyId, PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
3021 String body = PrefsPropsUtil.getContent(
3022 companyId, PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
3023
3024 subject = StringUtil.replace(
3025 subject,
3026 new String[] {
3027 "[$FROM_ADDRESS$]",
3028 "[$FROM_NAME$]",
3029 "[$PORTAL_URL$]",
3030 "[$TO_ADDRESS$]",
3031 "[$TO_NAME$]",
3032 "[$USER_ID$]",
3033 "[$USER_PASSWORD$]",
3034 "[$USER_SCREENNAME$]"
3035 },
3036 new String[] {
3037 fromAddress,
3038 fromName,
3039 company.getVirtualHost(),
3040 toAddress,
3041 toName,
3042 String.valueOf(user.getUserId()),
3043 password,
3044 user.getScreenName()
3045 });
3046
3047 body = StringUtil.replace(
3048 body,
3049 new String[] {
3050 "[$FROM_ADDRESS$]",
3051 "[$FROM_NAME$]",
3052 "[$PORTAL_URL$]",
3053 "[$TO_ADDRESS$]",
3054 "[$TO_NAME$]",
3055 "[$USER_ID$]",
3056 "[$USER_PASSWORD$]",
3057 "[$USER_SCREENNAME$]"
3058 },
3059 new String[] {
3060 fromAddress,
3061 fromName,
3062 company.getVirtualHost(),
3063 toAddress,
3064 toName,
3065 String.valueOf(user.getUserId()),
3066 password,
3067 user.getScreenName()
3068 });
3069
3070 InternetAddress from = new InternetAddress(fromAddress, fromName);
3071
3072 InternetAddress to = new InternetAddress(toAddress, toName);
3073
3074 MailMessage message = new MailMessage(from, to, subject, body, true);
3075
3076 mailService.sendEmail(message);
3077 }
3078
3079 protected void setEmailAddress(
3080 User user, String password, String firstName, String middleName,
3081 String lastName, String emailAddress) {
3082
3083 if (emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
3084 return;
3085 }
3086
3087 long userId = user.getUserId();
3088
3089
3091 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
3092 mailService.addUser(
3093 user.getCompanyId(), userId, password, firstName, middleName,
3094 lastName, emailAddress);
3095 }
3096
3097
3099 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
3100 mailService.updateEmailAddress(
3101 user.getCompanyId(), userId, emailAddress);
3102 }
3103
3104
3106 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
3107 mailService.deleteEmailAddress(user.getCompanyId(), userId);
3108 }
3109
3110 user.setEmailAddress(emailAddress);
3111 }
3112
3113 protected void updateUserGroupRoles(
3114 User user, long[] groupIds, long[] organizationIds,
3115 List<UserGroupRole> userGroupRoles)
3116 throws PortalException, SystemException {
3117
3118 if (userGroupRoles == null) {
3119 return;
3120 }
3121
3122 List<UserGroupRole> previousUserGroupRoles =
3123 userGroupRolePersistence.findByUserId(user.getUserId());
3124
3125 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
3126 if (userGroupRoles.contains(userGroupRole)) {
3127 userGroupRoles.remove(userGroupRole);
3128 }
3129 else {
3130 userGroupRoleLocalService.deleteUserGroupRole(
3131 userGroupRole);
3132 }
3133 }
3134
3135 long[] validGroupIds = null;
3136
3137 if (groupIds != null) {
3138 validGroupIds = ArrayUtil.clone(groupIds);
3139 }
3140 else {
3141 validGroupIds = user.getGroupIds();
3142 }
3143
3144 if (organizationIds == null) {
3145 organizationIds = user.getOrganizationIds();
3146 }
3147
3148 long[] organizationGroupIds = new long[organizationIds.length];
3149
3150 for (int i = 0; i < organizationIds.length; i++) {
3151 long organizationId = organizationIds[i];
3152
3153 Organization organization =
3154 organizationPersistence.findByPrimaryKey(
3155 organizationId);
3156
3157 Group organizationGroup = organization.getGroup();
3158
3159 organizationGroupIds[i] = organizationGroup.getGroupId();
3160 }
3161
3162 validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
3163
3164 Arrays.sort(validGroupIds);
3165
3166 for (UserGroupRole userGroupRole : userGroupRoles) {
3167 if (Arrays.binarySearch(
3168 validGroupIds, userGroupRole.getGroupId()) >= 0) {
3169
3170 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
3171 }
3172 }
3173 }
3174
3175 protected void validate(
3176 long userId, String screenName, String emailAddress,
3177 String firstName, String middleName, String lastName, String smsSn)
3178 throws PortalException, SystemException {
3179
3180 User user = userPersistence.findByPrimaryKey(userId);
3181
3182 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
3183 validateScreenName(user.getCompanyId(), userId, screenName);
3184 }
3185
3186 validateEmailAddress(user.getCompanyId(), emailAddress);
3187
3188 if (!user.isDefaultUser()) {
3189 if (Validator.isNotNull(emailAddress) &&
3190 !user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
3191
3192 if (userPersistence.fetchByC_EA(
3193 user.getCompanyId(), emailAddress) != null) {
3194
3195 throw new DuplicateUserEmailAddressException();
3196 }
3197 }
3198
3199 validateFullName(
3200 user.getCompanyId(), firstName, middleName, lastName);
3201 }
3202
3203 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
3204 throw new UserSmsException();
3205 }
3206 }
3207
3208 protected void validate(
3209 long companyId, long userId, boolean autoPassword, String password1,
3210 String password2, boolean autoScreenName, String screenName,
3211 String emailAddress, String firstName, String middleName,
3212 String lastName, long[] organizationIds)
3213 throws PortalException, SystemException {
3214
3215 Company company = companyPersistence.findByPrimaryKey(companyId);
3216
3217 if (company.isSystem()) {
3218 return;
3219 }
3220
3221 if (!autoScreenName) {
3222 validateScreenName(companyId, userId, screenName);
3223 }
3224
3225 if (!autoPassword) {
3226 PasswordPolicy passwordPolicy =
3227 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
3228
3229 PwdToolkitUtil.validate(
3230 companyId, 0, password1, password2, passwordPolicy);
3231 }
3232
3233 validateEmailAddress(companyId, emailAddress);
3234
3235 if (Validator.isNotNull(emailAddress)) {
3236 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
3237
3238 if (user != null) {
3239 throw new DuplicateUserEmailAddressException();
3240 }
3241 }
3242
3243 validateFullName(companyId, firstName, middleName, lastName);
3244 }
3245
3246 protected void validateEmailAddress(long companyId, String emailAddress)
3247 throws PortalException, SystemException {
3248
3249 if (Validator.isNull(emailAddress) &&
3250 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
3251
3252 return;
3253 }
3254
3255 if (!Validator.isEmailAddress(emailAddress) ||
3256 emailAddress.startsWith("root@") ||
3257 emailAddress.startsWith("postmaster@")) {
3258
3259 throw new UserEmailAddressException();
3260 }
3261
3262 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
3263 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
3264 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
3265
3266 for (int i = 0; i < reservedEmailAddresses.length; i++) {
3267 if (emailAddress.equalsIgnoreCase(reservedEmailAddresses[i])) {
3268 throw new ReservedUserEmailAddressException();
3269 }
3270 }
3271 }
3272
3273 protected void validateFullName(
3274 long companyId, String firstName, String middleName,
3275 String lastName)
3276 throws PortalException {
3277
3278 if (Validator.isNull(firstName)) {
3279 throw new ContactFirstNameException();
3280 }
3281 else if (Validator.isNull(lastName)) {
3282 throw new ContactLastNameException();
3283 }
3284
3285 FullNameValidator fullNameValidator =
3286 FullNameValidatorFactory.getInstance();
3287
3288 if (!fullNameValidator.validate(
3289 companyId, firstName, middleName, lastName)) {
3290
3291 throw new ContactFullNameException();
3292 }
3293 }
3294
3295 protected void validatePassword(
3296 long companyId, long userId, String password1, String password2)
3297 throws PortalException, SystemException {
3298
3299 if (Validator.isNull(password1) || Validator.isNull(password2)) {
3300 throw new UserPasswordException(
3301 UserPasswordException.PASSWORD_INVALID);
3302 }
3303
3304 if (!password1.equals(password2)) {
3305 throw new UserPasswordException(
3306 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
3307 }
3308
3309 PasswordPolicy passwordPolicy =
3310 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
3311
3312 PwdToolkitUtil.validate(
3313 companyId, userId, password1, password2, passwordPolicy);
3314 }
3315
3316 protected void validateReminderQuery(String question, String answer)
3317 throws PortalException {
3318
3319 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
3320 return;
3321 }
3322
3323 if (Validator.isNull(question)) {
3324 throw new UserReminderQueryException("Question cannot be null");
3325 }
3326
3327 if (Validator.isNull(answer)) {
3328 throw new UserReminderQueryException("Answer cannot be null");
3329 }
3330 }
3331
3332 protected void validateScreenName(
3333 long companyId, long userId, String screenName)
3334 throws PortalException, SystemException {
3335
3336 if (Validator.isNull(screenName)) {
3337 throw new UserScreenNameException();
3338 }
3339
3340 ScreenNameValidator screenNameValidator =
3341 ScreenNameValidatorFactory.getInstance();
3342
3343 if (!screenNameValidator.validate(companyId, screenName)) {
3344 throw new UserScreenNameException();
3345 }
3346
3347 if (Validator.isNumber(screenName) &&
3348 !screenName.equals(String.valueOf(userId))) {
3349
3350 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
3351 throw new UserScreenNameException();
3352 }
3353
3354 Group group = groupPersistence.fetchByPrimaryKey(
3355 GetterUtil.getLong(screenName));
3356
3357 if (group != null) {
3358 throw new UserScreenNameException();
3359 }
3360 }
3361
3362 for (char c : screenName.toCharArray()) {
3363 if ((!Validator.isChar(c)) && (!Validator.isDigit(c)) &&
3364 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
3365 (c != CharPool.UNDERLINE)) {
3366
3367 throw new UserScreenNameException();
3368 }
3369 }
3370
3371 String[] anonymousNames = PrincipalBean.ANONYMOUS_NAMES;
3372
3373 for (int i = 0; i < anonymousNames.length; i++) {
3374 if (screenName.equalsIgnoreCase(anonymousNames[i])) {
3375 throw new UserScreenNameException();
3376 }
3377 }
3378
3379 User user = userPersistence.fetchByC_SN(companyId, screenName);
3380
3381 if (user != null) {
3382 throw new DuplicateUserScreenNameException();
3383 }
3384
3385 String friendlyURL = StringPool.SLASH + screenName;
3386
3387 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
3388
3389 if (group != null) {
3390 throw new DuplicateUserScreenNameException();
3391 }
3392
3393 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
3394
3395 if (exceptionType != -1) {
3396 throw new UserScreenNameException(
3397 new GroupFriendlyURLException(exceptionType));
3398 }
3399
3400 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
3401 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
3402 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
3403
3404 for (int i = 0; i < reservedScreenNames.length; i++) {
3405 if (screenName.equalsIgnoreCase(reservedScreenNames[i])) {
3406 throw new ReservedUserScreenNameException();
3407 }
3408 }
3409 }
3410
3411 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
3412
3413 private static Map<Long, User> _defaultUsers =
3414 new ConcurrentHashMap<Long, User>();
3415
3416}