1
14
15 package com.liferay.portal.service.impl;
16
17 import com.liferay.portal.CompanyMaxUsersException;
18 import com.liferay.portal.ContactBirthdayException;
19 import com.liferay.portal.ContactFirstNameException;
20 import com.liferay.portal.ContactFullNameException;
21 import com.liferay.portal.ContactLastNameException;
22 import com.liferay.portal.DuplicateUserEmailAddressException;
23 import com.liferay.portal.DuplicateUserScreenNameException;
24 import com.liferay.portal.GroupFriendlyURLException;
25 import com.liferay.portal.ModelListenerException;
26 import com.liferay.portal.NoSuchContactException;
27 import com.liferay.portal.NoSuchGroupException;
28 import com.liferay.portal.NoSuchRoleException;
29 import com.liferay.portal.NoSuchUserException;
30 import com.liferay.portal.NoSuchUserGroupException;
31 import com.liferay.portal.PasswordExpiredException;
32 import com.liferay.portal.RequiredUserException;
33 import com.liferay.portal.ReservedUserEmailAddressException;
34 import com.liferay.portal.ReservedUserScreenNameException;
35 import com.liferay.portal.UserEmailAddressException;
36 import com.liferay.portal.UserIdException;
37 import com.liferay.portal.UserLockoutException;
38 import com.liferay.portal.UserPasswordException;
39 import com.liferay.portal.UserPortraitSizeException;
40 import com.liferay.portal.UserPortraitTypeException;
41 import com.liferay.portal.UserReminderQueryException;
42 import com.liferay.portal.UserScreenNameException;
43 import com.liferay.portal.UserSmsException;
44 import com.liferay.portal.kernel.annotation.Propagation;
45 import com.liferay.portal.kernel.annotation.Transactional;
46 import com.liferay.portal.kernel.exception.PortalException;
47 import com.liferay.portal.kernel.exception.SystemException;
48 import com.liferay.portal.kernel.image.ImageBag;
49 import com.liferay.portal.kernel.image.ImageProcessorUtil;
50 import com.liferay.portal.kernel.language.LanguageUtil;
51 import com.liferay.portal.kernel.log.Log;
52 import com.liferay.portal.kernel.log.LogFactoryUtil;
53 import com.liferay.portal.kernel.mail.MailMessage;
54 import com.liferay.portal.kernel.search.Hits;
55 import com.liferay.portal.kernel.search.Indexer;
56 import com.liferay.portal.kernel.search.IndexerRegistryUtil;
57 import com.liferay.portal.kernel.search.SearchContext;
58 import com.liferay.portal.kernel.search.Sort;
59 import com.liferay.portal.kernel.util.ArrayUtil;
60 import com.liferay.portal.kernel.util.Base64;
61 import com.liferay.portal.kernel.util.CharPool;
62 import com.liferay.portal.kernel.util.GetterUtil;
63 import com.liferay.portal.kernel.util.HtmlUtil;
64 import com.liferay.portal.kernel.util.KeyValuePair;
65 import com.liferay.portal.kernel.util.OrderByComparator;
66 import com.liferay.portal.kernel.util.PropsKeys;
67 import com.liferay.portal.kernel.util.StringPool;
68 import com.liferay.portal.kernel.util.StringUtil;
69 import com.liferay.portal.kernel.util.Validator;
70 import com.liferay.portal.model.Company;
71 import com.liferay.portal.model.CompanyConstants;
72 import com.liferay.portal.model.Contact;
73 import com.liferay.portal.model.ContactConstants;
74 import com.liferay.portal.model.Group;
75 import com.liferay.portal.model.Organization;
76 import com.liferay.portal.model.PasswordPolicy;
77 import com.liferay.portal.model.ResourceConstants;
78 import com.liferay.portal.model.Role;
79 import com.liferay.portal.model.RoleConstants;
80 import com.liferay.portal.model.Ticket;
81 import com.liferay.portal.model.User;
82 import com.liferay.portal.model.UserGroup;
83 import com.liferay.portal.model.UserGroupRole;
84 import com.liferay.portal.model.impl.LayoutImpl;
85 import com.liferay.portal.security.auth.AuthPipeline;
86 import com.liferay.portal.security.auth.Authenticator;
87 import com.liferay.portal.security.auth.EmailAddressGenerator;
88 import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
89 import com.liferay.portal.security.auth.FullNameGenerator;
90 import com.liferay.portal.security.auth.FullNameGeneratorFactory;
91 import com.liferay.portal.security.auth.FullNameValidator;
92 import com.liferay.portal.security.auth.FullNameValidatorFactory;
93 import com.liferay.portal.security.auth.PrincipalException;
94 import com.liferay.portal.security.auth.ScreenNameGenerator;
95 import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
96 import com.liferay.portal.security.auth.ScreenNameValidator;
97 import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
98 import com.liferay.portal.security.ldap.LDAPSettingsUtil;
99 import com.liferay.portal.security.permission.PermissionCacheUtil;
100 import com.liferay.portal.security.pwd.PwdEncryptor;
101 import com.liferay.portal.security.pwd.PwdToolkitUtil;
102 import com.liferay.portal.service.ServiceContext;
103 import com.liferay.portal.service.ServiceContextThreadLocal;
104 import com.liferay.portal.service.base.PrincipalBean;
105 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
106 import com.liferay.portal.util.PortalUtil;
107 import com.liferay.portal.util.PrefsPropsUtil;
108 import com.liferay.portal.util.PropsUtil;
109 import com.liferay.portal.util.PropsValues;
110 import com.liferay.portlet.enterpriseadmin.util.EnterpriseAdminUtil;
111 import com.liferay.portlet.imagegallery.ImageSizeException;
112 import com.liferay.portlet.messageboards.model.MBMessage;
113 import com.liferay.util.Encryptor;
114 import com.liferay.util.EncryptorException;
115
116 import java.awt.image.RenderedImage;
117
118 import java.io.IOException;
119 import java.io.Serializable;
120 import java.io.UnsupportedEncodingException;
121
122 import java.security.MessageDigest;
123 import java.security.NoSuchAlgorithmException;
124
125 import java.util.ArrayList;
126 import java.util.Arrays;
127 import java.util.Date;
128 import java.util.HashMap;
129 import java.util.HashSet;
130 import java.util.LinkedHashMap;
131 import java.util.List;
132 import java.util.Locale;
133 import java.util.Map;
134 import java.util.Set;
135 import java.util.concurrent.ConcurrentHashMap;
136
137 import javax.mail.internet.InternetAddress;
138
139
150 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
151
152 public void addDefaultGroups(long userId)
153 throws PortalException, SystemException {
154
155 User user = userPersistence.findByPrimaryKey(userId);
156
157 Set<Long> groupIdsSet = new HashSet<Long>();
158
159 String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
160 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
161 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
162
163 for (String defaultGroupName : defaultGroupNames) {
164 try {
165 Group group = groupPersistence.findByC_N(
166 user.getCompanyId(), defaultGroupName);
167
168 if (!userPersistence.containsGroup(
169 userId, group.getGroupId())) {
170
171 groupIdsSet.add(group.getGroupId());
172 }
173 }
174 catch (NoSuchGroupException nsge) {
175 }
176 }
177
178 long[] groupIds = ArrayUtil.toArray(
179 groupIdsSet.toArray(new Long[groupIdsSet.size()]));
180
181 groupLocalService.addUserGroups(userId, groupIds);
182 }
183
184 public void addDefaultRoles(long userId)
185 throws PortalException, SystemException {
186
187 User user = userPersistence.findByPrimaryKey(userId);
188
189 Set<Long> roleIdSet = new HashSet<Long>();
190
191 String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
192 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
193 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
194
195 for (String defaultRoleName : defaultRoleNames) {
196 try {
197 Role role = rolePersistence.findByC_N(
198 user.getCompanyId(), defaultRoleName);
199
200 if (!userPersistence.containsRole(
201 userId, role.getRoleId())) {
202
203 roleIdSet.add(role.getRoleId());
204 }
205 }
206 catch (NoSuchRoleException nsre) {
207 }
208 }
209
210 long[] roleIds = ArrayUtil.toArray(
211 roleIdSet.toArray(new Long[roleIdSet.size()]));
212
213 roleIds = EnterpriseAdminUtil.addRequiredRoles(user, roleIds);
214
215 userPersistence.addRoles(userId, roleIds);
216 }
217
218 public void addDefaultUserGroups(long userId)
219 throws PortalException, SystemException {
220
221 User user = userPersistence.findByPrimaryKey(userId);
222
223 Set<Long> userGroupIdSet = new HashSet<Long>();
224
225 String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
226 user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
227 StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
228
229 for (String defaultUserGroupName : defaultUserGroupNames) {
230 try {
231 UserGroup userGroup = userGroupPersistence.findByC_N(
232 user.getCompanyId(), defaultUserGroupName);
233
234 if (!userPersistence.containsUserGroup(
235 userId, userGroup.getUserGroupId())) {
236
237 userGroupIdSet.add(userGroup.getUserGroupId());
238 }
239 }
240 catch (NoSuchUserGroupException nsuge) {
241 }
242 }
243
244 long[] userGroupIds = ArrayUtil.toArray(
245 userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
246
247 for (long userGroupId : userGroupIds) {
248 userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
249 }
250
251 userPersistence.addUserGroups(userId, userGroupIds);
252 }
253
254 public void addGroupUsers(long groupId, long[] userIds)
255 throws PortalException, SystemException {
256
257 groupPersistence.addUsers(groupId, userIds);
258
259 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
260
261 indexer.reindex(userIds);
262
263 PermissionCacheUtil.clearCache();
264 }
265
266 public void addOrganizationUsers(long organizationId, long[] userIds)
267 throws PortalException, SystemException {
268
269 organizationPersistence.addUsers(organizationId, userIds);
270
271 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
272
273 indexer.reindex(userIds);
274
275 PermissionCacheUtil.clearCache();
276 }
277
278 public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
279 throws SystemException {
280
281 passwordPolicyRelLocalService.addPasswordPolicyRels(
282 passwordPolicyId, User.class.getName(), userIds);
283 }
284
285 public void addRoleUsers(long roleId, long[] userIds)
286 throws PortalException, SystemException {
287
288 rolePersistence.addUsers(roleId, userIds);
289
290 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
291
292 indexer.reindex(userIds);
293
294 PermissionCacheUtil.clearCache();
295 }
296
297 public void addTeamUsers(long teamId, long[] userIds)
298 throws PortalException, SystemException {
299
300 teamPersistence.addUsers(teamId, userIds);
301
302 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
303
304 indexer.reindex(userIds);
305
306 PermissionCacheUtil.clearCache();
307 }
308
309 public User addUser(
310 long creatorUserId, long companyId, boolean autoPassword,
311 String password1, String password2, boolean autoScreenName,
312 String screenName, String emailAddress, String openId,
313 Locale locale, String firstName, String middleName, String lastName,
314 int prefixId, int suffixId, boolean male, int birthdayMonth,
315 int birthdayDay, int birthdayYear, String jobTitle, long[] groupIds,
316 long[] organizationIds, long[] roleIds, long[] userGroupIds,
317 boolean sendEmail, ServiceContext serviceContext)
318 throws PortalException, SystemException {
319
320 ServiceContext previousServiceContext =
321 ServiceContextThreadLocal.getServiceContext();
322
323 ServiceContextThreadLocal.setServiceContext(serviceContext);
324
325 try {
326 return doAddUser(
327 creatorUserId, companyId, autoPassword, password1, password2,
328 autoScreenName, screenName, emailAddress, openId, locale,
329 firstName, middleName, lastName, prefixId, suffixId, male,
330 birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
331 organizationIds, roleIds, userGroupIds, sendEmail,
332 serviceContext);
333 }
334 finally {
335 ServiceContextThreadLocal.setServiceContext(previousServiceContext);
336 }
337 }
338
339 public void addUserGroupUsers(long userGroupId, long[] userIds)
340 throws PortalException, SystemException {
341
342 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
343
344 userGroupPersistence.addUsers(userGroupId, userIds);
345
346 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
347
348 indexer.reindex(userIds);
349
350 PermissionCacheUtil.clearCache();
351 }
352
353 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
354 public int authenticateByEmailAddress(
355 long companyId, String emailAddress, String password,
356 Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
357 throws PortalException, SystemException {
358
359 return authenticate(
360 companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
361 headerMap, parameterMap);
362 }
363
364 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
365 public int authenticateByScreenName(
366 long companyId, String screenName, String password,
367 Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
368 throws PortalException, SystemException {
369
370 return authenticate(
371 companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
372 headerMap, parameterMap);
373 }
374
375 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
376 public int authenticateByUserId(
377 long companyId, long userId, String password,
378 Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
379 throws PortalException, SystemException {
380
381 return authenticate(
382 companyId, String.valueOf(userId), password,
383 CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap);
384 }
385
386 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
387 public long authenticateForBasic(
388 long companyId, String authType, String login, String password)
389 throws PortalException, SystemException {
390
391 try {
392 User user = null;
393
394 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
395 user = getUserByEmailAddress(companyId, login);
396 }
397 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
398 user = getUserByScreenName(companyId, login);
399 }
400 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
401 user = getUserById(companyId, GetterUtil.getLong(login));
402 }
403
404 if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
405 return user.getUserId();
406 }
407
408 String userPassword = user.getPassword();
409
410 if (!user.isPasswordEncrypted()) {
411 userPassword = PwdEncryptor.encrypt(userPassword);
412 }
413
414 String encPassword = PwdEncryptor.encrypt(password);
415
416 if (userPassword.equals(password) ||
417 userPassword.equals(encPassword)) {
418
419 return user.getUserId();
420 }
421 }
422 catch (NoSuchUserException nsue) {
423 }
424
425 return 0;
426 }
427
428 @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
429 public boolean authenticateForJAAS(long userId, String encPassword) {
430 try {
431 User user = userPersistence.findByPrimaryKey(userId);
432
433 if (user.isDefaultUser()) {
434 _log.error(
435 "The default user should never be allowed to authenticate");
436
437 return false;
438 }
439
440 String password = user.getPassword();
441
442 if (user.isPasswordEncrypted()) {
443 if (password.equals(encPassword)) {
444 return true;
445 }
446
447 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
448 encPassword = PwdEncryptor.encrypt(encPassword, password);
449
450 if (password.equals(encPassword)) {
451 return true;
452 }
453 }
454 }
455 else {
456 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
457 if (password.equals(encPassword)) {
458 return true;
459 }
460 }
461
462 password = PwdEncryptor.encrypt(password);
463
464 if (password.equals(encPassword)) {
465 return true;
466 }
467 }
468 }
469 catch (Exception e) {
470 _log.error(e);
471 }
472
473 return false;
474 }
475
476 public void checkLockout(User user)
477 throws PortalException, SystemException {
478
479 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
480 return;
481 }
482
483 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
484
485 if (passwordPolicy.isLockout()) {
486
487
489 Date now = new Date();
490 int failedLoginAttempts = user.getFailedLoginAttempts();
491
492 if (failedLoginAttempts > 0) {
493 long failedLoginTime = user.getLastFailedLoginDate().getTime();
494 long elapsedTime = now.getTime() - failedLoginTime;
495 long requiredElapsedTime =
496 passwordPolicy.getResetFailureCount() * 1000;
497
498 if ((requiredElapsedTime != 0) &&
499 (elapsedTime > requiredElapsedTime)) {
500
501 user.setLastFailedLoginDate(null);
502 user.setFailedLoginAttempts(0);
503 }
504 }
505
506
508 if (user.isLockout()) {
509 long lockoutTime = user.getLockoutDate().getTime();
510 long elapsedTime = now.getTime() - lockoutTime;
511 long requiredElapsedTime =
512 passwordPolicy.getLockoutDuration() * 1000;
513
514 if ((requiredElapsedTime != 0) &&
515 (elapsedTime > requiredElapsedTime)) {
516
517 user.setLockout(false);
518 user.setLockoutDate(null);
519 }
520 }
521
522 if (user.isLockout()) {
523 throw new UserLockoutException();
524 }
525 }
526 }
527
528 public void checkLoginFailure(User user) throws SystemException {
529 Date now = new Date();
530
531 int failedLoginAttempts = user.getFailedLoginAttempts();
532
533 user.setLastFailedLoginDate(now);
534 user.setFailedLoginAttempts(++failedLoginAttempts);
535
536 userPersistence.update(user, false);
537 }
538
539 public void checkLoginFailureByEmailAddress(
540 long companyId, String emailAddress)
541 throws PortalException, SystemException {
542
543 User user = getUserByEmailAddress(companyId, emailAddress);
544
545 checkLoginFailure(user);
546 }
547
548 public void checkLoginFailureById(long userId)
549 throws PortalException, SystemException {
550
551 User user = userPersistence.findByPrimaryKey(userId);
552
553 checkLoginFailure(user);
554 }
555
556 public void checkLoginFailureByScreenName(long companyId, String screenName)
557 throws PortalException, SystemException {
558
559 User user = getUserByScreenName(companyId, screenName);
560
561 checkLoginFailure(user);
562 }
563
564 public void checkPasswordExpired(User user)
565 throws PortalException, SystemException {
566
567 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
568 return;
569 }
570
571 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
572
573
575 if (isPasswordExpired(user)) {
576 int graceLoginCount = user.getGraceLoginCount();
577
578 if (graceLoginCount < passwordPolicy.getGraceLimit()) {
579 user.setGraceLoginCount(++graceLoginCount);
580
581 userPersistence.update(user, false);
582 }
583 else {
584 throw new PasswordExpiredException();
585 }
586 }
587
588
590 if (isPasswordExpiringSoon(user)) {
591 user.setPasswordReset(true);
592
593 userPersistence.update(user, false);
594 }
595
596
598 if (passwordPolicy.isChangeable() &&
599 passwordPolicy.isChangeRequired()) {
600
601 if (user.getLastLoginDate() == null) {
602 boolean passwordReset = false;
603
604 if (passwordPolicy.isChangeable() &&
605 passwordPolicy.isChangeRequired()) {
606
607 passwordReset = true;
608 }
609
610 user.setPasswordReset(passwordReset);
611
612 userPersistence.update(user, false);
613 }
614 }
615 }
616
617 public KeyValuePair decryptUserId(
618 long companyId, String name, String password)
619 throws PortalException, SystemException {
620
621 Company company = companyPersistence.findByPrimaryKey(companyId);
622
623 try {
624 name = Encryptor.decrypt(company.getKeyObj(), name);
625 }
626 catch (EncryptorException ee) {
627 throw new SystemException(ee);
628 }
629
630 long userId = GetterUtil.getLong(name);
631
632 User user = userPersistence.findByPrimaryKey(userId);
633
634 try {
635 password = Encryptor.decrypt(company.getKeyObj(), password);
636 }
637 catch (EncryptorException ee) {
638 throw new SystemException(ee);
639 }
640
641 String encPassword = PwdEncryptor.encrypt(password);
642
643 if (user.getPassword().equals(encPassword)) {
644 if (isPasswordExpired(user)) {
645 user.setPasswordReset(true);
646
647 userPersistence.update(user, false);
648 }
649
650 return new KeyValuePair(name, password);
651 }
652 else {
653 throw new PrincipalException();
654 }
655 }
656
657 public void deletePortrait(long userId)
658 throws PortalException, SystemException {
659
660 User user = userPersistence.findByPrimaryKey(userId);
661
662 long portraitId = user.getPortraitId();
663
664 if (portraitId > 0) {
665 user.setPortraitId(0);
666
667 userPersistence.update(user, false);
668
669 imageLocalService.deleteImage(portraitId);
670 }
671 }
672
673 public void deleteRoleUser(long roleId, long userId)
674 throws PortalException, SystemException {
675
676 rolePersistence.removeUser(roleId, userId);
677
678 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
679
680 indexer.reindex(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 hasTeamUser(long teamId, long userId)
1211 throws SystemException {
1212
1213 return teamPersistence.containsUser(teamId, userId);
1214 }
1215
1216 public boolean hasUserGroupUser(long userGroupId, long userId)
1217 throws SystemException {
1218
1219 return userGroupPersistence.containsUser(userGroupId, userId);
1220 }
1221
1222 public boolean isPasswordExpired(User user)
1223 throws PortalException, SystemException {
1224
1225 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1226
1227 if (passwordPolicy.getExpireable()) {
1228 Date now = new Date();
1229
1230 if (user.getPasswordModifiedDate() == null) {
1231 user.setPasswordModifiedDate(now);
1232
1233 userLocalService.updateUser(user, false);
1234 }
1235
1236 long passwordStartTime = user.getPasswordModifiedDate().getTime();
1237 long elapsedTime = now.getTime() - passwordStartTime;
1238
1239 if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
1240 return true;
1241 }
1242 else {
1243 return false;
1244 }
1245 }
1246
1247 return false;
1248 }
1249
1250 public boolean isPasswordExpiringSoon(User user)
1251 throws PortalException, SystemException {
1252
1253 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1254
1255 if (passwordPolicy.isExpireable()) {
1256 Date now = new Date();
1257
1258 if (user.getPasswordModifiedDate() == null) {
1259 user.setPasswordModifiedDate(now);
1260
1261 userLocalService.updateUser(user, false);
1262 }
1263
1264 long timeModified = user.getPasswordModifiedDate().getTime();
1265 long passwordExpiresOn =
1266 (passwordPolicy.getMaxAge() * 1000) + timeModified;
1267
1268 long timeStartWarning =
1269 passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
1270
1271 if (now.getTime() > timeStartWarning) {
1272 return true;
1273 }
1274 else {
1275 return false;
1276 }
1277 }
1278
1279 return false;
1280 }
1281
1282 public List<User> search(
1283 long companyId, String keywords, Boolean active,
1284 LinkedHashMap<String, Object> params, int start, int end,
1285 OrderByComparator obc)
1286 throws SystemException {
1287
1288 return userFinder.findByKeywords(
1289 companyId, keywords, active, params, start, end, obc);
1290 }
1291
1292 public Hits search(
1293 long companyId, String keywords, Boolean active,
1294 LinkedHashMap<String, Object> params, int start, int end, Sort sort)
1295 throws SystemException {
1296
1297 String firstName = null;
1298 String middleName = null;
1299 String lastName = null;
1300 String screenName = null;
1301 String emailAddress = null;
1302 boolean andOperator = false;
1303
1304 if (Validator.isNotNull(keywords)) {
1305 firstName = keywords;
1306 middleName = keywords;
1307 lastName = keywords;
1308 screenName = keywords;
1309 emailAddress = keywords;
1310 }
1311 else {
1312 andOperator = true;
1313 }
1314
1315 return search(
1316 companyId, firstName, middleName, lastName, screenName,
1317 emailAddress, active, params, andOperator, start, end, sort);
1318 }
1319
1320 public List<User> search(
1321 long companyId, String firstName, String middleName,
1322 String lastName, String screenName, String emailAddress,
1323 Boolean active, LinkedHashMap<String, Object> params,
1324 boolean andSearch, int start, int end, OrderByComparator obc)
1325 throws SystemException {
1326
1327 return userFinder.findByC_FN_MN_LN_SN_EA_A(
1328 companyId, firstName, middleName, lastName, screenName,
1329 emailAddress, active, params, andSearch, start, end, obc);
1330 }
1331
1332 public Hits search(
1333 long companyId, String firstName, String middleName,
1334 String lastName, String screenName, String emailAddress,
1335 Boolean active, LinkedHashMap<String, Object> params,
1336 boolean andSearch, int start, int end, Sort sort)
1337 throws SystemException {
1338
1339 try {
1340 Map<String, Serializable> attributes =
1341 new HashMap<String, Serializable>();
1342
1343 attributes.put("active", active);
1344 attributes.put("emailAddress", emailAddress);
1345 attributes.put("firstName", firstName);
1346 attributes.put("lastName", lastName);
1347 attributes.put("middleName", middleName);
1348 attributes.put("params", params);
1349 attributes.put("screenName", screenName);
1350
1351 SearchContext searchContext = new SearchContext();
1352
1353 searchContext.setAndSearch(andSearch);
1354 searchContext.setAttributes(attributes);
1355 searchContext.setCompanyId(companyId);
1356 searchContext.setEnd(end);
1357 searchContext.setSorts(new Sort[] {sort});
1358 searchContext.setStart(start);
1359
1360 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1361
1362 return indexer.search(searchContext);
1363 }
1364 catch (Exception e) {
1365 throw new SystemException(e);
1366 }
1367 }
1368
1369 public int searchCount(
1370 long companyId, String keywords, Boolean active,
1371 LinkedHashMap<String, Object> params)
1372 throws SystemException {
1373
1374 return userFinder.countByKeywords(companyId, keywords, active, params);
1375 }
1376
1377 public int searchCount(
1378 long companyId, String firstName, String middleName,
1379 String lastName, String screenName, String emailAddress,
1380 Boolean active, LinkedHashMap<String, Object> params,
1381 boolean andSearch)
1382 throws SystemException {
1383
1384 return userFinder.countByC_FN_MN_LN_SN_EA_A(
1385 companyId, firstName, middleName, lastName, screenName,
1386 emailAddress, active, params, andSearch);
1387 }
1388
1389 public void sendPassword(
1390 long companyId, String emailAddress, String remoteAddr,
1391 String remoteHost, String userAgent, String fromName,
1392 String fromAddress, String subject, String body,
1393 ServiceContext serviceContext)
1394 throws PortalException, SystemException {
1395
1396 try {
1397 doSendPassword(
1398 companyId, emailAddress, remoteAddr, remoteHost, userAgent,
1399 fromName, fromAddress, subject, body, serviceContext);
1400 }
1401 catch (IOException ioe) {
1402 throw new SystemException(ioe);
1403 }
1404 }
1405
1406 public void setRoleUsers(long roleId, long[] userIds)
1407 throws PortalException, SystemException {
1408
1409 rolePersistence.setUsers(roleId, userIds);
1410
1411 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1412
1413 indexer.reindex(userIds);
1414
1415 PermissionCacheUtil.clearCache();
1416 }
1417
1418 public void setUserGroupUsers(long userGroupId, long[] userIds)
1419 throws PortalException, SystemException {
1420
1421 userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
1422
1423 userGroupPersistence.setUsers(userGroupId, userIds);
1424
1425 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1426
1427 indexer.reindex(userIds);
1428
1429 PermissionCacheUtil.clearCache();
1430 }
1431
1432 public void unsetGroupUsers(long groupId, long[] userIds)
1433 throws PortalException, SystemException {
1434
1435 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
1436
1437 groupPersistence.removeUsers(groupId, userIds);
1438
1439 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1440
1441 indexer.reindex(userIds);
1442
1443 PermissionCacheUtil.clearCache();
1444 }
1445
1446 public void unsetOrganizationUsers(long organizationId, long[] userIds)
1447 throws PortalException, SystemException {
1448
1449 Organization organization = organizationPersistence.findByPrimaryKey(
1450 organizationId);
1451
1452 Group group = organization.getGroup();
1453
1454 long groupId = group.getGroupId();
1455
1456 userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
1457
1458 organizationPersistence.removeUsers(organizationId, userIds);
1459
1460 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1461
1462 indexer.reindex(userIds);
1463
1464 PermissionCacheUtil.clearCache();
1465 }
1466
1467 public void unsetPasswordPolicyUsers(
1468 long passwordPolicyId, long[] userIds)
1469 throws SystemException {
1470
1471 passwordPolicyRelLocalService.deletePasswordPolicyRels(
1472 passwordPolicyId, User.class.getName(), userIds);
1473 }
1474
1475 public void unsetRoleUsers(long roleId, List<User> users)
1476 throws PortalException, SystemException {
1477
1478 Role role = rolePersistence.findByPrimaryKey(roleId);
1479
1480 if (role.getName().equals(RoleConstants.USER)) {
1481 return;
1482 }
1483
1484 rolePersistence.removeUsers(roleId, users);
1485
1486 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1487
1488 indexer.reindex(users);
1489
1490 PermissionCacheUtil.clearCache();
1491 }
1492
1493 public void unsetRoleUsers(long roleId, long[] userIds)
1494 throws PortalException, SystemException {
1495
1496 Role role = rolePersistence.findByPrimaryKey(roleId);
1497
1498 if (role.getName().equals(RoleConstants.USER)) {
1499 return;
1500 }
1501
1502 rolePersistence.removeUsers(roleId, userIds);
1503
1504 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1505
1506 indexer.reindex(userIds);
1507
1508 PermissionCacheUtil.clearCache();
1509 }
1510
1511 public void unsetTeamUsers(long teamId, long[] userIds)
1512 throws PortalException, SystemException {
1513
1514 teamPersistence.removeUsers(teamId, userIds);
1515
1516 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1517
1518 indexer.reindex(userIds);
1519
1520 PermissionCacheUtil.clearCache();
1521 }
1522
1523 public void unsetUserGroupUsers(long userGroupId, long[] userIds)
1524 throws PortalException, SystemException {
1525
1526 userGroupPersistence.removeUsers(userGroupId, userIds);
1527
1528 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1529
1530 indexer.reindex(userIds);
1531
1532 PermissionCacheUtil.clearCache();
1533 }
1534
1535 public User updateActive(long userId, boolean active)
1536 throws PortalException, SystemException {
1537
1538 User user = userPersistence.findByPrimaryKey(userId);
1539
1540 user.setActive(active);
1541
1542 userPersistence.update(user, false);
1543
1544 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1545
1546 indexer.reindex(user);
1547
1548 return user;
1549 }
1550
1551 public User updateAgreedToTermsOfUse(
1552 long userId, boolean agreedToTermsOfUse)
1553 throws PortalException, SystemException {
1554
1555 User user = userPersistence.findByPrimaryKey(userId);
1556
1557 user.setAgreedToTermsOfUse(agreedToTermsOfUse);
1558
1559 userPersistence.update(user, false);
1560
1561 return user;
1562 }
1563
1564 public void updateAsset(
1565 long userId, User user, long[] assetCategoryIds,
1566 String[] assetTagNames)
1567 throws PortalException, SystemException {
1568
1569 User owner = userPersistence.findByPrimaryKey(userId);
1570
1571 Company company = companyPersistence.findByPrimaryKey(
1572 owner.getCompanyId());
1573
1574 Group companyGroup = company.getGroup();
1575
1576 assetEntryLocalService.updateEntry(
1577 userId, companyGroup.getGroupId(), User.class.getName(),
1578 user.getUserId(), assetCategoryIds, assetTagNames, false, null,
1579 null, null, null, null, user.getFullName(), null, null, null, 0, 0,
1580 null, false);
1581 }
1582
1583 public User updateCreateDate(long userId, Date createDate)
1584 throws PortalException, SystemException {
1585
1586 User user = userPersistence.findByPrimaryKey(userId);
1587
1588 user.setCreateDate(createDate);
1589
1590 userPersistence.update(user, false);
1591
1592 return user;
1593 }
1594
1595 public User updateEmailAddress(
1596 long userId, String password, String emailAddress1,
1597 String emailAddress2)
1598 throws PortalException, SystemException {
1599
1600 emailAddress1 = emailAddress1.trim().toLowerCase();
1601 emailAddress2 = emailAddress2.trim().toLowerCase();
1602
1603 if (!emailAddress1.equals(emailAddress2)) {
1604 throw new UserEmailAddressException();
1605 }
1606
1607 User user = userPersistence.findByPrimaryKey(userId);
1608
1609 validateEmailAddress(user.getCompanyId(), emailAddress1);
1610 validateEmailAddress(user.getCompanyId(), emailAddress2);
1611
1612 if (!user.getEmailAddress().equalsIgnoreCase(emailAddress1)) {
1613 if (userPersistence.fetchByC_EA(
1614 user.getCompanyId(), emailAddress1) != null) {
1615
1616 throw new DuplicateUserEmailAddressException();
1617 }
1618 }
1619
1620 setEmailAddress(
1621 user, password, user.getFirstName(), user.getMiddleName(),
1622 user.getLastName(), emailAddress1);
1623
1624 userPersistence.update(user, false);
1625
1626 return user;
1627 }
1628
1629 public void updateGroups(long userId, long[] newGroupIds)
1630 throws PortalException, SystemException {
1631
1632 if (newGroupIds == null) {
1633 return;
1634 }
1635
1636 List<Group> oldGroups = userPersistence.getGroups(userId);
1637
1638 List<Long> oldGroupIds = new ArrayList<Long>(oldGroups.size());
1639
1640 for (Group oldGroup : oldGroups) {
1641 long oldGroupId = oldGroup.getGroupId();
1642
1643 oldGroupIds.add(oldGroupId);
1644
1645 if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
1646 unsetGroupUsers(oldGroupId, new long[] {userId});
1647 }
1648 }
1649
1650 for (long newGroupId : newGroupIds) {
1651 if (!oldGroupIds.contains(newGroupId)) {
1652 addGroupUsers(newGroupId, new long[] {userId});
1653 }
1654 }
1655
1656 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1657
1658 indexer.reindex(new long[] {userId});
1659
1660 PermissionCacheUtil.clearCache();
1661 }
1662
1663 public User updateLastLogin(long userId, String loginIP)
1664 throws PortalException, SystemException {
1665
1666 User user = userPersistence.findByPrimaryKey(userId);
1667
1668 Date lastLoginDate = user.getLoginDate();
1669
1670 if (lastLoginDate == null) {
1671 lastLoginDate = new Date();
1672 }
1673
1674 user.setLoginDate(new Date());
1675 user.setLoginIP(loginIP);
1676 user.setLastLoginDate(lastLoginDate);
1677 user.setLastLoginIP(user.getLoginIP());
1678 user.setLastFailedLoginDate(null);
1679 user.setFailedLoginAttempts(0);
1680
1681 userPersistence.update(user, false);
1682
1683 return user;
1684 }
1685
1686 public User updateLockout(User user, boolean lockout)
1687 throws PortalException, SystemException {
1688
1689 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1690
1691 if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
1692 return user;
1693 }
1694
1695 Date lockoutDate = null;
1696
1697 if (lockout) {
1698 lockoutDate = new Date();
1699 }
1700
1701 user.setLockout(lockout);
1702 user.setLockoutDate(lockoutDate);
1703
1704 if (!lockout) {
1705 user.setLastFailedLoginDate(lockoutDate);
1706 user.setFailedLoginAttempts(0);
1707 }
1708
1709 userPersistence.update(user, false);
1710
1711 return user;
1712 }
1713
1714 public User updateLockoutByEmailAddress(
1715 long companyId, String emailAddress, boolean lockout)
1716 throws PortalException, SystemException {
1717
1718 User user = getUserByEmailAddress(companyId, emailAddress);
1719
1720 return updateLockout(user, lockout);
1721 }
1722
1723 public User updateLockoutById(long userId, boolean lockout)
1724 throws PortalException, SystemException {
1725
1726 User user = userPersistence.findByPrimaryKey(userId);
1727
1728 return updateLockout(user, lockout);
1729 }
1730
1731 public User updateLockoutByScreenName(
1732 long companyId, String screenName, boolean lockout)
1733 throws PortalException, SystemException {
1734
1735 User user = getUserByScreenName(companyId, screenName);
1736
1737 return updateLockout(user, lockout);
1738 }
1739
1740 public User updateModifiedDate(long userId, Date modifiedDate)
1741 throws PortalException, SystemException {
1742
1743 User user = userPersistence.findByPrimaryKey(userId);
1744
1745 user.setModifiedDate(modifiedDate);
1746
1747 userPersistence.update(user, false);
1748
1749 return user;
1750 }
1751
1752 public void updateOpenId(long userId, String openId)
1753 throws PortalException, SystemException {
1754
1755 openId = openId.trim();
1756
1757 User user = userPersistence.findByPrimaryKey(userId);
1758
1759 user.setOpenId(openId);
1760
1761 userPersistence.update(user, false);
1762 }
1763
1764 public void updateOrganizations(long userId, long[] newOrganizationIds)
1765 throws PortalException, SystemException {
1766
1767 if (newOrganizationIds == null) {
1768 return;
1769 }
1770
1771 List<Organization> oldOrganizations = userPersistence.getOrganizations(
1772 userId);
1773
1774 List<Long> oldOrganizationIds = new ArrayList<Long>(
1775 oldOrganizations.size());
1776
1777 for (Organization oldOrganization : oldOrganizations) {
1778 long oldOrganizationId = oldOrganization.getOrganizationId();
1779
1780 oldOrganizationIds.add(oldOrganizationId);
1781
1782 if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
1783 unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
1784 }
1785 }
1786
1787 for (long newOrganizationId : newOrganizationIds) {
1788 if (!oldOrganizationIds.contains(newOrganizationId)) {
1789 addOrganizationUsers(newOrganizationId, new long[] {userId});
1790 }
1791 }
1792
1793 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1794
1795 indexer.reindex(new long[] {userId});
1796
1797 PermissionCacheUtil.clearCache();
1798 }
1799
1800 public User updatePassword(
1801 long userId, String password1, String password2,
1802 boolean passwordReset)
1803 throws PortalException, SystemException {
1804
1805 return updatePassword(
1806 userId, password1, password2, passwordReset, false);
1807 }
1808
1809 public User updatePassword(
1810 long userId, String password1, String password2,
1811 boolean passwordReset, boolean silentUpdate)
1812 throws PortalException, SystemException {
1813
1814 User user = userPersistence.findByPrimaryKey(userId);
1815
1816
1819 if (!silentUpdate) {
1820 validatePassword(user.getCompanyId(), userId, password1, password2);
1821 }
1822
1823 String oldEncPwd = user.getPassword();
1824
1825 if (!user.isPasswordEncrypted()) {
1826 oldEncPwd = PwdEncryptor.encrypt(user.getPassword());
1827 }
1828
1829 String newEncPwd = PwdEncryptor.encrypt(password1);
1830
1831 if (user.hasCompanyMx()) {
1832 mailService.updatePassword(user.getCompanyId(), userId, password1);
1833 }
1834
1835 user.setPassword(newEncPwd);
1836 user.setPasswordUnencrypted(password1);
1837 user.setPasswordEncrypted(true);
1838 user.setPasswordReset(passwordReset);
1839 user.setPasswordModifiedDate(new Date());
1840 user.setGraceLoginCount(0);
1841
1842 if (!silentUpdate) {
1843 user.setPasswordModified(true);
1844 }
1845
1846 try {
1847 userPersistence.update(user, false);
1848 }
1849 catch (ModelListenerException mle) {
1850 String msg = GetterUtil.getString(mle.getCause().getMessage());
1851
1852 if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1853 String passwordHistory = PrefsPropsUtil.getString(
1854 user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
1855
1856 if (msg.indexOf(passwordHistory) != -1) {
1857 throw new UserPasswordException(
1858 UserPasswordException.PASSWORD_ALREADY_USED);
1859 }
1860 }
1861
1862 throw new UserPasswordException(
1863 UserPasswordException.PASSWORD_INVALID);
1864 }
1865
1866 if (!silentUpdate) {
1867 user.setPasswordModified(false);
1868
1869 passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
1870 }
1871
1872 return user;
1873 }
1874
1875 public User updatePasswordManually(
1876 long userId, String password, boolean passwordEncrypted,
1877 boolean passwordReset, Date passwordModifiedDate)
1878 throws PortalException, SystemException {
1879
1880
1882 User user = userPersistence.findByPrimaryKey(userId);
1883
1884 user.setPassword(password);
1885 user.setPasswordEncrypted(passwordEncrypted);
1886 user.setPasswordReset(passwordReset);
1887 user.setPasswordModifiedDate(passwordModifiedDate);
1888
1889 userPersistence.update(user, false);
1890
1891 return user;
1892 }
1893
1894 public void updatePasswordReset(long userId, boolean passwordReset)
1895 throws PortalException, SystemException {
1896
1897 User user = userPersistence.findByPrimaryKey(userId);
1898
1899 user.setPasswordReset(passwordReset);
1900
1901 userPersistence.update(user, false);
1902 }
1903
1904 public void updatePortrait(long userId, byte[] bytes)
1905 throws PortalException, SystemException {
1906
1907 User user = userPersistence.findByPrimaryKey(userId);
1908
1909 long imageMaxSize = PrefsPropsUtil.getLong(
1910 PropsKeys.USERS_IMAGE_MAX_SIZE);
1911
1912 if ((imageMaxSize > 0) &&
1913 ((bytes == null) || (bytes.length > imageMaxSize))) {
1914
1915 throw new UserPortraitSizeException();
1916 }
1917
1918 long portraitId = user.getPortraitId();
1919
1920 if (portraitId <= 0) {
1921 portraitId = counterLocalService.increment();
1922
1923 user.setPortraitId(portraitId);
1924
1925 userPersistence.update(user, false);
1926 }
1927
1928 try {
1929 ImageBag imageBag = ImageProcessorUtil.read(bytes);
1930
1931 RenderedImage renderedImage = imageBag.getRenderedImage();
1932
1933 if (renderedImage == null) {
1934 throw new UserPortraitTypeException();
1935 }
1936
1937 renderedImage = ImageProcessorUtil.scale(
1938 renderedImage, PropsValues.USERS_IMAGE_MAX_HEIGHT,
1939 PropsValues.USERS_IMAGE_MAX_WIDTH);
1940
1941 String contentType = imageBag.getType();
1942
1943 imageLocalService.updateImage(
1944 portraitId,
1945 ImageProcessorUtil.getBytes(renderedImage, contentType));
1946 }
1947 catch (IOException ioe) {
1948 throw new ImageSizeException(ioe);
1949 }
1950 }
1951
1952 public void updateReminderQuery(long userId, String question, String answer)
1953 throws PortalException, SystemException {
1954
1955 validateReminderQuery(question, answer) ;
1956
1957 User user = userPersistence.findByPrimaryKey(userId);
1958
1959 user.setReminderQueryQuestion(question);
1960 user.setReminderQueryAnswer(answer);
1961
1962 userPersistence.update(user, false);
1963 }
1964
1965 public void updateScreenName(long userId, String screenName)
1966 throws PortalException, SystemException {
1967
1968
1970 User user = userPersistence.findByPrimaryKey(userId);
1971
1972 screenName = getScreenName(screenName);
1973
1974 validateScreenName(user.getCompanyId(), userId, screenName);
1975
1976 user.setScreenName(screenName);
1977
1978 userPersistence.update(user, false);
1979
1980
1982 Group group = groupLocalService.getUserGroup(
1983 user.getCompanyId(), userId);
1984
1985 group.setFriendlyURL(StringPool.SLASH + screenName);
1986
1987 groupPersistence.update(group, false);
1988 }
1989
1990 public User updateUser(
1991 long userId, String oldPassword, String newPassword1,
1992 String newPassword2, boolean passwordReset,
1993 String reminderQueryQuestion, String reminderQueryAnswer,
1994 String screenName, String emailAddress, String openId,
1995 String languageId, String timeZoneId, String greeting,
1996 String comments, String firstName, String middleName,
1997 String lastName, int prefixId, int suffixId, boolean male,
1998 int birthdayMonth, int birthdayDay, int birthdayYear, String smsSn,
1999 String aimSn, String facebookSn, String icqSn, String jabberSn,
2000 String msnSn, String mySpaceSn, String skypeSn, String twitterSn,
2001 String ymSn, String jobTitle, long[] groupIds,
2002 long[] organizationIds, long[] roleIds,
2003 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
2004 ServiceContext serviceContext)
2005 throws PortalException, SystemException {
2006
2007 ServiceContext previousServiceContext =
2008 ServiceContextThreadLocal.getServiceContext();
2009
2010 ServiceContextThreadLocal.setServiceContext(serviceContext);
2011
2012 try {
2013 return doUpdateUser(
2014 userId, oldPassword, newPassword1, newPassword2, passwordReset,
2015 reminderQueryQuestion, reminderQueryAnswer, screenName,
2016 emailAddress, openId, languageId, timeZoneId, greeting,
2017 comments, firstName, middleName, lastName, prefixId, suffixId,
2018 male, birthdayMonth, birthdayDay, birthdayYear, smsSn, aimSn,
2019 facebookSn, icqSn, jabberSn, msnSn, mySpaceSn, skypeSn,
2020 twitterSn, ymSn, jobTitle, groupIds, organizationIds, roleIds,
2021 userGroupRoles, userGroupIds, serviceContext);
2022 }
2023 finally {
2024 ServiceContextThreadLocal.setServiceContext(previousServiceContext);
2025 }
2026 }
2027
2028 protected int authenticate(
2029 long companyId, String login, String password, String authType,
2030 Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
2031 throws PortalException, SystemException {
2032
2033 login = login.trim().toLowerCase();
2034
2035 long userId = GetterUtil.getLong(login);
2036
2037
2039 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2040 if (!Validator.isEmailAddress(login)) {
2041 throw new UserEmailAddressException();
2042 }
2043 }
2044 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2045 if (Validator.isNull(login)) {
2046 throw new UserScreenNameException();
2047 }
2048 }
2049 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2050 if (Validator.isNull(login)) {
2051 throw new UserIdException();
2052 }
2053 }
2054
2055 if (Validator.isNull(password)) {
2056 throw new UserPasswordException(
2057 UserPasswordException.PASSWORD_INVALID);
2058 }
2059
2060 int authResult = Authenticator.FAILURE;
2061
2062
2064 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2065 authResult = AuthPipeline.authenticateByEmailAddress(
2066 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
2067 headerMap, parameterMap);
2068 }
2069 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2070 authResult = AuthPipeline.authenticateByScreenName(
2071 PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
2072 headerMap, parameterMap);
2073 }
2074 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2075 authResult = AuthPipeline.authenticateByUserId(
2076 PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
2077 headerMap, parameterMap);
2078 }
2079
2080
2082 User user = null;
2083
2084 try {
2085 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2086 user = userPersistence.findByC_EA(companyId, login);
2087 }
2088 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2089 user = userPersistence.findByC_SN(companyId, login);
2090 }
2091 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2092 user = userPersistence.findByC_U(
2093 companyId, GetterUtil.getLong(login));
2094 }
2095 }
2096 catch (NoSuchUserException nsue) {
2097 return Authenticator.DNE;
2098 }
2099
2100 if (user.isDefaultUser()) {
2101 _log.error(
2102 "The default user should never be allowed to authenticate");
2103
2104 return Authenticator.DNE;
2105 }
2106
2107 if (!user.isPasswordEncrypted()) {
2108 user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
2109 user.setPasswordEncrypted(true);
2110
2111 userPersistence.update(user, false);
2112 }
2113
2114
2117 checkLockout(user);
2118
2119 checkPasswordExpired(user);
2120
2121
2123 if (authResult == Authenticator.SUCCESS) {
2124 if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
2125 String encPassword = PwdEncryptor.encrypt(
2126 password, user.getPassword());
2127
2128 if (user.getPassword().equals(encPassword)) {
2129 authResult = Authenticator.SUCCESS;
2130 }
2131 else if (GetterUtil.getBoolean(PropsUtil.get(
2132 PropsKeys.AUTH_MAC_ALLOW))) {
2133
2134 try {
2135 MessageDigest digester = MessageDigest.getInstance(
2136 PropsUtil.get(PropsKeys.AUTH_MAC_ALGORITHM));
2137
2138 digester.update(login.getBytes("UTF8"));
2139
2140 String shardKey =
2141 PropsUtil.get(PropsKeys.AUTH_MAC_SHARED_KEY);
2142
2143 encPassword = Base64.encode(
2144 digester.digest(shardKey.getBytes("UTF8")));
2145
2146 if (password.equals(encPassword)) {
2147 authResult = Authenticator.SUCCESS;
2148 }
2149 else {
2150 authResult = Authenticator.FAILURE;
2151 }
2152 }
2153 catch (NoSuchAlgorithmException nsae) {
2154 throw new SystemException(nsae);
2155 }
2156 catch (UnsupportedEncodingException uee) {
2157 throw new SystemException(uee);
2158 }
2159 }
2160 else {
2161 authResult = Authenticator.FAILURE;
2162 }
2163 }
2164 }
2165
2166
2168 if (authResult == Authenticator.SUCCESS) {
2169 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2170 authResult = AuthPipeline.authenticateByEmailAddress(
2171 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
2172 headerMap, parameterMap);
2173 }
2174 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2175 authResult = AuthPipeline.authenticateByScreenName(
2176 PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
2177 headerMap, parameterMap);
2178 }
2179 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2180 authResult = AuthPipeline.authenticateByUserId(
2181 PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
2182 headerMap, parameterMap);
2183 }
2184 }
2185
2186
2188 if (authResult == Authenticator.FAILURE) {
2189 try {
2190 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2191 AuthPipeline.onFailureByEmailAddress(
2192 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
2193 parameterMap);
2194 }
2195 else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2196 AuthPipeline.onFailureByScreenName(
2197 PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
2198 parameterMap);
2199 }
2200 else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2201 AuthPipeline.onFailureByUserId(
2202 PropsKeys.AUTH_FAILURE, companyId, userId, headerMap,
2203 parameterMap);
2204 }
2205
2206
2208 if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
2209 user.getCompanyId())) {
2210
2211 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2212
2213 int failedLoginAttempts = user.getFailedLoginAttempts();
2214 int maxFailures = passwordPolicy.getMaxFailure();
2215
2216 if ((failedLoginAttempts >= maxFailures) &&
2217 (maxFailures != 0)) {
2218
2219 if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2220 AuthPipeline.onMaxFailuresByEmailAddress(
2221 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
2222 headerMap, parameterMap);
2223 }
2224 else if (authType.equals(
2225 CompanyConstants.AUTH_TYPE_SN)) {
2226
2227 AuthPipeline.onMaxFailuresByScreenName(
2228 PropsKeys.AUTH_MAX_FAILURES, companyId, login,
2229 headerMap, parameterMap);
2230 }
2231 else if (authType.equals(
2232 CompanyConstants.AUTH_TYPE_ID)) {
2233
2234 AuthPipeline.onMaxFailuresByUserId(
2235 PropsKeys.AUTH_MAX_FAILURES, companyId, userId,
2236 headerMap, parameterMap);
2237 }
2238 }
2239 }
2240 }
2241 catch (Exception e) {
2242 _log.error(e, e);
2243 }
2244 }
2245
2246 return authResult;
2247 }
2248
2249 protected User doAddUser(
2250 long creatorUserId, long companyId, boolean autoPassword,
2251 String password1, String password2, boolean autoScreenName,
2252 String screenName, String emailAddress, String openId,
2253 Locale locale, String firstName, String middleName, String lastName,
2254 int prefixId, int suffixId, boolean male, int birthdayMonth,
2255 int birthdayDay, int birthdayYear, String jobTitle, long[] groupIds,
2256 long[] organizationIds, long[] roleIds, long[] userGroupIds,
2257 boolean sendEmail, ServiceContext serviceContext)
2258 throws PortalException, SystemException {
2259
2260
2262 Company company = companyPersistence.findByPrimaryKey(companyId);
2263 screenName = getScreenName(screenName);
2264 emailAddress = emailAddress.trim().toLowerCase();
2265 openId = openId.trim();
2266 Date now = new Date();
2267
2268 if (PrefsPropsUtil.getBoolean(
2269 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
2270
2271 autoScreenName = true;
2272 }
2273
2274 long userId = counterLocalService.increment();
2275
2276 EmailAddressGenerator emailAddressGenerator =
2277 EmailAddressGeneratorFactory.getInstance();
2278
2279 if (emailAddressGenerator.isGenerated(emailAddress)) {
2280 emailAddress = StringPool.BLANK;
2281 }
2282
2283 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
2284 Validator.isNull(emailAddress)) {
2285
2286 emailAddress = emailAddressGenerator.generate(companyId, userId);
2287 }
2288
2289 validate(
2290 companyId, userId, autoPassword, password1, password2,
2291 autoScreenName, screenName, emailAddress, firstName, middleName,
2292 lastName, organizationIds);
2293
2294 if (autoPassword) {
2295 PasswordPolicy passwordPolicy =
2296 passwordPolicyLocalService.getPasswordPolicy(
2297 companyId, organizationIds);
2298
2299 password1 = PwdToolkitUtil.generate(passwordPolicy);
2300 }
2301 else {
2302 if (Validator.isNull(password1) || Validator.isNull(password2)) {
2303 throw new UserPasswordException(
2304 UserPasswordException.PASSWORD_INVALID);
2305 }
2306 }
2307
2308 if (autoScreenName) {
2309 ScreenNameGenerator screenNameGenerator =
2310 ScreenNameGeneratorFactory.getInstance();
2311
2312 try {
2313 screenName = screenNameGenerator.generate(
2314 companyId, userId, emailAddress);
2315 }
2316 catch (Exception e) {
2317 throw new SystemException(e);
2318 }
2319 }
2320
2321 User defaultUser = getDefaultUser(companyId);
2322
2323 FullNameGenerator fullNameGenerator =
2324 FullNameGeneratorFactory.getInstance();
2325
2326 String fullName = fullNameGenerator.getFullName(
2327 firstName, middleName, lastName);
2328
2329 String greeting = LanguageUtil.format(
2330 locale, "welcome-x", " " + fullName, false);
2331
2332 User user = userPersistence.create(userId);
2333
2334 user.setCompanyId(companyId);
2335 user.setCreateDate(now);
2336 user.setModifiedDate(now);
2337 user.setDefaultUser(false);
2338 user.setContactId(counterLocalService.increment());
2339 user.setPassword(PwdEncryptor.encrypt(password1));
2340 user.setPasswordUnencrypted(password1);
2341 user.setPasswordEncrypted(true);
2342 user.setPasswordReset(false);
2343 user.setScreenName(screenName);
2344 user.setEmailAddress(emailAddress);
2345 user.setOpenId(openId);
2346 user.setLanguageId(locale.toString());
2347 user.setTimeZoneId(defaultUser.getTimeZoneId());
2348 user.setGreeting(greeting);
2349 user.setFirstName(firstName);
2350 user.setMiddleName(middleName);
2351 user.setLastName(lastName);
2352 user.setJobTitle(jobTitle);
2353 user.setActive(true);
2354
2355 userPersistence.update(user, false);
2356
2357
2359 String creatorUserName = StringPool.BLANK;
2360
2361 if (creatorUserId <= 0) {
2362 creatorUserId = user.getUserId();
2363
2364
2367 }
2369 else {
2370 User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
2371
2372 creatorUserName = creatorUser.getFullName();
2373 }
2374
2375 resourceLocalService.addResources(
2376 companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
2377 false, false, false);
2378
2379
2381 if (user.hasCompanyMx()) {
2382 mailService.addUser(
2383 companyId, userId, password1, firstName, middleName, lastName,
2384 emailAddress);
2385 }
2386
2387
2389 Date birthday = PortalUtil.getDate(
2390 birthdayMonth, birthdayDay, birthdayYear,
2391 new ContactBirthdayException());
2392
2393 Contact contact = contactPersistence.create(user.getContactId());
2394
2395 contact.setCompanyId(user.getCompanyId());
2396 contact.setUserId(creatorUserId);
2397 contact.setUserName(creatorUserName);
2398 contact.setCreateDate(now);
2399 contact.setModifiedDate(now);
2400 contact.setAccountId(company.getAccountId());
2401 contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
2402 contact.setFirstName(firstName);
2403 contact.setMiddleName(middleName);
2404 contact.setLastName(lastName);
2405 contact.setPrefixId(prefixId);
2406 contact.setSuffixId(suffixId);
2407 contact.setMale(male);
2408 contact.setBirthday(birthday);
2409 contact.setJobTitle(jobTitle);
2410
2411 contactPersistence.update(contact, false);
2412
2413
2415 groupLocalService.addGroup(
2416 user.getUserId(), User.class.getName(), user.getUserId(), null,
2417 null, 0, StringPool.SLASH + screenName, true, null);
2418
2419
2421 if (groupIds != null) {
2422 groupLocalService.addUserGroups(userId, groupIds);
2423 }
2424
2425 addDefaultGroups(userId);
2426
2427
2429 updateOrganizations(userId, organizationIds);
2430
2431
2433 if (roleIds != null) {
2434 roleIds = EnterpriseAdminUtil.addRequiredRoles(user, roleIds);
2435
2436 userPersistence.setRoles(userId, roleIds);
2437 }
2438
2439 addDefaultRoles(userId);
2440
2441
2443 if (userGroupIds != null) {
2444 for (long userGroupId : userGroupIds) {
2445 userGroupLocalService.copyUserGroupLayouts(
2446 userGroupId, new long[] {userId});
2447 }
2448
2449 userPersistence.setUserGroups(userId, userGroupIds);
2450 }
2451
2452 addDefaultUserGroups(userId);
2453
2454
2456 if (serviceContext != null) {
2457 updateAsset(
2458 creatorUserId, user, serviceContext.getAssetCategoryIds(),
2459 serviceContext.getAssetTagNames());
2460 }
2461
2462
2464 user.setExpandoBridgeAttributes(serviceContext);
2465
2466
2468 if (sendEmail) {
2469 try {
2470 sendEmail(user, password1);
2471 }
2472 catch (IOException ioe) {
2473 throw new SystemException(ioe);
2474 }
2475 }
2476
2477
2479 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
2480
2481 indexer.reindex(user);
2482
2483 return user;
2484 }
2485
2486 protected void doSendPassword(
2487 long companyId, String emailAddress, String remoteAddr,
2488 String remoteHost, String userAgent, String fromName,
2489 String fromAddress, String subject, String body,
2490 ServiceContext serviceContext)
2491 throws IOException, PortalException, SystemException {
2492
2493 Company company = companyPersistence.findByPrimaryKey(companyId);
2494
2495 if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
2496 return;
2497 }
2498
2499 emailAddress = emailAddress.trim().toLowerCase();
2500
2501 if (!Validator.isEmailAddress(emailAddress)) {
2502 throw new UserEmailAddressException();
2503 }
2504
2505 User user = userPersistence.findByC_EA(companyId, emailAddress);
2506
2507 PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2508
2509 String newPassword = StringPool.BLANK;
2510 String passwordResetURL = StringPool.BLANK;
2511
2512 if (company.isSendPasswordResetLink()) {
2513 Date expirationDate = new Date(
2514 System.currentTimeMillis() +
2515 (passwordPolicy.getResetTicketMaxAge() * 1000));
2516
2517 Ticket ticket = ticketLocalService.addTicket(
2518 companyId, User.class.getName(), user.getUserId(),
2519 expirationDate, serviceContext);
2520
2521 passwordResetURL =
2522 serviceContext.getPortalURL() + serviceContext.getPathMain() +
2523 "/portal/update_password?ticket=" + ticket.getKey();
2524 }
2525 else {
2526 if (!PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
2527 PwdEncryptor.TYPE_NONE)) {
2528
2529 newPassword = PwdToolkitUtil.generate(passwordPolicy);
2530
2531 boolean passwordReset = false;
2532
2533 if (passwordPolicy.getChangeable() &&
2534 passwordPolicy.getChangeRequired()) {
2535
2536 passwordReset = true;
2537 }
2538
2539 user.setPassword(PwdEncryptor.encrypt(newPassword));
2540 user.setPasswordUnencrypted(newPassword);
2541 user.setPasswordEncrypted(true);
2542 user.setPasswordReset(passwordReset);
2543 user.setPasswordModified(true);
2544 user.setPasswordModifiedDate(new Date());
2545
2546 userPersistence.update(user, false);
2547
2548 user.setPasswordModified(false);
2549 }
2550 else {
2551 newPassword = user.getPassword();
2552 }
2553 }
2554
2555 if (Validator.isNull(fromName)) {
2556 fromName = PrefsPropsUtil.getString(
2557 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
2558 }
2559
2560 if (Validator.isNull(fromAddress)) {
2561 fromAddress = PrefsPropsUtil.getString(
2562 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
2563 }
2564
2565 String toName = user.getFullName();
2566 String toAddress = user.getEmailAddress();
2567
2568 if (Validator.isNull(subject)) {
2569 if (company.isSendPasswordResetLink()) {
2570 subject = PrefsPropsUtil.getContent(
2571 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
2572 }
2573 else {
2574 subject = PrefsPropsUtil.getContent(
2575 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
2576 }
2577 }
2578
2579 if (Validator.isNull(body)) {
2580 if (company.isSendPasswordResetLink()) {
2581 body = PrefsPropsUtil.getContent(
2582 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
2583 }
2584 else {
2585 body = PrefsPropsUtil.getContent(
2586 companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
2587 }
2588 }
2589
2590 subject = StringUtil.replace(
2591 subject,
2592 new String[] {
2593 "[$FROM_ADDRESS$]",
2594 "[$FROM_NAME$]",
2595 "[$PASSWORD_RESET_URL$]",
2596 "[$PORTAL_URL$]",
2597 "[$REMOTE_ADDRESS$]",
2598 "[$REMOTE_HOST$]",
2599 "[$TO_ADDRESS$]",
2600 "[$TO_NAME$]",
2601 "[$USER_AGENT$]",
2602 "[$USER_ID$]",
2603 "[$USER_PASSWORD$]",
2604 "[$USER_SCREENNAME$]"
2605 },
2606 new String[] {
2607 fromAddress,
2608 fromName,
2609 passwordResetURL,
2610 company.getVirtualHost(),
2611 remoteAddr,
2612 remoteHost,
2613 toAddress,
2614 toName,
2615 HtmlUtil.escape(userAgent),
2616 String.valueOf(user.getUserId()),
2617 newPassword,
2618 user.getScreenName()
2619 });
2620
2621 body = StringUtil.replace(
2622 body,
2623 new String[] {
2624 "[$FROM_ADDRESS$]",
2625 "[$FROM_NAME$]",
2626 "[$PASSWORD_RESET_URL$]",
2627 "[$PORTAL_URL$]",
2628 "[$REMOTE_ADDRESS$]",
2629 "[$REMOTE_HOST$]",
2630 "[$TO_ADDRESS$]",
2631 "[$TO_NAME$]",
2632 "[$USER_AGENT$]",
2633 "[$USER_ID$]",
2634 "[$USER_PASSWORD$]",
2635 "[$USER_SCREENNAME$]"
2636 },
2637 new String[] {
2638 fromAddress,
2639 fromName,
2640 passwordResetURL,
2641 company.getVirtualHost(),
2642 remoteAddr,
2643 remoteHost,
2644 toAddress,
2645 toName,
2646 HtmlUtil.escape(userAgent),
2647 String.valueOf(user.getUserId()),
2648 newPassword,
2649 user.getScreenName()
2650 });
2651
2652 InternetAddress from = new InternetAddress(fromAddress, fromName);
2653
2654 InternetAddress to = new InternetAddress(toAddress, toName);
2655
2656 MailMessage message = new MailMessage(from, to, subject, body, true);
2657
2658 mailService.sendEmail(message);
2659 }
2660
2661 protected User doUpdateUser(
2662 long userId, String oldPassword, String newPassword1,
2663 String newPassword2, boolean passwordReset,
2664 String reminderQueryQuestion, String reminderQueryAnswer,
2665 String screenName, String emailAddress, String openId,
2666 String languageId, String timeZoneId, String greeting,
2667 String comments, String firstName, String middleName,
2668 String lastName, int prefixId, int suffixId, boolean male,
2669 int birthdayMonth, int birthdayDay, int birthdayYear, String smsSn,
2670 String aimSn, String facebookSn, String icqSn, String jabberSn,
2671 String msnSn, String mySpaceSn, String skypeSn, String twitterSn,
2672 String ymSn, String jobTitle, long[] groupIds,
2673 long[] organizationIds, long[] roleIds,
2674 List<UserGroupRole> userGroupRoles, long[] userGroupIds,
2675 ServiceContext serviceContext)
2676 throws PortalException, SystemException {
2677
2678
2680 User user = userPersistence.findByPrimaryKey(userId);
2681 Company company = companyPersistence.findByPrimaryKey(
2682 user.getCompanyId());
2683 String password = oldPassword;
2684 screenName = getScreenName(screenName);
2685 emailAddress = emailAddress.trim().toLowerCase();
2686 openId = openId.trim();
2687 String oldFullName = user.getFullName();
2688 aimSn = aimSn.trim().toLowerCase();
2689 facebookSn = facebookSn.trim().toLowerCase();
2690 icqSn = icqSn.trim().toLowerCase();
2691 jabberSn = jabberSn.trim().toLowerCase();
2692 msnSn = msnSn.trim().toLowerCase();
2693 mySpaceSn = mySpaceSn.trim().toLowerCase();
2694 skypeSn = skypeSn.trim().toLowerCase();
2695 twitterSn = twitterSn.trim().toLowerCase();
2696 ymSn = ymSn.trim().toLowerCase();
2697 Date now = new Date();
2698
2699 EmailAddressGenerator emailAddressGenerator =
2700 EmailAddressGeneratorFactory.getInstance();
2701
2702 if (emailAddressGenerator.isGenerated(emailAddress)) {
2703 emailAddress = StringPool.BLANK;
2704 }
2705
2706 if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
2707 Validator.isNull(emailAddress)) {
2708
2709 emailAddress = emailAddressGenerator.generate(
2710 user.getCompanyId(), userId);
2711 }
2712
2713 validate(
2714 userId, screenName, emailAddress, firstName, middleName, lastName,
2715 smsSn);
2716
2717 if (Validator.isNotNull(newPassword1) ||
2718 Validator.isNotNull(newPassword2)) {
2719
2720 user = updatePassword(
2721 userId, newPassword1, newPassword2, passwordReset);
2722
2723 password = newPassword1;
2724 }
2725
2726 user.setModifiedDate(now);
2727
2728 if (user.getContactId() <= 0) {
2729 user.setContactId(counterLocalService.increment());
2730 }
2731
2732 user.setPasswordReset(passwordReset);
2733
2734 if (Validator.isNotNull(reminderQueryQuestion) &&
2735 Validator.isNotNull(reminderQueryAnswer)) {
2736
2737 user.setReminderQueryQuestion(reminderQueryQuestion);
2738 user.setReminderQueryAnswer(reminderQueryAnswer);
2739 }
2740
2741 user.setScreenName(screenName);
2742
2743 setEmailAddress(
2744 user, password, firstName, middleName, lastName, emailAddress);
2745
2746 user.setOpenId(openId);
2747 user.setLanguageId(languageId);
2748 user.setTimeZoneId(timeZoneId);
2749 user.setGreeting(greeting);
2750 user.setComments(comments);
2751 user.setFirstName(firstName);
2752 user.setMiddleName(middleName);
2753 user.setLastName(lastName);
2754 user.setJobTitle(jobTitle);
2755
2756 userPersistence.update(user, false);
2757
2758
2760 Date birthday = PortalUtil.getDate(
2761 birthdayMonth, birthdayDay, birthdayYear,
2762 new ContactBirthdayException());
2763
2764 long contactId = user.getContactId();
2765
2766 Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
2767
2768 if (contact == null) {
2769 contact = contactPersistence.create(contactId);
2770
2771 contact.setCompanyId(user.getCompanyId());
2772 contact.setUserName(StringPool.BLANK);
2773 contact.setCreateDate(now);
2774 contact.setAccountId(company.getAccountId());
2775 contact.setParentContactId(
2776 ContactConstants.DEFAULT_PARENT_CONTACT_ID);
2777 }
2778
2779 contact.setModifiedDate(now);
2780 contact.setFirstName(firstName);
2781 contact.setMiddleName(middleName);
2782 contact.setLastName(lastName);
2783 contact.setPrefixId(prefixId);
2784 contact.setSuffixId(suffixId);
2785 contact.setMale(male);
2786 contact.setBirthday(birthday);
2787 contact.setSmsSn(smsSn);
2788 contact.setAimSn(aimSn);
2789 contact.setFacebookSn(facebookSn);
2790 contact.setIcqSn(icqSn);
2791 contact.setJabberSn(jabberSn);
2792 contact.setMsnSn(msnSn);
2793 contact.setMySpaceSn(mySpaceSn);
2794 contact.setSkypeSn(skypeSn);
2795 contact.setTwitterSn(twitterSn);
2796 contact.setYmSn(ymSn);
2797 contact.setJobTitle(jobTitle);
2798
2799 contactPersistence.update(contact, false);
2800
2801
2803 Group group = groupLocalService.getUserGroup(
2804 user.getCompanyId(), userId);
2805
2806 group.setFriendlyURL(StringPool.SLASH + screenName);
2807
2808 groupPersistence.update(group, false);
2809
2810
2812 updateGroups(userId, groupIds);
2813
2814
2816 updateOrganizations(userId, organizationIds);
2817
2818
2820 if (roleIds != null) {
2821 roleIds = EnterpriseAdminUtil.addRequiredRoles(user, roleIds);
2822
2823 userPersistence.setRoles(userId, roleIds);
2824 }
2825
2826
2828 updateUserGroupRoles(user, groupIds, organizationIds, userGroupRoles);
2829
2830
2832 if (userGroupIds != null) {
2833 userGroupLocalService.copyUserGroupLayouts(userGroupIds, userId);
2834
2835 userPersistence.setUserGroups(userId, userGroupIds);
2836 }
2837
2838
2840 announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
2841
2842
2844 if (serviceContext != null) {
2845 updateAsset(
2846 userId, user, serviceContext.getAssetCategoryIds(),
2847 serviceContext.getAssetTagNames());
2848 }
2849
2850
2852 user.setExpandoBridgeAttributes(serviceContext);
2853
2854
2856 if (GetterUtil.getBoolean(
2857 PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
2858 !oldFullName.equals(user.getFullName())) {
2859
2860 mbMessageLocalService.updateUserName(userId, user.getFullName());
2861 }
2862
2863
2865 Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
2866
2867 indexer.reindex(user);
2868
2869
2871 PermissionCacheUtil.clearCache();
2872
2873 return user;
2874 }
2875
2876 protected String getScreenName(String screenName) {
2877 return StringUtil.lowerCase(StringUtil.trim(screenName));
2878 }
2879
2880 protected long[] getUserIds(List<User> users) {
2881 long[] userIds = new long[users.size()];
2882
2883 for (int i = 0; i < users.size(); i++) {
2884 User user = users.get(i);
2885
2886 userIds[i] = user.getUserId();
2887 }
2888
2889 return userIds;
2890 }
2891
2892 protected void sendEmail(User user, String password)
2893 throws IOException, PortalException, SystemException {
2894
2895 if (!PrefsPropsUtil.getBoolean(
2896 user.getCompanyId(),
2897 PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
2898
2899 return;
2900 }
2901
2902 long companyId = user.getCompanyId();
2903
2904 Company company = companyPersistence.findByPrimaryKey(companyId);
2905
2906 String fromName = PrefsPropsUtil.getString(
2907 companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
2908 String fromAddress = PrefsPropsUtil.getString(
2909 companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
2910
2911 String toName = user.getFullName();
2912 String toAddress = user.getEmailAddress();
2913
2914 String subject = PrefsPropsUtil.getContent(
2915 companyId, PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
2916 String body = PrefsPropsUtil.getContent(
2917 companyId, PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
2918
2919 subject = StringUtil.replace(
2920 subject,
2921 new String[] {
2922 "[$FROM_ADDRESS$]",
2923 "[$FROM_NAME$]",
2924 "[$PORTAL_URL$]",
2925 "[$TO_ADDRESS$]",
2926 "[$TO_NAME$]",
2927 "[$USER_ID$]",
2928 "[$USER_PASSWORD$]",
2929 "[$USER_SCREENNAME$]"
2930 },
2931 new String[] {
2932 fromAddress,
2933 fromName,
2934 company.getVirtualHost(),
2935 toAddress,
2936 toName,
2937 String.valueOf(user.getUserId()),
2938 password,
2939 user.getScreenName()
2940 });
2941
2942 body = StringUtil.replace(
2943 body,
2944 new String[] {
2945 "[$FROM_ADDRESS$]",
2946 "[$FROM_NAME$]",
2947 "[$PORTAL_URL$]",
2948 "[$TO_ADDRESS$]",
2949 "[$TO_NAME$]",
2950 "[$USER_ID$]",
2951 "[$USER_PASSWORD$]",
2952 "[$USER_SCREENNAME$]"
2953 },
2954 new String[] {
2955 fromAddress,
2956 fromName,
2957 company.getVirtualHost(),
2958 toAddress,
2959 toName,
2960 String.valueOf(user.getUserId()),
2961 password,
2962 user.getScreenName()
2963 });
2964
2965 InternetAddress from = new InternetAddress(fromAddress, fromName);
2966
2967 InternetAddress to = new InternetAddress(toAddress, toName);
2968
2969 MailMessage message = new MailMessage(from, to, subject, body, true);
2970
2971 mailService.sendEmail(message);
2972 }
2973
2974 protected void setEmailAddress(
2975 User user, String password, String firstName, String middleName,
2976 String lastName, String emailAddress)
2977 throws PortalException, SystemException {
2978
2979 if (emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
2980 return;
2981 }
2982
2983 long userId = user.getUserId();
2984
2985
2987 if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
2988 mailService.addUser(
2989 user.getCompanyId(), userId, password, firstName, middleName,
2990 lastName, emailAddress);
2991 }
2992
2993
2995 else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
2996 mailService.updateEmailAddress(
2997 user.getCompanyId(), userId, emailAddress);
2998 }
2999
3000
3002 else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
3003 mailService.deleteEmailAddress(user.getCompanyId(), userId);
3004 }
3005
3006 user.setEmailAddress(emailAddress);
3007 }
3008
3009 protected void updateUserGroupRoles(
3010 User user, long[] groupIds, long[] organizationIds,
3011 List<UserGroupRole> userGroupRoles)
3012 throws PortalException, SystemException {
3013
3014 if (userGroupRoles == null) {
3015 return;
3016 }
3017
3018 List<UserGroupRole> previousUserGroupRoles =
3019 userGroupRolePersistence.findByUserId(user.getUserId());
3020
3021 for (UserGroupRole userGroupRole : previousUserGroupRoles) {
3022 if (userGroupRoles.contains(userGroupRole)) {
3023 userGroupRoles.remove(userGroupRole);
3024 }
3025 else {
3026 userGroupRoleLocalService.deleteUserGroupRole(
3027 userGroupRole);
3028 }
3029 }
3030
3031 long[] validGroupIds = null;
3032
3033 if (groupIds != null) {
3034 validGroupIds = ArrayUtil.clone(groupIds);
3035 }
3036 else {
3037 validGroupIds = user.getGroupIds();
3038 }
3039
3040 if (organizationIds == null) {
3041 organizationIds = user.getOrganizationIds();
3042 }
3043
3044 long[] organizationGroupIds = new long[organizationIds.length];
3045
3046 for (int i = 0; i < organizationIds.length; i++) {
3047 long organizationId = organizationIds[i];
3048
3049 Organization organization =
3050 organizationPersistence.findByPrimaryKey(
3051 organizationId);
3052
3053 Group organizationGroup = organization.getGroup();
3054
3055 organizationGroupIds[i] = organizationGroup.getGroupId();
3056 }
3057
3058 validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
3059
3060 Arrays.sort(validGroupIds);
3061
3062 for (UserGroupRole userGroupRole : userGroupRoles) {
3063 if (Arrays.binarySearch(
3064 validGroupIds, userGroupRole.getGroupId()) >= 0) {
3065
3066 userGroupRoleLocalService.addUserGroupRole(userGroupRole);
3067 }
3068 }
3069 }
3070
3071 protected void validate(
3072 long companyId, long userId, boolean autoPassword, String password1,
3073 String password2, boolean autoScreenName, String screenName,
3074 String emailAddress, String firstName, String middleName,
3075 String lastName, long[] organizationIds)
3076 throws PortalException, SystemException {
3077
3078 Company company = companyPersistence.findByPrimaryKey(companyId);
3079
3080 if (company.isSystem()) {
3081 return;
3082 }
3083
3084 if ((company.getMaxUsers() > 0) &&
3085 (company.getMaxUsers() <=
3086 searchCount(companyId, null, true, null))) {
3087
3088 throw new CompanyMaxUsersException();
3089 }
3090
3091 if (!autoScreenName) {
3092 validateScreenName(companyId, userId, screenName);
3093 }
3094
3095 if (!autoPassword) {
3096 PasswordPolicy passwordPolicy =
3097 passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
3098
3099 PwdToolkitUtil.validate(
3100 companyId, 0, password1, password2, passwordPolicy);
3101 }
3102
3103 validateEmailAddress(companyId, emailAddress);
3104
3105 if (Validator.isNotNull(emailAddress)) {
3106 User user = userPersistence.fetchByC_EA(companyId, emailAddress);
3107
3108 if (user != null) {
3109 throw new DuplicateUserEmailAddressException();
3110 }
3111 }
3112
3113 validateFullName(companyId, firstName, middleName, lastName);
3114 }
3115
3116 protected void validate(
3117 long userId, String screenName, String emailAddress,
3118 String firstName, String middleName, String lastName, String smsSn)
3119 throws PortalException, SystemException {
3120
3121 User user = userPersistence.findByPrimaryKey(userId);
3122
3123 if (!user.getScreenName().equalsIgnoreCase(screenName)) {
3124 validateScreenName(user.getCompanyId(), userId, screenName);
3125 }
3126
3127 validateEmailAddress(user.getCompanyId(), emailAddress);
3128
3129 if (!user.isDefaultUser()) {
3130 if (Validator.isNotNull(emailAddress) &&
3131 !user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
3132
3133 if (userPersistence.fetchByC_EA(
3134 user.getCompanyId(), emailAddress) != null) {
3135
3136 throw new DuplicateUserEmailAddressException();
3137 }
3138 }
3139
3140 validateFullName(
3141 user.getCompanyId(), firstName, middleName, lastName);
3142 }
3143
3144 if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
3145 throw new UserSmsException();
3146 }
3147 }
3148
3149 protected void validateEmailAddress(long companyId, String emailAddress)
3150 throws PortalException, SystemException {
3151
3152 if (Validator.isNull(emailAddress) &&
3153 !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
3154
3155 return;
3156 }
3157
3158 if (!Validator.isEmailAddress(emailAddress) ||
3159 emailAddress.startsWith("root@") ||
3160 emailAddress.startsWith("postmaster@")) {
3161
3162 throw new UserEmailAddressException();
3163 }
3164
3165 String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
3166 companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
3167 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
3168
3169 for (int i = 0; i < reservedEmailAddresses.length; i++) {
3170 if (emailAddress.equalsIgnoreCase(reservedEmailAddresses[i])) {
3171 throw new ReservedUserEmailAddressException();
3172 }
3173 }
3174 }
3175
3176 protected void validateFullName(
3177 long companyId, String firstName, String middleName,
3178 String lastName)
3179 throws PortalException {
3180
3181 if (Validator.isNull(firstName)) {
3182 throw new ContactFirstNameException();
3183 }
3184 else if (Validator.isNull(lastName)) {
3185 throw new ContactLastNameException();
3186 }
3187
3188 FullNameValidator fullNameValidator =
3189 FullNameValidatorFactory.getInstance();
3190
3191 if (!fullNameValidator.validate(
3192 companyId, firstName, middleName, lastName)) {
3193
3194 throw new ContactFullNameException();
3195 }
3196 }
3197
3198 protected void validatePassword(
3199 long companyId, long userId, String password1, String password2)
3200 throws PortalException, SystemException {
3201
3202 if (Validator.isNull(password1) || Validator.isNull(password2)) {
3203 throw new UserPasswordException(
3204 UserPasswordException.PASSWORD_INVALID);
3205 }
3206
3207 if (!password1.equals(password2)) {
3208 throw new UserPasswordException(
3209 UserPasswordException.PASSWORDS_DO_NOT_MATCH);
3210 }
3211
3212 PasswordPolicy passwordPolicy =
3213 passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
3214
3215 PwdToolkitUtil.validate(
3216 companyId, userId, password1, password2, passwordPolicy);
3217 }
3218
3219 protected void validateReminderQuery(String question, String answer)
3220 throws PortalException {
3221
3222 if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
3223 return;
3224 }
3225
3226 if (Validator.isNull(question)) {
3227 throw new UserReminderQueryException("Question cannot be null");
3228 }
3229
3230 if (Validator.isNull(answer)) {
3231 throw new UserReminderQueryException("Answer cannot be null");
3232 }
3233 }
3234
3235 protected void validateScreenName(
3236 long companyId, long userId, String screenName)
3237 throws PortalException, SystemException {
3238
3239 if (Validator.isNull(screenName)) {
3240 throw new UserScreenNameException();
3241 }
3242
3243 ScreenNameValidator screenNameValidator =
3244 ScreenNameValidatorFactory.getInstance();
3245
3246 if (!screenNameValidator.validate(companyId, screenName)) {
3247 throw new UserScreenNameException();
3248 }
3249
3250 if (Validator.isNumber(screenName) &&
3251 !screenName.equals(String.valueOf(userId))) {
3252
3253 if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
3254 throw new UserScreenNameException();
3255 }
3256
3257 Group group = groupPersistence.fetchByPrimaryKey(
3258 GetterUtil.getLong(screenName));
3259
3260 if (group != null) {
3261 throw new UserScreenNameException();
3262 }
3263 }
3264
3265 for (char c : screenName.toCharArray()) {
3266 if ((!Validator.isChar(c)) && (!Validator.isDigit(c)) &&
3267 (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
3268 (c != CharPool.UNDERLINE)) {
3269
3270 throw new UserScreenNameException();
3271 }
3272 }
3273
3274 String[] anonymousNames = PrincipalBean.ANONYMOUS_NAMES;
3275
3276 for (int i = 0; i < anonymousNames.length; i++) {
3277 if (screenName.equalsIgnoreCase(anonymousNames[i])) {
3278 throw new UserScreenNameException();
3279 }
3280 }
3281
3282 User user = userPersistence.fetchByC_SN(companyId, screenName);
3283
3284 if (user != null) {
3285 throw new DuplicateUserScreenNameException();
3286 }
3287
3288 String friendlyURL = StringPool.SLASH + screenName;
3289
3290 Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
3291
3292 if (group != null) {
3293 throw new DuplicateUserScreenNameException();
3294 }
3295
3296 int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
3297
3298 if (exceptionType != -1) {
3299 throw new UserScreenNameException(
3300 new GroupFriendlyURLException(exceptionType));
3301 }
3302
3303 String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
3304 companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
3305 StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
3306
3307 for (int i = 0; i < reservedScreenNames.length; i++) {
3308 if (screenName.equalsIgnoreCase(reservedScreenNames[i])) {
3309 throw new ReservedUserScreenNameException();
3310 }
3311 }
3312 }
3313
3314 private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
3315
3316 private static Map<Long, User> _defaultUsers =
3317 new ConcurrentHashMap<Long, User>();
3318
3319}