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