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