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