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 type, 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        if (SocialRelationConstants.isTypeUni(type)) {
1003            params.put(
1004                "socialRelationUnidirectional",
1005                new Long[] {userId, new Long(type)});
1006        }
1007        else {
1008            params.put(
1009                "socialRelationBidirectional",
1010                new Long[] {userId, userId, userId, new Long(type)});
1011        }
1012
1013        return search(
1014            user.getCompanyId(), null, null, params, begin, end, null);
1015    }
1016
1017    public int getSocialUsersCount(long userId, int type)
1018        throws PortalException, SystemException {
1019
1020        User user = userPersistence.findByPrimaryKey(userId);
1021
1022        LinkedHashMap<String, Object> params =
1023            new LinkedHashMap<String, Object>();
1024
1025        if (SocialRelationConstants.isTypeUni(type)) {
1026            params.put(
1027                "socialRelationUnidirectional",
1028                new Long[] {userId, new Long(type)});
1029        }
1030        else {
1031            params.put(
1032                "socialRelationBidirectional",
1033                new Long[] {userId, userId, userId, new Long(type)});
1034        }
1035
1036        return searchCount(user.getCompanyId(), null, null, params);
1037    }
1038
1039    public List<User> getUserGroupUsers(long userGroupId)
1040        throws PortalException, SystemException {
1041
1042        return userGroupPersistence.getUsers(userGroupId);
1043    }
1044
1045    public int getUserGroupUsersCount(long userGroupId) throws SystemException {
1046        return userGroupPersistence.getUsersSize(userGroupId);
1047    }
1048
1049    public int getUserGroupUsersCount(long userGroupId, boolean active)
1050        throws PortalException, SystemException {
1051
1052        UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
1053            userGroupId);
1054
1055        LinkedHashMap<String, Object> params =
1056            new LinkedHashMap<String, Object>();
1057
1058        params.put("usersUserGroups", new Long(userGroupId));
1059
1060        return searchCount(userGroup.getCompanyId(), null, active, params);
1061    }
1062
1063    public User getUserByContactId(long contactId)
1064        throws PortalException, SystemException {
1065
1066        return userPersistence.findByContactId(contactId);
1067    }
1068
1069    public User getUserByEmailAddress(long companyId, String emailAddress)
1070        throws PortalException, SystemException {
1071
1072        emailAddress = emailAddress.trim().toLowerCase();
1073
1074        return userPersistence.findByC_EA(companyId, emailAddress);
1075    }
1076
1077    public User getUserById(long userId)
1078        throws PortalException, SystemException {
1079
1080        return userPersistence.findByPrimaryKey(userId);
1081    }
1082
1083    public User getUserById(long companyId, long userId)
1084        throws PortalException, SystemException {
1085
1086        return userPersistence.findByC_U(companyId, userId);
1087    }
1088
1089    public User getUserByPortraitId(long portraitId)
1090        throws PortalException, SystemException {
1091
1092        return userPersistence.findByPortraitId(portraitId);
1093    }
1094
1095    public User getUserByScreenName(long companyId, String screenName)
1096        throws PortalException, SystemException {
1097
1098        screenName = getScreenName(screenName);
1099
1100        return userPersistence.findByC_SN(companyId, screenName);
1101    }
1102
1103    public long getUserIdByEmailAddress(long companyId, String emailAddress)
1104        throws PortalException, SystemException {
1105
1106        emailAddress = emailAddress.trim().toLowerCase();
1107
1108        User user = userPersistence.findByC_EA(companyId, emailAddress);
1109
1110        return user.getUserId();
1111    }
1112
1113    public long getUserIdByScreenName(long companyId, String screenName)
1114        throws PortalException, SystemException {
1115
1116        screenName = getScreenName(screenName);
1117
1118        User user = userPersistence.findByC_SN(companyId, screenName);
1119
1120        return user.getUserId();
1121    }
1122
1123    public boolean hasGroupUser(long groupId, long userId)
1124        throws PortalException, SystemException {
1125
1126        return groupPersistence.containsUser(groupId, userId);
1127    }
1128
1129    public boolean hasOrganizationUser(long organizationId, long userId)
1130        throws PortalException, SystemException {
1131
1132        return organizationPersistence.containsUser(organizationId, userId);
1133    }
1134
1135    public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
1136        throws PortalException, SystemException {
1137
1138        return passwordPolicyRelLocalService.hasPasswordPolicyRel(
1139            passwordPolicyId, User.class.getName(), userId);
1140    }
1141
1142    public boolean hasRoleUser(long roleId, long userId)
1143        throws PortalException, SystemException {
1144
1145        return rolePersistence.containsUser(roleId, userId);
1146    }
1147
1148    public boolean hasUserGroupUser(long userGroupId, long userId)
1149        throws PortalException, SystemException {
1150
1151        return userGroupPersistence.containsUser(userGroupId, userId);
1152    }
1153
1154    public boolean isPasswordExpired(User user)
1155        throws PortalException, SystemException {
1156
1157        PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1158
1159        if (passwordPolicy.getExpireable()) {
1160            Date now = new Date();
1161
1162            if (user.getPasswordModifiedDate() == null) {
1163                user.setPasswordModifiedDate(now);
1164
1165                userPersistence.update(user, false);
1166            }
1167
1168            long passwordStartTime = user.getPasswordModifiedDate().getTime();
1169            long elapsedTime = now.getTime() - passwordStartTime;
1170
1171            if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
1172                return true;
1173            }
1174            else {
1175                return false;
1176            }
1177        }
1178
1179        return false;
1180    }
1181
1182    public boolean isPasswordExpiringSoon(User user)
1183        throws PortalException, SystemException {
1184
1185        PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1186
1187        if (passwordPolicy.isExpireable()) {
1188            Date now = new Date();
1189
1190            if (user.getPasswordModifiedDate() == null) {
1191                user.setPasswordModifiedDate(now);
1192
1193                userPersistence.update(user, false);
1194            }
1195
1196            long timeModified = user.getPasswordModifiedDate().getTime();
1197            long passwordExpiresOn =
1198                (passwordPolicy.getMaxAge() * 1000) + timeModified;
1199
1200            long timeStartWarning =
1201                passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
1202
1203            if (now.getTime() > timeStartWarning) {
1204                return true;
1205            }
1206            else {
1207                return false;
1208            }
1209        }
1210
1211        return false;
1212    }
1213
1214    public List<User> search(
1215            long companyId, String keywords, Boolean active,
1216            LinkedHashMap<String, Object> params, int begin, int end,
1217            OrderByComparator obc)
1218        throws SystemException {
1219
1220        return userFinder.findByKeywords(
1221            companyId, keywords, active, params, begin, end, obc);
1222    }
1223
1224    public List<User> search(
1225            long companyId, String firstName, String middleName,
1226            String lastName, String screenName, String emailAddress,
1227            Boolean active, LinkedHashMap<String, Object> params,
1228            boolean andSearch, int begin, int end, OrderByComparator obc)
1229        throws SystemException {
1230
1231        return userFinder.findByC_FN_MN_LN_SN_EA_A(
1232            companyId, firstName, middleName, lastName, screenName,
1233            emailAddress, active, params, andSearch, begin, end, obc);
1234    }
1235
1236    public int searchCount(
1237            long companyId, String keywords, Boolean active,
1238            LinkedHashMap<String, Object> params)
1239        throws SystemException {
1240
1241        return userFinder.countByKeywords(companyId, keywords, active, params);
1242    }
1243
1244    public int searchCount(
1245            long companyId, String firstName, String middleName,
1246            String lastName, String screenName, String emailAddress,
1247            Boolean active, LinkedHashMap<String, Object> params,
1248            boolean andSearch)
1249        throws SystemException {
1250
1251        return userFinder.countByC_FN_MN_LN_SN_EA_A(
1252            companyId, firstName, middleName, lastName, screenName,
1253            emailAddress, active, params, andSearch);
1254    }
1255
1256    public void sendPassword(
1257            long companyId, String emailAddress, String remoteAddr,
1258            String remoteHost, String userAgent)
1259        throws PortalException, SystemException {
1260
1261        try {
1262            doSendPassword(
1263                companyId, emailAddress, remoteAddr, remoteHost, userAgent);
1264        }
1265        catch (IOException ioe) {
1266            throw new SystemException(ioe);
1267        }
1268    }
1269
1270    public void setRoleUsers(long roleId, long[] userIds)
1271        throws PortalException, SystemException {
1272
1273        rolePersistence.setUsers(roleId, userIds);
1274
1275        PermissionCacheUtil.clearCache();
1276    }
1277
1278    public void setUserGroupUsers(long userGroupId, long[] userIds)
1279        throws PortalException, SystemException {
1280
1281        userGroupPersistence.setUsers(userGroupId, userIds);
1282
1283        PermissionCacheUtil.clearCache();
1284    }
1285
1286    public void unsetGroupUsers(long groupId, long[] userIds)
1287        throws PortalException, SystemException {
1288
1289        userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
1290
1291        groupPersistence.removeUsers(groupId, userIds);
1292
1293        PermissionCacheUtil.clearCache();
1294    }
1295
1296    public void unsetOrganizationUsers(long organizationId, long[] userIds)
1297        throws PortalException, SystemException {
1298
1299        Organization organization = organizationPersistence.findByPrimaryKey(
1300            organizationId);
1301
1302        Group group = organization.getGroup();
1303
1304        long groupId = group.getGroupId();
1305
1306        userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
1307
1308        organizationPersistence.removeUsers(organizationId, userIds);
1309
1310        PermissionCacheUtil.clearCache();
1311    }
1312
1313    public void unsetPasswordPolicyUsers(
1314            long passwordPolicyId, long[] userIds)
1315        throws PortalException, SystemException {
1316
1317        passwordPolicyRelLocalService.deletePasswordPolicyRels(
1318            passwordPolicyId, User.class.getName(), userIds);
1319    }
1320
1321    public void unsetRoleUsers(long roleId, long[] userIds)
1322        throws PortalException, SystemException {
1323
1324        rolePersistence.removeUsers(roleId, userIds);
1325
1326        PermissionCacheUtil.clearCache();
1327    }
1328
1329    public void unsetUserGroupUsers(long userGroupId, long[] userIds)
1330        throws PortalException, SystemException {
1331
1332        userGroupPersistence.removeUsers(userGroupId, userIds);
1333
1334        PermissionCacheUtil.clearCache();
1335    }
1336
1337    public User updateActive(long userId, boolean active)
1338        throws PortalException, SystemException {
1339
1340        User user = userPersistence.findByPrimaryKey(userId);
1341
1342        user.setActive(active);
1343
1344        userPersistence.update(user, false);
1345
1346        return user;
1347    }
1348
1349    public User updateAgreedToTermsOfUse(
1350            long userId, boolean agreedToTermsOfUse)
1351        throws PortalException, SystemException {
1352
1353        User user = userPersistence.findByPrimaryKey(userId);
1354
1355        user.setAgreedToTermsOfUse(agreedToTermsOfUse);
1356
1357        userPersistence.update(user, false);
1358
1359        return user;
1360    }
1361
1362    public User updateCreateDate(long userId, Date createDate)
1363        throws PortalException, SystemException {
1364
1365        User user = userPersistence.findByPrimaryKey(userId);
1366
1367        user.setCreateDate(createDate);
1368
1369        userPersistence.update(user, false);
1370
1371        return user;
1372    }
1373
1374    public User updateLastLogin(long userId, String loginIP)
1375        throws PortalException, SystemException {
1376
1377        User user = userPersistence.findByPrimaryKey(userId);
1378
1379        Date lastLoginDate = user.getLoginDate();
1380
1381        if (lastLoginDate == null) {
1382            lastLoginDate = new Date();
1383        }
1384
1385        user.setLoginDate(new Date());
1386        user.setLoginIP(loginIP);
1387        user.setLastLoginDate(lastLoginDate);
1388        user.setLastLoginIP(user.getLoginIP());
1389        user.setLastFailedLoginDate(null);
1390        user.setFailedLoginAttempts(0);
1391
1392        userPersistence.update(user, false);
1393
1394        return user;
1395    }
1396
1397    public User updateLockout(User user, boolean lockout)
1398        throws PortalException, SystemException {
1399
1400        PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1401
1402        if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
1403            return user;
1404        }
1405
1406        Date lockoutDate = null;
1407
1408        if (lockout) {
1409            lockoutDate = new Date();
1410        }
1411
1412        user.setLockout(lockout);
1413        user.setLockoutDate(lockoutDate);
1414
1415        if (!lockout) {
1416            user.setLastFailedLoginDate(lockoutDate);
1417            user.setFailedLoginAttempts(0);
1418        }
1419
1420        userPersistence.update(user, false);
1421
1422        return user;
1423    }
1424
1425    public User updateLockoutByEmailAddress(
1426            long companyId, String emailAddress, boolean lockout)
1427        throws PortalException, SystemException {
1428
1429        User user = getUserByEmailAddress(companyId, emailAddress);
1430
1431        return updateLockout(user, lockout);
1432    }
1433
1434    public User updateLockoutById(long userId, boolean lockout)
1435        throws PortalException, SystemException {
1436
1437        User user = userPersistence.findByPrimaryKey(userId);
1438
1439        return updateLockout(user, lockout);
1440    }
1441
1442    public User updateLockoutByScreenName(
1443            long companyId, String screenName, boolean lockout)
1444        throws PortalException, SystemException {
1445
1446        User user = getUserByScreenName(companyId, screenName);
1447
1448        return updateLockout(user, lockout);
1449    }
1450
1451    public User updateModifiedDate(long userId, Date modifiedDate)
1452        throws PortalException, SystemException {
1453
1454        User user = userPersistence.findByPrimaryKey(userId);
1455
1456        user.setModifiedDate(modifiedDate);
1457
1458        userPersistence.update(user, false);
1459
1460        return user;
1461    }
1462
1463    public void updateOrganizations(
1464            long userId, long[] newOrganizationIds)
1465        throws PortalException, SystemException {
1466
1467        List<Organization> oldOrganizations = userPersistence.getOrganizations(
1468            userId);
1469
1470        List<Long> oldOrganizationIds = new ArrayList<Long>(
1471            oldOrganizations.size());
1472
1473        for (int i = 0; i < oldOrganizations.size(); i++) {
1474            Organization oldOrganization = oldOrganizations.get(i);
1475
1476            long oldOrganizationId = oldOrganization.getOrganizationId();
1477
1478            oldOrganizationIds.add(oldOrganizationId);
1479
1480            if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
1481                unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
1482            }
1483        }
1484
1485        for (int i = 0; i < newOrganizationIds.length; i++) {
1486            long newOrganizationId = newOrganizationIds[i];
1487
1488            if (!oldOrganizationIds.contains(newOrganizationId)) {
1489                addOrganizationUsers(newOrganizationId, new long[] {userId});
1490            }
1491        }
1492
1493        PermissionCacheUtil.clearCache();
1494    }
1495
1496    public User updatePassword(
1497            long userId, String password1, String password2,
1498            boolean passwordReset)
1499        throws PortalException, SystemException {
1500
1501        return updatePassword(
1502            userId, password1, password2, passwordReset, false);
1503    }
1504
1505    public User updatePassword(
1506            long userId, String password1, String password2,
1507            boolean passwordReset, boolean silentUpdate)
1508        throws PortalException, SystemException {
1509
1510        User user = userPersistence.findByPrimaryKey(userId);
1511
1512        // Use silentUpdate so that imported user passwords are not exported
1513        // or validated
1514
1515        if (!silentUpdate) {
1516            validatePassword(user.getCompanyId(), userId, password1, password2);
1517        }
1518
1519        String oldEncPwd = user.getPassword();
1520
1521        if (!user.isPasswordEncrypted()) {
1522            oldEncPwd = PwdEncryptor.encrypt(user.getPassword());
1523        }
1524
1525        String newEncPwd = PwdEncryptor.encrypt(password1);
1526
1527        if (user.hasCompanyMx()) {
1528            try {
1529                mailService.updatePassword(userId, password1);
1530            }
1531            catch (RemoteException re) {
1532                throw new SystemException(re);
1533            }
1534        }
1535
1536        user.setPassword(newEncPwd);
1537        user.setPasswordUnencrypted(password1);
1538        user.setPasswordEncrypted(true);
1539        user.setPasswordReset(passwordReset);
1540        user.setPasswordModifiedDate(new Date());
1541        user.setGraceLoginCount(0);
1542
1543        if (!silentUpdate) {
1544            user.setPasswordModified(true);
1545        }
1546
1547        try {
1548            userPersistence.update(user, false);
1549        }
1550        catch (ModelListenerException mle) {
1551            String msg = GetterUtil.getString(mle.getCause().getMessage());
1552
1553            if (PortalLDAPUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1554                String passwordHistory = PrefsPropsUtil.getString(
1555                    user.getCompanyId(), PropsUtil.LDAP_ERROR_PASSWORD_HISTORY);
1556
1557                if (msg.indexOf(passwordHistory) != -1) {
1558                    throw new UserPasswordException(
1559                        UserPasswordException.PASSWORD_ALREADY_USED);
1560                }
1561            }
1562
1563            throw new UserPasswordException(
1564                UserPasswordException.PASSWORD_INVALID);
1565        }
1566
1567        if (!silentUpdate) {
1568            user.setPasswordModified(false);
1569        }
1570
1571        passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
1572
1573        return user;
1574    }
1575
1576    public User updatePasswordManually(
1577            long userId, String password, boolean passwordEncrypted,
1578            boolean passwordReset, Date passwordModifiedDate)
1579        throws PortalException, SystemException {
1580
1581        // This method should only be used to manually massage data
1582
1583        User user = userPersistence.findByPrimaryKey(userId);
1584
1585        user.setPassword(password);
1586        user.setPasswordEncrypted(passwordEncrypted);
1587        user.setPasswordReset(passwordReset);
1588        user.setPasswordModifiedDate(passwordModifiedDate);
1589
1590        userPersistence.update(user, false);
1591
1592        return user;
1593    }
1594
1595    public void updatePasswordReset(long userId, boolean passwordReset)
1596        throws PortalException, SystemException {
1597
1598        User user = userPersistence.findByPrimaryKey(userId);
1599
1600        user.setPasswordReset(passwordReset);
1601
1602        userPersistence.update(user, false);
1603    }
1604
1605    public void updatePortrait(long userId, byte[] bytes)
1606        throws PortalException, SystemException {
1607
1608        User user = userPersistence.findByPrimaryKey(userId);
1609
1610        long imageMaxSize = GetterUtil.getLong(
1611            PropsUtil.get(PropsUtil.USERS_IMAGE_MAX_SIZE));
1612
1613        if ((imageMaxSize > 0) &&
1614            ((bytes == null) || (bytes.length > imageMaxSize))) {
1615
1616            throw new UserPortraitException();
1617        }
1618
1619        long portraitId = user.getPortraitId();
1620
1621        if (portraitId <= 0) {
1622            portraitId = counterLocalService.increment();
1623
1624            user.setPortraitId(portraitId);
1625        }
1626
1627        ImageLocalUtil.updateImage(portraitId, bytes);
1628    }
1629
1630    public void updateScreenName(long userId, String screenName)
1631        throws PortalException, SystemException {
1632
1633        // User
1634
1635        User user = userPersistence.findByPrimaryKey(userId);
1636
1637        screenName = getScreenName(screenName);
1638
1639        validateScreenName(user.getCompanyId(), userId, screenName);
1640
1641        user.setScreenName(screenName);
1642
1643        userPersistence.update(user, false);
1644
1645        // Group
1646
1647        Group group = groupLocalService.getUserGroup(
1648            user.getCompanyId(), userId);
1649
1650        group.setFriendlyURL(StringPool.SLASH + screenName);
1651
1652        groupPersistence.update(group, false);
1653    }
1654
1655    public User updateUser(
1656            long userId, String oldPassword, boolean passwordReset,
1657            String screenName, String emailAddress, String languageId,
1658            String timeZoneId, String greeting, String comments,
1659            String firstName, String middleName, String lastName, int prefixId,
1660            int suffixId, boolean male, int birthdayMonth, int birthdayDay,
1661            int birthdayYear, String smsSn, String aimSn, String icqSn,
1662            String jabberSn, String msnSn, String skypeSn, String ymSn,
1663            String jobTitle, long[] organizationIds)
1664        throws PortalException, SystemException {
1665
1666        String newPassword1 = StringPool.BLANK;
1667        String newPassword2 = StringPool.BLANK;
1668
1669        return updateUser(
1670            userId, oldPassword, newPassword1, newPassword2, passwordReset,
1671            screenName, emailAddress, languageId, timeZoneId, greeting,
1672            comments, firstName, middleName, lastName, prefixId, suffixId, male,
1673            birthdayMonth, birthdayDay, birthdayYear, smsSn, aimSn, icqSn,
1674            jabberSn, msnSn, skypeSn, ymSn, jobTitle, organizationIds);
1675    }
1676
1677    public User updateUser(
1678            long userId, String oldPassword, String newPassword1,
1679            String newPassword2, boolean passwordReset, String screenName,
1680            String emailAddress, String languageId, String timeZoneId,
1681            String greeting, String comments, String firstName,
1682            String middleName, String lastName, int prefixId, int suffixId,
1683            boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
1684            String smsSn, String aimSn, String icqSn, String jabberSn,
1685            String msnSn, String skypeSn, String ymSn, String jobTitle,
1686            long[] organizationIds)
1687        throws PortalException, SystemException {
1688
1689        // User
1690
1691        String password = oldPassword;
1692        screenName = getScreenName(screenName);
1693        emailAddress = emailAddress.trim().toLowerCase();
1694        Date now = new Date();
1695
1696        validate(userId, screenName, emailAddress, firstName, lastName, smsSn);
1697
1698        if (Validator.isNotNull(newPassword1) ||
1699            Validator.isNotNull(newPassword2)) {
1700
1701            updatePassword(userId, newPassword1, newPassword2, passwordReset);
1702
1703            password = newPassword1;
1704        }
1705
1706        User user = userPersistence.findByPrimaryKey(userId);
1707        Company company = companyPersistence.findByPrimaryKey(
1708            user.getCompanyId());
1709
1710        user.setModifiedDate(now);
1711
1712        if (user.getContactId() <= 0) {
1713            user.setContactId(counterLocalService.increment());
1714        }
1715
1716        user.setPasswordReset(passwordReset);
1717        user.setScreenName(screenName);
1718
1719        if (!emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
1720
1721            // test@test.com -> test@liferay.com
1722
1723            try {
1724                if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
1725                    mailService.addUser(
1726                        userId, password, firstName, middleName, lastName,
1727                        emailAddress);
1728                }
1729
1730                // test@liferay.com -> bob@liferay.com
1731
1732                else if (user.hasCompanyMx() &&
1733                         user.hasCompanyMx(emailAddress)) {
1734
1735                    mailService.updateEmailAddress(userId, emailAddress);
1736                }
1737
1738                // test@liferay.com -> test@test.com
1739
1740                else if (user.hasCompanyMx() &&
1741                         !user.hasCompanyMx(emailAddress)) {
1742
1743                    mailService.deleteEmailAddress(userId);
1744                }
1745            }
1746            catch (RemoteException re) {
1747                throw new SystemException(re);
1748            }
1749
1750            user.setEmailAddress(emailAddress);
1751        }
1752
1753        user.setLanguageId(languageId);
1754        user.setTimeZoneId(timeZoneId);
1755        user.setGreeting(greeting);
1756        user.setComments(comments);
1757
1758        userPersistence.update(user, false);
1759
1760        // Contact
1761
1762        Date birthday = PortalUtil.getDate(
1763            birthdayMonth, birthdayDay, birthdayYear,
1764            new ContactBirthdayException());
1765
1766        long contactId = user.getContactId();
1767
1768        Contact contact = null;
1769
1770        try {
1771            contact = contactPersistence.findByPrimaryKey(contactId);
1772        }
1773        catch (NoSuchContactException nsce) {
1774            contact = contactPersistence.create(contactId);
1775
1776            contact.setCompanyId(user.getCompanyId());
1777            contact.setUserName(StringPool.BLANK);
1778            contact.setCreateDate(now);
1779            contact.setAccountId(company.getAccountId());
1780            contact.setParentContactId(
1781                ContactConstants.DEFAULT_PARENT_CONTACT_ID);
1782        }
1783
1784        contact.setModifiedDate(now);
1785        contact.setFirstName(firstName);
1786        contact.setMiddleName(middleName);
1787        contact.setLastName(lastName);
1788        contact.setPrefixId(prefixId);
1789        contact.setSuffixId(suffixId);
1790        contact.setMale(male);
1791        contact.setBirthday(birthday);
1792        contact.setSmsSn(smsSn);
1793        contact.setAimSn(aimSn);
1794        contact.setIcqSn(icqSn);
1795        contact.setJabberSn(jabberSn);
1796        contact.setMsnSn(msnSn);
1797        contact.setSkypeSn(skypeSn);
1798        contact.setYmSn(ymSn);
1799        contact.setJobTitle(jobTitle);
1800
1801        contactPersistence.update(contact, false);
1802
1803        // Organizations
1804
1805        updateOrganizations(userId, organizationIds);
1806
1807        // Group
1808
1809        Group group = groupLocalService.getUserGroup(
1810            user.getCompanyId(), userId);
1811
1812        group.setFriendlyURL(StringPool.SLASH + screenName);
1813
1814        groupPersistence.update(group, false);
1815
1816        // Announcements
1817
1818        announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
1819
1820        // Permission cache
1821
1822        PermissionCacheUtil.clearCache();
1823
1824        return user;
1825    }
1826
1827    protected int authenticate(
1828            long companyId, String login, String password, String authType,
1829            Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
1830        throws PortalException, SystemException {
1831
1832        login = login.trim().toLowerCase();
1833
1834        long userId = GetterUtil.getLong(login);
1835
1836        // User input validation
1837
1838        if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1839            if (!Validator.isEmailAddress(login)) {
1840                throw new UserEmailAddressException();
1841            }
1842        }
1843        else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1844            if (Validator.isNull(login)) {
1845                throw new UserScreenNameException();
1846            }
1847        }
1848        else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1849            if (Validator.isNull(login)) {
1850                throw new UserIdException();
1851            }
1852        }
1853
1854        if (Validator.isNull(password)) {
1855            throw new UserPasswordException(
1856                UserPasswordException.PASSWORD_INVALID);
1857        }
1858
1859        int authResult = Authenticator.FAILURE;
1860
1861        // Pre-authentication pipeline
1862
1863        String[] authPipelinePre =
1864            PropsUtil.getArray(PropsUtil.AUTH_PIPELINE_PRE);
1865
1866        if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1867            authResult = AuthPipeline.authenticateByEmailAddress(
1868                authPipelinePre, companyId, login, password, headerMap,
1869                parameterMap);
1870        }
1871        else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1872            authResult = AuthPipeline.authenticateByScreenName(
1873                authPipelinePre, companyId, login, password, headerMap,
1874                parameterMap);
1875        }
1876        else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1877            authResult = AuthPipeline.authenticateByUserId(
1878                authPipelinePre, companyId, userId, password, headerMap,
1879                parameterMap);
1880        }
1881
1882        // Get user
1883
1884        User user = null;
1885
1886        try {
1887            if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1888                user = userPersistence.findByC_EA(companyId, login);
1889            }
1890            else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1891                user = userPersistence.findByC_SN(companyId, login);
1892            }
1893            else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1894                user = userPersistence.findByC_U(
1895                    companyId, GetterUtil.getLong(login));
1896            }
1897        }
1898        catch (NoSuchUserException nsue) {
1899            return Authenticator.DNE;
1900        }
1901
1902        if (user.isDefaultUser()) {
1903            _log.error(
1904                "The default user should never be allowed to authenticate");
1905
1906            return Authenticator.DNE;
1907        }
1908
1909        if (!user.isPasswordEncrypted()) {
1910            user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
1911            user.setPasswordEncrypted(true);
1912
1913            userPersistence.update(user, false);
1914        }
1915
1916        // Check password policy to see if the is account locked out or if the
1917        // password is expired
1918
1919        checkLockout(user);
1920
1921        checkPasswordExpired(user);
1922
1923        // Authenticate against the User_ table
1924
1925        if (authResult == Authenticator.SUCCESS) {
1926            if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
1927                String encPassword = PwdEncryptor.encrypt(
1928                    password, user.getPassword());
1929
1930                if (user.getPassword().equals(encPassword)) {
1931                    authResult = Authenticator.SUCCESS;
1932                }
1933                else if (GetterUtil.getBoolean(PropsUtil.get(
1934                            PropsUtil.AUTH_MAC_ALLOW))) {
1935
1936                    try {
1937                        MessageDigest digester = MessageDigest.getInstance(
1938                            PropsUtil.get(PropsUtil.AUTH_MAC_ALGORITHM));
1939
1940                        digester.update(login.getBytes("UTF8"));
1941
1942                        String shardKey =
1943                            PropsUtil.get(PropsUtil.AUTH_MAC_SHARED_KEY);
1944
1945                        encPassword = Base64.encode(
1946                            digester.digest(shardKey.getBytes("UTF8")));
1947
1948                        if (password.equals(encPassword)) {
1949                            authResult = Authenticator.SUCCESS;
1950                        }
1951                        else {
1952                            authResult = Authenticator.FAILURE;
1953                        }
1954                    }
1955                    catch (NoSuchAlgorithmException nsae) {
1956                        throw new SystemException(nsae);
1957                    }
1958                    catch (UnsupportedEncodingException uee) {
1959                        throw new SystemException(uee);
1960                    }
1961                }
1962                else {
1963                    authResult = Authenticator.FAILURE;
1964                }
1965            }
1966        }
1967
1968        // Post-authentication pipeline
1969
1970        if (authResult == Authenticator.SUCCESS) {
1971            String[] authPipelinePost =
1972                PropsUtil.getArray(PropsUtil.AUTH_PIPELINE_POST);
1973
1974            if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1975                authResult = AuthPipeline.authenticateByEmailAddress(
1976                    authPipelinePost, companyId, login, password, headerMap,
1977                    parameterMap);
1978            }
1979            else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1980                authResult = AuthPipeline.authenticateByScreenName(
1981                    authPipelinePost, companyId, login, password, headerMap,
1982                    parameterMap);
1983            }
1984            else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1985                authResult = AuthPipeline.authenticateByUserId(
1986                    authPipelinePost, companyId, userId, password, headerMap,
1987                    parameterMap);
1988            }
1989        }
1990
1991        // Execute code triggered by authentication failure
1992
1993        if (authResult == Authenticator.FAILURE) {
1994            try {
1995                String[] authFailure =
1996                    PropsUtil.getArray(PropsUtil.AUTH_FAILURE);
1997
1998                if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1999                    AuthPipeline.onFailureByEmailAddress(
2000                        authFailure, companyId, login, headerMap, parameterMap);
2001                }
2002                else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2003                    AuthPipeline.onFailureByScreenName(
2004                        authFailure, companyId, login, headerMap, parameterMap);
2005                }
2006                else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2007                    AuthPipeline.onFailureByUserId(
2008                        authFailure, companyId, userId, headerMap,
2009                        parameterMap);
2010                }
2011
2012                // Let LDAP handle max failure event
2013
2014                if (!PortalLDAPUtil.isPasswordPolicyEnabled(
2015                        user.getCompanyId())) {
2016
2017                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2018
2019                    int failedLoginAttempts = user.getFailedLoginAttempts();
2020                    int maxFailures = passwordPolicy.getMaxFailure();
2021
2022                    if ((failedLoginAttempts >= maxFailures) &&
2023                        (maxFailures != 0)) {
2024
2025                        String[] authMaxFailures =
2026                            PropsUtil.getArray(PropsUtil.AUTH_MAX_FAILURES);
2027
2028                        if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2029                            AuthPipeline.onMaxFailuresByEmailAddress(
2030                                authMaxFailures, companyId, login, headerMap,
2031                                parameterMap);
2032                        }
2033                        else if (authType.equals(
2034                                    CompanyConstants.AUTH_TYPE_SN)) {
2035
2036                            AuthPipeline.onMaxFailuresByScreenName(
2037                                authMaxFailures, companyId, login, headerMap,
2038                                parameterMap);
2039                        }
2040                        else if (authType.equals(
2041                                    CompanyConstants.AUTH_TYPE_ID)) {
2042
2043                            AuthPipeline.onMaxFailuresByUserId(
2044                                authMaxFailures, companyId, userId, headerMap,
2045                                parameterMap);
2046                        }
2047                    }
2048                }
2049            }
2050            catch (Exception e) {
2051                _log.error(e, e);
2052            }
2053        }
2054
2055        return authResult;
2056    }
2057
2058    protected void doSendPassword(
2059            long companyId, String emailAddress, String remoteAddr,
2060            String remoteHost, String userAgent)
2061        throws IOException, PortalException, SystemException {
2062
2063        if (!PrefsPropsUtil.getBoolean(
2064                companyId, PropsUtil.COMPANY_SECURITY_SEND_PASSWORD) ||
2065            !PrefsPropsUtil.getBoolean(
2066                companyId, PropsUtil.ADMIN_EMAIL_PASSWORD_SENT_ENABLED)) {
2067
2068            return;
2069        }
2070
2071        emailAddress = emailAddress.trim().toLowerCase();
2072
2073        if (!Validator.isEmailAddress(emailAddress)) {
2074            throw new UserEmailAddressException();
2075        }
2076
2077        Company company = companyPersistence.findByPrimaryKey(companyId);
2078
2079        User user = userPersistence.findByC_EA(companyId, emailAddress);
2080
2081        PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2082
2083        /*if (user.hasCompanyMx()) {
2084            throw new SendPasswordException();
2085        }*/
2086
2087        String newPassword = null;
2088
2089        if (!PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
2090                PwdEncryptor.TYPE_NONE)) {
2091
2092            newPassword = PwdToolkitUtil.generate();
2093
2094            boolean passwordReset = false;
2095
2096            if (passwordPolicy.getChangeable() &&
2097                passwordPolicy.getChangeRequired()) {
2098
2099                passwordReset = true;
2100            }
2101
2102            user.setPassword(PwdEncryptor.encrypt(newPassword));
2103            user.setPasswordUnencrypted(newPassword);
2104            user.setPasswordEncrypted(true);
2105            user.setPasswordReset(passwordReset);
2106
2107            userPersistence.update(user, false);
2108        }
2109        else {
2110            newPassword = user.getPassword();
2111        }
2112
2113        String fromName = PrefsPropsUtil.getString(
2114            companyId, PropsUtil.ADMIN_EMAIL_FROM_NAME);
2115        String fromAddress = PrefsPropsUtil.getString(
2116            companyId, PropsUtil.ADMIN_EMAIL_FROM_ADDRESS);
2117
2118        String toName = user.getFullName();
2119        String toAddress = user.getEmailAddress();
2120
2121        String subject = PrefsPropsUtil.getContent(
2122            companyId, PropsUtil.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
2123        String body = PrefsPropsUtil.getContent(
2124            companyId, PropsUtil.ADMIN_EMAIL_PASSWORD_SENT_BODY);
2125
2126        subject = StringUtil.replace(
2127            subject,
2128            new String[] {
2129                "[$FROM_ADDRESS$]",
2130                "[$FROM_NAME$]",
2131                "[$PORTAL_URL$]",
2132                "[$REMOTE_ADDRESS$]",
2133                "[$REMOTE_HOST$]",
2134                "[$TO_ADDRESS$]",
2135                "[$TO_NAME$]",
2136                "[$USER_AGENT$]",
2137                "[$USER_ID$]",
2138                "[$USER_PASSWORD$]",
2139                "[$USER_SCREENNAME$]"
2140            },
2141            new String[] {
2142                fromAddress,
2143                fromName,
2144                company.getVirtualHost(),
2145                remoteAddr,
2146                remoteHost,
2147                toAddress,
2148                toName,
2149                HtmlUtil.escape(userAgent),
2150                String.valueOf(user.getUserId()),
2151                newPassword,
2152                user.getScreenName()
2153            });
2154
2155        body = StringUtil.replace(
2156            body,
2157            new String[] {
2158                "[$FROM_ADDRESS$]",
2159                "[$FROM_NAME$]",
2160                "[$PORTAL_URL$]",
2161                "[$REMOTE_ADDRESS$]",
2162                "[$REMOTE_HOST$]",
2163                "[$TO_ADDRESS$]",
2164                "[$TO_NAME$]",
2165                "[$USER_AGENT$]",
2166                "[$USER_ID$]",
2167                "[$USER_PASSWORD$]",
2168                "[$USER_SCREENNAME$]"
2169            },
2170            new String[] {
2171                fromAddress,
2172                fromName,
2173                company.getVirtualHost(),
2174                remoteAddr,
2175                remoteHost,
2176                toAddress,
2177                toName,
2178                HtmlUtil.escape(userAgent),
2179                String.valueOf(user.getUserId()),
2180                newPassword,
2181                user.getScreenName()
2182            });
2183
2184        InternetAddress from = new InternetAddress(fromAddress, fromName);
2185
2186        InternetAddress to = new InternetAddress(toAddress, toName);
2187
2188        MailMessage message = new MailMessage(from, to, subject, body, true);
2189
2190        mailService.sendEmail(message);
2191    }
2192
2193    protected String getScreenName(String screenName) {
2194        return Normalizer.normalizeToAscii(screenName.trim().toLowerCase());
2195    }
2196
2197    protected void sendEmail(User user, String password)
2198        throws IOException, PortalException, SystemException {
2199
2200        if (!PrefsPropsUtil.getBoolean(
2201                user.getCompanyId(),
2202                PropsUtil.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
2203
2204            return;
2205        }
2206
2207        long companyId = user.getCompanyId();
2208
2209        Company company = companyPersistence.findByPrimaryKey(companyId);
2210
2211        String fromName = PrefsPropsUtil.getString(
2212            companyId, PropsUtil.ADMIN_EMAIL_FROM_NAME);
2213        String fromAddress = PrefsPropsUtil.getString(
2214            companyId, PropsUtil.ADMIN_EMAIL_FROM_ADDRESS);
2215
2216        String toName = user.getFullName();
2217        String toAddress = user.getEmailAddress();
2218
2219        String subject = PrefsPropsUtil.getContent(
2220            companyId, PropsUtil.ADMIN_EMAIL_USER_ADDED_SUBJECT);
2221        String body = PrefsPropsUtil.getContent(
2222            companyId, PropsUtil.ADMIN_EMAIL_USER_ADDED_BODY);
2223
2224        subject = StringUtil.replace(
2225            subject,
2226            new String[] {
2227                "[$FROM_ADDRESS$]",
2228                "[$FROM_NAME$]",
2229                "[$PORTAL_URL$]",
2230                "[$TO_ADDRESS$]",
2231                "[$TO_NAME$]",
2232                "[$USER_ID$]",
2233                "[$USER_PASSWORD$]",
2234                "[$USER_SCREENNAME$]"
2235            },
2236            new String[] {
2237                fromAddress,
2238                fromName,
2239                company.getVirtualHost(),
2240                toAddress,
2241                toName,
2242                String.valueOf(user.getUserId()),
2243                password,
2244                user.getScreenName()
2245            });
2246
2247        body = StringUtil.replace(
2248            body,
2249            new String[] {
2250                "[$FROM_ADDRESS$]",
2251                "[$FROM_NAME$]",
2252                "[$PORTAL_URL$]",
2253                "[$TO_ADDRESS$]",
2254                "[$TO_NAME$]",
2255                "[$USER_ID$]",
2256                "[$USER_PASSWORD$]",
2257                "[$USER_SCREENNAME$]"
2258            },
2259            new String[] {
2260                fromAddress,
2261                fromName,
2262                company.getVirtualHost(),
2263                toAddress,
2264                toName,
2265                String.valueOf(user.getUserId()),
2266                password,
2267                user.getScreenName()
2268            });
2269
2270        InternetAddress from = new InternetAddress(fromAddress, fromName);
2271
2272        InternetAddress to = new InternetAddress(toAddress, toName);
2273
2274        MailMessage message = new MailMessage(from, to, subject, body, true);
2275
2276        mailService.sendEmail(message);
2277    }
2278
2279    protected void validate(
2280            long userId, String screenName, String emailAddress,
2281            String firstName, String lastName, String smsSn)
2282        throws PortalException, SystemException {
2283
2284        User user = userPersistence.findByPrimaryKey(userId);
2285
2286        if (!user.getScreenName().equalsIgnoreCase(screenName)) {
2287            validateScreenName(user.getCompanyId(), userId, screenName);
2288        }
2289
2290        validateEmailAddress(emailAddress);
2291
2292        if (!user.isDefaultUser()) {
2293            try {
2294                if (!user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
2295                    if (userPersistence.findByC_EA(
2296                            user.getCompanyId(), emailAddress) != null) {
2297
2298                        throw new DuplicateUserEmailAddressException();
2299                    }
2300                }
2301            }
2302            catch (NoSuchUserException nsue) {
2303            }
2304
2305            String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
2306                user.getCompanyId(), PropsUtil.ADMIN_RESERVED_EMAIL_ADDRESSES,
2307                StringPool.NEW_LINE,
2308                PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
2309
2310            for (int i = 0; i < reservedEmailAddresses.length; i++) {
2311                if (emailAddress.equalsIgnoreCase(reservedEmailAddresses[i])) {
2312                    throw new ReservedUserEmailAddressException();
2313                }
2314            }
2315
2316            if (Validator.isNull(firstName)) {
2317                throw new ContactFirstNameException();
2318            }
2319            else if (Validator.isNull(lastName)) {
2320                throw new ContactLastNameException();
2321            }
2322        }
2323
2324        if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
2325            throw new UserSmsException();
2326        }
2327    }
2328
2329    protected void validate(
2330            long companyId, long userId, boolean autoPassword, String password1,
2331            String password2, boolean autoScreenName, String screenName,
2332            String emailAddress, String firstName, String lastName,
2333            long[] organizationIds)
2334        throws PortalException, SystemException {
2335
2336        if (!autoScreenName) {
2337            validateScreenName(companyId, userId, screenName);
2338        }
2339
2340        if (!autoPassword) {
2341            PasswordPolicy passwordPolicy =
2342                passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
2343
2344            PwdToolkitUtil.validate(
2345                companyId, 0, password1, password2, passwordPolicy);
2346        }
2347
2348        validateEmailAddress(emailAddress);
2349
2350        try {
2351            User user = userPersistence.findByC_EA(companyId, emailAddress);
2352
2353            if (user != null) {
2354                throw new DuplicateUserEmailAddressException();
2355            }
2356        }
2357        catch (NoSuchUserException nsue) {
2358        }
2359
2360        String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
2361            companyId, PropsUtil.ADMIN_RESERVED_EMAIL_ADDRESSES,
2362            StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
2363
2364        for (int i = 0; i < reservedEmailAddresses.length; i++) {
2365            if (emailAddress.equalsIgnoreCase(reservedEmailAddresses[i])) {
2366                throw new ReservedUserEmailAddressException();
2367            }
2368        }
2369
2370        if (Validator.isNull(firstName)) {
2371            throw new ContactFirstNameException();
2372        }
2373        else if (Validator.isNull(lastName)) {
2374            throw new ContactLastNameException();
2375        }
2376    }
2377
2378    protected void validateEmailAddress(String emailAddress)
2379        throws PortalException {
2380
2381        if (!Validator.isEmailAddress(emailAddress) ||
2382            emailAddress.startsWith("root@") ||
2383            emailAddress.startsWith("postmaster@")) {
2384
2385            throw new UserEmailAddressException();
2386        }
2387    }
2388
2389    protected void validatePassword(
2390            long companyId, long userId, String password1, String password2)
2391        throws PortalException, SystemException {
2392
2393        if (Validator.isNull(password1) || Validator.isNull(password2)) {
2394            throw new UserPasswordException(
2395                UserPasswordException.PASSWORD_INVALID);
2396        }
2397
2398        if (!password1.equals(password2)) {
2399            throw new UserPasswordException(
2400                UserPasswordException.PASSWORDS_DO_NOT_MATCH);
2401        }
2402
2403        PasswordPolicy passwordPolicy =
2404            passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
2405
2406        PwdToolkitUtil.validate(
2407            companyId, userId, password1, password2, passwordPolicy);
2408    }
2409
2410    protected void validateScreenName(
2411            long companyId, long userId, String screenName)
2412        throws PortalException, SystemException {
2413
2414        if (Validator.isNull(screenName)) {
2415            throw new UserScreenNameException();
2416        }
2417
2418        ScreenNameValidator screenNameValidator =
2419            (ScreenNameValidator)InstancePool.get(
2420                PropsValues.USERS_SCREEN_NAME_VALIDATOR);
2421
2422        if (screenNameValidator != null) {
2423            if (!screenNameValidator.validate(companyId, screenName)) {
2424                throw new UserScreenNameException();
2425            }
2426        }
2427
2428        if (Validator.isNumber(screenName) &&
2429            !screenName.equals(String.valueOf(userId))) {
2430
2431            throw new UserScreenNameException();
2432        }
2433
2434        String[] anonymousNames = PrincipalBean.ANONYMOUS_NAMES;
2435
2436        for (int i = 0; i < anonymousNames.length; i++) {
2437            if (screenName.equalsIgnoreCase(anonymousNames[i])) {
2438                throw new UserScreenNameException();
2439            }
2440        }
2441
2442        User user = userPersistence.fetchByC_SN(companyId, screenName);
2443
2444        if (user != null) {
2445            throw new DuplicateUserScreenNameException();
2446        }
2447
2448        String friendlyURL = StringPool.SLASH + screenName;
2449
2450        Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
2451
2452        if (group != null) {
2453            throw new DuplicateUserScreenNameException();
2454        }
2455
2456        int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
2457
2458        if (exceptionType != -1) {
2459            throw new UserScreenNameException(
2460                new GroupFriendlyURLException(exceptionType));
2461        }
2462
2463        String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
2464            companyId, PropsUtil.ADMIN_RESERVED_SCREEN_NAMES,
2465            StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
2466
2467        for (int i = 0; i < reservedScreenNames.length; i++) {
2468            if (screenName.equalsIgnoreCase(reservedScreenNames[i])) {
2469                throw new ReservedUserScreenNameException();
2470            }
2471        }
2472    }
2473
2474    private static Log _log = LogFactory.getLog(UserLocalServiceImpl.class);
2475
2476}