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