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