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