1
22
23 package com.liferay.portal.service.impl;
24
25 import com.liferay.portal.ContactBirthdayException;
26 import com.liferay.portal.ContactFirstNameException;
27 import com.liferay.portal.ContactLastNameException;
28 import com.liferay.portal.DuplicateUserEmailAddressException;
29 import com.liferay.portal.DuplicateUserScreenNameException;
30 import com.liferay.portal.GroupFriendlyURLException;
31 import com.liferay.portal.ModelListenerException;
32 import com.liferay.portal.NoSuchContactException;
33 import com.liferay.portal.NoSuchGroupException;
34 import com.liferay.portal.NoSuchRoleException;
35 import com.liferay.portal.NoSuchUserException;
36 import com.liferay.portal.NoSuchUserGroupException;
37 import com.liferay.portal.PasswordExpiredException;
38 import com.liferay.portal.PortalException;
39 import com.liferay.portal.RequiredUserException;
40 import com.liferay.portal.ReservedUserEmailAddressException;
41 import com.liferay.portal.ReservedUserScreenNameException;
42 import com.liferay.portal.SystemException;
43 import com.liferay.portal.UserEmailAddressException;
44 import com.liferay.portal.UserIdException;
45 import com.liferay.portal.UserLockoutException;
46 import com.liferay.portal.UserPasswordException;
47 import com.liferay.portal.UserPortraitException;
48 import com.liferay.portal.UserScreenNameException;
49 import com.liferay.portal.UserSmsException;
50 import com.liferay.portal.kernel.annotation.Propagation;
51 import com.liferay.portal.kernel.annotation.Transactional;
52 import com.liferay.portal.kernel.language.LanguageUtil;
53 import com.liferay.portal.kernel.log.Log;
54 import com.liferay.portal.kernel.log.LogFactoryUtil;
55 import com.liferay.portal.kernel.mail.MailMessage;
56 import com.liferay.portal.kernel.util.ArrayUtil;
57 import com.liferay.portal.kernel.util.Base64;
58 import com.liferay.portal.kernel.util.CharPool;
59 import com.liferay.portal.kernel.util.GetterUtil;
60 import com.liferay.portal.kernel.util.HtmlUtil;
61 import com.liferay.portal.kernel.util.InstancePool;
62 import com.liferay.portal.kernel.util.KeyValuePair;
63 import com.liferay.portal.kernel.util.OrderByComparator;
64 import com.liferay.portal.kernel.util.StringPool;
65 import com.liferay.portal.kernel.util.StringUtil;
66 import com.liferay.portal.kernel.util.Validator;
67 import com.liferay.portal.lar.PortletDataHandlerKeys;
68 import com.liferay.portal.lar.UserIdStrategy;
69 import com.liferay.portal.model.Company;
70 import com.liferay.portal.model.CompanyConstants;
71 import com.liferay.portal.model.Contact;
72 import com.liferay.portal.model.ContactConstants;
73 import com.liferay.portal.model.Group;
74 import com.liferay.portal.model.Organization;
75 import com.liferay.portal.model.PasswordPolicy;
76 import com.liferay.portal.model.ResourceConstants;
77 import com.liferay.portal.model.Role;
78 import com.liferay.portal.model.RoleConstants;
79 import com.liferay.portal.model.User;
80 import com.liferay.portal.model.UserGroup;
81 import com.liferay.portal.model.impl.LayoutImpl;
82 import com.liferay.portal.security.auth.AuthPipeline;
83 import com.liferay.portal.security.auth.Authenticator;
84 import com.liferay.portal.security.auth.PrincipalException;
85 import com.liferay.portal.security.auth.ScreenNameGenerator;
86 import com.liferay.portal.security.auth.ScreenNameValidator;
87 import com.liferay.portal.security.ldap.PortalLDAPUtil;
88 import com.liferay.portal.security.permission.PermissionCacheUtil;
89 import com.liferay.portal.security.pwd.PwdEncryptor;
90 import com.liferay.portal.security.pwd.PwdToolkitUtil;
91 import com.liferay.portal.service.base.PrincipalBean;
92 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
93 import com.liferay.portal.util.PortalUtil;
94 import com.liferay.portal.util.PrefsPropsUtil;
95 import com.liferay.portal.util.PropsKeys;
96 import com.liferay.portal.util.PropsUtil;
97 import com.liferay.portal.util.PropsValues;
98 import com.liferay.util.Encryptor;
99 import com.liferay.util.EncryptorException;
100
101 import java.io.ByteArrayInputStream;
102 import java.io.IOException;
103 import java.io.UnsupportedEncodingException;
104
105 import java.security.MessageDigest;
106 import java.security.NoSuchAlgorithmException;
107
108 import java.util.ArrayList;
109 import java.util.Date;
110 import java.util.HashSet;
111 import java.util.LinkedHashMap;
112 import java.util.List;
113 import java.util.Locale;
114 import java.util.Map;
115 import java.util.Set;
116 import java.util.concurrent.ConcurrentHashMap;
117
118 import javax.mail.internet.InternetAddress;
119
120
128 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
129
130 public void addGroupUsers(long groupId, long[] userIds)
131 throws PortalException, SystemException {
132
133 groupPersistence.addUsers(groupId, userIds);
134
135 Group group = groupPersistence.findByPrimaryKey(groupId);
136
137 Role role = rolePersistence.findByC_N(
138 group.getCompanyId(), RoleConstants.COMMUNITY_MEMBER);
139
140 for (int i = 0; i < userIds.length; i++) {
141 long userId = userIds[i];
142
143 userGroupRoleLocalService.addUserGroupRoles(
144 userId, groupId, new long[] {role.getRoleId()});
145 }
146
147 PermissionCacheUtil.clearCache();
148 }
149
150 public void addOrganizationUsers(long organizationId, long[] userIds)
151 throws PortalException, SystemException {
152
153 organizationPersistence.addUsers(organizationId, userIds);
154
155 Organization organization = organizationPersistence.findByPrimaryKey(
156 organizationId);
157
158 Group group = organization.getGroup();
159
160 long groupId = group.getGroupId();
161
162 Role role = rolePersistence.findByC_N(
163 group.getCompanyId(), RoleConstants.ORGANIZATION_MEMBER);
164
165 for (int i = 0; i < userIds.length; i++) {
166 long userId = userIds[i];
167
168 userGroupRoleLocalService.addUserGroupRoles(
169 userId, groupId, new long[] {role.getRoleId()});
170 }
171
172 PermissionCacheUtil.clearCache();
173 }
174
175 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
176 throws SystemException {
177
178 passwordPolicyRelLocalService.addPasswordPolicyRels(
179 passwordPolicyId, User.class.getName(), userIds);
180 }
181
182 public void addRoleUsers(long roleId, long[] userIds)
183 throws SystemException {
184
185 rolePersistence.addUsers(roleId, userIds);
186
187 PermissionCacheUtil.clearCache();
188 }
189
190 public void addUserGroupUsers(long userGroupId, long[] userIds)
191 throws PortalException, SystemException {
192
193 copyUserGroupLayouts(userGroupId, userIds);
194
195 userGroupPersistence.addUsers(userGroupId, userIds);
196
197 PermissionCacheUtil.clearCache();
198 }
199
200 public User addUser(
201 long creatorUserId, long companyId, boolean autoPassword,
202 String password1, String password2, boolean autoScreenName,
203 String screenName, String emailAddress, Locale locale,
204 String firstName, String middleName, String lastName, int prefixId,
205 int suffixId, boolean male, int birthdayMonth, int birthdayDay,
206 int birthdayYear, String jobTitle, long[] organizationIds,
207 boolean sendEmail)
208 throws PortalException, SystemException {
209
210
212 Company company = companyPersistence.findByPrimaryKey(companyId);
213 screenName = getScreenName(screenName);
214 emailAddress = emailAddress.trim().toLowerCase();
215 Date now = new Date();
216
217 if (PropsValues.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE) {
218 autoScreenName = true;
219 }
220
221 long userId = counterLocalService.increment();
222
223 validate(
224 companyId, userId, autoPassword, password1, password2,
225 autoScreenName, screenName, emailAddress, firstName, lastName,
226 organizationIds);
227
228 if (autoPassword) {
229 password1 = PwdToolkitUtil.generate();
230 }
231 else {
232 if (Validator.isNull(password1) || Validator.isNull(password2)) {
233 throw new UserPasswordException(
234 UserPasswordException.PASSWORD_INVALID);
235 }
236 }
237
238 if (autoScreenName) {
239 ScreenNameGenerator screenNameGenerator =
240 (ScreenNameGenerator)InstancePool.get(
241 PropsValues.USERS_SCREEN_NAME_GENERATOR);
242
243 try {
244 screenName = screenNameGenerator.generate(
245 companyId, userId, emailAddress);
246 }
247 catch (Exception e) {
248 throw new SystemException(e);
249 }
250 }
251
252 User defaultUser = getDefaultUser(companyId);
253
254 String fullName = ContactConstants.getFullName(
255 firstName, middleName, lastName);
256
257 String greeting = LanguageUtil.format(
258 companyId, locale, "welcome-x", " " + fullName, false);
259
260 User user = userPersistence.create(userId);
261
262 user.setCompanyId(companyId);
263 user.setCreateDate(now);
264 user.setModifiedDate(now);
265 user.setDefaultUser(false);
266 user.setContactId(counterLocalService.increment());
267 user.setPassword(PwdEncryptor.encrypt(password1));
268 user.setPasswordUnencrypted(password1);
269 user.setPasswordEncrypted(true);
270 user.setPasswordReset(false);
271 user.setScreenName(screenName);
272 user.setEmailAddress(emailAddress);
273 user.setLanguageId(locale.toString());
274 user.setTimeZoneId(defaultUser.getTimeZoneId());
275 user.setGreeting(greeting);
276 user.setFirstName(firstName);
277 user.setMiddleName(middleName);
278 user.setLastName(lastName);
279 user.setJobTitle(jobTitle);
280 user.setActive(true);
281
282 userPersistence.update(user, false);
283
284
286 String creatorUserName = StringPool.BLANK;
287
288 if (creatorUserId <= 0) {
289 creatorUserId = user.getUserId();
290
291
294 }
296 else {
297 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
298
299 creatorUserName = creatorUser.getFullName();
300 }
301
302 resourceLocalService.addResources(
303 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
304 false, false, false);
305
306
308 if (user.hasCompanyMx()) {
309 mailService.addUser(
310 companyId, userId, password1, firstName, middleName, lastName,
311 emailAddress);
312 }
313
314
316 Date birthday = PortalUtil.getDate(
317 birthdayMonth, birthdayDay, birthdayYear,
318 new ContactBirthdayException());
319
320 Contact contact = contactPersistence.create(user.getContactId());
321
322 contact.setCompanyId(user.getCompanyId());
323 contact.setUserId(creatorUserId);
324 contact.setUserName(creatorUserName);
325 contact.setCreateDate(now);
326 contact.setModifiedDate(now);
327 contact.setAccountId(company.getAccountId());
328 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
329 contact.setFirstName(firstName);
330 contact.setMiddleName(middleName);
331 contact.setLastName(lastName);
332 contact.setPrefixId(prefixId);
333 contact.setSuffixId(suffixId);
334 contact.setMale(male);
335 contact.setBirthday(birthday);
336 contact.setJobTitle(jobTitle);
337
338 contactPersistence.update(contact, false);
339
340
342 updateOrganizations(userId, organizationIds);
343
344
346 groupLocalService.addGroup(
347 user.getUserId(), User.class.getName(), user.getUserId(), null,
348 null, 0, StringPool.SLASH + screenName, true);
349
350
352 Set<Long> groupIdsSet = new HashSet<Long>();
353
354 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
355 companyId, PropsKeys.ADMIN_DEFAULT_GROUP_NAMES, StringPool.NEW_LINE,
356 PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
357
358 for (String defaultGroupName : defaultGroupNames) {
359 try {
360 Group group = groupPersistence.findByC_N(
361 companyId, defaultGroupName);
362
363 groupIdsSet.add(group.getGroupId());
364 }
365 catch (NoSuchGroupException nsge) {
366 }
367 }
368
369 long[] groupIds = ArrayUtil.toArray(
370 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
371
372 groupLocalService.addUserGroups(userId, groupIds);
373
374
376 List<Role> roles = new ArrayList<Role>();
377
378 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
379 companyId, PropsKeys.ADMIN_DEFAULT_ROLE_NAMES, StringPool.NEW_LINE,
380 PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
381
382 for (String defaultRoleName : defaultRoleNames) {
383 try {
384 Role role = rolePersistence.findByC_N(
385 companyId, defaultRoleName);
386
387 roles.add(role);
388 }
389 catch (NoSuchRoleException nsge) {
390 }
391 }
392
393 userPersistence.setRoles(userId, roles);
394
395
397 List<UserGroup> userGroups = new ArrayList<UserGroup>();
398
399 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
400 companyId, PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
401 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
402
403 for (String defaultUserGroupName : defaultUserGroupNames) {
404 try {
405 UserGroup userGroup = userGroupPersistence.findByC_N(
406 companyId, defaultUserGroupName);
407
408 userGroups.add(userGroup);
409
410 copyUserGroupLayouts(
411 userGroup.getUserGroupId(), new long[] {userId});
412 }
413 catch (NoSuchUserGroupException nsuge) {
414 }
415 }
416
417 userPersistence.setUserGroups(userId, userGroups);
418
419
421 if (sendEmail) {
422 try {
423 sendEmail(user, password1);
424 }
425 catch (IOException ioe) {
426 throw new SystemException(ioe);
427 }
428 }
429
430 return user;
431 }
432
433 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
434 public int authenticateByEmailAddress(
435 long companyId, String emailAddress, String password,
436 Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
437 throws PortalException, SystemException {
438
439 return authenticate(
440 companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
441 headerMap, parameterMap);
442 }
443
444 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
445 public int authenticateByScreenName(
446 long companyId, String screenName, String password,
447 Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
448 throws PortalException, SystemException {
449
450 return authenticate(
451 companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
452 headerMap, parameterMap);
453 }
454
455 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
456 public int authenticateByUserId(
457 long companyId, long userId, String password,
458 Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
459 throws PortalException, SystemException {
460
461 return authenticate(
462 companyId, String.valueOf(userId), password,
463 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap);
464 }
465
466 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
467 public long authenticateForBasic(
468 long companyId, String authType, String login, String password)
469 throws PortalException, SystemException {
470
471 try {
472 User user = null;
473
474 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
475 user = getUserByEmailAddress(companyId, login);
476 }
477 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
478 user = getUserByScreenName(companyId, login);
479 }
480 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
481 user = getUserById(companyId, GetterUtil.getLong(login));
482 }
483
484 if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
485 return user.getUserId();
486 }
487
488 String userPassword = user.getPassword();
489
490 if (!user.isPasswordEncrypted()) {
491 userPassword = PwdEncryptor.encrypt(userPassword);
492 }
493
494 String encPassword = PwdEncryptor.encrypt(password);
495
496 if (userPassword.equals(password) ||
497 userPassword.equals(encPassword)) {
498
499 return user.getUserId();
500 }
501 }
502 catch (NoSuchUserException nsue) {
503 }
504
505 return 0;
506 }
507
508 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
509 public boolean authenticateForJAAS(long userId, String encPassword) {
510 try {
511 User user = userPersistence.findByPrimaryKey(userId);
512
513 if (user.isDefaultUser()) {
514 _log.error(
515 "The default user should never be allowed to authenticate");
516
517 return false;
518 }
519
520 String password = user.getPassword();
521
522 if (user.isPasswordEncrypted()) {
523 if (password.equals(encPassword)) {
524 return true;
525 }
526
527 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
528 encPassword = PwdEncryptor.encrypt(encPassword, password);
529
530 if (password.equals(encPassword)) {
531 return true;
532 }
533 }
534 }
535 else {
536 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
537 if (password.equals(encPassword)) {
538 return true;
539 }
540 }
541
542 password = PwdEncryptor.encrypt(password);
543
544 if (password.equals(encPassword)) {
545 return true;
546 }
547 }
548 }
549 catch (Exception e) {
550 _log.error(e);
551 }
552
553 return false;
554 }
555
556 public void checkLockout(User user)
557 throws PortalException, SystemException {
558
559 if (PortalLDAPUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
560 return;
561 }
562
563 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
564
565 if (passwordPolicy.isLockout()) {
566
567
569 Date now = new Date();
570 int failedLoginAttempts = user.getFailedLoginAttempts();
571
572 if (failedLoginAttempts > 0) {
573 long failedLoginTime = user.getLastFailedLoginDate().getTime();
574 long elapsedTime = now.getTime() - failedLoginTime;
575 long requiredElapsedTime =
576 passwordPolicy.getResetFailureCount() * 1000;
577
578 if ((requiredElapsedTime != 0) &&
579 (elapsedTime > requiredElapsedTime)) {
580
581 user.setLastFailedLoginDate(null);
582 user.setFailedLoginAttempts(0);
583 }
584 }
585
586
588 if (user.isLockout()) {
589 long lockoutTime = user.getLockoutDate().getTime();
590 long elapsedTime = now.getTime() - lockoutTime;
591 long requiredElapsedTime =
592 passwordPolicy.getLockoutDuration() * 1000;
593
594 if ((requiredElapsedTime != 0) &&
595 (elapsedTime > requiredElapsedTime)) {
596
597 user.setLockout(false);
598 user.setLockoutDate(null);
599 }
600 }
601
602 if (user.isLockout()) {
603 throw new UserLockoutException();
604 }
605 }
606 }
607
608 public void checkLoginFailure(User user) throws SystemException {
609 Date now = new Date();
610
611 int failedLoginAttempts = user.getFailedLoginAttempts();
612
613 user.setLastFailedLoginDate(now);
614 user.setFailedLoginAttempts(++failedLoginAttempts);
615
616 userPersistence.update(user, false);
617 }
618
619 public void checkLoginFailureByEmailAddress(
620 long companyId, String emailAddress)
621 throws PortalException, SystemException {
622
623 User user = getUserByEmailAddress(companyId, emailAddress);
624
625 checkLoginFailure(user);
626 }
627
628 public void checkLoginFailureById(long userId)
629 throws PortalException, SystemException {
630
631 User user = userPersistence.findByPrimaryKey(userId);
632
633 checkLoginFailure(user);
634 }
635
636 public void checkLoginFailureByScreenName(long companyId, String screenName)
637 throws PortalException, SystemException {
638
639 User user = getUserByScreenName(companyId, screenName);
640
641 checkLoginFailure(user);
642 }
643
644 public void checkPasswordExpired(User user)
645 throws PortalException, SystemException {
646
647 if (PortalLDAPUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
648 return;
649 }
650
651 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
652
653
655 if (isPasswordExpired(user)) {
656 int graceLoginCount = user.getGraceLoginCount();
657
658 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
659 user.setGraceLoginCount(++graceLoginCount);
660
661 userPersistence.update(user, false);
662 }
663 else {
664 throw new PasswordExpiredException();
665 }
666 }
667
668
670 if (isPasswordExpiringSoon(user)) {
671 user.setPasswordReset(true);
672
673 userPersistence.update(user, false);
674 }
675
676
678 if (passwordPolicy.isChangeable() &&
679 passwordPolicy.isChangeRequired()) {
680
681 if (user.getLastLoginDate() == null) {
682 boolean passwordReset = false;
683
684 if (passwordPolicy.isChangeable() &&
685 passwordPolicy.isChangeRequired()) {
686
687 passwordReset = true;
688 }
689
690 user.setPasswordReset(passwordReset);
691
692 userPersistence.update(user, false);
693 }
694 }
695 }
696
697 public void clearOrganizationUsers(long organizationId)
698 throws SystemException {
699
700 organizationPersistence.clearUsers(organizationId);
701
702 PermissionCacheUtil.clearCache();
703 }
704
705 public void clearUserGroupUsers(long userGroupId) throws SystemException {
706 userGroupPersistence.clearUsers(userGroupId);
707
708 PermissionCacheUtil.clearCache();
709 }
710
711 public KeyValuePair decryptUserId(
712 long companyId, String name, String password)
713 throws PortalException, SystemException {
714
715 Company company = companyPersistence.findByPrimaryKey(companyId);
716
717 try {
718 name = Encryptor.decrypt(company.getKeyObj(), name);
719 }
720 catch (EncryptorException ee) {
721 throw new SystemException(ee);
722 }
723
724 long userId = GetterUtil.getLong(name);
725
726 User user = userPersistence.findByPrimaryKey(userId);
727
728 try {
729 password = Encryptor.decrypt(company.getKeyObj(), password);
730 }
731 catch (EncryptorException ee) {
732 throw new SystemException(ee);
733 }
734
735 String encPassword = PwdEncryptor.encrypt(password);
736
737 if (user.getPassword().equals(encPassword)) {
738 if (isPasswordExpired(user)) {
739 user.setPasswordReset(true);
740
741 userPersistence.update(user, false);
742 }
743
744 return new KeyValuePair(name, password);
745 }
746 else {
747 throw new PrincipalException();
748 }
749 }
750
751 public void deletePasswordPolicyUser(long passwordPolicyId, long userId)
752 throws SystemException {
753
754 passwordPolicyRelLocalService.deletePasswordPolicyRel(
755 passwordPolicyId, User.class.getName(), userId);
756 }
757
758 public void deleteRoleUser(long roleId, long userId)
759 throws SystemException {
760
761 rolePersistence.removeUser(roleId, userId);
762
763 PermissionCacheUtil.clearCache();
764 }
765
766 public void deleteUser(long userId)
767 throws PortalException, SystemException {
768
769 if (!PropsValues.USERS_DELETE) {
770 throw new RequiredUserException();
771 }
772
773 User user = userPersistence.findByPrimaryKey(userId);
774
775
777 browserTrackerLocalService.deleteUserBrowserTracker(userId);
778
779
781 Group group = user.getGroup();
782
783 if (group != null) {
784 groupLocalService.deleteGroup(group.getGroupId());
785 }
786
787
789 imageLocalService.deleteImage(user.getPortraitId());
790
791
793 passwordPolicyRelLocalService.deletePasswordPolicyRel(
794 User.class.getName(), userId);
795
796
798 passwordTrackerLocalService.deletePasswordTrackers(userId);
799
800
802 subscriptionLocalService.deleteSubscriptions(userId);
803
804
806 userIdMapperLocalService.deleteUserIdMappers(userId);
807
808
810 announcementsDeliveryLocalService.deleteDeliveries(userId);
811
812
814 blogsStatsUserLocalService.deleteStatsUserByUserId(userId);
815
816
818 dlFileRankLocalService.deleteFileRanks(userId);
819
820
822 expandoValueLocalService.deleteValues(User.class.getName(), userId);
823
824
826 mbBanLocalService.deleteBansByBanUserId(userId);
827 mbMessageFlagLocalService.deleteFlags(userId);
828 mbStatsUserLocalService.deleteStatsUsersByUserId(userId);
829
830
832 shoppingCartLocalService.deleteUserCarts(userId);
833
834
836 socialActivityLocalService.deleteUserActivities(userId);
837 socialRequestLocalService.deleteReceiverUserRequests(userId);
838 socialRequestLocalService.deleteUserRequests(userId);
839
840
842 mailService.deleteUser(user.getCompanyId(), userId);
843
844
846 try {
847 contactLocalService.deleteContact(user.getContactId());
848 }
849 catch (NoSuchContactException nsce) {
850 }
851
852
854 resourceLocalService.deleteResource(
855 user.getCompanyId(), User.class.getName(),
856 ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
857
858
860 userGroupRoleLocalService.deleteUserGroupRolesByUserId(userId);
861
862
864 userPersistence.remove(userId);
865
866
868 PermissionCacheUtil.clearCache();
869 }
870
871 public String encryptUserId(String name)
872 throws PortalException, SystemException {
873
874 long userId = GetterUtil.getLong(name);
875
876 User user = userPersistence.findByPrimaryKey(userId);
877
878 Company company = companyPersistence.findByPrimaryKey(
879 user.getCompanyId());
880
881 try {
882 return Encryptor.encrypt(company.getKeyObj(), name);
883 }
884 catch (EncryptorException ee) {
885 throw new SystemException(ee);
886 }
887 }
888
889 public User getDefaultUser(long companyId)
890 throws PortalException, SystemException {
891
892 User userModel = _defaultUsers.get(companyId);
893
894 if (userModel == null) {
895 userModel = userPersistence.findByC_DU(companyId, true);
896
897 _defaultUsers.put(companyId, userModel);
898 }
899
900 return userModel;
901 }
902
903 public long getDefaultUserId(long companyId)
904 throws PortalException, SystemException {
905
906 User user = getDefaultUser(companyId);
907
908 return user.getUserId();
909 }
910
911 public long[] getGroupUserIds(long groupId) throws SystemException {
912 return getUserIds(getGroupUsers(groupId));
913 }
914
915 public List<User> getGroupUsers(long groupId) throws SystemException {
916 return groupPersistence.getUsers(groupId);
917 }
918
919 public int getGroupUsersCount(long groupId) throws SystemException {
920 return groupPersistence.getUsersSize(groupId);
921 }
922
923 public int getGroupUsersCount(long groupId, boolean active)
924 throws PortalException, SystemException {
925
926 Group group = groupPersistence.findByPrimaryKey(groupId);
927
928 LinkedHashMap<String, Object> params =
929 new LinkedHashMap<String, Object>();
930
931 params.put("usersGroups", new Long(groupId));
932
933 return searchCount(group.getCompanyId(), null, active, params);
934 }
935
936 public List<User> getNoAnnouncementsDeliveries(String type)
937 throws SystemException {
938
939 return userFinder.findByNoAnnouncementsDeliveries(type);
940 }
941
942 public List<User> getNoContacts() throws SystemException {
943 return userFinder.findByNoContacts();
944 }
945
946 public List<User> getNoGroups() throws SystemException {
947 return userFinder.findByNoGroups();
948 }
949
950 public long[] getOrganizationUserIds(long organizationId)
951 throws SystemException {
952
953 return getUserIds(getOrganizationUsers(organizationId));
954 }
955
956 public List<User> getOrganizationUsers(long organizationId)
957 throws SystemException {
958
959 return organizationPersistence.getUsers(organizationId);
960 }
961
962 public int getOrganizationUsersCount(long organizationId)
963 throws SystemException {
964
965 return organizationPersistence.getUsersSize(organizationId);
966 }
967
968 public int getOrganizationUsersCount(long organizationId, boolean active)
969 throws PortalException, SystemException {
970
971 Organization organization = organizationPersistence.findByPrimaryKey(
972 organizationId);
973
974 LinkedHashMap<String, Object> params =
975 new LinkedHashMap<String, Object>();
976
977 params.put("usersOrgs", new Long(organizationId));
978
979 return searchCount(organization.getCompanyId(), null, active, params);
980 }
981
982 public List<User> getPermissionUsers(
983 long companyId, long groupId, String name, String primKey,
984 String actionId, String firstName, String middleName,
985 String lastName, String emailAddress, boolean andOperator,
986 int start, int end)
987 throws SystemException {
988
989 int orgGroupPermissionsCount =
990 permissionUserFinder.countByOrgGroupPermissions(
991 companyId, name, primKey, actionId);
992
993 if (orgGroupPermissionsCount > 0) {
994 return permissionUserFinder.findByUserAndOrgGroupPermission(
995 companyId, name, primKey, actionId, firstName, middleName,
996 lastName, emailAddress, andOperator, start, end);
997 }
998 else {
999 return permissionUserFinder.findByPermissionAndRole(
1000 companyId, groupId, name, primKey, actionId, firstName,
1001 middleName, lastName, emailAddress, andOperator, start, end);
1002 }
1003 }
1004
1005 public int getPermissionUsersCount(
1006 long companyId, long groupId, String name, String primKey,
1007 String actionId, String firstName, String middleName,
1008 String lastName, String emailAddress, boolean andOperator)
1009 throws SystemException {
1010
1011 int orgGroupPermissionsCount =
1012 permissionUserFinder.countByOrgGroupPermissions(
1013 companyId, name, primKey, actionId);
1014
1015 if (orgGroupPermissionsCount > 0) {
1016 return permissionUserFinder.countByUserAndOrgGroupPermission(
1017 companyId, name, primKey, actionId, firstName, middleName,
1018 lastName, emailAddress, andOperator);
1019 }
1020 else {
1021 return permissionUserFinder.countByPermissionAndRole(
1022 companyId, groupId, name, primKey, actionId, firstName,
1023 middleName, lastName, emailAddress, andOperator);
1024 }
1025 }
1026
1027 public long[] getRoleUserIds(long roleId) throws SystemException {
1028 return getUserIds(getRoleUsers(roleId));
1029 }
1030
1031 public List<User> getRoleUsers(long roleId) throws SystemException {
1032 return rolePersistence.getUsers(roleId);
1033 }
1034
1035 public List<User> getRoleUsers(long roleId, int start, int end)
1036 throws SystemException {
1037
1038 return rolePersistence.getUsers(roleId, start, end);
1039 }
1040
1041 public int getRoleUsersCount(long roleId) throws SystemException {
1042 return rolePersistence.getUsersSize(roleId);
1043 }
1044
1045 public int getRoleUsersCount(long roleId, boolean active)
1046 throws PortalException, SystemException {
1047
1048 Role role = rolePersistence.findByPrimaryKey(
1049 roleId);
1050
1051 LinkedHashMap<String, Object> params =
1052 new LinkedHashMap<String, Object>();
1053
1054 params.put("usersRoles", new Long(roleId));
1055
1056 return searchCount(role.getCompanyId(), null, active, params);
1057 }
1058
1059 public List<User> getSocialUsers(
1060 long userId, int start, int end, OrderByComparator obc)
1061 throws PortalException, SystemException {
1062
1063 User user = userPersistence.findByPrimaryKey(userId);
1064
1065 LinkedHashMap<String, Object> params =
1066 new LinkedHashMap<String, Object>();
1067
1068 params.put("socialRelation", new Long[] {userId});
1069
1070 return search(
1071 user.getCompanyId(), null, true, params, start, end, obc);
1072 }
1073
1074 public List<User> getSocialUsers(
1075 long userId, int type, int start, int end, OrderByComparator obc)
1076 throws PortalException, SystemException {
1077
1078 User user = userPersistence.findByPrimaryKey(userId);
1079
1080 LinkedHashMap<String, Object> params =
1081 new LinkedHashMap<String, Object>();
1082
1083 params.put("socialRelationType", new Long[] {userId, new Long(type)});
1084
1085 return search(user.getCompanyId(), null, true, params, start, end, obc);
1086 }
1087
1088 public List<User> getSocialUsers(
1089 long userId1, long userId2, int start, int end,
1090 OrderByComparator obc)
1091 throws PortalException, SystemException {
1092
1093 User user1 = userPersistence.findByPrimaryKey(userId1);
1094
1095 LinkedHashMap<String, Object> params =
1096 new LinkedHashMap<String, Object>();
1097
1098 params.put("socialMutualRelation", new Long[] {userId1, userId2});
1099
1100 return search(
1101 user1.getCompanyId(), null, true, params, start, end, obc);
1102 }
1103
1104 public List<User> getSocialUsers(
1105 long userId1, long userId2, int type, int start, int end,
1106 OrderByComparator obc)
1107 throws PortalException, SystemException {
1108
1109 User user1 = userPersistence.findByPrimaryKey(userId1);
1110
1111 LinkedHashMap<String, Object> params =
1112 new LinkedHashMap<String, Object>();
1113
1114 params.put(
1115 "socialMutualRelationType",
1116 new Long[] {userId1, new Long(type), userId2, new Long(type)});
1117
1118 return search(
1119 user1.getCompanyId(), null, true, params, start, end, obc);
1120 }
1121
1122 public int getSocialUsersCount(long userId)
1123 throws PortalException, SystemException {
1124
1125 User user = userPersistence.findByPrimaryKey(userId);
1126
1127 LinkedHashMap<String, Object> params =
1128 new LinkedHashMap<String, Object>();
1129
1130 params.put("socialRelation", new Long[] {userId});
1131
1132 return searchCount(user.getCompanyId(), null, true, params);
1133 }
1134
1135 public int getSocialUsersCount(long userId, int type)
1136 throws PortalException, SystemException {
1137
1138 User user = userPersistence.findByPrimaryKey(userId);
1139
1140 LinkedHashMap<String, Object> params =
1141 new LinkedHashMap<String, Object>();
1142
1143 params.put("socialRelationType", new Long[] {userId, new Long(type)});
1144
1145 return searchCount(user.getCompanyId(), null, true, params);
1146 }
1147
1148 public int getSocialUsersCount(long userId1, long userId2)
1149 throws PortalException, SystemException {
1150
1151 User user1 = userPersistence.findByPrimaryKey(userId1);
1152
1153 LinkedHashMap<String, Object> params =
1154 new LinkedHashMap<String, Object>();
1155
1156 params.put("socialMutualRelation", new Long[] {userId1, userId2});
1157
1158 return searchCount(user1.getCompanyId(), null, true, params);
1159 }
1160
1161 public int getSocialUsersCount(long userId1, long userId2, int type)
1162 throws PortalException, SystemException {
1163
1164 User user1 = userPersistence.findByPrimaryKey(userId1);
1165
1166 LinkedHashMap<String, Object> params =
1167 new LinkedHashMap<String, Object>();
1168
1169 params.put(
1170 "socialMutualRelationType",
1171 new Long[] {userId1, new Long(type), userId2, new Long(type)});
1172
1173 return searchCount(user1.getCompanyId(), null, true, params);
1174 }
1175
1176 public List<User> getUserGroupUsers(long userGroupId)
1177 throws SystemException {
1178
1179 return userGroupPersistence.getUsers(userGroupId);
1180 }
1181
1182 public int getUserGroupUsersCount(long userGroupId) throws SystemException {
1183 return userGroupPersistence.getUsersSize(userGroupId);
1184 }
1185
1186 public int getUserGroupUsersCount(long userGroupId, boolean active)
1187 throws PortalException, SystemException {
1188
1189 UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
1190 userGroupId);
1191
1192 LinkedHashMap<String, Object> params =
1193 new LinkedHashMap<String, Object>();
1194
1195 params.put("usersUserGroups", new Long(userGroupId));
1196
1197 return searchCount(userGroup.getCompanyId(), null, active, params);
1198 }
1199
1200 public User getUserByContactId(long contactId)
1201 throws PortalException, SystemException {
1202
1203 return userPersistence.findByContactId(contactId);
1204 }
1205
1206 public User getUserByEmailAddress(long companyId, String emailAddress)
1207 throws PortalException, SystemException {
1208
1209 emailAddress = emailAddress.trim().toLowerCase();
1210
1211 return userPersistence.findByC_EA(companyId, emailAddress);
1212 }
1213
1214 public User getUserById(long userId)
1215 throws PortalException, SystemException {
1216
1217 return userPersistence.findByPrimaryKey(userId);
1218 }
1219
1220 public User getUserById(long companyId, long userId)
1221 throws PortalException, SystemException {
1222
1223 return userPersistence.findByC_U(companyId, userId);
1224 }
1225
1226 public User getUserByOpenId(String openId)
1227 throws PortalException, SystemException {
1228
1229 return userPersistence.findByOpenId(openId);
1230 }
1231
1232 public User getUserByPortraitId(long portraitId)
1233 throws PortalException, SystemException {
1234
1235 return userPersistence.findByPortraitId(portraitId);
1236 }
1237
1238 public User getUserByScreenName(long companyId, String screenName)
1239 throws PortalException, SystemException {
1240
1241 screenName = getScreenName(screenName);
1242
1243 return userPersistence.findByC_SN(companyId, screenName);
1244 }
1245
1246 public long getUserIdByEmailAddress(long companyId, String emailAddress)
1247 throws PortalException, SystemException {
1248
1249 emailAddress = emailAddress.trim().toLowerCase();
1250
1251 User user = userPersistence.findByC_EA(companyId, emailAddress);
1252
1253 return user.getUserId();
1254 }
1255
1256 public long getUserIdByScreenName(long companyId, String screenName)
1257 throws PortalException, SystemException {
1258
1259 screenName = getScreenName(screenName);
1260
1261 User user = userPersistence.findByC_SN(companyId, screenName);
1262
1263 return user.getUserId();
1264 }
1265
1266 public boolean hasGroupUser(long groupId, long userId)
1267 throws SystemException {
1268
1269 return groupPersistence.containsUser(groupId, userId);
1270 }
1271
1272 public boolean hasOrganizationUser(long organizationId, long userId)
1273 throws SystemException {
1274
1275 return organizationPersistence.containsUser(organizationId, userId);
1276 }
1277
1278 public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
1279 throws SystemException {
1280
1281 return passwordPolicyRelLocalService.hasPasswordPolicyRel(
1282 passwordPolicyId, User.class.getName(), userId);
1283 }
1284
1285 public boolean hasRoleUser(long roleId, long userId)
1286 throws SystemException {
1287
1288 return rolePersistence.containsUser(roleId, userId);
1289 }
1290
1291
1296 public boolean hasRoleUser(
1297 long companyId, String name, long userId, boolean inherited)
1298 throws PortalException, SystemException {
1299
1300 return roleLocalService.hasUserRole(userId, companyId, name, inherited);
1301 }
1302
1303 public boolean hasUserGroupUser(long userGroupId, long userId)
1304 throws SystemException {
1305
1306 return userGroupPersistence.containsUser(userGroupId, userId);
1307 }
1308
1309 public boolean isPasswordExpired(User user)
1310 throws PortalException, SystemException {
1311
1312 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1313
1314 if (passwordPolicy.getExpireable()) {
1315 Date now = new Date();
1316
1317 if (user.getPasswordModifiedDate() == null) {
1318 user.setPasswordModifiedDate(now);
1319
1320 userLocalService.updateUser(user, false);
1321 }
1322
1323 long passwordStartTime = user.getPasswordModifiedDate().getTime();
1324 long elapsedTime = now.getTime() - passwordStartTime;
1325
1326 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
1327 return true;
1328 }
1329 else {
1330 return false;
1331 }
1332 }
1333
1334 return false;
1335 }
1336
1337 public boolean isPasswordExpiringSoon(User user)
1338 throws PortalException, SystemException {
1339
1340 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1341
1342 if (passwordPolicy.isExpireable()) {
1343 Date now = new Date();
1344
1345 if (user.getPasswordModifiedDate() == null) {
1346 user.setPasswordModifiedDate(now);
1347
1348 userLocalService.updateUser(user, false);
1349 }
1350
1351 long timeModified = user.getPasswordModifiedDate().getTime();
1352 long passwordExpiresOn =
1353 (passwordPolicy.getMaxAge() * 1000) + timeModified;
1354
1355 long timeStartWarning =
1356 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
1357
1358 if (now.getTime() > timeStartWarning) {
1359 return true;
1360 }
1361 else {
1362 return false;
1363 }
1364 }
1365
1366 return false;
1367 }
1368
1369 public List<User> search(
1370 long companyId, String keywords, Boolean active,
1371 LinkedHashMap<String, Object> params, int start, int end,
1372 OrderByComparator obc)
1373 throws SystemException {
1374
1375 return userFinder.findByKeywords(
1376 companyId, keywords, active, params, start, end, obc);
1377 }
1378
1379 public List<User> search(
1380 long companyId, String firstName, String middleName,
1381 String lastName, String screenName, String emailAddress,
1382 Boolean active, LinkedHashMap<String, Object> params,
1383 boolean andSearch, int start, int end, OrderByComparator obc)
1384 throws SystemException {
1385
1386 return userFinder.findByC_FN_MN_LN_SN_EA_A(
1387 companyId, firstName, middleName, lastName, screenName,
1388 emailAddress, active, params, andSearch, start, end, obc);
1389 }
1390
1391 public int searchCount(
1392 long companyId, String keywords, Boolean active,
1393 LinkedHashMap<String, Object> params)
1394 throws SystemException {
1395
1396 return userFinder.countByKeywords(companyId, keywords, active, params);
1397 }
1398
1399 public int searchCount(
1400 long companyId, String firstName, String middleName,
1401 String lastName, String screenName, String emailAddress,
1402 Boolean active, LinkedHashMap<String, Object> params,
1403 boolean andSearch)
1404 throws SystemException {
1405
1406 return userFinder.countByC_FN_MN_LN_SN_EA_A(
1407 companyId, firstName, middleName, lastName, screenName,
1408 emailAddress, active, params, andSearch);
1409 }
1410
1411 public void sendPassword(
1412 long companyId, String emailAddress, String remoteAddr,
1413 String remoteHost, String userAgent)
1414 throws PortalException, SystemException {
1415
1416 try {
1417 doSendPassword(
1418 companyId, emailAddress, remoteAddr, remoteHost, userAgent);
1419 }
1420 catch (IOException ioe) {
1421 throw new SystemException(ioe);
1422 }
1423 }
1424
1425 public void setRoleUsers(long roleId, long[] userIds)
1426 throws SystemException {
1427
1428 rolePersistence.setUsers(roleId, userIds);
1429
1430 PermissionCacheUtil.clearCache();
1431 }
1432
1433 public void setUserGroupUsers(long userGroupId, long[] userIds)
1434 throws PortalException, SystemException {
1435
1436 copyUserGroupLayouts(userGroupId, userIds);
1437
1438 userGroupPersistence.setUsers(userGroupId, userIds);
1439
1440 PermissionCacheUtil.clearCache();
1441 }
1442
1443 public void unsetGroupUsers(long groupId, long[] userIds)
1444 throws SystemException {
1445
1446 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
1447
1448 groupPersistence.removeUsers(groupId, userIds);
1449
1450 PermissionCacheUtil.clearCache();
1451 }
1452
1453 public void unsetOrganizationUsers(long organizationId, long[] userIds)
1454 throws PortalException, SystemException {
1455
1456 Organization organization = organizationPersistence.findByPrimaryKey(
1457 organizationId);
1458
1459 Group group = organization.getGroup();
1460
1461 long groupId = group.getGroupId();
1462
1463 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
1464
1465 organizationPersistence.removeUsers(organizationId, userIds);
1466
1467 PermissionCacheUtil.clearCache();
1468 }
1469
1470 public void unsetPasswordPolicyUsers(
1471 long passwordPolicyId, long[] userIds)
1472 throws SystemException {
1473
1474 passwordPolicyRelLocalService.deletePasswordPolicyRels(
1475 passwordPolicyId, User.class.getName(), userIds);
1476 }
1477
1478 public void unsetRoleUsers(long roleId, long[] userIds)
1479 throws SystemException {
1480
1481 rolePersistence.removeUsers(roleId, userIds);
1482
1483 PermissionCacheUtil.clearCache();
1484 }
1485
1486 public void unsetRoleUsers(long roleId, List<User> users)
1487 throws SystemException {
1488
1489 rolePersistence.removeUsers(roleId, users);
1490
1491 PermissionCacheUtil.clearCache();
1492 }
1493
1494 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
1495 throws SystemException {
1496
1497 userGroupPersistence.removeUsers(userGroupId, userIds);
1498
1499 PermissionCacheUtil.clearCache();
1500 }
1501
1502 public User updateActive(long userId, boolean active)
1503 throws PortalException, SystemException {
1504
1505 User user = userPersistence.findByPrimaryKey(userId);
1506
1507 user.setActive(active);
1508
1509 userPersistence.update(user, false);
1510
1511 return user;
1512 }
1513
1514 public User updateAgreedToTermsOfUse(
1515 long userId, boolean agreedToTermsOfUse)
1516 throws PortalException, SystemException {
1517
1518 User user = userPersistence.findByPrimaryKey(userId);
1519
1520 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
1521
1522 userPersistence.update(user, false);
1523
1524 return user;
1525 }
1526
1527 public User updateCreateDate(long userId, Date createDate)
1528 throws PortalException, SystemException {
1529
1530 User user = userPersistence.findByPrimaryKey(userId);
1531
1532 user.setCreateDate(createDate);
1533
1534 userPersistence.update(user, false);
1535
1536 return user;
1537 }
1538
1539 public User updateLastLogin(long userId, String loginIP)
1540 throws PortalException, SystemException {
1541
1542 User user = userPersistence.findByPrimaryKey(userId);
1543
1544 Date lastLoginDate = user.getLoginDate();
1545
1546 if (lastLoginDate == null) {
1547 lastLoginDate = new Date();
1548 }
1549
1550 user.setLoginDate(new Date());
1551 user.setLoginIP(loginIP);
1552 user.setLastLoginDate(lastLoginDate);
1553 user.setLastLoginIP(user.getLoginIP());
1554 user.setLastFailedLoginDate(null);
1555 user.setFailedLoginAttempts(0);
1556
1557 userPersistence.update(user, false);
1558
1559 return user;
1560 }
1561
1562 public User updateLockout(User user, boolean lockout)
1563 throws PortalException, SystemException {
1564
1565 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1566
1567 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
1568 return user;
1569 }
1570
1571 Date lockoutDate = null;
1572
1573 if (lockout) {
1574 lockoutDate = new Date();
1575 }
1576
1577 user.setLockout(lockout);
1578 user.setLockoutDate(lockoutDate);
1579
1580 if (!lockout) {
1581 user.setLastFailedLoginDate(lockoutDate);
1582 user.setFailedLoginAttempts(0);
1583 }
1584
1585 userPersistence.update(user, false);
1586
1587 return user;
1588 }
1589
1590 public User updateLockoutByEmailAddress(
1591 long companyId, String emailAddress, boolean lockout)
1592 throws PortalException, SystemException {
1593
1594 User user = getUserByEmailAddress(companyId, emailAddress);
1595
1596 return updateLockout(user, lockout);
1597 }
1598
1599 public User updateLockoutById(long userId, boolean lockout)
1600 throws PortalException, SystemException {
1601
1602 User user = userPersistence.findByPrimaryKey(userId);
1603
1604 return updateLockout(user, lockout);
1605 }
1606
1607 public User updateLockoutByScreenName(
1608 long companyId, String screenName, boolean lockout)
1609 throws PortalException, SystemException {
1610
1611 User user = getUserByScreenName(companyId, screenName);
1612
1613 return updateLockout(user, lockout);
1614 }
1615
1616 public User updateModifiedDate(long userId, Date modifiedDate)
1617 throws PortalException, SystemException {
1618
1619 User user = userPersistence.findByPrimaryKey(userId);
1620
1621 user.setModifiedDate(modifiedDate);
1622
1623 userPersistence.update(user, false);
1624
1625 return user;
1626 }
1627
1628 public void updateOpenId(long userId, String openId)
1629 throws PortalException, SystemException {
1630
1631 User user = userPersistence.findByPrimaryKey(userId);
1632
1633 user.setOpenId(openId);
1634
1635 userPersistence.update(user, false);
1636 }
1637
1638 public void updateOrganizations(long userId, long[] newOrganizationIds)
1639 throws PortalException, SystemException {
1640
1641 List<Organization> oldOrganizations = userPersistence.getOrganizations(
1642 userId);
1643
1644 List<Long> oldOrganizationIds = new ArrayList<Long>(
1645 oldOrganizations.size());
1646
1647 for (int i = 0; i < oldOrganizations.size(); i++) {
1648 Organization oldOrganization = oldOrganizations.get(i);
1649
1650 long oldOrganizationId = oldOrganization.getOrganizationId();
1651
1652 oldOrganizationIds.add(oldOrganizationId);
1653
1654 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
1655 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
1656 }
1657 }
1658
1659 for (int i = 0; i < newOrganizationIds.length; i++) {
1660 long newOrganizationId = newOrganizationIds[i];
1661
1662 if (!oldOrganizationIds.contains(newOrganizationId)) {
1663 addOrganizationUsers(newOrganizationId, new long[] {userId});
1664 }
1665 }
1666
1667 PermissionCacheUtil.clearCache();
1668 }
1669
1670 public User updatePassword(
1671 long userId, String password1, String password2,
1672 boolean passwordReset)
1673 throws PortalException, SystemException {
1674
1675 return updatePassword(
1676 userId, password1, password2, passwordReset, false);
1677 }
1678
1679 public User updatePassword(
1680 long userId, String password1, String password2,
1681 boolean passwordReset, boolean silentUpdate)
1682 throws PortalException, SystemException {
1683
1684 User user = userPersistence.findByPrimaryKey(userId);
1685
1686
1689 if (!silentUpdate) {
1690 validatePassword(user.getCompanyId(), userId, password1, password2);
1691 }
1692
1693 String oldEncPwd = user.getPassword();
1694
1695 if (!user.isPasswordEncrypted()) {
1696 oldEncPwd = PwdEncryptor.encrypt(user.getPassword());
1697 }
1698
1699 String newEncPwd = PwdEncryptor.encrypt(password1);
1700
1701 if (user.hasCompanyMx()) {
1702 mailService.updatePassword(user.getCompanyId(), userId, password1);
1703 }
1704
1705 user.setPassword(newEncPwd);
1706 user.setPasswordUnencrypted(password1);
1707 user.setPasswordEncrypted(true);
1708 user.setPasswordReset(passwordReset);
1709 user.setPasswordModifiedDate(new Date());
1710 user.setGraceLoginCount(0);
1711
1712 if (!silentUpdate) {
1713 user.setPasswordModified(true);
1714 }
1715
1716 try {
1717 userPersistence.update(user, false);
1718 }
1719 catch (ModelListenerException mle) {
1720 String msg = GetterUtil.getString(mle.getCause().getMessage());
1721
1722 if (PortalLDAPUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1723 String passwordHistory = PrefsPropsUtil.getString(
1724 user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
1725
1726 if (msg.indexOf(passwordHistory) != -1) {
1727 throw new UserPasswordException(
1728 UserPasswordException.PASSWORD_ALREADY_USED);
1729 }
1730 }
1731
1732 throw new UserPasswordException(
1733 UserPasswordException.PASSWORD_INVALID);
1734 }
1735
1736 if (!silentUpdate) {
1737 user.setPasswordModified(false);
1738
1739 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
1740 }
1741
1742 return user;
1743 }
1744
1745 public User updatePasswordManually(
1746 long userId, String password, boolean passwordEncrypted,
1747 boolean passwordReset, Date passwordModifiedDate)
1748 throws PortalException, SystemException {
1749
1750
1752 User user = userPersistence.findByPrimaryKey(userId);
1753
1754 user.setPassword(password);
1755 user.setPasswordEncrypted(passwordEncrypted);
1756 user.setPasswordReset(passwordReset);
1757 user.setPasswordModifiedDate(passwordModifiedDate);
1758
1759 userPersistence.update(user, false);
1760
1761 return user;
1762 }
1763
1764 public void updatePasswordReset(long userId, boolean passwordReset)
1765 throws PortalException, SystemException {
1766
1767 User user = userPersistence.findByPrimaryKey(userId);
1768
1769 user.setPasswordReset(passwordReset);
1770
1771 userPersistence.update(user, false);
1772 }
1773
1774 public void updatePortrait(long userId, byte[] bytes)
1775 throws PortalException, SystemException {
1776
1777 User user = userPersistence.findByPrimaryKey(userId);
1778
1779 long imageMaxSize = PrefsPropsUtil.getLong(
1780 PropsKeys.USERS_IMAGE_MAX_SIZE);
1781
1782 if ((imageMaxSize > 0) &&
1783 ((bytes == null) || (bytes.length > imageMaxSize))) {
1784
1785 throw new UserPortraitException();
1786 }
1787
1788 long portraitId = user.getPortraitId();
1789
1790 if (portraitId <= 0) {
1791 portraitId = counterLocalService.increment();
1792
1793 user.setPortraitId(portraitId);
1794
1795 userPersistence.update(user, false);
1796 }
1797
1798 imageLocalService.updateImage(portraitId, bytes);
1799 }
1800
1801 public void updateScreenName(long userId, String screenName)
1802 throws PortalException, SystemException {
1803
1804
1806 User user = userPersistence.findByPrimaryKey(userId);
1807
1808 screenName = getScreenName(screenName);
1809
1810 validateScreenName(user.getCompanyId(), userId, screenName);
1811
1812 user.setScreenName(screenName);
1813
1814 userPersistence.update(user, false);
1815
1816
1818 Group group = groupLocalService.getUserGroup(
1819 user.getCompanyId(), userId);
1820
1821 group.setFriendlyURL(StringPool.SLASH + screenName);
1822
1823 groupPersistence.update(group, false);
1824 }
1825
1826 public User updateUser(
1827 long userId, String oldPassword, boolean passwordReset,
1828 String screenName, String emailAddress, String languageId,
1829 String timeZoneId, String greeting, String comments,
1830 String firstName, String middleName, String lastName, int prefixId,
1831 int suffixId, boolean male, int birthdayMonth, int birthdayDay,
1832 int birthdayYear, String smsSn, String aimSn, String facebookSn,
1833 String icqSn, String jabberSn, String msnSn, String mySpaceSn,
1834 String skypeSn, String twitterSn, String ymSn, String jobTitle,
1835 long[] organizationIds)
1836 throws PortalException, SystemException {
1837
1838 String newPassword1 = StringPool.BLANK;
1839 String newPassword2 = StringPool.BLANK;
1840
1841 return updateUser(
1842 userId, oldPassword, newPassword1, newPassword2, passwordReset,
1843 screenName, emailAddress, languageId, timeZoneId, greeting,
1844 comments, firstName, middleName, lastName, prefixId, suffixId, male,
1845 birthdayMonth, birthdayDay, birthdayYear, smsSn, aimSn, facebookSn,
1846 icqSn, jabberSn, msnSn, mySpaceSn, skypeSn, twitterSn, ymSn,
1847 jobTitle, organizationIds);
1848 }
1849
1850 public User updateUser(
1851 long userId, String oldPassword, String newPassword1,
1852 String newPassword2, boolean passwordReset, String screenName,
1853 String emailAddress, String languageId, String timeZoneId,
1854 String greeting, String comments, String firstName,
1855 String middleName, String lastName, int prefixId, int suffixId,
1856 boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
1857 String smsSn, String aimSn, String facebookSn, String icqSn,
1858 String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
1859 String twitterSn, String ymSn, String jobTitle,
1860 long[] organizationIds)
1861 throws PortalException, SystemException {
1862
1863
1865 String password = oldPassword;
1866 screenName = getScreenName(screenName);
1867 emailAddress = emailAddress.trim().toLowerCase();
1868 aimSn = aimSn.trim().toLowerCase();
1869 facebookSn = facebookSn.trim().toLowerCase();
1870 icqSn = icqSn.trim().toLowerCase();
1871 jabberSn = jabberSn.trim().toLowerCase();
1872 msnSn = msnSn.trim().toLowerCase();
1873 mySpaceSn = mySpaceSn.trim().toLowerCase();
1874 skypeSn = skypeSn.trim().toLowerCase();
1875 twitterSn = twitterSn.trim().toLowerCase();
1876 ymSn = ymSn.trim().toLowerCase();
1877 Date now = new Date();
1878
1879 validate(userId, screenName, emailAddress, firstName, lastName, smsSn);
1880
1881 if (Validator.isNotNull(newPassword1) ||
1882 Validator.isNotNull(newPassword2)) {
1883
1884 updatePassword(userId, newPassword1, newPassword2, passwordReset);
1885
1886 password = newPassword1;
1887 }
1888
1889 User user = userPersistence.findByPrimaryKey(userId);
1890 Company company = companyPersistence.findByPrimaryKey(
1891 user.getCompanyId());
1892
1893 user.setModifiedDate(now);
1894
1895 if (user.getContactId() <= 0) {
1896 user.setContactId(counterLocalService.increment());
1897 }
1898
1899 user.setPasswordReset(passwordReset);
1900 user.setScreenName(screenName);
1901
1902 if (!emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
1903
1904
1906 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
1907 mailService.addUser(
1908 user.getCompanyId(), userId, password, firstName,
1909 middleName, lastName, emailAddress);
1910 }
1911
1912
1914 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
1915 mailService.updateEmailAddress(
1916 user.getCompanyId(), userId, emailAddress);
1917 }
1918
1919
1921 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
1922 mailService.deleteEmailAddress(user.getCompanyId(), userId);
1923 }
1924
1925 user.setEmailAddress(emailAddress);
1926 }
1927
1928 user.setLanguageId(languageId);
1929 user.setTimeZoneId(timeZoneId);
1930 user.setGreeting(greeting);
1931 user.setComments(comments);
1932 user.setFirstName(firstName);
1933 user.setMiddleName(middleName);
1934 user.setLastName(lastName);
1935 user.setJobTitle(jobTitle);
1936
1937 userPersistence.update(user, false);
1938
1939
1941 Date birthday = PortalUtil.getDate(
1942 birthdayMonth, birthdayDay, birthdayYear,
1943 new ContactBirthdayException());
1944
1945 long contactId = user.getContactId();
1946
1947 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
1948
1949 if (contact == null) {
1950 contact = contactPersistence.create(contactId);
1951
1952 contact.setCompanyId(user.getCompanyId());
1953 contact.setUserName(StringPool.BLANK);
1954 contact.setCreateDate(now);
1955 contact.setAccountId(company.getAccountId());
1956 contact.setParentContactId(
1957 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
1958 }
1959
1960 contact.setModifiedDate(now);
1961 contact.setFirstName(firstName);
1962 contact.setMiddleName(middleName);
1963 contact.setLastName(lastName);
1964 contact.setPrefixId(prefixId);
1965 contact.setSuffixId(suffixId);
1966 contact.setMale(male);
1967 contact.setBirthday(birthday);
1968 contact.setSmsSn(smsSn);
1969 contact.setAimSn(aimSn);
1970 contact.setFacebookSn(facebookSn);
1971 contact.setIcqSn(icqSn);
1972 contact.setJabberSn(jabberSn);
1973 contact.setMsnSn(msnSn);
1974 contact.setMySpaceSn(mySpaceSn);
1975 contact.setSkypeSn(skypeSn);
1976 contact.setTwitterSn(twitterSn);
1977 contact.setYmSn(ymSn);
1978 contact.setJobTitle(jobTitle);
1979
1980 contactPersistence.update(contact, false);
1981
1982
1984 updateOrganizations(userId, organizationIds);
1985
1986
1988 Group group = groupLocalService.getUserGroup(
1989 user.getCompanyId(), userId);
1990
1991 group.setFriendlyURL(StringPool.SLASH + screenName);
1992
1993 groupPersistence.update(group, false);
1994
1995
1997 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
1998
1999
2001 PermissionCacheUtil.clearCache();
2002
2003 return user;
2004 }
2005
2006 protected int authenticate(
2007 long companyId, String login, String password, String authType,
2008 Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
2009 throws PortalException, SystemException {
2010
2011 login = login.trim().toLowerCase();
2012
2013 long userId = GetterUtil.getLong(login);
2014
2015
2017 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2018 if (!Validator.isEmailAddress(login)) {
2019 throw new UserEmailAddressException();
2020 }
2021 }
2022 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2023 if (Validator.isNull(login)) {
2024 throw new UserScreenNameException();
2025 }
2026 }
2027 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2028 if (Validator.isNull(login)) {
2029 throw new UserIdException();
2030 }
2031 }
2032
2033 if (Validator.isNull(password)) {
2034 throw new UserPasswordException(
2035 UserPasswordException.PASSWORD_INVALID);
2036 }
2037
2038 int authResult = Authenticator.FAILURE;
2039
2040
2042 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2043 authResult = AuthPipeline.authenticateByEmailAddress(
2044 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
2045 headerMap, parameterMap);
2046 }
2047 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2048 authResult = AuthPipeline.authenticateByScreenName(
2049 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
2050 headerMap, parameterMap);
2051 }
2052 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2053 authResult = AuthPipeline.authenticateByUserId(
2054 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
2055 headerMap, parameterMap);
2056 }
2057
2058
2060 User user = null;
2061
2062 try {
2063 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2064 user = userPersistence.findByC_EA(companyId, login);
2065 }
2066 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2067 user = userPersistence.findByC_SN(companyId, login);
2068 }
2069 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2070 user = userPersistence.findByC_U(
2071 companyId, GetterUtil.getLong(login));
2072 }
2073 }
2074 catch (NoSuchUserException nsue) {
2075 return Authenticator.DNE;
2076 }
2077
2078 if (user.isDefaultUser()) {
2079 _log.error(
2080 "The default user should never be allowed to authenticate");
2081
2082 return Authenticator.DNE;
2083 }
2084
2085 if (!user.isPasswordEncrypted()) {
2086 user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
2087 user.setPasswordEncrypted(true);
2088
2089 userPersistence.update(user, false);
2090 }
2091
2092
2095 checkLockout(user);
2096
2097 checkPasswordExpired(user);
2098
2099
2101 if (authResult == Authenticator.SUCCESS) {
2102 if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
2103 String encPassword = PwdEncryptor.encrypt(
2104 password, user.getPassword());
2105
2106 if (user.getPassword().equals(encPassword)) {
2107 authResult = Authenticator.SUCCESS;
2108 }
2109 else if (GetterUtil.getBoolean(PropsUtil.get(
2110 PropsKeys.AUTH_MAC_ALLOW))) {
2111
2112 try {
2113 MessageDigest digester = MessageDigest.getInstance(
2114 PropsUtil.get(PropsKeys.AUTH_MAC_ALGORITHM));
2115
2116 digester.update(login.getBytes("UTF8"));
2117
2118 String shardKey =
2119 PropsUtil.get(PropsKeys.AUTH_MAC_SHARED_KEY);
2120
2121 encPassword = Base64.encode(
2122 digester.digest(shardKey.getBytes("UTF8")));
2123
2124 if (password.equals(encPassword)) {
2125 authResult = Authenticator.SUCCESS;
2126 }
2127 else {
2128 authResult = Authenticator.FAILURE;
2129 }
2130 }
2131 catch (NoSuchAlgorithmException nsae) {
2132 throw new SystemException(nsae);
2133 }
2134 catch (UnsupportedEncodingException uee) {
2135 throw new SystemException(uee);
2136 }
2137 }
2138 else {
2139 authResult = Authenticator.FAILURE;
2140 }
2141 }
2142 }
2143
2144
2146 if (authResult == Authenticator.SUCCESS) {
2147 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2148 authResult = AuthPipeline.authenticateByEmailAddress(
2149 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
2150 headerMap, parameterMap);
2151 }
2152 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2153 authResult = AuthPipeline.authenticateByScreenName(
2154 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
2155 headerMap, parameterMap);
2156 }
2157 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2158 authResult = AuthPipeline.authenticateByUserId(
2159 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
2160 headerMap, parameterMap);
2161 }
2162 }
2163
2164
2166 if (authResult == Authenticator.FAILURE) {
2167 try {
2168 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2169 AuthPipeline.onFailureByEmailAddress(
2170 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
2171 parameterMap);
2172 }
2173 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2174 AuthPipeline.onFailureByScreenName(
2175 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
2176 parameterMap);
2177 }
2178 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2179 AuthPipeline.onFailureByUserId(
2180 PropsKeys.AUTH_FAILURE, companyId, userId, headerMap,
2181 parameterMap);
2182 }
2183
2184
2186 if (!PortalLDAPUtil.isPasswordPolicyEnabled(
2187 user.getCompanyId())) {
2188
2189 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2190
2191 int failedLoginAttempts = user.getFailedLoginAttempts();
2192 int maxFailures = passwordPolicy.getMaxFailure();
2193
2194 if ((failedLoginAttempts >= maxFailures) &&
2195 (maxFailures != 0)) {
2196
2197 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2198 AuthPipeline.onMaxFailuresByEmailAddress(
2199 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
2200 headerMap, parameterMap);
2201 }
2202 else if (authType.equals(
2203 CompanyConstants.AUTH_TYPE_SN)) {
2204
2205 AuthPipeline.onMaxFailuresByScreenName(
2206 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
2207 headerMap, parameterMap);
2208 }
2209 else if (authType.equals(
2210 CompanyConstants.AUTH_TYPE_ID)) {
2211
2212 AuthPipeline.onMaxFailuresByUserId(
2213 PropsKeys.AUTH_MAX_FAILURES, companyId, userId,
2214 headerMap, parameterMap);
2215 }
2216 }
2217 }
2218 }
2219 catch (Exception e) {
2220 _log.error(e, e);
2221 }
2222 }
2223
2224 return authResult;
2225 }
2226
2227 protected void copyUserGroupLayouts(long userGroupId, long userId)
2228 throws PortalException, SystemException {
2229
2230 UserGroup userGroup = userGroupLocalService.getUserGroup(userGroupId);
2231 User user = getUserById(userId);
2232
2233 Map<String, String[]> parameterMap = getLayoutTemplatesParameters();
2234
2235 if (userGroup.hasPrivateLayouts()) {
2236 long sourceGroupId = userGroup.getGroup().getGroupId();
2237 long targetGroupId = user.getGroup().getGroupId();
2238
2239 byte[] bytes = layoutLocalService.exportLayouts(
2240 sourceGroupId, true, parameterMap, null, null);
2241
2242 ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
2243
2244 layoutLocalService.importLayouts(
2245 userId, targetGroupId, true, parameterMap, bais);
2246 }
2247
2248 if (userGroup.hasPublicLayouts()) {
2249 long sourceGroupId = userGroup.getGroup().getGroupId();
2250 long targetGroupId = user.getGroup().getGroupId();
2251
2252 byte[] bytes = layoutLocalService.exportLayouts(
2253 sourceGroupId, false, parameterMap, null, null);
2254
2255 ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
2256
2257 layoutLocalService.importLayouts(
2258 userId, targetGroupId, false, parameterMap, bais);
2259 }
2260 }
2261
2262 protected void copyUserGroupLayouts(long userGroupId, long userIds[])
2263 throws PortalException, SystemException {
2264
2265 for (long userId : userIds) {
2266 if (!userGroupPersistence.containsUser(userGroupId, userId)) {
2267 copyUserGroupLayouts(userGroupId, userId);
2268 }
2269 }
2270 }
2271
2272 protected void doSendPassword(
2273 long companyId, String emailAddress, String remoteAddr,
2274 String remoteHost, String userAgent)
2275 throws IOException, PortalException, SystemException {
2276
2277 if (!PrefsPropsUtil.getBoolean(
2278 companyId, PropsKeys.COMPANY_SECURITY_SEND_PASSWORD) ||
2279 !PrefsPropsUtil.getBoolean(
2280 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_ENABLED)) {
2281
2282 return;
2283 }
2284
2285 emailAddress = emailAddress.trim().toLowerCase();
2286
2287 if (!Validator.isEmailAddress(emailAddress)) {
2288 throw new UserEmailAddressException();
2289 }
2290
2291 Company company = companyPersistence.findByPrimaryKey(companyId);
2292
2293 User user = userPersistence.findByC_EA(companyId, emailAddress);
2294
2295 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2296
2297
2300
2301 String newPassword = null;
2302
2303 if (!PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
2304 PwdEncryptor.TYPE_NONE)) {
2305
2306 newPassword = PwdToolkitUtil.generate();
2307
2308 boolean passwordReset = false;
2309
2310 if (passwordPolicy.getChangeable() &&
2311 passwordPolicy.getChangeRequired()) {
2312
2313 passwordReset = true;
2314 }
2315
2316 user.setPassword(PwdEncryptor.encrypt(newPassword));
2317 user.setPasswordUnencrypted(newPassword);
2318 user.setPasswordEncrypted(true);
2319 user.setPasswordReset(passwordReset);
2320 user.setPasswordModified(true);
2321 user.setPasswordModifiedDate(new Date());
2322
2323 userPersistence.update(user, false);
2324
2325 user.setPasswordModified(false);
2326 }
2327 else {
2328 newPassword = user.getPassword();
2329 }
2330
2331 String fromName = PrefsPropsUtil.getString(
2332 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
2333 String fromAddress = PrefsPropsUtil.getString(
2334 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
2335
2336 String toName = user.getFullName();
2337 String toAddress = user.getEmailAddress();
2338
2339 String subject = PrefsPropsUtil.getContent(
2340 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
2341 String body = PrefsPropsUtil.getContent(
2342 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
2343
2344 subject = StringUtil.replace(
2345 subject,
2346 new String[] {
2347 "[$FROM_ADDRESS$]",
2348 "[$FROM_NAME$]",
2349 "[$PORTAL_URL$]",
2350 "[$REMOTE_ADDRESS$]",
2351 "[$REMOTE_HOST$]",
2352 "[$TO_ADDRESS$]",
2353 "[$TO_NAME$]",
2354 "[$USER_AGENT$]",
2355 "[$USER_ID$]",
2356 "[$USER_PASSWORD$]",
2357 "[$USER_SCREENNAME$]"
2358 },
2359 new String[] {
2360 fromAddress,
2361 fromName,
2362 company.getVirtualHost(),
2363 remoteAddr,
2364 remoteHost,
2365 toAddress,
2366 toName,
2367 HtmlUtil.escape(userAgent),
2368 String.valueOf(user.getUserId()),
2369 newPassword,
2370 user.getScreenName()
2371 });
2372
2373 body = StringUtil.replace(
2374 body,
2375 new String[] {
2376 "[$FROM_ADDRESS$]",
2377 "[$FROM_NAME$]",
2378 "[$PORTAL_URL$]",
2379 "[$REMOTE_ADDRESS$]",
2380 "[$REMOTE_HOST$]",
2381 "[$TO_ADDRESS$]",
2382 "[$TO_NAME$]",
2383 "[$USER_AGENT$]",
2384 "[$USER_ID$]",
2385 "[$USER_PASSWORD$]",
2386 "[$USER_SCREENNAME$]"
2387 },
2388 new String[] {
2389 fromAddress,
2390 fromName,
2391 company.getVirtualHost(),
2392 remoteAddr,
2393 remoteHost,
2394 toAddress,
2395 toName,
2396 HtmlUtil.escape(userAgent),
2397 String.valueOf(user.getUserId()),
2398 newPassword,
2399 user.getScreenName()
2400 });
2401
2402 InternetAddress from = new InternetAddress(fromAddress, fromName);
2403
2404 InternetAddress to = new InternetAddress(toAddress, toName);
2405
2406 MailMessage message = new MailMessage(from, to, subject, body, true);
2407
2408 mailService.sendEmail(message);
2409 }
2410
2411 protected Map<String, String[]> getLayoutTemplatesParameters() {
2412 Map<String, String[]> parameterMap =
2413 new LinkedHashMap<String, String[]>();
2414
2415 parameterMap.put(
2416 PortletDataHandlerKeys.DATA_STRATEGY,
2417 new String[] {PortletDataHandlerKeys.DATA_STRATEGY_MIRROR});
2418 parameterMap.put(
2419 PortletDataHandlerKeys.DELETE_MISSING_LAYOUTS,
2420 new String[] {Boolean.FALSE.toString()});
2421 parameterMap.put(
2422 PortletDataHandlerKeys.DELETE_PORTLET_DATA,
2423 new String[] {Boolean.FALSE.toString()});
2424 parameterMap.put(
2425 PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE,
2426 new String[] {PortletDataHandlerKeys.
2427 LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_NAME});
2428 parameterMap.put(
2429 PortletDataHandlerKeys.PERMISSIONS,
2430 new String[] {Boolean.TRUE.toString()});
2431 parameterMap.put(
2432 PortletDataHandlerKeys.PORTLET_DATA,
2433 new String[] {Boolean.TRUE.toString()});
2434 parameterMap.put(
2435 PortletDataHandlerKeys.PORTLET_DATA_ALL,
2436 new String[] {Boolean.TRUE.toString()});
2437 parameterMap.put(
2438 PortletDataHandlerKeys.PORTLET_SETUP,
2439 new String[] {Boolean.TRUE.toString()});
2440 parameterMap.put(
2441 PortletDataHandlerKeys.PORTLET_USER_PREFERENCES,
2442 new String[] {Boolean.TRUE.toString()});
2443 parameterMap.put(
2444 PortletDataHandlerKeys.PORTLETS_MERGE_MODE,
2445 new String[] {PortletDataHandlerKeys.
2446 PORTLETS_MERGE_MODE_ADD_TO_BOTTOM});
2447 parameterMap.put(
2448 PortletDataHandlerKeys.THEME,
2449 new String[] {Boolean.FALSE.toString()});
2450 parameterMap.put(
2451 PortletDataHandlerKeys.USER_ID_STRATEGY,
2452 new String[] {UserIdStrategy.CURRENT_USER_ID});
2453 parameterMap.put(
2454 PortletDataHandlerKeys.USER_PERMISSIONS,
2455 new String[] {Boolean.FALSE.toString()});
2456
2457 return parameterMap;
2458 }
2459
2460 protected String getScreenName(String screenName) {
2461 return StringUtil.lowerCase(StringUtil.trim(screenName));
2462 }
2463
2464 protected long[] getUserIds(List<User> users) {
2465 long[] userIds = new long[users.size()];
2466
2467 for (int i = 0; i < users.size(); i++) {
2468 User user = users.get(i);
2469
2470 userIds[i] = user.getUserId();
2471 }
2472
2473 return userIds;
2474 }
2475
2476 protected void sendEmail(User user, String password)
2477 throws IOException, PortalException, SystemException {
2478
2479 if (!PrefsPropsUtil.getBoolean(
2480 user.getCompanyId(),
2481 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
2482
2483 return;
2484 }
2485
2486 long companyId = user.getCompanyId();
2487
2488 Company company = companyPersistence.findByPrimaryKey(companyId);
2489
2490 String fromName = PrefsPropsUtil.getString(
2491 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
2492 String fromAddress = PrefsPropsUtil.getString(
2493 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
2494
2495 String toName = user.getFullName();
2496 String toAddress = user.getEmailAddress();
2497
2498 String subject = PrefsPropsUtil.getContent(
2499 companyId, PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
2500 String body = PrefsPropsUtil.getContent(
2501 companyId, PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
2502
2503 subject = StringUtil.replace(
2504 subject,
2505 new String[] {
2506 "[$FROM_ADDRESS$]",
2507 "[$FROM_NAME$]",
2508 "[$PORTAL_URL$]",
2509 "[$TO_ADDRESS$]",
2510 "[$TO_NAME$]",
2511 "[$USER_ID$]",
2512 "[$USER_PASSWORD$]",
2513 "[$USER_SCREENNAME$]"
2514 },
2515 new String[] {
2516 fromAddress,
2517 fromName,
2518 company.getVirtualHost(),
2519 toAddress,
2520 toName,
2521 String.valueOf(user.getUserId()),
2522 password,
2523 user.getScreenName()
2524 });
2525
2526 body = StringUtil.replace(
2527 body,
2528 new String[] {
2529 "[$FROM_ADDRESS$]",
2530 "[$FROM_NAME$]",
2531 "[$PORTAL_URL$]",
2532 "[$TO_ADDRESS$]",
2533 "[$TO_NAME$]",
2534 "[$USER_ID$]",
2535 "[$USER_PASSWORD$]",
2536 "[$USER_SCREENNAME$]"
2537 },
2538 new String[] {
2539 fromAddress,
2540 fromName,
2541 company.getVirtualHost(),
2542 toAddress,
2543 toName,
2544 String.valueOf(user.getUserId()),
2545 password,
2546 user.getScreenName()
2547 });
2548
2549 InternetAddress from = new InternetAddress(fromAddress, fromName);
2550
2551 InternetAddress to = new InternetAddress(toAddress, toName);
2552
2553 MailMessage message = new MailMessage(from, to, subject, body, true);
2554
2555 mailService.sendEmail(message);
2556 }
2557
2558 protected void validate(
2559 long userId, String screenName, String emailAddress,
2560 String firstName, String lastName, String smsSn)
2561 throws PortalException, SystemException {
2562
2563 User user = userPersistence.findByPrimaryKey(userId);
2564
2565 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
2566 validateScreenName(user.getCompanyId(), userId, screenName);
2567 }
2568
2569 validateEmailAddress(emailAddress);
2570
2571 if (!user.isDefaultUser()) {
2572 if (!user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
2573 if (userPersistence.fetchByC_EA(
2574 user.getCompanyId(), emailAddress) != null) {
2575
2576 throw new DuplicateUserEmailAddressException();
2577 }
2578 }
2579
2580 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
2581 user.getCompanyId(), PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
2582 StringPool.NEW_LINE,
2583 PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
2584
2585 for (int i = 0; i < reservedEmailAddresses.length; i++) {
2586 if (emailAddress.equalsIgnoreCase(reservedEmailAddresses[i])) {
2587 throw new ReservedUserEmailAddressException();
2588 }
2589 }
2590
2591 if (Validator.isNull(firstName)) {
2592 throw new ContactFirstNameException();
2593 }
2594 else if (Validator.isNull(lastName)) {
2595 throw new ContactLastNameException();
2596 }
2597 }
2598
2599 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
2600 throw new UserSmsException();
2601 }
2602 }
2603
2604 protected void validate(
2605 long companyId, long userId, boolean autoPassword, String password1,
2606 String password2, boolean autoScreenName, String screenName,
2607 String emailAddress, String firstName, String lastName,
2608 long[] organizationIds)
2609 throws PortalException, SystemException {
2610
2611 Company company = companyPersistence.findByPrimaryKey(companyId);
2612
2613 if (company.isSystem()) {
2614 return;
2615 }
2616
2617 if (!autoScreenName) {
2618 validateScreenName(companyId, userId, screenName);
2619 }
2620
2621 if (!autoPassword) {
2622 PasswordPolicy passwordPolicy =
2623 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
2624
2625 PwdToolkitUtil.validate(
2626 companyId, 0, password1, password2, passwordPolicy);
2627 }
2628
2629 validateEmailAddress(emailAddress);
2630
2631 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
2632
2633 if (user != null) {
2634 throw new DuplicateUserEmailAddressException();
2635 }
2636
2637 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
2638 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
2639 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
2640
2641 for (int i = 0; i < reservedEmailAddresses.length; i++) {
2642 if (emailAddress.equalsIgnoreCase(reservedEmailAddresses[i])) {
2643 throw new ReservedUserEmailAddressException();
2644 }
2645 }
2646
2647 if (Validator.isNull(firstName)) {
2648 throw new ContactFirstNameException();
2649 }
2650 else if (Validator.isNull(lastName)) {
2651 throw new ContactLastNameException();
2652 }
2653 }
2654
2655 protected void validateEmailAddress(String emailAddress)
2656 throws PortalException {
2657
2658 if (!Validator.isEmailAddress(emailAddress) ||
2659 emailAddress.startsWith("root@") ||
2660 emailAddress.startsWith("postmaster@")) {
2661
2662 throw new UserEmailAddressException();
2663 }
2664 }
2665
2666 protected void validatePassword(
2667 long companyId, long userId, String password1, String password2)
2668 throws PortalException, SystemException {
2669
2670 if (Validator.isNull(password1) || Validator.isNull(password2)) {
2671 throw new UserPasswordException(
2672 UserPasswordException.PASSWORD_INVALID);
2673 }
2674
2675 if (!password1.equals(password2)) {
2676 throw new UserPasswordException(
2677 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
2678 }
2679
2680 PasswordPolicy passwordPolicy =
2681 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
2682
2683 PwdToolkitUtil.validate(
2684 companyId, userId, password1, password2, passwordPolicy);
2685 }
2686
2687 protected void validateScreenName(
2688 long companyId, long userId, String screenName)
2689 throws PortalException, SystemException {
2690
2691 if (Validator.isNull(screenName)) {
2692 throw new UserScreenNameException();
2693 }
2694
2695 ScreenNameValidator screenNameValidator =
2696 (ScreenNameValidator)InstancePool.get(
2697 PropsValues.USERS_SCREEN_NAME_VALIDATOR);
2698
2699 if (screenNameValidator != null) {
2700 if (!screenNameValidator.validate(companyId, screenName)) {
2701 throw new UserScreenNameException();
2702 }
2703 }
2704
2705 if (Validator.isNumber(screenName) &&
2706 !screenName.equals(String.valueOf(userId))) {
2707
2708 throw new UserScreenNameException();
2709 }
2710
2711 for (char c : screenName.toCharArray()) {
2712 if ((!Validator.isChar(c)) && (!Validator.isDigit(c)) &&
2713 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
2714 (c != CharPool.UNDERLINE)) {
2715
2716 throw new UserScreenNameException();
2717 }
2718 }
2719
2720 String[] anonymousNames = PrincipalBean.ANONYMOUS_NAMES;
2721
2722 for (int i = 0; i < anonymousNames.length; i++) {
2723 if (screenName.equalsIgnoreCase(anonymousNames[i])) {
2724 throw new UserScreenNameException();
2725 }
2726 }
2727
2728 User user = userPersistence.fetchByC_SN(companyId, screenName);
2729
2730 if (user != null) {
2731 throw new DuplicateUserScreenNameException();
2732 }
2733
2734 String friendlyURL = StringPool.SLASH + screenName;
2735
2736 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
2737
2738 if (group != null) {
2739 throw new DuplicateUserScreenNameException();
2740 }
2741
2742 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
2743
2744 if (exceptionType != -1) {
2745 throw new UserScreenNameException(
2746 new GroupFriendlyURLException(exceptionType));
2747 }
2748
2749 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
2750 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
2751 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
2752
2753 for (int i = 0; i < reservedScreenNames.length; i++) {
2754 if (screenName.equalsIgnoreCase(reservedScreenNames[i])) {
2755 throw new ReservedUserScreenNameException();
2756 }
2757 }
2758 }
2759
2760 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
2761
2762 private static Map<Long, User> _defaultUsers =
2763 new ConcurrentHashMap<Long, User>();
2764
2765}