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