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