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