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