1   /**
2    * Copyright (c) 2000-2008 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.service.impl;
24  
25  import com.liferay.portal.ContactBirthdayException;
26  import com.liferay.portal.ContactFirstNameException;
27  import com.liferay.portal.ContactLastNameException;
28  import com.liferay.portal.DuplicateUserEmailAddressException;
29  import com.liferay.portal.DuplicateUserScreenNameException;
30  import com.liferay.portal.GroupFriendlyURLException;
31  import com.liferay.portal.ModelListenerException;
32  import com.liferay.portal.NoSuchGroupException;
33  import com.liferay.portal.NoSuchRoleException;
34  import com.liferay.portal.NoSuchUserException;
35  import com.liferay.portal.NoSuchUserGroupException;
36  import com.liferay.portal.PasswordExpiredException;
37  import com.liferay.portal.PortalException;
38  import com.liferay.portal.RequiredUserException;
39  import com.liferay.portal.ReservedUserEmailAddressException;
40  import com.liferay.portal.ReservedUserScreenNameException;
41  import com.liferay.portal.SystemException;
42  import com.liferay.portal.UserEmailAddressException;
43  import com.liferay.portal.UserIdException;
44  import com.liferay.portal.UserLockoutException;
45  import com.liferay.portal.UserPasswordException;
46  import com.liferay.portal.UserPortraitException;
47  import com.liferay.portal.UserScreenNameException;
48  import com.liferay.portal.UserSmsException;
49  import com.liferay.portal.kernel.language.LanguageUtil;
50  import com.liferay.portal.kernel.mail.MailMessage;
51  import com.liferay.portal.kernel.util.ArrayUtil;
52  import com.liferay.portal.kernel.util.Base64;
53  import com.liferay.portal.kernel.util.CharPool;
54  import com.liferay.portal.kernel.util.GetterUtil;
55  import com.liferay.portal.kernel.util.HtmlUtil;
56  import com.liferay.portal.kernel.util.InstancePool;
57  import com.liferay.portal.kernel.util.KeyValuePair;
58  import com.liferay.portal.kernel.util.OrderByComparator;
59  import com.liferay.portal.kernel.util.StringPool;
60  import com.liferay.portal.kernel.util.StringUtil;
61  import com.liferay.portal.kernel.util.Validator;
62  import com.liferay.portal.lar.PortletDataHandlerKeys;
63  import com.liferay.portal.lar.UserIdStrategy;
64  import com.liferay.portal.model.Company;
65  import com.liferay.portal.model.CompanyConstants;
66  import com.liferay.portal.model.Contact;
67  import com.liferay.portal.model.ContactConstants;
68  import com.liferay.portal.model.Group;
69  import com.liferay.portal.model.Organization;
70  import com.liferay.portal.model.PasswordPolicy;
71  import com.liferay.portal.model.ResourceConstants;
72  import com.liferay.portal.model.Role;
73  import com.liferay.portal.model.RoleConstants;
74  import com.liferay.portal.model.User;
75  import com.liferay.portal.model.UserGroup;
76  import com.liferay.portal.model.impl.LayoutImpl;
77  import com.liferay.portal.security.auth.AuthPipeline;
78  import com.liferay.portal.security.auth.Authenticator;
79  import com.liferay.portal.security.auth.PrincipalException;
80  import com.liferay.portal.security.auth.ScreenNameGenerator;
81  import com.liferay.portal.security.auth.ScreenNameValidator;
82  import com.liferay.portal.security.ldap.PortalLDAPUtil;
83  import com.liferay.portal.security.permission.PermissionCacheUtil;
84  import com.liferay.portal.security.pwd.PwdEncryptor;
85  import com.liferay.portal.security.pwd.PwdToolkitUtil;
86  import com.liferay.portal.service.base.PrincipalBean;
87  import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
88  import com.liferay.portal.util.PortalUtil;
89  import com.liferay.portal.util.PrefsPropsUtil;
90  import com.liferay.portal.util.PropsKeys;
91  import com.liferay.portal.util.PropsUtil;
92  import com.liferay.portal.util.PropsValues;
93  import com.liferay.util.Encryptor;
94  import com.liferay.util.EncryptorException;
95  import com.liferay.util.Normalizer;
96  
97  import java.io.ByteArrayInputStream;
98  import java.io.IOException;
99  import java.io.UnsupportedEncodingException;
100 
101 import java.security.MessageDigest;
102 import java.security.NoSuchAlgorithmException;
103 
104 import java.util.ArrayList;
105 import java.util.Date;
106 import java.util.LinkedHashMap;
107 import java.util.List;
108 import java.util.Locale;
109 import java.util.Map;
110 import java.util.concurrent.ConcurrentHashMap;
111 
112 import javax.mail.internet.InternetAddress;
113 
114 import org.apache.commons.logging.Log;
115 import org.apache.commons.logging.LogFactory;
116 
117 /**
118  * <a href="UserLocalServiceImpl.java.html"><b><i>View Source</i></b></a>
119  *
120  * @author Brian Wing Shun Chan
121  * @author Scott Lee
122  * @author Raymond Augé
123  * @author Jorge Ferrer
124  *
125  */
126 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
127 
128     public void addGroupUsers(long groupId, long[] userIds)
129         throws PortalException, SystemException {
130 
131         groupPersistence.addUsers(groupId, userIds);
132 
133         Group group = groupPersistence.findByPrimaryKey(groupId);
134 
135         Role role = rolePersistence.findByC_N(
136             group.getCompanyId(), RoleConstants.COMMUNITY_MEMBER);
137 
138         for (int i = 0; i < userIds.length; i++) {
139             long userId = userIds[i];
140 
141             userGroupRoleLocalService.addUserGroupRoles(
142                 userId, groupId, new long[] {role.getRoleId()});
143         }
144 
145         PermissionCacheUtil.clearCache();
146     }
147 
148     public void addOrganizationUsers(long organizationId, long[] userIds)
149         throws PortalException, SystemException {
150 
151         organizationPersistence.addUsers(organizationId, userIds);
152 
153         Organization organization = organizationPersistence.findByPrimaryKey(
154             organizationId);
155 
156         Group group = organization.getGroup();
157 
158         long groupId = group.getGroupId();
159 
160         Role role = rolePersistence.findByC_N(
161             group.getCompanyId(), RoleConstants.ORGANIZATION_MEMBER);
162 
163         for (int i = 0; i < userIds.length; i++) {
164             long userId = userIds[i];
165 
166             userGroupRoleLocalService.addUserGroupRoles(
167                 userId, groupId, new long[] {role.getRoleId()});
168         }
169 
170         PermissionCacheUtil.clearCache();
171     }
172 
173     public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
174         throws SystemException {
175 
176         passwordPolicyRelLocalService.addPasswordPolicyRels(
177             passwordPolicyId, User.class.getName(), userIds);
178     }
179 
180     public void addRoleUsers(long roleId, long[] userIds)
181         throws SystemException {
182 
183         rolePersistence.addUsers(roleId, userIds);
184 
185         PermissionCacheUtil.clearCache();
186     }
187 
188     public void addUserGroupUsers(long userGroupId, long[] userIds)
189         throws PortalException, SystemException {
190 
191         copyUserGroupLayouts(userGroupId, userIds);
192 
193         userGroupPersistence.addUsers(userGroupId, userIds);
194 
195         PermissionCacheUtil.clearCache();
196     }
197 
198     public User addUser(
199             long creatorUserId, long companyId, boolean autoPassword,
200             String password1, String password2, boolean autoScreenName,
201             String screenName, String emailAddress, Locale locale,
202             String firstName, String middleName, String lastName, int prefixId,
203             int suffixId, boolean male, int birthdayMonth, int birthdayDay,
204             int birthdayYear, String jobTitle, long[] organizationIds,
205             boolean sendEmail)
206         throws PortalException, SystemException {
207 
208         // User
209 
210         Company company = companyPersistence.findByPrimaryKey(companyId);
211         screenName = getScreenName(screenName);
212         emailAddress = emailAddress.trim().toLowerCase();
213         Date now = new Date();
214 
215         if (PropsValues.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE) {
216             autoScreenName = true;
217         }
218 
219         long userId = counterLocalService.increment();
220 
221         validate(
222             companyId, userId, autoPassword, password1, password2,
223             autoScreenName, screenName, emailAddress, firstName, lastName,
224             organizationIds);
225 
226         if (autoPassword) {
227             password1 = PwdToolkitUtil.generate();
228         }
229 
230         if (autoScreenName) {
231             ScreenNameGenerator screenNameGenerator =
232                 (ScreenNameGenerator)InstancePool.get(
233                     PropsValues.USERS_SCREEN_NAME_GENERATOR);
234 
235             try {
236                 screenName = screenNameGenerator.generate(
237                     companyId, userId, emailAddress);
238             }
239             catch (Exception e) {
240                 throw new SystemException(e);
241             }
242         }
243 
244         User defaultUser = getDefaultUser(companyId);
245 
246         String fullName = ContactConstants.getFullName(
247             firstName, middleName, lastName);
248 
249         String greeting = LanguageUtil.format(
250             companyId, locale, "welcome-x", " " + fullName, false);
251 
252         User user = userPersistence.create(userId);
253 
254         user.setCompanyId(companyId);
255         user.setCreateDate(now);
256         user.setModifiedDate(now);
257         user.setDefaultUser(false);
258         user.setContactId(counterLocalService.increment());
259         user.setPassword(PwdEncryptor.encrypt(password1));
260         user.setPasswordUnencrypted(password1);
261         user.setPasswordEncrypted(true);
262         user.setPasswordReset(false);
263         user.setScreenName(screenName);
264         user.setEmailAddress(emailAddress);
265         user.setLanguageId(locale.toString());
266         user.setTimeZoneId(defaultUser.getTimeZoneId());
267         user.setGreeting(greeting);
268         user.setActive(true);
269 
270         userPersistence.update(user, false);
271 
272         // Resources
273 
274         String creatorUserName = StringPool.BLANK;
275 
276         if (creatorUserId <= 0) {
277             creatorUserId = user.getUserId();
278 
279             // Don't grab the full name from the User object because it doesn't
280             // have a corresponding Contact object yet
281 
282             //creatorUserName = user.getFullName();
283         }
284         else {
285             User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
286 
287             creatorUserName = creatorUser.getFullName();
288         }
289 
290         resourceLocalService.addResources(
291             companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
292             false, false, false);
293 
294         // Mail
295 
296         if (user.hasCompanyMx()) {
297             mailService.addUser(
298                 userId, password1, firstName, middleName, lastName,
299                 emailAddress);
300         }
301 
302         // Contact
303 
304         Date birthday = PortalUtil.getDate(
305             birthdayMonth, birthdayDay, birthdayYear,
306             new ContactBirthdayException());
307 
308         Contact contact = contactPersistence.create(user.getContactId());
309 
310         contact.setCompanyId(user.getCompanyId());
311         contact.setUserId(creatorUserId);
312         contact.setUserName(creatorUserName);
313         contact.setCreateDate(now);
314         contact.setModifiedDate(now);
315         contact.setAccountId(company.getAccountId());
316         contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
317         contact.setFirstName(firstName);
318         contact.setMiddleName(middleName);
319         contact.setLastName(lastName);
320         contact.setPrefixId(prefixId);
321         contact.setSuffixId(suffixId);
322         contact.setMale(male);
323         contact.setBirthday(birthday);
324         contact.setJobTitle(jobTitle);
325 
326         contactPersistence.update(contact, false);
327 
328         // Organizations
329 
330         updateOrganizations(userId, organizationIds);
331 
332         // Group
333 
334         groupLocalService.addGroup(
335             user.getUserId(), User.class.getName(), user.getUserId(), null,
336             null, 0, StringPool.SLASH + screenName, true);
337 
338         // Default groups
339 
340         String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
341             companyId, PropsKeys.ADMIN_DEFAULT_GROUP_NAMES, StringPool.NEW_LINE,
342             PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
343 
344         long[] groupIds = new long[defaultGroupNames.length];
345 
346         for (int i = 0; i < defaultGroupNames.length; i++) {
347             try {
348                 Group group = groupFinder.findByC_N(
349                     companyId, defaultGroupNames[i]);
350 
351                 groupIds[i] = group.getGroupId();
352             }
353             catch (NoSuchGroupException nsge) {
354             }
355         }
356 
357         groupLocalService.addUserGroups(userId, groupIds);
358 
359         // Default roles
360 
361         List<Role> roles = new ArrayList<Role>();
362 
363         String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
364             companyId, PropsKeys.ADMIN_DEFAULT_ROLE_NAMES, StringPool.NEW_LINE,
365             PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
366 
367         for (int i = 0; i < defaultRoleNames.length; i++) {
368             try {
369                 Role role = roleFinder.findByC_N(
370                     companyId, defaultRoleNames[i]);
371 
372                 roles.add(role);
373             }
374             catch (NoSuchRoleException nsge) {
375             }
376         }
377 
378         userPersistence.setRoles(userId, roles);
379 
380         // Default user groups
381 
382         List<UserGroup> userGroups = new ArrayList<UserGroup>();
383 
384         String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
385             companyId, PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
386             StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
387 
388         for (int i = 0; i < defaultUserGroupNames.length; i++) {
389             try {
390                 UserGroup userGroup = userGroupFinder.findByC_N(
391                     companyId, defaultUserGroupNames[i]);
392 
393                 userGroups.add(userGroup);
394 
395                 copyUserGroupLayouts(
396                     userGroup.getUserGroupId(), new long[] {userId});
397             }
398             catch (NoSuchUserGroupException nsuge) {
399             }
400         }
401 
402         userPersistence.setUserGroups(userId, userGroups);
403 
404         // Email
405 
406         if (sendEmail) {
407             try {
408                 sendEmail(user, password1);
409             }
410             catch (IOException ioe) {
411                 throw new SystemException(ioe);
412             }
413         }
414 
415         return user;
416     }
417 
418     public int authenticateByEmailAddress(
419             long companyId, String emailAddress, String password,
420             Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
421         throws PortalException, SystemException {
422 
423         return authenticate(
424             companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
425             headerMap, parameterMap);
426     }
427 
428     public int authenticateByScreenName(
429             long companyId, String screenName, String password,
430             Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
431         throws PortalException, SystemException {
432 
433         return authenticate(
434             companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
435             headerMap, parameterMap);
436     }
437 
438     public int authenticateByUserId(
439             long companyId, long userId, String password,
440             Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
441         throws PortalException, SystemException {
442 
443         return authenticate(
444             companyId, String.valueOf(userId), password,
445             CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap);
446     }
447 
448     public long authenticateForBasic(
449             long companyId, String authType, String login, String password)
450         throws PortalException, SystemException {
451 
452         try {
453             User user = null;
454 
455             if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
456                 user = getUserByEmailAddress(companyId, login);
457             }
458             else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
459                 user = getUserByScreenName(companyId, login);
460             }
461             else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
462                 user = getUserById(companyId, GetterUtil.getLong(login));
463             }
464 
465             String userPassword = user.getPassword();
466 
467             if (!user.isPasswordEncrypted()) {
468                 userPassword = PwdEncryptor.encrypt(userPassword);
469             }
470 
471             String encPassword = PwdEncryptor.encrypt(password);
472 
473             if (userPassword.equals(password) ||
474                 userPassword.equals(encPassword)) {
475 
476                 return user.getUserId();
477             }
478         }
479         catch (NoSuchUserException nsue) {
480         }
481 
482         return 0;
483     }
484 
485     public boolean authenticateForJAAS(long userId, String encPassword) {
486         try {
487             User user = userPersistence.findByPrimaryKey(userId);
488 
489             if (user.isDefaultUser()) {
490                 _log.error(
491                     "The default user should never be allowed to authenticate");
492 
493                 return false;
494             }
495 
496             String password = user.getPassword();
497 
498             if (user.isPasswordEncrypted()) {
499                 if (password.equals(encPassword)) {
500                     return true;
501                 }
502 
503                 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
504                     encPassword = PwdEncryptor.encrypt(encPassword, password);
505 
506                     if (password.equals(encPassword)) {
507                         return true;
508                     }
509                 }
510             }
511             else {
512                 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
513                     if (password.equals(encPassword)) {
514                         return true;
515                     }
516                 }
517 
518                 password = PwdEncryptor.encrypt(password);
519 
520                 if (password.equals(encPassword)) {
521                     return true;
522                 }
523             }
524         }
525         catch (Exception e) {
526             _log.error(e);
527         }
528 
529         return false;
530     }
531 
532     public void checkLockout(User user)
533         throws PortalException, SystemException {
534 
535         if (PortalLDAPUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
536             return;
537         }
538 
539         PasswordPolicy passwordPolicy = user.getPasswordPolicy();
540 
541         if (passwordPolicy.isLockout()) {
542 
543             // Reset failure count
544 
545             Date now = new Date();
546             int failedLoginAttempts = user.getFailedLoginAttempts();
547 
548             if (failedLoginAttempts > 0) {
549                 long failedLoginTime = user.getLastFailedLoginDate().getTime();
550                 long elapsedTime = now.getTime() - failedLoginTime;
551                 long requiredElapsedTime =
552                     passwordPolicy.getResetFailureCount() * 1000;
553 
554                 if ((requiredElapsedTime != 0) &&
555                     (elapsedTime > requiredElapsedTime)) {
556 
557                     user.setLastFailedLoginDate(null);
558                     user.setFailedLoginAttempts(0);
559                 }
560             }
561 
562             // Reset lockout
563 
564             if (user.isLockout()) {
565                 long lockoutTime = user.getLockoutDate().getTime();
566                 long elapsedTime = now.getTime() - lockoutTime;
567                 long requiredElapsedTime =
568                     passwordPolicy.getLockoutDuration() * 1000;
569 
570                 if ((requiredElapsedTime != 0) &&
571                     (elapsedTime > requiredElapsedTime)) {
572 
573                     user.setLockout(false);
574                     user.setLockoutDate(null);
575                 }
576             }
577 
578             if (user.isLockout()) {
579                 throw new UserLockoutException();
580             }
581         }
582     }
583 
584     public void checkLoginFailure(User user) throws SystemException {
585         Date now = new Date();
586 
587         int failedLoginAttempts = user.getFailedLoginAttempts();
588 
589         user.setLastFailedLoginDate(now);
590         user.setFailedLoginAttempts(++failedLoginAttempts);
591 
592         userPersistence.update(user, false);
593     }
594 
595     public void checkLoginFailureByEmailAddress(
596             long companyId, String emailAddress)
597         throws PortalException, SystemException {
598 
599         User user = getUserByEmailAddress(companyId, emailAddress);
600 
601         checkLoginFailure(user);
602     }
603 
604     public void checkLoginFailureById(long userId)
605         throws PortalException, SystemException {
606 
607         User user = userPersistence.findByPrimaryKey(userId);
608 
609         checkLoginFailure(user);
610     }
611 
612     public void checkLoginFailureByScreenName(long companyId, String screenName)
613         throws PortalException, SystemException {
614 
615         User user = getUserByScreenName(companyId, screenName);
616 
617         checkLoginFailure(user);
618     }
619 
620     public void checkPasswordExpired(User user)
621         throws PortalException, SystemException {
622 
623         if (PortalLDAPUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
624             return;
625         }
626 
627         PasswordPolicy passwordPolicy = user.getPasswordPolicy();
628 
629         // Check if password has expired
630 
631         if (isPasswordExpired(user)) {
632             int graceLoginCount = user.getGraceLoginCount();
633 
634             if (graceLoginCount < passwordPolicy.getGraceLimit()) {
635                 user.setGraceLoginCount(++graceLoginCount);
636 
637                 userPersistence.update(user, false);
638             }
639             else {
640                 throw new PasswordExpiredException();
641             }
642         }
643 
644         // Check if warning message should be sent
645 
646         if (isPasswordExpiringSoon(user)) {
647             user.setPasswordReset(true);
648 
649             userPersistence.update(user, false);
650         }
651 
652         // Check if user should be forced to change password on first login
653 
654         if (passwordPolicy.isChangeable() &&
655             passwordPolicy.isChangeRequired()) {
656 
657             if (user.getLastLoginDate() == null) {
658                 boolean passwordReset = false;
659 
660                 if (passwordPolicy.isChangeable() &&
661                     passwordPolicy.isChangeRequired()) {
662 
663                     passwordReset = true;
664                 }
665 
666                 user.setPasswordReset(passwordReset);
667 
668                 userPersistence.update(user, false);
669             }
670         }
671     }
672 
673     public void clearOrganizationUsers(long organizationId)
674         throws SystemException {
675 
676         organizationPersistence.clearUsers(organizationId);
677 
678         PermissionCacheUtil.clearCache();
679     }
680 
681     public void clearUserGroupUsers(long userGroupId) throws SystemException {
682         userGroupPersistence.clearUsers(userGroupId);
683 
684         PermissionCacheUtil.clearCache();
685     }
686 
687     public KeyValuePair decryptUserId(
688             long companyId, String name, String password)
689         throws PortalException, SystemException {
690 
691         Company company = companyPersistence.findByPrimaryKey(companyId);
692 
693         try {
694             name = Encryptor.decrypt(company.getKeyObj(), name);
695         }
696         catch (EncryptorException ee) {
697             throw new SystemException(ee);
698         }
699 
700         long userId = GetterUtil.getLong(name);
701 
702         User user = userPersistence.findByPrimaryKey(userId);
703 
704         try {
705             password = Encryptor.decrypt(company.getKeyObj(), password);
706         }
707         catch (EncryptorException ee) {
708             throw new SystemException(ee);
709         }
710 
711         String encPassword = PwdEncryptor.encrypt(password);
712 
713         if (user.getPassword().equals(encPassword)) {
714             if (isPasswordExpired(user)) {
715                 user.setPasswordReset(true);
716 
717                 userPersistence.update(user, false);
718             }
719 
720             return new KeyValuePair(name, password);
721         }
722         else {
723             throw new PrincipalException();
724         }
725     }
726 
727     public void deletePasswordPolicyUser(long passwordPolicyId, long userId)
728         throws SystemException {
729 
730         passwordPolicyRelLocalService.deletePasswordPolicyRel(
731             passwordPolicyId, User.class.getName(), userId);
732     }
733 
734     public void deleteRoleUser(long roleId, long userId)
735         throws SystemException {
736 
737         rolePersistence.removeUser(roleId, userId);
738 
739         PermissionCacheUtil.clearCache();
740     }
741 
742     public void deleteUser(long userId)
743         throws PortalException, SystemException {
744 
745         if (!PropsValues.USERS_DELETE) {
746             throw new RequiredUserException();
747         }
748 
749         User user = userPersistence.findByPrimaryKey(userId);
750 
751         // Group
752 
753         Group group = user.getGroup();
754 
755         groupLocalService.deleteGroup(group.getGroupId());
756 
757         // Portrait
758 
759         imageLocalService.deleteImage(user.getPortraitId());
760 
761         // Password policy relation
762 
763         passwordPolicyRelLocalService.deletePasswordPolicyRel(
764             User.class.getName(), userId);
765 
766         // Old passwords
767 
768         passwordTrackerLocalService.deletePasswordTrackers(userId);
769 
770         // Subscriptions
771 
772         subscriptionLocalService.deleteSubscriptions(userId);
773 
774         // External user ids
775 
776         userIdMapperLocalService.deleteUserIdMappers(userId);
777 
778         // Announcements
779 
780         announcementsDeliveryLocalService.deleteDeliveries(userId);
781 
782         // Blogs
783 
784         blogsStatsUserLocalService.deleteStatsUserByUserId(userId);
785 
786         // Document library
787 
788         dlFileRankLocalService.deleteFileRanks(userId);
789 
790         // Expando
791 
792         expandoValueLocalService.deleteValues(User.class.getName(), userId);
793 
794         // Message boards
795 
796         mbBanLocalService.deleteBansByBanUserId(userId);
797         mbMessageFlagLocalService.deleteFlags(userId);
798         mbStatsUserLocalService.deleteStatsUserByUserId(userId);
799 
800         // Shopping cart
801 
802         shoppingCartLocalService.deleteUserCarts(userId);
803 
804         // Social
805 
806         socialActivityLocalService.deleteUserActivities(userId);
807         socialRequestLocalService.deleteReceiverUserRequests(userId);
808         socialRequestLocalService.deleteUserRequests(userId);
809 
810         // Mail
811 
812         mailService.deleteUser(userId, user.getCompanyMx());
813 
814         // Contact
815 
816         contactLocalService.deleteContact(user.getContactId());
817 
818         // Resources
819 
820         resourceLocalService.deleteResource(
821             user.getCompanyId(), User.class.getName(),
822             ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
823 
824         // Group roles
825 
826         userGroupRoleLocalService.deleteUserGroupRolesByUserId(userId);
827 
828         // User
829 
830         userPersistence.remove(userId);
831 
832         // Permission cache
833 
834         PermissionCacheUtil.clearCache();
835     }
836 
837     public String encryptUserId(String name)
838         throws PortalException, SystemException {
839 
840         long userId = GetterUtil.getLong(name);
841 
842         User user = userPersistence.findByPrimaryKey(userId);
843 
844         Company company = companyPersistence.findByPrimaryKey(
845             user.getCompanyId());
846 
847         try {
848             return Encryptor.encrypt(company.getKeyObj(), name);
849         }
850         catch (EncryptorException ee) {
851             throw new SystemException(ee);
852         }
853     }
854 
855     public User getDefaultUser(long companyId)
856         throws PortalException, SystemException {
857 
858         User userModel = _defaultUsers.get(companyId);
859 
860         if (userModel == null) {
861             userModel = userPersistence.findByC_DU(companyId, true);
862 
863             _defaultUsers.put(companyId, userModel);
864         }
865 
866         return userModel;
867     }
868 
869     public long getDefaultUserId(long companyId)
870         throws PortalException, SystemException {
871 
872         User user = getDefaultUser(companyId);
873 
874         return user.getUserId();
875     }
876 
877     public List<User> getGroupUsers(long groupId) throws SystemException {
878         return groupPersistence.getUsers(groupId);
879     }
880 
881     public int getGroupUsersCount(long groupId) throws SystemException {
882         return groupPersistence.getUsersSize(groupId);
883     }
884 
885     public int getGroupUsersCount(long groupId, boolean active)
886         throws PortalException, SystemException {
887 
888         Group group = groupPersistence.findByPrimaryKey(groupId);
889 
890         LinkedHashMap<String, Object> params =
891             new LinkedHashMap<String, Object>();
892 
893         params.put("usersGroups", new Long(groupId));
894 
895         return searchCount(group.getCompanyId(), null, active, params);
896     }
897 
898     public List<User> getNoAnnouncementsDeliveries(String type)
899         throws SystemException {
900 
901         return userFinder.findByNoAnnouncementsDeliveries(type);
902     }
903 
904     public List<User> getOrganizationUsers(long organizationId)
905         throws SystemException {
906 
907         return organizationPersistence.getUsers(organizationId);
908     }
909 
910     public int getOrganizationUsersCount(long organizationId)
911         throws SystemException {
912 
913         return organizationPersistence.getUsersSize(organizationId);
914     }
915 
916     public int getOrganizationUsersCount(long organizationId, boolean active)
917         throws PortalException, SystemException {
918 
919         Organization organization = organizationPersistence.findByPrimaryKey(
920             organizationId);
921 
922         LinkedHashMap<String, Object> params =
923             new LinkedHashMap<String, Object>();
924 
925         params.put("usersOrgs", new Long(organizationId));
926 
927         return searchCount(organization.getCompanyId(), null, active, params);
928     }
929 
930     public List<User> getPermissionUsers(
931             long companyId, long groupId, String name, String primKey,
932             String actionId, String firstName, String middleName,
933             String lastName, String emailAddress, boolean andOperator,
934             int start, int end)
935         throws SystemException {
936 
937         int orgGroupPermissionsCount =
938             permissionUserFinder.countByOrgGroupPermissions(
939                 companyId, name, primKey, actionId);
940 
941         if (orgGroupPermissionsCount > 0) {
942             return permissionUserFinder.findByUserAndOrgGroupPermission(
943                 companyId, name, primKey, actionId, firstName, middleName,
944                 lastName, emailAddress, andOperator, start, end);
945         }
946         else {
947             return permissionUserFinder.findByPermissionAndRole(
948                 companyId, groupId, name, primKey, actionId, firstName,
949                 middleName, lastName, emailAddress, andOperator, start, end);
950         }
951     }
952 
953     public int getPermissionUsersCount(
954             long companyId, long groupId, String name, String primKey,
955             String actionId, String firstName, String middleName,
956             String lastName, String emailAddress, boolean andOperator)
957         throws SystemException {
958 
959         int orgGroupPermissionsCount =
960             permissionUserFinder.countByOrgGroupPermissions(
961                 companyId, name, primKey, actionId);
962 
963         if (orgGroupPermissionsCount > 0) {
964             return permissionUserFinder.countByUserAndOrgGroupPermission(
965                 companyId, name, primKey, actionId, firstName, middleName,
966                 lastName, emailAddress, andOperator);
967         }
968         else {
969             return permissionUserFinder.countByPermissionAndRole(
970                 companyId, groupId, name, primKey, actionId, firstName,
971                 middleName, lastName, emailAddress, andOperator);
972         }
973     }
974 
975     public List<User> getRoleUsers(long roleId) throws SystemException {
976         return rolePersistence.getUsers(roleId);
977     }
978 
979     public int getRoleUsersCount(long roleId) throws SystemException {
980         return rolePersistence.getUsersSize(roleId);
981     }
982 
983     public int getRoleUsersCount(long roleId, boolean active)
984         throws PortalException, SystemException {
985 
986         Role role = rolePersistence.findByPrimaryKey(
987             roleId);
988 
989         LinkedHashMap<String, Object> params =
990             new LinkedHashMap<String, Object>();
991 
992         params.put("usersRoles", new Long(roleId));
993 
994         return searchCount(role.getCompanyId(), null, active, params);
995     }
996 
997     public List<User> getSocialUsers(
998             long userId, int start, int end, OrderByComparator obc)
999         throws PortalException, SystemException {
1000
1001        User user = userPersistence.findByPrimaryKey(userId);
1002
1003        LinkedHashMap<String, Object> params =
1004            new LinkedHashMap<String, Object>();
1005
1006        params.put("socialRelation", new Long[] {userId});
1007
1008        return search(
1009            user.getCompanyId(), null, null, params, start, end, obc);
1010    }
1011
1012    public List<User> getSocialUsers(
1013            long userId, int type, int start, int end, OrderByComparator obc)
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("socialRelationType", new Long[] {userId, new Long(type)});
1022
1023        return search(user.getCompanyId(), null, null, params, start, end, obc);
1024    }
1025
1026    public List<User> getSocialUsers(
1027            long userId1, long userId2, int start, int end,
1028            OrderByComparator obc)
1029        throws PortalException, SystemException {
1030
1031        User user1 = userPersistence.findByPrimaryKey(userId1);
1032
1033        LinkedHashMap<String, Object> params =
1034            new LinkedHashMap<String, Object>();
1035
1036        params.put("socialMutualRelation", new Long[] {userId1, userId2});
1037
1038        return search(
1039            user1.getCompanyId(), null, null, params, start, end, obc);
1040    }
1041
1042    public List<User> getSocialUsers(
1043            long userId1, long userId2, int type, int start, int end,
1044            OrderByComparator obc)
1045        throws PortalException, SystemException {
1046
1047        User user1 = userPersistence.findByPrimaryKey(userId1);
1048
1049        LinkedHashMap<String, Object> params =
1050            new LinkedHashMap<String, Object>();
1051
1052        params.put(
1053            "socialMutualRelationType",
1054            new Long[] {userId1, new Long(type), userId2, new Long(type)});
1055
1056        return search(
1057            user1.getCompanyId(), null, null, params, start, end, obc);
1058    }
1059
1060    public int getSocialUsersCount(long userId)
1061        throws PortalException, SystemException {
1062
1063        User user = userPersistence.findByPrimaryKey(userId);
1064
1065        LinkedHashMap<String, Object> params =
1066            new LinkedHashMap<String, Object>();
1067
1068        params.put("socialRelation", new Long[] {userId});
1069
1070        return searchCount(user.getCompanyId(), null, null, params);
1071    }
1072
1073    public int getSocialUsersCount(long userId, int type)
1074        throws PortalException, SystemException {
1075
1076        User user = userPersistence.findByPrimaryKey(userId);
1077
1078        LinkedHashMap<String, Object> params =
1079            new LinkedHashMap<String, Object>();
1080
1081        params.put("socialRelationType", new Long[] {userId, new Long(type)});
1082
1083        return searchCount(user.getCompanyId(), null, null, params);
1084    }
1085
1086    public int getSocialUsersCount(long userId1, long userId2)
1087        throws PortalException, SystemException {
1088
1089        User user1 = userPersistence.findByPrimaryKey(userId1);
1090
1091        LinkedHashMap<String, Object> params =
1092            new LinkedHashMap<String, Object>();
1093
1094        params.put("socialMutualRelation", new Long[] {userId1, userId2});
1095
1096        return searchCount(user1.getCompanyId(), null, null, params);
1097    }
1098
1099    public int getSocialUsersCount(long userId1, long userId2, int type)
1100        throws PortalException, SystemException {
1101
1102        User user1 = userPersistence.findByPrimaryKey(userId1);
1103
1104        LinkedHashMap<String, Object> params =
1105            new LinkedHashMap<String, Object>();
1106
1107        params.put(
1108            "socialMutualRelationType",
1109            new Long[] {userId1, new Long(type), userId2, new Long(type)});
1110
1111        return searchCount(user1.getCompanyId(), null, null, params);
1112    }
1113
1114    public List<User> getUserGroupUsers(long userGroupId)
1115        throws SystemException {
1116
1117        return userGroupPersistence.getUsers(userGroupId);
1118    }
1119
1120    public int getUserGroupUsersCount(long userGroupId) throws SystemException {
1121        return userGroupPersistence.getUsersSize(userGroupId);
1122    }
1123
1124    public int getUserGroupUsersCount(long userGroupId, boolean active)
1125        throws PortalException, SystemException {
1126
1127        UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
1128            userGroupId);
1129
1130        LinkedHashMap<String, Object> params =
1131            new LinkedHashMap<String, Object>();
1132
1133        params.put("usersUserGroups", new Long(userGroupId));
1134
1135        return searchCount(userGroup.getCompanyId(), null, active, params);
1136    }
1137
1138    public User getUserByContactId(long contactId)
1139        throws PortalException, SystemException {
1140
1141        return userPersistence.findByContactId(contactId);
1142    }
1143
1144    public User getUserByEmailAddress(long companyId, String emailAddress)
1145        throws PortalException, SystemException {
1146
1147        emailAddress = emailAddress.trim().toLowerCase();
1148
1149        return userPersistence.findByC_EA(companyId, emailAddress);
1150    }
1151
1152    public User getUserById(long userId)
1153        throws PortalException, SystemException {
1154
1155        return userPersistence.findByPrimaryKey(userId);
1156    }
1157
1158    public User getUserById(long companyId, long userId)
1159        throws PortalException, SystemException {
1160
1161        return userPersistence.findByC_U(companyId, userId);
1162    }
1163
1164    public User getUserByOpenId(String openId)
1165        throws PortalException, SystemException {
1166
1167        return userPersistence.findByOpenId(openId);
1168    }
1169
1170    public User getUserByPortraitId(long portraitId)
1171        throws PortalException, SystemException {
1172
1173        return userPersistence.findByPortraitId(portraitId);
1174    }
1175
1176    public User getUserByScreenName(long companyId, String screenName)
1177        throws PortalException, SystemException {
1178
1179        screenName = getScreenName(screenName);
1180
1181        return userPersistence.findByC_SN(companyId, screenName);
1182    }
1183
1184    public long getUserIdByEmailAddress(long companyId, String emailAddress)
1185        throws PortalException, SystemException {
1186
1187        emailAddress = emailAddress.trim().toLowerCase();
1188
1189        User user = userPersistence.findByC_EA(companyId, emailAddress);
1190
1191        return user.getUserId();
1192    }
1193
1194    public long getUserIdByScreenName(long companyId, String screenName)
1195        throws PortalException, SystemException {
1196
1197        screenName = getScreenName(screenName);
1198
1199        User user = userPersistence.findByC_SN(companyId, screenName);
1200
1201        return user.getUserId();
1202    }
1203
1204    public boolean hasGroupUser(long groupId, long userId)
1205        throws SystemException {
1206
1207        return groupPersistence.containsUser(groupId, userId);
1208    }
1209
1210    public boolean hasOrganizationUser(long organizationId, long userId)
1211        throws SystemException {
1212
1213        return organizationPersistence.containsUser(organizationId, userId);
1214    }
1215
1216    public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
1217        throws SystemException {
1218
1219        return passwordPolicyRelLocalService.hasPasswordPolicyRel(
1220            passwordPolicyId, User.class.getName(), userId);
1221    }
1222
1223    public boolean hasRoleUser(long roleId, long userId)
1224        throws SystemException {
1225
1226        return rolePersistence.containsUser(roleId, userId);
1227    }
1228
1229    public boolean hasUserGroupUser(long userGroupId, long userId)
1230        throws SystemException {
1231
1232        return userGroupPersistence.containsUser(userGroupId, userId);
1233    }
1234
1235    public boolean isPasswordExpired(User user)
1236        throws PortalException, SystemException {
1237
1238        PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1239
1240        if (passwordPolicy.getExpireable()) {
1241            Date now = new Date();
1242
1243            if (user.getPasswordModifiedDate() == null) {
1244                user.setPasswordModifiedDate(now);
1245
1246                userPersistence.update(user, false);
1247            }
1248
1249            long passwordStartTime = user.getPasswordModifiedDate().getTime();
1250            long elapsedTime = now.getTime() - passwordStartTime;
1251
1252            if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
1253                return true;
1254            }
1255            else {
1256                return false;
1257            }
1258        }
1259
1260        return false;
1261    }
1262
1263    public boolean isPasswordExpiringSoon(User user)
1264        throws PortalException, SystemException {
1265
1266        PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1267
1268        if (passwordPolicy.isExpireable()) {
1269            Date now = new Date();
1270
1271            if (user.getPasswordModifiedDate() == null) {
1272                user.setPasswordModifiedDate(now);
1273
1274                userPersistence.update(user, false);
1275            }
1276
1277            long timeModified = user.getPasswordModifiedDate().getTime();
1278            long passwordExpiresOn =
1279                (passwordPolicy.getMaxAge() * 1000) + timeModified;
1280
1281            long timeStartWarning =
1282                passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
1283
1284            if (now.getTime() > timeStartWarning) {
1285                return true;
1286            }
1287            else {
1288                return false;
1289            }
1290        }
1291
1292        return false;
1293    }
1294
1295    public List<User> search(
1296            long companyId, String keywords, Boolean active,
1297            LinkedHashMap<String, Object> params, int start, int end,
1298            OrderByComparator obc)
1299        throws SystemException {
1300
1301        return userFinder.findByKeywords(
1302            companyId, keywords, active, params, start, end, obc);
1303    }
1304
1305    public List<User> search(
1306            long companyId, String firstName, String middleName,
1307            String lastName, String screenName, String emailAddress,
1308            Boolean active, LinkedHashMap<String, Object> params,
1309            boolean andSearch, int start, int end, OrderByComparator obc)
1310        throws SystemException {
1311
1312        return userFinder.findByC_FN_MN_LN_SN_EA_A(
1313            companyId, firstName, middleName, lastName, screenName,
1314            emailAddress, active, params, andSearch, start, end, obc);
1315    }
1316
1317    public int searchCount(
1318            long companyId, String keywords, Boolean active,
1319            LinkedHashMap<String, Object> params)
1320        throws SystemException {
1321
1322        return userFinder.countByKeywords(companyId, keywords, active, params);
1323    }
1324
1325    public int searchCount(
1326            long companyId, String firstName, String middleName,
1327            String lastName, String screenName, String emailAddress,
1328            Boolean active, LinkedHashMap<String, Object> params,
1329            boolean andSearch)
1330        throws SystemException {
1331
1332        return userFinder.countByC_FN_MN_LN_SN_EA_A(
1333            companyId, firstName, middleName, lastName, screenName,
1334            emailAddress, active, params, andSearch);
1335    }
1336
1337    public void sendPassword(
1338            long companyId, String emailAddress, String remoteAddr,
1339            String remoteHost, String userAgent)
1340        throws PortalException, SystemException {
1341
1342        try {
1343            doSendPassword(
1344                companyId, emailAddress, remoteAddr, remoteHost, userAgent);
1345        }
1346        catch (IOException ioe) {
1347            throw new SystemException(ioe);
1348        }
1349    }
1350
1351    public void setRoleUsers(long roleId, long[] userIds)
1352        throws SystemException {
1353
1354        rolePersistence.setUsers(roleId, userIds);
1355
1356        PermissionCacheUtil.clearCache();
1357    }
1358
1359    public void setUserGroupUsers(long userGroupId, long[] userIds)
1360        throws PortalException, SystemException {
1361
1362        copyUserGroupLayouts(userGroupId, userIds);
1363
1364        userGroupPersistence.setUsers(userGroupId, userIds);
1365
1366        PermissionCacheUtil.clearCache();
1367    }
1368
1369    public void unsetGroupUsers(long groupId, long[] userIds)
1370        throws SystemException {
1371
1372        userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
1373
1374        groupPersistence.removeUsers(groupId, userIds);
1375
1376        PermissionCacheUtil.clearCache();
1377    }
1378
1379    public void unsetOrganizationUsers(long organizationId, long[] userIds)
1380        throws PortalException, SystemException {
1381
1382        Organization organization = organizationPersistence.findByPrimaryKey(
1383            organizationId);
1384
1385        Group group = organization.getGroup();
1386
1387        long groupId = group.getGroupId();
1388
1389        userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
1390
1391        organizationPersistence.removeUsers(organizationId, userIds);
1392
1393        PermissionCacheUtil.clearCache();
1394    }
1395
1396    public void unsetPasswordPolicyUsers(
1397            long passwordPolicyId, long[] userIds)
1398        throws SystemException {
1399
1400        passwordPolicyRelLocalService.deletePasswordPolicyRels(
1401            passwordPolicyId, User.class.getName(), userIds);
1402    }
1403
1404    public void unsetRoleUsers(long roleId, long[] userIds)
1405        throws SystemException {
1406
1407        rolePersistence.removeUsers(roleId, userIds);
1408
1409        PermissionCacheUtil.clearCache();
1410    }
1411
1412    public void unsetRoleUsers(long roleId, List<User> users)
1413        throws SystemException {
1414
1415        rolePersistence.removeUsers(roleId, users);
1416
1417        PermissionCacheUtil.clearCache();
1418    }
1419
1420    public void unsetUserGroupUsers(long userGroupId, long[] userIds)
1421        throws SystemException {
1422
1423        userGroupPersistence.removeUsers(userGroupId, userIds);
1424
1425        PermissionCacheUtil.clearCache();
1426    }
1427
1428    public User updateActive(long userId, boolean active)
1429        throws PortalException, SystemException {
1430
1431        User user = userPersistence.findByPrimaryKey(userId);
1432
1433        user.setActive(active);
1434
1435        userPersistence.update(user, false);
1436
1437        return user;
1438    }
1439
1440    public User updateAgreedToTermsOfUse(
1441            long userId, boolean agreedToTermsOfUse)
1442        throws PortalException, SystemException {
1443
1444        User user = userPersistence.findByPrimaryKey(userId);
1445
1446        user.setAgreedToTermsOfUse(agreedToTermsOfUse);
1447
1448        userPersistence.update(user, false);
1449
1450        return user;
1451    }
1452
1453    public User updateCreateDate(long userId, Date createDate)
1454        throws PortalException, SystemException {
1455
1456        User user = userPersistence.findByPrimaryKey(userId);
1457
1458        user.setCreateDate(createDate);
1459
1460        userPersistence.update(user, false);
1461
1462        return user;
1463    }
1464
1465    public User updateLastLogin(long userId, String loginIP)
1466        throws PortalException, SystemException {
1467
1468        User user = userPersistence.findByPrimaryKey(userId);
1469
1470        Date lastLoginDate = user.getLoginDate();
1471
1472        if (lastLoginDate == null) {
1473            lastLoginDate = new Date();
1474        }
1475
1476        user.setLoginDate(new Date());
1477        user.setLoginIP(loginIP);
1478        user.setLastLoginDate(lastLoginDate);
1479        user.setLastLoginIP(user.getLoginIP());
1480        user.setLastFailedLoginDate(null);
1481        user.setFailedLoginAttempts(0);
1482
1483        userPersistence.update(user, false);
1484
1485        return user;
1486    }
1487
1488    public User updateLockout(User user, boolean lockout)
1489        throws PortalException, SystemException {
1490
1491        PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1492
1493        if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
1494            return user;
1495        }
1496
1497        Date lockoutDate = null;
1498
1499        if (lockout) {
1500            lockoutDate = new Date();
1501        }
1502
1503        user.setLockout(lockout);
1504        user.setLockoutDate(lockoutDate);
1505
1506        if (!lockout) {
1507            user.setLastFailedLoginDate(lockoutDate);
1508            user.setFailedLoginAttempts(0);
1509        }
1510
1511        userPersistence.update(user, false);
1512
1513        return user;
1514    }
1515
1516    public User updateLockoutByEmailAddress(
1517            long companyId, String emailAddress, boolean lockout)
1518        throws PortalException, SystemException {
1519
1520        User user = getUserByEmailAddress(companyId, emailAddress);
1521
1522        return updateLockout(user, lockout);
1523    }
1524
1525    public User updateLockoutById(long userId, boolean lockout)
1526        throws PortalException, SystemException {
1527
1528        User user = userPersistence.findByPrimaryKey(userId);
1529
1530        return updateLockout(user, lockout);
1531    }
1532
1533    public User updateLockoutByScreenName(
1534            long companyId, String screenName, boolean lockout)
1535        throws PortalException, SystemException {
1536
1537        User user = getUserByScreenName(companyId, screenName);
1538
1539        return updateLockout(user, lockout);
1540    }
1541
1542    public User updateModifiedDate(long userId, Date modifiedDate)
1543        throws PortalException, SystemException {
1544
1545        User user = userPersistence.findByPrimaryKey(userId);
1546
1547        user.setModifiedDate(modifiedDate);
1548
1549        userPersistence.update(user, false);
1550
1551        return user;
1552    }
1553
1554    public void updateOpenId(long userId, String openId)
1555        throws PortalException, SystemException {
1556
1557        User user = userPersistence.findByPrimaryKey(userId);
1558
1559        user.setOpenId(openId);
1560
1561        userPersistence.update(user, false);
1562    }
1563
1564    public void updateOrganizations(long userId, long[] newOrganizationIds)
1565        throws PortalException, SystemException {
1566
1567        List<Organization> oldOrganizations = userPersistence.getOrganizations(
1568            userId);
1569
1570        List<Long> oldOrganizationIds = new ArrayList<Long>(
1571            oldOrganizations.size());
1572
1573        for (int i = 0; i < oldOrganizations.size(); i++) {
1574            Organization oldOrganization = oldOrganizations.get(i);
1575
1576            long oldOrganizationId = oldOrganization.getOrganizationId();
1577
1578            oldOrganizationIds.add(oldOrganizationId);
1579
1580            if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
1581                unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
1582            }
1583        }
1584
1585        for (int i = 0; i < newOrganizationIds.length; i++) {
1586            long newOrganizationId = newOrganizationIds[i];
1587
1588            if (!oldOrganizationIds.contains(newOrganizationId)) {
1589                addOrganizationUsers(newOrganizationId, new long[] {userId});
1590            }
1591        }
1592
1593        PermissionCacheUtil.clearCache();
1594    }
1595
1596    public User updatePassword(
1597            long userId, String password1, String password2,
1598            boolean passwordReset)
1599        throws PortalException, SystemException {
1600
1601        return updatePassword(
1602            userId, password1, password2, passwordReset, false);
1603    }
1604
1605    public User updatePassword(
1606            long userId, String password1, String password2,
1607            boolean passwordReset, boolean silentUpdate)
1608        throws PortalException, SystemException {
1609
1610        User user = userPersistence.findByPrimaryKey(userId);
1611
1612        // Use silentUpdate so that imported user passwords are not exported
1613        // or validated
1614
1615        if (!silentUpdate) {
1616            validatePassword(user.getCompanyId(), userId, password1, password2);
1617        }
1618
1619        String oldEncPwd = user.getPassword();
1620
1621        if (!user.isPasswordEncrypted()) {
1622            oldEncPwd = PwdEncryptor.encrypt(user.getPassword());
1623        }
1624
1625        String newEncPwd = PwdEncryptor.encrypt(password1);
1626
1627        if (user.hasCompanyMx()) {
1628            mailService.updatePassword(userId, password1);
1629        }
1630
1631        user.setPassword(newEncPwd);
1632        user.setPasswordUnencrypted(password1);
1633        user.setPasswordEncrypted(true);
1634        user.setPasswordReset(passwordReset);
1635        user.setPasswordModifiedDate(new Date());
1636        user.setGraceLoginCount(0);
1637
1638        if (!silentUpdate) {
1639            user.setPasswordModified(true);
1640        }
1641
1642        try {
1643            userPersistence.update(user, false);
1644        }
1645        catch (ModelListenerException mle) {
1646            String msg = GetterUtil.getString(mle.getCause().getMessage());
1647
1648            if (PortalLDAPUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1649                String passwordHistory = PrefsPropsUtil.getString(
1650                    user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
1651
1652                if (msg.indexOf(passwordHistory) != -1) {
1653                    throw new UserPasswordException(
1654                        UserPasswordException.PASSWORD_ALREADY_USED);
1655                }
1656            }
1657
1658            throw new UserPasswordException(
1659                UserPasswordException.PASSWORD_INVALID);
1660        }
1661
1662        if (!silentUpdate) {
1663            user.setPasswordModified(false);
1664        }
1665
1666        passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
1667
1668        return user;
1669    }
1670
1671    public User updatePasswordManually(
1672            long userId, String password, boolean passwordEncrypted,
1673            boolean passwordReset, Date passwordModifiedDate)
1674        throws PortalException, SystemException {
1675
1676        // This method should only be used to manually massage data
1677
1678        User user = userPersistence.findByPrimaryKey(userId);
1679
1680        user.setPassword(password);
1681        user.setPasswordEncrypted(passwordEncrypted);
1682        user.setPasswordReset(passwordReset);
1683        user.setPasswordModifiedDate(passwordModifiedDate);
1684
1685        userPersistence.update(user, false);
1686
1687        return user;
1688    }
1689
1690    public void updatePasswordReset(long userId, boolean passwordReset)
1691        throws PortalException, SystemException {
1692
1693        User user = userPersistence.findByPrimaryKey(userId);
1694
1695        user.setPasswordReset(passwordReset);
1696
1697        userPersistence.update(user, false);
1698    }
1699
1700    public void updatePortrait(long userId, byte[] bytes)
1701        throws PortalException, SystemException {
1702
1703        User user = userPersistence.findByPrimaryKey(userId);
1704
1705        long imageMaxSize = GetterUtil.getLong(
1706            PropsUtil.get(PropsKeys.USERS_IMAGE_MAX_SIZE));
1707
1708        if ((imageMaxSize > 0) &&
1709            ((bytes == null) || (bytes.length > imageMaxSize))) {
1710
1711            throw new UserPortraitException();
1712        }
1713
1714        long portraitId = user.getPortraitId();
1715
1716        if (portraitId <= 0) {
1717            portraitId = counterLocalService.increment();
1718
1719            user.setPortraitId(portraitId);
1720        }
1721
1722        imageLocalService.updateImage(portraitId, bytes);
1723    }
1724
1725    public void updateScreenName(long userId, String screenName)
1726        throws PortalException, SystemException {
1727
1728        // User
1729
1730        User user = userPersistence.findByPrimaryKey(userId);
1731
1732        screenName = getScreenName(screenName);
1733
1734        validateScreenName(user.getCompanyId(), userId, screenName);
1735
1736        user.setScreenName(screenName);
1737
1738        userPersistence.update(user, false);
1739
1740        // Group
1741
1742        Group group = groupLocalService.getUserGroup(
1743            user.getCompanyId(), userId);
1744
1745        group.setFriendlyURL(StringPool.SLASH + screenName);
1746
1747        groupPersistence.update(group, false);
1748    }
1749
1750    public User updateUser(
1751            long userId, String oldPassword, boolean passwordReset,
1752            String screenName, String emailAddress, String languageId,
1753            String timeZoneId, String greeting, String comments,
1754            String firstName, String middleName, String lastName, int prefixId,
1755            int suffixId, boolean male, int birthdayMonth, int birthdayDay,
1756            int birthdayYear, String smsSn, String aimSn, String facebookSn,
1757            String icqSn, String jabberSn, String msnSn, String mySpaceSn,
1758            String skypeSn, String twitterSn, String ymSn, String jobTitle,
1759            long[] organizationIds)
1760        throws PortalException, SystemException {
1761
1762        String newPassword1 = StringPool.BLANK;
1763        String newPassword2 = StringPool.BLANK;
1764
1765        return updateUser(
1766            userId, oldPassword, newPassword1, newPassword2, passwordReset,
1767            screenName, emailAddress, languageId, timeZoneId, greeting,
1768            comments, firstName, middleName, lastName, prefixId, suffixId, male,
1769            birthdayMonth, birthdayDay, birthdayYear, smsSn, aimSn, facebookSn,
1770            icqSn, jabberSn, msnSn, mySpaceSn, skypeSn, twitterSn, ymSn,
1771            jobTitle, organizationIds);
1772    }
1773
1774    public User updateUser(
1775            long userId, String oldPassword, String newPassword1,
1776            String newPassword2, boolean passwordReset, String screenName,
1777            String emailAddress, String languageId, String timeZoneId,
1778            String greeting, String comments, String firstName,
1779            String middleName, String lastName, int prefixId, int suffixId,
1780            boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
1781            String smsSn, String aimSn, String facebookSn, String icqSn,
1782            String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
1783            String twitterSn, String ymSn, String jobTitle,
1784            long[] organizationIds)
1785        throws PortalException, SystemException {
1786
1787        // User
1788
1789        String password = oldPassword;
1790        screenName = getScreenName(screenName);
1791        emailAddress = emailAddress.trim().toLowerCase();
1792        aimSn.trim().toLowerCase();
1793        facebookSn.trim().toLowerCase();
1794        icqSn.trim().toLowerCase();
1795        jabberSn.trim().toLowerCase();
1796        msnSn.trim().toLowerCase();
1797        mySpaceSn.trim().toLowerCase();
1798        skypeSn.trim().toLowerCase();
1799        twitterSn.trim().toLowerCase();
1800        ymSn.trim().toLowerCase();
1801        Date now = new Date();
1802
1803        validate(userId, screenName, emailAddress, firstName, lastName, smsSn);
1804
1805        if (Validator.isNotNull(newPassword1) ||
1806            Validator.isNotNull(newPassword2)) {
1807
1808            updatePassword(userId, newPassword1, newPassword2, passwordReset);
1809
1810            password = newPassword1;
1811        }
1812
1813        User user = userPersistence.findByPrimaryKey(userId);
1814        Company company = companyPersistence.findByPrimaryKey(
1815            user.getCompanyId());
1816
1817        user.setModifiedDate(now);
1818
1819        if (user.getContactId() <= 0) {
1820            user.setContactId(counterLocalService.increment());
1821        }
1822
1823        user.setPasswordReset(passwordReset);
1824        user.setScreenName(screenName);
1825
1826        if (!emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
1827
1828            // test@test.com -> test@liferay.com
1829
1830            if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
1831                mailService.addUser(
1832                    userId, password, firstName, middleName, lastName,
1833                    emailAddress);
1834            }
1835
1836            // test@liferay.com -> bob@liferay.com
1837
1838            else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
1839                mailService.updateEmailAddress(userId, emailAddress);
1840            }
1841
1842            // test@liferay.com -> test@test.com
1843
1844            else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
1845                mailService.deleteEmailAddress(userId);
1846            }
1847
1848            user.setEmailAddress(emailAddress);
1849        }
1850
1851        user.setLanguageId(languageId);
1852        user.setTimeZoneId(timeZoneId);
1853        user.setGreeting(greeting);
1854        user.setComments(comments);
1855
1856        userPersistence.update(user, false);
1857
1858        // Contact
1859
1860        Date birthday = PortalUtil.getDate(
1861            birthdayMonth, birthdayDay, birthdayYear,
1862            new ContactBirthdayException());
1863
1864        long contactId = user.getContactId();
1865
1866        Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
1867
1868        if (contact == null) {
1869            contact = contactPersistence.create(contactId);
1870
1871            contact.setCompanyId(user.getCompanyId());
1872            contact.setUserName(StringPool.BLANK);
1873            contact.setCreateDate(now);
1874            contact.setAccountId(company.getAccountId());
1875            contact.setParentContactId(
1876                ContactConstants.DEFAULT_PARENT_CONTACT_ID);
1877        }
1878
1879        contact.setModifiedDate(now);
1880        contact.setFirstName(firstName);
1881        contact.setMiddleName(middleName);
1882        contact.setLastName(lastName);
1883        contact.setPrefixId(prefixId);
1884        contact.setSuffixId(suffixId);
1885        contact.setMale(male);
1886        contact.setBirthday(birthday);
1887        contact.setSmsSn(smsSn);
1888        contact.setAimSn(aimSn);
1889        contact.setFacebookSn(facebookSn);
1890        contact.setIcqSn(icqSn);
1891        contact.setJabberSn(jabberSn);
1892        contact.setMsnSn(msnSn);
1893        contact.setMySpaceSn(mySpaceSn);
1894        contact.setSkypeSn(skypeSn);
1895        contact.setTwitterSn(twitterSn);
1896        contact.setYmSn(ymSn);
1897        contact.setJobTitle(jobTitle);
1898
1899        contactPersistence.update(contact, false);
1900
1901        // Organizations
1902
1903        updateOrganizations(userId, organizationIds);
1904
1905        // Group
1906
1907        Group group = groupLocalService.getUserGroup(
1908            user.getCompanyId(), userId);
1909
1910        group.setFriendlyURL(StringPool.SLASH + screenName);
1911
1912        groupPersistence.update(group, false);
1913
1914        // Announcements
1915
1916        announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
1917
1918        // Permission cache
1919
1920        PermissionCacheUtil.clearCache();
1921
1922        return user;
1923    }
1924
1925    protected int authenticate(
1926            long companyId, String login, String password, String authType,
1927            Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
1928        throws PortalException, SystemException {
1929
1930        login = login.trim().toLowerCase();
1931
1932        long userId = GetterUtil.getLong(login);
1933
1934        // User input validation
1935
1936        if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1937            if (!Validator.isEmailAddress(login)) {
1938                throw new UserEmailAddressException();
1939            }
1940        }
1941        else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1942            if (Validator.isNull(login)) {
1943                throw new UserScreenNameException();
1944            }
1945        }
1946        else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1947            if (Validator.isNull(login)) {
1948                throw new UserIdException();
1949            }
1950        }
1951
1952        if (Validator.isNull(password)) {
1953            throw new UserPasswordException(
1954                UserPasswordException.PASSWORD_INVALID);
1955        }
1956
1957        int authResult = Authenticator.FAILURE;
1958
1959        // Pre-authentication pipeline
1960
1961        String[] authPipelinePre =
1962            PropsUtil.getArray(PropsKeys.AUTH_PIPELINE_PRE);
1963
1964        if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1965            authResult = AuthPipeline.authenticateByEmailAddress(
1966                authPipelinePre, companyId, login, password, headerMap,
1967                parameterMap);
1968        }
1969        else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1970            authResult = AuthPipeline.authenticateByScreenName(
1971                authPipelinePre, companyId, login, password, headerMap,
1972                parameterMap);
1973        }
1974        else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1975            authResult = AuthPipeline.authenticateByUserId(
1976                authPipelinePre, companyId, userId, password, headerMap,
1977                parameterMap);
1978        }
1979
1980        // Get user
1981
1982        User user = null;
1983
1984        try {
1985            if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1986                user = userPersistence.findByC_EA(companyId, login);
1987            }
1988            else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1989                user = userPersistence.findByC_SN(companyId, login);
1990            }
1991            else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1992                user = userPersistence.findByC_U(
1993                    companyId, GetterUtil.getLong(login));
1994            }
1995        }
1996        catch (NoSuchUserException nsue) {
1997            return Authenticator.DNE;
1998        }
1999
2000        if (user.isDefaultUser()) {
2001            _log.error(
2002                "The default user should never be allowed to authenticate");
2003
2004            return Authenticator.DNE;
2005        }
2006
2007        if (!user.isPasswordEncrypted()) {
2008            user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
2009            user.setPasswordEncrypted(true);
2010
2011            userPersistence.update(user, false);
2012        }
2013
2014        // Check password policy to see if the is account locked out or if the
2015        // password is expired
2016
2017        checkLockout(user);
2018
2019        checkPasswordExpired(user);
2020
2021        // Authenticate against the User_ table
2022
2023        if (authResult == Authenticator.SUCCESS) {
2024            if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
2025                String encPassword = PwdEncryptor.encrypt(
2026                    password, user.getPassword());
2027
2028                if (user.getPassword().equals(encPassword)) {
2029                    authResult = Authenticator.SUCCESS;
2030                }
2031                else if (GetterUtil.getBoolean(PropsUtil.get(
2032                            PropsKeys.AUTH_MAC_ALLOW))) {
2033
2034                    try {
2035                        MessageDigest digester = MessageDigest.getInstance(
2036                            PropsUtil.get(PropsKeys.AUTH_MAC_ALGORITHM));
2037
2038                        digester.update(login.getBytes("UTF8"));
2039
2040                        String shardKey =
2041                            PropsUtil.get(PropsKeys.AUTH_MAC_SHARED_KEY);
2042
2043                        encPassword = Base64.encode(
2044                            digester.digest(shardKey.getBytes("UTF8")));
2045
2046                        if (password.equals(encPassword)) {
2047                            authResult = Authenticator.SUCCESS;
2048                        }
2049                        else {
2050                            authResult = Authenticator.FAILURE;
2051                        }
2052                    }
2053                    catch (NoSuchAlgorithmException nsae) {
2054                        throw new SystemException(nsae);
2055                    }
2056                    catch (UnsupportedEncodingException uee) {
2057                        throw new SystemException(uee);
2058                    }
2059                }
2060                else {
2061                    authResult = Authenticator.FAILURE;
2062                }
2063            }
2064        }
2065
2066        // Post-authentication pipeline
2067
2068        if (authResult == Authenticator.SUCCESS) {
2069            String[] authPipelinePost =
2070                PropsUtil.getArray(PropsKeys.AUTH_PIPELINE_POST);
2071
2072            if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2073                authResult = AuthPipeline.authenticateByEmailAddress(
2074                    authPipelinePost, companyId, login, password, headerMap,
2075                    parameterMap);
2076            }
2077            else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2078                authResult = AuthPipeline.authenticateByScreenName(
2079                    authPipelinePost, companyId, login, password, headerMap,
2080                    parameterMap);
2081            }
2082            else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2083                authResult = AuthPipeline.authenticateByUserId(
2084                    authPipelinePost, companyId, userId, password, headerMap,
2085                    parameterMap);
2086            }
2087        }
2088
2089        // Execute code triggered by authentication failure
2090
2091        if (authResult == Authenticator.FAILURE) {
2092            try {
2093                String[] authFailure =
2094                    PropsUtil.getArray(PropsKeys.AUTH_FAILURE);
2095
2096                if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2097                    AuthPipeline.onFailureByEmailAddress(
2098                        authFailure, companyId, login, headerMap, parameterMap);
2099                }
2100                else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2101                    AuthPipeline.onFailureByScreenName(
2102                        authFailure, companyId, login, headerMap, parameterMap);
2103                }
2104                else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2105                    AuthPipeline.onFailureByUserId(
2106                        authFailure, companyId, userId, headerMap,
2107                        parameterMap);
2108                }
2109
2110                // Let LDAP handle max failure event
2111
2112                if (!PortalLDAPUtil.isPasswordPolicyEnabled(
2113                        user.getCompanyId())) {
2114
2115                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2116
2117                    int failedLoginAttempts = user.getFailedLoginAttempts();
2118                    int maxFailures = passwordPolicy.getMaxFailure();
2119
2120                    if ((failedLoginAttempts >= maxFailures) &&
2121                        (maxFailures != 0)) {
2122
2123                        String[] authMaxFailures =
2124                            PropsUtil.getArray(PropsKeys.AUTH_MAX_FAILURES);
2125
2126                        if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2127                            AuthPipeline.onMaxFailuresByEmailAddress(
2128                                authMaxFailures, companyId, login, headerMap,
2129                                parameterMap);
2130                        }
2131                        else if (authType.equals(
2132                                    CompanyConstants.AUTH_TYPE_SN)) {
2133
2134                            AuthPipeline.onMaxFailuresByScreenName(
2135                                authMaxFailures, companyId, login, headerMap,
2136                                parameterMap);
2137                        }
2138                        else if (authType.equals(
2139                                    CompanyConstants.AUTH_TYPE_ID)) {
2140
2141                            AuthPipeline.onMaxFailuresByUserId(
2142                                authMaxFailures, companyId, userId, headerMap,
2143                                parameterMap);
2144                        }
2145                    }
2146                }
2147            }
2148            catch (Exception e) {
2149                _log.error(e, e);
2150            }
2151        }
2152
2153        return authResult;
2154    }
2155
2156    protected void copyUserGroupLayouts(long userGroupId, long userId)
2157        throws PortalException, SystemException {
2158
2159        UserGroup userGroup = userGroupLocalService.getUserGroup(userGroupId);
2160        User user = getUserById(userId);
2161
2162        Map<String, String[]> parameterMap = getLayoutTemplatesParameters();
2163
2164        if (userGroup.hasPrivateLayouts()) {
2165            long sourceGroupId = userGroup.getGroup().getGroupId();
2166            long targetGroupId = user.getGroup().getGroupId();
2167
2168            byte[] bytes = layoutLocalService.exportLayouts(
2169                sourceGroupId, true, parameterMap, null, null);
2170
2171            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
2172
2173            layoutLocalService.importLayouts(
2174                userId, targetGroupId, true, parameterMap, bais);
2175        }
2176
2177        if (userGroup.hasPublicLayouts()) {
2178            long sourceGroupId = userGroup.getGroup().getGroupId();
2179            long targetGroupId = user.getGroup().getGroupId();
2180
2181            byte[] bytes = layoutLocalService.exportLayouts(
2182                sourceGroupId, false, parameterMap, null, null);
2183
2184            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
2185
2186            layoutLocalService.importLayouts(
2187                userId, targetGroupId, false, parameterMap, bais);
2188        }
2189    }
2190
2191    protected void copyUserGroupLayouts(long userGroupId, long userIds[])
2192        throws PortalException, SystemException {
2193
2194        for (long userId : userIds) {
2195            if (!userGroupPersistence.containsUser(userGroupId, userId)) {
2196                copyUserGroupLayouts(userGroupId, userId);
2197            }
2198        }
2199    }
2200
2201    protected void doSendPassword(
2202            long companyId, String emailAddress, String remoteAddr,
2203            String remoteHost, String userAgent)
2204        throws IOException, PortalException, SystemException {
2205
2206        if (!PrefsPropsUtil.getBoolean(
2207                companyId, PropsKeys.COMPANY_SECURITY_SEND_PASSWORD) ||
2208            !PrefsPropsUtil.getBoolean(
2209                companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_ENABLED)) {
2210
2211            return;
2212        }
2213
2214        emailAddress = emailAddress.trim().toLowerCase();
2215
2216        if (!Validator.isEmailAddress(emailAddress)) {
2217            throw new UserEmailAddressException();
2218        }
2219
2220        Company company = companyPersistence.findByPrimaryKey(companyId);
2221
2222        User user = userPersistence.findByC_EA(companyId, emailAddress);
2223
2224        PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2225
2226        /*if (user.hasCompanyMx()) {
2227            throw new SendPasswordException();
2228        }*/
2229
2230        String newPassword = null;
2231
2232        if (!PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
2233                PwdEncryptor.TYPE_NONE)) {
2234
2235            newPassword = PwdToolkitUtil.generate();
2236
2237            boolean passwordReset = false;
2238
2239            if (passwordPolicy.getChangeable() &&
2240                passwordPolicy.getChangeRequired()) {
2241
2242                passwordReset = true;
2243            }
2244
2245            user.setPassword(PwdEncryptor.encrypt(newPassword));
2246            user.setPasswordUnencrypted(newPassword);
2247            user.setPasswordEncrypted(true);
2248            user.setPasswordReset(passwordReset);
2249
2250            userPersistence.update(user, false);
2251        }
2252        else {
2253            newPassword = user.getPassword();
2254        }
2255
2256        String fromName = PrefsPropsUtil.getString(
2257            companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
2258        String fromAddress = PrefsPropsUtil.getString(
2259            companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
2260
2261        String toName = user.getFullName();
2262        String toAddress = user.getEmailAddress();
2263
2264        String subject = PrefsPropsUtil.getContent(
2265            companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
2266        String body = PrefsPropsUtil.getContent(
2267            companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
2268
2269        subject = StringUtil.replace(
2270            subject,
2271            new String[] {
2272                "[$FROM_ADDRESS$]",
2273                "[$FROM_NAME$]",
2274                "[$PORTAL_URL$]",
2275                "[$REMOTE_ADDRESS$]",
2276                "[$REMOTE_HOST$]",
2277                "[$TO_ADDRESS$]",
2278                "[$TO_NAME$]",
2279                "[$USER_AGENT$]",
2280                "[$USER_ID$]",
2281                "[$USER_PASSWORD$]",
2282                "[$USER_SCREENNAME$]"
2283            },
2284            new String[] {
2285                fromAddress,
2286                fromName,
2287                company.getVirtualHost(),
2288                remoteAddr,
2289                remoteHost,
2290                toAddress,
2291                toName,
2292                HtmlUtil.escape(userAgent),
2293                String.valueOf(user.getUserId()),
2294                newPassword,
2295                user.getScreenName()
2296            });
2297
2298        body = StringUtil.replace(
2299            body,
2300            new String[] {
2301                "[$FROM_ADDRESS$]",
2302                "[$FROM_NAME$]",
2303                "[$PORTAL_URL$]",
2304                "[$REMOTE_ADDRESS$]",
2305                "[$REMOTE_HOST$]",
2306                "[$TO_ADDRESS$]",
2307                "[$TO_NAME$]",
2308                "[$USER_AGENT$]",
2309                "[$USER_ID$]",
2310                "[$USER_PASSWORD$]",
2311                "[$USER_SCREENNAME$]"
2312            },
2313            new String[] {
2314                fromAddress,
2315                fromName,
2316                company.getVirtualHost(),
2317                remoteAddr,
2318                remoteHost,
2319                toAddress,
2320                toName,
2321                HtmlUtil.escape(userAgent),
2322                String.valueOf(user.getUserId()),
2323                newPassword,
2324                user.getScreenName()
2325            });
2326
2327        InternetAddress from = new InternetAddress(fromAddress, fromName);
2328
2329        InternetAddress to = new InternetAddress(toAddress, toName);
2330
2331        MailMessage message = new MailMessage(from, to, subject, body, true);
2332
2333        mailService.sendEmail(message);
2334    }
2335
2336    protected Map<String, String[]> getLayoutTemplatesParameters() {
2337        Map<String, String[]> parameterMap =
2338            new LinkedHashMap<String, String[]>();
2339
2340        parameterMap.put(
2341            PortletDataHandlerKeys.DATA_STRATEGY,
2342            new String[] {PortletDataHandlerKeys.DATA_STRATEGY_MIRROR});
2343        parameterMap.put(
2344            PortletDataHandlerKeys.DELETE_MISSING_LAYOUTS,
2345            new String[] {Boolean.FALSE.toString()});
2346        parameterMap.put(
2347            PortletDataHandlerKeys.DELETE_PORTLET_DATA,
2348            new String[] {Boolean.FALSE.toString()});
2349        parameterMap.put(
2350            PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE,
2351            new String[] {PortletDataHandlerKeys.
2352                LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_NAME});
2353        parameterMap.put(
2354            PortletDataHandlerKeys.PERMISSIONS,
2355            new String[] {Boolean.TRUE.toString()});
2356        parameterMap.put(
2357            PortletDataHandlerKeys.PORTLET_DATA,
2358            new String[] {Boolean.TRUE.toString()});
2359        parameterMap.put(
2360            PortletDataHandlerKeys.PORTLET_DATA_ALL,
2361            new String[] {Boolean.TRUE.toString()});
2362        parameterMap.put(
2363            PortletDataHandlerKeys.PORTLET_SETUP,
2364            new String[] {Boolean.TRUE.toString()});
2365        parameterMap.put(
2366            PortletDataHandlerKeys.PORTLET_USER_PREFERENCES,
2367            new String[] {Boolean.TRUE.toString()});
2368        parameterMap.put(
2369            PortletDataHandlerKeys.PORTLETS_MERGE_MODE,
2370            new String[] {PortletDataHandlerKeys.
2371                PORTLETS_MERGE_MODE_ADD_TO_BOTTOM});
2372        parameterMap.put(
2373            PortletDataHandlerKeys.THEME,
2374            new String[] {Boolean.FALSE.toString()});
2375        parameterMap.put(
2376            PortletDataHandlerKeys.USER_ID_STRATEGY,
2377            new String[] {UserIdStrategy.CURRENT_USER_ID});
2378        parameterMap.put(
2379            PortletDataHandlerKeys.USER_PERMISSIONS,
2380            new String[] {Boolean.FALSE.toString()});
2381
2382        return parameterMap;
2383    }
2384
2385    protected String getScreenName(String screenName) {
2386        return Normalizer.normalizeToAscii(screenName.trim().toLowerCase());
2387    }
2388
2389    protected void sendEmail(User user, String password)
2390        throws IOException, PortalException, SystemException {
2391
2392        if (!PrefsPropsUtil.getBoolean(
2393                user.getCompanyId(),
2394                PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
2395
2396            return;
2397        }
2398
2399        long companyId = user.getCompanyId();
2400
2401        Company company = companyPersistence.findByPrimaryKey(companyId);
2402
2403        String fromName = PrefsPropsUtil.getString(
2404            companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
2405        String fromAddress = PrefsPropsUtil.getString(
2406            companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
2407
2408        String toName = user.getFullName();
2409        String toAddress = user.getEmailAddress();
2410
2411        String subject = PrefsPropsUtil.getContent(
2412            companyId, PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
2413        String body = PrefsPropsUtil.getContent(
2414            companyId, PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
2415
2416        subject = StringUtil.replace(
2417            subject,
2418            new String[] {
2419                "[$FROM_ADDRESS$]",
2420                "[$FROM_NAME$]",
2421                "[$PORTAL_URL$]",
2422                "[$TO_ADDRESS$]",
2423                "[$TO_NAME$]",
2424                "[$USER_ID$]",
2425                "[$USER_PASSWORD$]",
2426                "[$USER_SCREENNAME$]"
2427            },
2428            new String[] {
2429                fromAddress,
2430                fromName,
2431                company.getVirtualHost(),
2432                toAddress,
2433                toName,
2434                String.valueOf(user.getUserId()),
2435                password,
2436                user.getScreenName()
2437            });
2438
2439        body = StringUtil.replace(
2440            body,
2441            new String[] {
2442                "[$FROM_ADDRESS$]",
2443                "[$FROM_NAME$]",
2444                "[$PORTAL_URL$]",
2445                "[$TO_ADDRESS$]",
2446                "[$TO_NAME$]",
2447                "[$USER_ID$]",
2448                "[$USER_PASSWORD$]",
2449                "[$USER_SCREENNAME$]"
2450            },
2451            new String[] {
2452                fromAddress,
2453                fromName,
2454                company.getVirtualHost(),
2455                toAddress,
2456                toName,
2457                String.valueOf(user.getUserId()),
2458                password,
2459                user.getScreenName()
2460            });
2461
2462        InternetAddress from = new InternetAddress(fromAddress, fromName);
2463
2464        InternetAddress to = new InternetAddress(toAddress, toName);
2465
2466        MailMessage message = new MailMessage(from, to, subject, body, true);
2467
2468        mailService.sendEmail(message);
2469    }
2470
2471    protected void validate(
2472            long userId, String screenName, String emailAddress,
2473            String firstName, String lastName, String smsSn)
2474        throws PortalException, SystemException {
2475
2476        User user = userPersistence.findByPrimaryKey(userId);
2477
2478        if (!user.getScreenName().equalsIgnoreCase(screenName)) {
2479            validateScreenName(user.getCompanyId(), userId, screenName);
2480        }
2481
2482        validateEmailAddress(emailAddress);
2483
2484        if (!user.isDefaultUser()) {
2485            if (!user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
2486                if (userPersistence.fetchByC_EA(
2487                        user.getCompanyId(), emailAddress) != null) {
2488
2489                    throw new DuplicateUserEmailAddressException();
2490                }
2491            }
2492
2493            String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
2494                user.getCompanyId(), PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
2495                StringPool.NEW_LINE,
2496                PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
2497
2498            for (int i = 0; i < reservedEmailAddresses.length; i++) {
2499                if (emailAddress.equalsIgnoreCase(reservedEmailAddresses[i])) {
2500                    throw new ReservedUserEmailAddressException();
2501                }
2502            }
2503
2504            if (Validator.isNull(firstName)) {
2505                throw new ContactFirstNameException();
2506            }
2507            else if (Validator.isNull(lastName)) {
2508                throw new ContactLastNameException();
2509            }
2510        }
2511
2512        if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
2513            throw new UserSmsException();
2514        }
2515    }
2516
2517    protected void validate(
2518            long companyId, long userId, boolean autoPassword, String password1,
2519            String password2, boolean autoScreenName, String screenName,
2520            String emailAddress, String firstName, String lastName,
2521            long[] organizationIds)
2522        throws PortalException, SystemException {
2523
2524        if (!autoScreenName) {
2525            validateScreenName(companyId, userId, screenName);
2526        }
2527
2528        if (!autoPassword) {
2529            PasswordPolicy passwordPolicy =
2530                passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
2531
2532            PwdToolkitUtil.validate(
2533                companyId, 0, password1, password2, passwordPolicy);
2534        }
2535
2536        validateEmailAddress(emailAddress);
2537
2538        User user = userPersistence.fetchByC_EA(companyId, emailAddress);
2539
2540        if (user != null) {
2541            throw new DuplicateUserEmailAddressException();
2542        }
2543
2544        String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
2545            companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
2546            StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
2547
2548        for (int i = 0; i < reservedEmailAddresses.length; i++) {
2549            if (emailAddress.equalsIgnoreCase(reservedEmailAddresses[i])) {
2550                throw new ReservedUserEmailAddressException();
2551            }
2552        }
2553
2554        if (Validator.isNull(firstName)) {
2555            throw new ContactFirstNameException();
2556        }
2557        else if (Validator.isNull(lastName)) {
2558            throw new ContactLastNameException();
2559        }
2560    }
2561
2562    protected void validateEmailAddress(String emailAddress)
2563        throws PortalException {
2564
2565        if (!Validator.isEmailAddress(emailAddress) ||
2566            emailAddress.startsWith("root@") ||
2567            emailAddress.startsWith("postmaster@")) {
2568
2569            throw new UserEmailAddressException();
2570        }
2571    }
2572
2573    protected void validatePassword(
2574            long companyId, long userId, String password1, String password2)
2575        throws PortalException, SystemException {
2576
2577        if (Validator.isNull(password1) || Validator.isNull(password2)) {
2578            throw new UserPasswordException(
2579                UserPasswordException.PASSWORD_INVALID);
2580        }
2581
2582        if (!password1.equals(password2)) {
2583            throw new UserPasswordException(
2584                UserPasswordException.PASSWORDS_DO_NOT_MATCH);
2585        }
2586
2587        PasswordPolicy passwordPolicy =
2588            passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
2589
2590        PwdToolkitUtil.validate(
2591            companyId, userId, password1, password2, passwordPolicy);
2592    }
2593
2594    protected void validateScreenName(
2595            long companyId, long userId, String screenName)
2596        throws PortalException, SystemException {
2597
2598        if (Validator.isNull(screenName)) {
2599            throw new UserScreenNameException();
2600        }
2601
2602        ScreenNameValidator screenNameValidator =
2603            (ScreenNameValidator)InstancePool.get(
2604                PropsValues.USERS_SCREEN_NAME_VALIDATOR);
2605
2606        if (screenNameValidator != null) {
2607            if (!screenNameValidator.validate(companyId, screenName)) {
2608                throw new UserScreenNameException();
2609            }
2610        }
2611
2612        if (Validator.isNumber(screenName) &&
2613            !screenName.equals(String.valueOf(userId))) {
2614
2615            throw new UserScreenNameException();
2616        }
2617
2618        for (char c : screenName.toCharArray()) {
2619            if ((!Validator.isChar(c)) && (!Validator.isDigit(c)) &&
2620                (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
2621                (c != CharPool.UNDERLINE)) {
2622
2623                throw new UserScreenNameException();
2624            }
2625        }
2626
2627        String[] anonymousNames = PrincipalBean.ANONYMOUS_NAMES;
2628
2629        for (int i = 0; i < anonymousNames.length; i++) {
2630            if (screenName.equalsIgnoreCase(anonymousNames[i])) {
2631                throw new UserScreenNameException();
2632            }
2633        }
2634
2635        User user = userPersistence.fetchByC_SN(companyId, screenName);
2636
2637        if (user != null) {
2638            throw new DuplicateUserScreenNameException();
2639        }
2640
2641        String friendlyURL = StringPool.SLASH + screenName;
2642
2643        Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
2644
2645        if (group != null) {
2646            throw new DuplicateUserScreenNameException();
2647        }
2648
2649        int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
2650
2651        if (exceptionType != -1) {
2652            throw new UserScreenNameException(
2653                new GroupFriendlyURLException(exceptionType));
2654        }
2655
2656        String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
2657            companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
2658            StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
2659
2660        for (int i = 0; i < reservedScreenNames.length; i++) {
2661            if (screenName.equalsIgnoreCase(reservedScreenNames[i])) {
2662                throw new ReservedUserScreenNameException();
2663            }
2664        }
2665    }
2666
2667    private static Log _log = LogFactory.getLog(UserLocalServiceImpl.class);
2668
2669    private static Map<Long, User> _defaultUsers =
2670        new ConcurrentHashMap<Long, User>();
2671
2672}