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