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