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