1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    *
5    *
6    *
7    * The contents of this file are subject to the terms of the Liferay Enterprise
8    * Subscription License ("License"). You may not use this file except in
9    * compliance with the License. You can obtain a copy of the License by
10   * contacting Liferay, Inc. See the License for the specific language governing
11   * permissions and limitations under the License, including but not limited to
12   * distribution rights of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.service.impl;
24  
25  import com.liferay.portal.ContactBirthdayException;
26  import com.liferay.portal.ContactFirstNameException;
27  import com.liferay.portal.ContactLastNameException;
28  import com.liferay.portal.DuplicateUserEmailAddressException;
29  import com.liferay.portal.DuplicateUserScreenNameException;
30  import com.liferay.portal.GroupFriendlyURLException;
31  import com.liferay.portal.ModelListenerException;
32  import com.liferay.portal.NoSuchContactException;
33  import com.liferay.portal.NoSuchGroupException;
34  import com.liferay.portal.NoSuchRoleException;
35  import com.liferay.portal.NoSuchUserException;
36  import com.liferay.portal.NoSuchUserGroupException;
37  import com.liferay.portal.PasswordExpiredException;
38  import com.liferay.portal.PortalException;
39  import com.liferay.portal.RequiredUserException;
40  import com.liferay.portal.ReservedUserEmailAddressException;
41  import com.liferay.portal.ReservedUserScreenNameException;
42  import com.liferay.portal.SystemException;
43  import com.liferay.portal.UserEmailAddressException;
44  import com.liferay.portal.UserIdException;
45  import com.liferay.portal.UserLockoutException;
46  import com.liferay.portal.UserPasswordException;
47  import com.liferay.portal.UserPortraitException;
48  import com.liferay.portal.UserReminderQueryException;
49  import com.liferay.portal.UserScreenNameException;
50  import com.liferay.portal.UserSmsException;
51  import com.liferay.portal.kernel.annotation.Propagation;
52  import com.liferay.portal.kernel.annotation.Transactional;
53  import com.liferay.portal.kernel.language.LanguageUtil;
54  import com.liferay.portal.kernel.log.Log;
55  import com.liferay.portal.kernel.log.LogFactoryUtil;
56  import com.liferay.portal.kernel.mail.MailMessage;
57  import com.liferay.portal.kernel.search.BooleanClauseOccur;
58  import com.liferay.portal.kernel.search.BooleanQuery;
59  import com.liferay.portal.kernel.search.BooleanQueryFactoryUtil;
60  import com.liferay.portal.kernel.search.Field;
61  import com.liferay.portal.kernel.search.Hits;
62  import com.liferay.portal.kernel.search.ParseException;
63  import com.liferay.portal.kernel.search.SearchEngineUtil;
64  import com.liferay.portal.kernel.search.SearchException;
65  import com.liferay.portal.kernel.search.Sort;
66  import com.liferay.portal.kernel.util.ArrayUtil;
67  import com.liferay.portal.kernel.util.Base64;
68  import com.liferay.portal.kernel.util.CharPool;
69  import com.liferay.portal.kernel.util.GetterUtil;
70  import com.liferay.portal.kernel.util.HtmlUtil;
71  import com.liferay.portal.kernel.util.InstancePool;
72  import com.liferay.portal.kernel.util.KeyValuePair;
73  import com.liferay.portal.kernel.util.ListUtil;
74  import com.liferay.portal.kernel.util.OrderByComparator;
75  import com.liferay.portal.kernel.util.PropsKeys;
76  import com.liferay.portal.kernel.util.SetUtil;
77  import com.liferay.portal.kernel.util.StringPool;
78  import com.liferay.portal.kernel.util.StringUtil;
79  import com.liferay.portal.kernel.util.UnicodeProperties;
80  import com.liferay.portal.kernel.util.Validator;
81  import com.liferay.portal.lar.PortletDataHandlerKeys;
82  import com.liferay.portal.lar.UserIdStrategy;
83  import com.liferay.portal.model.Company;
84  import com.liferay.portal.model.CompanyConstants;
85  import com.liferay.portal.model.Contact;
86  import com.liferay.portal.model.ContactConstants;
87  import com.liferay.portal.model.Group;
88  import com.liferay.portal.model.Organization;
89  import com.liferay.portal.model.PasswordPolicy;
90  import com.liferay.portal.model.ResourceConstants;
91  import com.liferay.portal.model.Role;
92  import com.liferay.portal.model.RoleConstants;
93  import com.liferay.portal.model.User;
94  import com.liferay.portal.model.UserGroup;
95  import com.liferay.portal.model.UserGroupRole;
96  import com.liferay.portal.model.impl.LayoutImpl;
97  import com.liferay.portal.security.auth.AuthPipeline;
98  import com.liferay.portal.security.auth.Authenticator;
99  import com.liferay.portal.security.auth.EmailAddressGenerator;
100 import com.liferay.portal.security.auth.PrincipalException;
101 import com.liferay.portal.security.auth.ScreenNameGenerator;
102 import com.liferay.portal.security.auth.ScreenNameValidator;
103 import com.liferay.portal.security.ldap.PortalLDAPUtil;
104 import com.liferay.portal.security.permission.PermissionCacheUtil;
105 import com.liferay.portal.security.pwd.PwdEncryptor;
106 import com.liferay.portal.security.pwd.PwdToolkitUtil;
107 import com.liferay.portal.service.ServiceContext;
108 import com.liferay.portal.service.base.PrincipalBean;
109 import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
110 import com.liferay.portal.util.PortalUtil;
111 import com.liferay.portal.util.PrefsPropsUtil;
112 import com.liferay.portal.util.PropsUtil;
113 import com.liferay.portal.util.PropsValues;
114 import com.liferay.portlet.enterpriseadmin.util.EnterpriseAdminUtil;
115 import com.liferay.portlet.enterpriseadmin.util.UserIndexer;
116 import com.liferay.portlet.expando.model.ExpandoBridge;
117 import com.liferay.portlet.expando.model.ExpandoColumnConstants;
118 import com.liferay.portlet.expando.util.ExpandoBridgeFactoryUtil;
119 import com.liferay.portlet.expando.util.ExpandoBridgeIndexer;
120 import com.liferay.util.Encryptor;
121 import com.liferay.util.EncryptorException;
122 
123 import java.io.ByteArrayInputStream;
124 import java.io.IOException;
125 import java.io.UnsupportedEncodingException;
126 
127 import java.security.MessageDigest;
128 import java.security.NoSuchAlgorithmException;
129 
130 import java.util.ArrayList;
131 import java.util.Date;
132 import java.util.HashSet;
133 import java.util.LinkedHashMap;
134 import java.util.List;
135 import java.util.Locale;
136 import java.util.Map;
137 import java.util.Set;
138 import java.util.concurrent.ConcurrentHashMap;
139 
140 import javax.mail.internet.InternetAddress;
141 
142 /**
143  * <a href="UserLocalServiceImpl.java.html"><b><i>View Source</i></b></a>
144  *
145  * @author Brian Wing Shun Chan
146  * @author Scott Lee
147  * @author Raymond Augé
148  * @author Jorge Ferrer
149  * @author Julio Camarero
150  * @author Wesley Gong
151  */
152 public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
153 
154     public void addGroupUsers(long groupId, long[] userIds)
155         throws PortalException, SystemException {
156 
157         groupPersistence.addUsers(groupId, userIds);
158 
159         Group group = groupPersistence.findByPrimaryKey(groupId);
160 
161         Role role = rolePersistence.findByC_N(
162             group.getCompanyId(), RoleConstants.COMMUNITY_MEMBER);
163 
164         for (int i = 0; i < userIds.length; i++) {
165             long userId = userIds[i];
166 
167             userGroupRoleLocalService.addUserGroupRoles(
168                 userId, groupId, new long[] {role.getRoleId()});
169         }
170 
171         try {
172             UserIndexer.updateUsers(userIds);
173         }
174         catch (SearchException se) {
175             _log.error("Indexing " + StringUtil.merge(userIds), se);
176         }
177 
178         PermissionCacheUtil.clearCache();
179     }
180 
181     public void addOrganizationUsers(long organizationId, long[] userIds)
182         throws PortalException, SystemException {
183 
184         organizationPersistence.addUsers(organizationId, userIds);
185 
186         Organization organization = organizationPersistence.findByPrimaryKey(
187             organizationId);
188 
189         Group group = organization.getGroup();
190 
191         long groupId = group.getGroupId();
192 
193         Role role = rolePersistence.findByC_N(
194             group.getCompanyId(), RoleConstants.ORGANIZATION_MEMBER);
195 
196         for (int i = 0; i < userIds.length; i++) {
197             long userId = userIds[i];
198 
199             userGroupRoleLocalService.addUserGroupRoles(
200                 userId, groupId, new long[] {role.getRoleId()});
201         }
202 
203         try {
204             UserIndexer.updateUsers(userIds);
205         }
206         catch (SearchException se) {
207             _log.error("Indexing " + StringUtil.merge(userIds), se);
208         }
209 
210         PermissionCacheUtil.clearCache();
211     }
212 
213     public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
214         throws SystemException {
215 
216         passwordPolicyRelLocalService.addPasswordPolicyRels(
217             passwordPolicyId, User.class.getName(), userIds);
218     }
219 
220     public void addRoleUsers(long roleId, long[] userIds)
221         throws SystemException {
222 
223         rolePersistence.addUsers(roleId, userIds);
224 
225         try {
226             UserIndexer.updateUsers(userIds);
227         }
228         catch (SearchException se) {
229             _log.error("Indexing " + StringUtil.merge(userIds), se);
230         }
231 
232         PermissionCacheUtil.clearCache();
233     }
234 
235     public void addUserGroupUsers(long userGroupId, long[] userIds)
236         throws PortalException, SystemException {
237 
238         copyUserGroupLayouts(userGroupId, userIds);
239 
240         userGroupPersistence.addUsers(userGroupId, userIds);
241 
242         try {
243             UserIndexer.updateUsers(userIds);
244         }
245         catch (SearchException se) {
246             _log.error("Indexing " + StringUtil.merge(userIds), se);
247         }
248 
249         PermissionCacheUtil.clearCache();
250     }
251 
252     public User addUser(
253             long creatorUserId, long companyId, boolean autoPassword,
254             String password1, String password2, boolean autoScreenName,
255             String screenName, String emailAddress, String openId,
256             Locale locale, String firstName, String middleName, String lastName,
257             int prefixId, int suffixId, boolean male, int birthdayMonth,
258             int birthdayDay, int birthdayYear, String jobTitle, long[] groupIds,
259             long[] organizationIds, long[] roleIds, long[] userGroupIds,
260             boolean sendEmail, ServiceContext serviceContext)
261         throws PortalException, SystemException {
262 
263         // User
264 
265         Company company = companyPersistence.findByPrimaryKey(companyId);
266         screenName = getScreenName(screenName);
267         emailAddress = emailAddress.trim().toLowerCase();
268         openId = openId.trim();
269         Date now = new Date();
270 
271         if (PrefsPropsUtil.getBoolean(
272                 companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
273 
274             autoScreenName = true;
275         }
276 
277         long userId = counterLocalService.increment();
278 
279         EmailAddressGenerator emailAddressGenerator =
280             (EmailAddressGenerator)InstancePool.get(
281                 PropsValues.USERS_EMAIL_ADDRESS_GENERATOR);
282 
283         if (emailAddressGenerator.isGenerated(emailAddress)) {
284             emailAddress = StringPool.BLANK;
285         }
286 
287         if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
288             Validator.isNull(emailAddress)) {
289 
290             emailAddress = emailAddressGenerator.generate(companyId, userId);
291         }
292 
293         validate(
294             companyId, userId, autoPassword, password1, password2,
295             autoScreenName, screenName, emailAddress, firstName, lastName,
296             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                 (ScreenNameGenerator)InstancePool.get(
311                     PropsValues.USERS_SCREEN_NAME_GENERATOR);
312 
313             try {
314                 screenName = screenNameGenerator.generate(
315                     companyId, userId, emailAddress);
316             }
317             catch (Exception e) {
318                 throw new SystemException(e);
319             }
320         }
321 
322         User defaultUser = getDefaultUser(companyId);
323 
324         String fullName = ContactConstants.getFullName(
325             firstName, middleName, lastName);
326 
327         String greeting = LanguageUtil.format(
328             locale, "welcome-x", " " + fullName, false);
329 
330         User user = userPersistence.create(userId);
331 
332         user.setCompanyId(companyId);
333         user.setCreateDate(now);
334         user.setModifiedDate(now);
335         user.setDefaultUser(false);
336         user.setContactId(counterLocalService.increment());
337         user.setPassword(PwdEncryptor.encrypt(password1));
338         user.setPasswordUnencrypted(password1);
339         user.setPasswordEncrypted(true);
340         user.setPasswordReset(false);
341         user.setScreenName(screenName);
342         user.setEmailAddress(emailAddress);
343         user.setOpenId(openId);
344         user.setLanguageId(locale.toString());
345         user.setTimeZoneId(defaultUser.getTimeZoneId());
346         user.setGreeting(greeting);
347         user.setFirstName(firstName);
348         user.setMiddleName(middleName);
349         user.setLastName(lastName);
350         user.setJobTitle(jobTitle);
351         user.setActive(true);
352 
353         userPersistence.update(user, false);
354 
355         // Resources
356 
357         String creatorUserName = StringPool.BLANK;
358 
359         if (creatorUserId <= 0) {
360             creatorUserId = user.getUserId();
361 
362             // Don't grab the full name from the User object because it doesn't
363             // have a corresponding Contact object yet
364 
365             //creatorUserName = user.getFullName();
366         }
367         else {
368             User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
369 
370             creatorUserName = creatorUser.getFullName();
371         }
372 
373         resourceLocalService.addResources(
374             companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
375             false, false, false);
376 
377         // Expando
378 
379         user.setExpandoBridgeAttributes(serviceContext);
380 
381         // Mail
382 
383         if (user.hasCompanyMx()) {
384             mailService.addUser(
385                 companyId, userId, password1, firstName, middleName, lastName,
386                 emailAddress);
387         }
388 
389         // Contact
390 
391         Date birthday = PortalUtil.getDate(
392             birthdayMonth, birthdayDay, birthdayYear,
393             new ContactBirthdayException());
394 
395         Contact contact = contactPersistence.create(user.getContactId());
396 
397         contact.setCompanyId(user.getCompanyId());
398         contact.setUserId(creatorUserId);
399         contact.setUserName(creatorUserName);
400         contact.setCreateDate(now);
401         contact.setModifiedDate(now);
402         contact.setAccountId(company.getAccountId());
403         contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
404         contact.setFirstName(firstName);
405         contact.setMiddleName(middleName);
406         contact.setLastName(lastName);
407         contact.setPrefixId(prefixId);
408         contact.setSuffixId(suffixId);
409         contact.setMale(male);
410         contact.setBirthday(birthday);
411         contact.setJobTitle(jobTitle);
412 
413         contactPersistence.update(contact, false);
414 
415         // Group
416 
417         groupLocalService.addGroup(
418             user.getUserId(), User.class.getName(), user.getUserId(), null,
419             null, 0, StringPool.SLASH + screenName, true, null);
420 
421         // Groups
422 
423         Set<Long> groupIdsSet = SetUtil.fromArray(groupIds);
424 
425         String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
426             companyId, PropsKeys.ADMIN_DEFAULT_GROUP_NAMES, StringPool.NEW_LINE,
427             PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
428 
429         for (String defaultGroupName : defaultGroupNames) {
430             try {
431                 Group group = groupPersistence.findByC_N(
432                     companyId, defaultGroupName);
433 
434                 groupIdsSet.add(group.getGroupId());
435             }
436             catch (NoSuchGroupException nsge) {
437             }
438         }
439 
440         groupIds = ArrayUtil.toArray(
441             groupIdsSet.toArray(new Long[groupIdsSet.size()]));
442 
443         groupLocalService.addUserGroups(userId, groupIds);
444 
445         // Organizations
446 
447         updateOrganizations(userId, organizationIds);
448 
449         // Roles
450 
451         Set<Long> roleIdsSet = SetUtil.fromArray(roleIds);
452 
453         String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
454             companyId, PropsKeys.ADMIN_DEFAULT_ROLE_NAMES, StringPool.NEW_LINE,
455             PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
456 
457         for (String defaultRoleName : defaultRoleNames) {
458             try {
459                 Role role = rolePersistence.findByC_N(
460                     companyId, defaultRoleName);
461 
462                 roleIdsSet.add(role.getRoleId());
463             }
464             catch (NoSuchRoleException nsge) {
465             }
466         }
467 
468         roleIds = ArrayUtil.toArray(
469             roleIdsSet.toArray(new Long[roleIdsSet.size()]));
470 
471         roleIds = EnterpriseAdminUtil.addRequiredRoles(userId, roleIds);
472 
473         userPersistence.setRoles(userId, roleIds);
474 
475         // User groups
476 
477         Set<UserGroup> userGroups = new HashSet<UserGroup>();
478 
479         String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
480             companyId, PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
481             StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
482 
483         for (String defaultUserGroupName : defaultUserGroupNames) {
484             try {
485                 UserGroup userGroup = userGroupPersistence.findByC_N(
486                     companyId, defaultUserGroupName);
487 
488                 userGroups.add(userGroup);
489 
490                 copyUserGroupLayouts(
491                     userGroup.getUserGroupId(), new long[] {userId});
492             }
493             catch (NoSuchUserGroupException nsuge) {
494             }
495         }
496 
497         if (userGroupIds != null) {
498             for (long userGroupId : userGroupIds) {
499                 try{
500                     UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
501                         userGroupId);
502 
503                     userGroups.add(userGroup);
504 
505                     copyUserGroupLayouts(userGroupId, new long[] {userId});
506                 }
507                 catch (NoSuchUserGroupException nsuge) {
508                 }
509             }
510         }
511 
512         userPersistence.setUserGroups(
513             userId, ListUtil.fromCollection(userGroups));
514 
515         // Email
516 
517         if (sendEmail) {
518             try {
519                 sendEmail(user, password1);
520             }
521             catch (IOException ioe) {
522                 throw new SystemException(ioe);
523             }
524         }
525 
526         // Tags
527 
528         if (serviceContext != null) {
529             updateTagsAsset(
530                 creatorUserId, user, serviceContext.getTagsEntries());
531         }
532 
533         // Indexer
534 
535         try {
536             UserIndexer.updateUser(user);
537         }
538         catch (SearchException se) {
539             _log.error("Indexing " + userId, se);
540         }
541 
542         return user;
543     }
544 
545     @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
546     public int authenticateByEmailAddress(
547             long companyId, String emailAddress, String password,
548             Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
549         throws PortalException, SystemException {
550 
551         return authenticate(
552             companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
553             headerMap, parameterMap);
554     }
555 
556     @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
557     public int authenticateByScreenName(
558             long companyId, String screenName, String password,
559             Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
560         throws PortalException, SystemException {
561 
562         return authenticate(
563             companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
564             headerMap, parameterMap);
565     }
566 
567     @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
568     public int authenticateByUserId(
569             long companyId, long userId, String password,
570             Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
571         throws PortalException, SystemException {
572 
573         return authenticate(
574             companyId, String.valueOf(userId), password,
575             CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap);
576     }
577 
578     @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
579     public long authenticateForBasic(
580             long companyId, String authType, String login, String password)
581         throws PortalException, SystemException {
582 
583         try {
584             User user = null;
585 
586             if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
587                 user = getUserByEmailAddress(companyId, login);
588             }
589             else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
590                 user = getUserByScreenName(companyId, login);
591             }
592             else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
593                 user = getUserById(companyId, GetterUtil.getLong(login));
594             }
595 
596             if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
597                 return user.getUserId();
598             }
599 
600             String userPassword = user.getPassword();
601 
602             if (!user.isPasswordEncrypted()) {
603                 userPassword = PwdEncryptor.encrypt(userPassword);
604             }
605 
606             String encPassword = PwdEncryptor.encrypt(password);
607 
608             if (userPassword.equals(password) ||
609                 userPassword.equals(encPassword)) {
610 
611                 return user.getUserId();
612             }
613         }
614         catch (NoSuchUserException nsue) {
615         }
616 
617         return 0;
618     }
619 
620     @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
621     public boolean authenticateForJAAS(long userId, String encPassword) {
622         try {
623             User user = userPersistence.findByPrimaryKey(userId);
624 
625             if (user.isDefaultUser()) {
626                 _log.error(
627                     "The default user should never be allowed to authenticate");
628 
629                 return false;
630             }
631 
632             String password = user.getPassword();
633 
634             if (user.isPasswordEncrypted()) {
635                 if (password.equals(encPassword)) {
636                     return true;
637                 }
638 
639                 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
640                     encPassword = PwdEncryptor.encrypt(encPassword, password);
641 
642                     if (password.equals(encPassword)) {
643                         return true;
644                     }
645                 }
646             }
647             else {
648                 if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
649                     if (password.equals(encPassword)) {
650                         return true;
651                     }
652                 }
653 
654                 password = PwdEncryptor.encrypt(password);
655 
656                 if (password.equals(encPassword)) {
657                     return true;
658                 }
659             }
660         }
661         catch (Exception e) {
662             _log.error(e);
663         }
664 
665         return false;
666     }
667 
668     public void checkLockout(User user)
669         throws PortalException, SystemException {
670 
671         if (PortalLDAPUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
672             return;
673         }
674 
675         PasswordPolicy passwordPolicy = user.getPasswordPolicy();
676 
677         if (passwordPolicy.isLockout()) {
678 
679             // Reset failure count
680 
681             Date now = new Date();
682             int failedLoginAttempts = user.getFailedLoginAttempts();
683 
684             if (failedLoginAttempts > 0) {
685                 long failedLoginTime = user.getLastFailedLoginDate().getTime();
686                 long elapsedTime = now.getTime() - failedLoginTime;
687                 long requiredElapsedTime =
688                     passwordPolicy.getResetFailureCount() * 1000;
689 
690                 if ((requiredElapsedTime != 0) &&
691                     (elapsedTime > requiredElapsedTime)) {
692 
693                     user.setLastFailedLoginDate(null);
694                     user.setFailedLoginAttempts(0);
695                 }
696             }
697 
698             // Reset lockout
699 
700             if (user.isLockout()) {
701                 long lockoutTime = user.getLockoutDate().getTime();
702                 long elapsedTime = now.getTime() - lockoutTime;
703                 long requiredElapsedTime =
704                     passwordPolicy.getLockoutDuration() * 1000;
705 
706                 if ((requiredElapsedTime != 0) &&
707                     (elapsedTime > requiredElapsedTime)) {
708 
709                     user.setLockout(false);
710                     user.setLockoutDate(null);
711                 }
712             }
713 
714             if (user.isLockout()) {
715                 throw new UserLockoutException();
716             }
717         }
718     }
719 
720     public void checkLoginFailure(User user) throws SystemException {
721         Date now = new Date();
722 
723         int failedLoginAttempts = user.getFailedLoginAttempts();
724 
725         user.setLastFailedLoginDate(now);
726         user.setFailedLoginAttempts(++failedLoginAttempts);
727 
728         userPersistence.update(user, false);
729     }
730 
731     public void checkLoginFailureByEmailAddress(
732             long companyId, String emailAddress)
733         throws PortalException, SystemException {
734 
735         User user = getUserByEmailAddress(companyId, emailAddress);
736 
737         checkLoginFailure(user);
738     }
739 
740     public void checkLoginFailureById(long userId)
741         throws PortalException, SystemException {
742 
743         User user = userPersistence.findByPrimaryKey(userId);
744 
745         checkLoginFailure(user);
746     }
747 
748     public void checkLoginFailureByScreenName(long companyId, String screenName)
749         throws PortalException, SystemException {
750 
751         User user = getUserByScreenName(companyId, screenName);
752 
753         checkLoginFailure(user);
754     }
755 
756     public void checkPasswordExpired(User user)
757         throws PortalException, SystemException {
758 
759         if (PortalLDAPUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
760             return;
761         }
762 
763         PasswordPolicy passwordPolicy = user.getPasswordPolicy();
764 
765         // Check if password has expired
766 
767         if (isPasswordExpired(user)) {
768             int graceLoginCount = user.getGraceLoginCount();
769 
770             if (graceLoginCount < passwordPolicy.getGraceLimit()) {
771                 user.setGraceLoginCount(++graceLoginCount);
772 
773                 userPersistence.update(user, false);
774             }
775             else {
776                 throw new PasswordExpiredException();
777             }
778         }
779 
780         // Check if warning message should be sent
781 
782         if (isPasswordExpiringSoon(user)) {
783             user.setPasswordReset(true);
784 
785             userPersistence.update(user, false);
786         }
787 
788         // Check if user should be forced to change password on first login
789 
790         if (passwordPolicy.isChangeable() &&
791             passwordPolicy.isChangeRequired()) {
792 
793             if (user.getLastLoginDate() == null) {
794                 boolean passwordReset = false;
795 
796                 if (passwordPolicy.isChangeable() &&
797                     passwordPolicy.isChangeRequired()) {
798 
799                     passwordReset = true;
800                 }
801 
802                 user.setPasswordReset(passwordReset);
803 
804                 userPersistence.update(user, false);
805             }
806         }
807     }
808 
809     public void clearOrganizationUsers(long organizationId)
810         throws SystemException {
811 
812         organizationPersistence.clearUsers(organizationId);
813 
814         PermissionCacheUtil.clearCache();
815     }
816 
817     public void clearUserGroupUsers(long userGroupId) throws SystemException {
818         userGroupPersistence.clearUsers(userGroupId);
819 
820         PermissionCacheUtil.clearCache();
821     }
822 
823     public KeyValuePair decryptUserId(
824             long companyId, String name, String password)
825         throws PortalException, SystemException {
826 
827         Company company = companyPersistence.findByPrimaryKey(companyId);
828 
829         try {
830             name = Encryptor.decrypt(company.getKeyObj(), name);
831         }
832         catch (EncryptorException ee) {
833             throw new SystemException(ee);
834         }
835 
836         long userId = GetterUtil.getLong(name);
837 
838         User user = userPersistence.findByPrimaryKey(userId);
839 
840         try {
841             password = Encryptor.decrypt(company.getKeyObj(), password);
842         }
843         catch (EncryptorException ee) {
844             throw new SystemException(ee);
845         }
846 
847         String encPassword = PwdEncryptor.encrypt(password);
848 
849         if (user.getPassword().equals(encPassword)) {
850             if (isPasswordExpired(user)) {
851                 user.setPasswordReset(true);
852 
853                 userPersistence.update(user, false);
854             }
855 
856             return new KeyValuePair(name, password);
857         }
858         else {
859             throw new PrincipalException();
860         }
861     }
862 
863     public void deletePasswordPolicyUser(long passwordPolicyId, long userId)
864         throws SystemException {
865 
866         passwordPolicyRelLocalService.deletePasswordPolicyRel(
867             passwordPolicyId, User.class.getName(), userId);
868     }
869 
870     public void deletePortrait(long userId)
871         throws PortalException, SystemException {
872 
873         User user = userPersistence.findByPrimaryKey(userId);
874 
875         long portraitId = user.getPortraitId();
876 
877         if (portraitId > 0) {
878             user.setPortraitId(0);
879 
880             userPersistence.update(user, false);
881 
882             imageLocalService.deleteImage(portraitId);
883         }
884     }
885 
886     public void deleteRoleUser(long roleId, long userId)
887         throws SystemException {
888 
889         rolePersistence.removeUser(roleId, userId);
890 
891         PermissionCacheUtil.clearCache();
892     }
893 
894     public void deleteUser(long userId)
895         throws PortalException, SystemException {
896 
897         if (!PropsValues.USERS_DELETE) {
898             throw new RequiredUserException();
899         }
900 
901         User user = userPersistence.findByPrimaryKey(userId);
902 
903         // Indexer
904 
905         try {
906             UserIndexer.deleteUser(user.getCompanyId(), user.getUserId());
907         }
908         catch (SearchException se) {
909             _log.error("Indexing " + userId, se);
910         }
911 
912         // Browser tracker
913 
914         browserTrackerLocalService.deleteUserBrowserTracker(userId);
915 
916         // Group
917 
918         Group group = user.getGroup();
919 
920         if (group != null) {
921             groupLocalService.deleteGroup(group.getGroupId());
922         }
923 
924         // Portrait
925 
926         imageLocalService.deleteImage(user.getPortraitId());
927 
928         // Password policy relation
929 
930         passwordPolicyRelLocalService.deletePasswordPolicyRel(
931             User.class.getName(), userId);
932 
933         // Old passwords
934 
935         passwordTrackerLocalService.deletePasswordTrackers(userId);
936 
937         // Subscriptions
938 
939         subscriptionLocalService.deleteSubscriptions(userId);
940 
941         // External user ids
942 
943         userIdMapperLocalService.deleteUserIdMappers(userId);
944 
945         // Announcements
946 
947         announcementsDeliveryLocalService.deleteDeliveries(userId);
948 
949         // Blogs
950 
951         blogsStatsUserLocalService.deleteStatsUserByUserId(userId);
952 
953         // Document library
954 
955         dlFileRankLocalService.deleteFileRanks(userId);
956 
957         // Expando
958 
959         expandoValueLocalService.deleteValues(User.class.getName(), userId);
960 
961         // Message boards
962 
963         mbBanLocalService.deleteBansByBanUserId(userId);
964         mbMessageFlagLocalService.deleteFlags(userId);
965         mbStatsUserLocalService.deleteStatsUsersByUserId(userId);
966 
967         // Shopping cart
968 
969         shoppingCartLocalService.deleteUserCarts(userId);
970 
971         // Social
972 
973         socialActivityLocalService.deleteUserActivities(userId);
974         socialRequestLocalService.deleteReceiverUserRequests(userId);
975         socialRequestLocalService.deleteUserRequests(userId);
976 
977         // Tags
978 
979         tagsAssetLocalService.deleteAsset(User.class.getName(), userId);
980 
981         // Mail
982 
983         mailService.deleteUser(user.getCompanyId(), userId);
984 
985         // Contact
986 
987         try {
988             contactLocalService.deleteContact(user.getContactId());
989         }
990         catch (NoSuchContactException nsce) {
991         }
992 
993         // Resources
994 
995         resourceLocalService.deleteResource(
996             user.getCompanyId(), User.class.getName(),
997             ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
998 
999         // Group roles
1000
1001        userGroupRoleLocalService.deleteUserGroupRolesByUserId(userId);
1002
1003        // User
1004
1005        userPersistence.remove(userId);
1006
1007        // Permission cache
1008
1009        PermissionCacheUtil.clearCache();
1010    }
1011
1012    public String encryptUserId(String name)
1013        throws PortalException, SystemException {
1014
1015        long userId = GetterUtil.getLong(name);
1016
1017        User user = userPersistence.findByPrimaryKey(userId);
1018
1019        Company company = companyPersistence.findByPrimaryKey(
1020            user.getCompanyId());
1021
1022        try {
1023            return Encryptor.encrypt(company.getKeyObj(), name);
1024        }
1025        catch (EncryptorException ee) {
1026            throw new SystemException(ee);
1027        }
1028    }
1029
1030    public User getDefaultUser(long companyId)
1031        throws PortalException, SystemException {
1032
1033        User userModel = _defaultUsers.get(companyId);
1034
1035        if (userModel == null) {
1036            userModel = userPersistence.findByC_DU(companyId, true);
1037
1038            _defaultUsers.put(companyId, userModel);
1039        }
1040
1041        return userModel;
1042    }
1043
1044    public long getDefaultUserId(long companyId)
1045        throws PortalException, SystemException {
1046
1047        User user = getDefaultUser(companyId);
1048
1049        return user.getUserId();
1050    }
1051
1052    public long[] getGroupUserIds(long groupId) throws SystemException {
1053        return getUserIds(getGroupUsers(groupId));
1054    }
1055
1056    public List<User> getGroupUsers(long groupId) throws SystemException {
1057        return groupPersistence.getUsers(groupId);
1058    }
1059
1060    public int getGroupUsersCount(long groupId) throws SystemException {
1061        return groupPersistence.getUsersSize(groupId);
1062    }
1063
1064    public int getGroupUsersCount(long groupId, boolean active)
1065        throws PortalException, SystemException {
1066
1067        Group group = groupPersistence.findByPrimaryKey(groupId);
1068
1069        LinkedHashMap<String, Object> params =
1070            new LinkedHashMap<String, Object>();
1071
1072        params.put("usersGroups", new Long(groupId));
1073
1074        return searchCount(group.getCompanyId(), null, active, params);
1075    }
1076
1077    public List<User> getNoAnnouncementsDeliveries(String type)
1078        throws SystemException {
1079
1080        return userFinder.findByNoAnnouncementsDeliveries(type);
1081    }
1082
1083    public List<User> getNoContacts() throws SystemException {
1084        return userFinder.findByNoContacts();
1085    }
1086
1087    public List<User> getNoGroups() throws SystemException {
1088        return userFinder.findByNoGroups();
1089    }
1090
1091    public long[] getOrganizationUserIds(long organizationId)
1092        throws SystemException {
1093
1094        return getUserIds(getOrganizationUsers(organizationId));
1095    }
1096
1097    public List<User> getOrganizationUsers(long organizationId)
1098        throws SystemException {
1099
1100        return organizationPersistence.getUsers(organizationId);
1101    }
1102
1103    public int getOrganizationUsersCount(long organizationId)
1104        throws SystemException {
1105
1106        return organizationPersistence.getUsersSize(organizationId);
1107    }
1108
1109    public int getOrganizationUsersCount(long organizationId, boolean active)
1110        throws PortalException, SystemException {
1111
1112        Organization organization = organizationPersistence.findByPrimaryKey(
1113            organizationId);
1114
1115        LinkedHashMap<String, Object> params =
1116            new LinkedHashMap<String, Object>();
1117
1118        params.put("usersOrgs", new Long(organizationId));
1119
1120        return searchCount(organization.getCompanyId(), null, active, params);
1121    }
1122
1123    public List<User> getPermissionUsers(
1124            long companyId, long groupId, String name, String primKey,
1125            String actionId, String firstName, String middleName,
1126            String lastName, String emailAddress, boolean andOperator,
1127            int start, int end)
1128        throws SystemException {
1129
1130        int orgGroupPermissionsCount =
1131            permissionUserFinder.countByOrgGroupPermissions(
1132                companyId, name, primKey, actionId);
1133
1134        if (orgGroupPermissionsCount > 0) {
1135            return permissionUserFinder.findByUserAndOrgGroupPermission(
1136                companyId, name, primKey, actionId, firstName, middleName,
1137                lastName, emailAddress, andOperator, start, end);
1138        }
1139        else {
1140            return permissionUserFinder.findByPermissionAndRole(
1141                companyId, groupId, name, primKey, actionId, firstName,
1142                middleName, lastName, emailAddress, andOperator, start, end);
1143        }
1144    }
1145
1146    public int getPermissionUsersCount(
1147            long companyId, long groupId, String name, String primKey,
1148            String actionId, String firstName, String middleName,
1149            String lastName, String emailAddress, boolean andOperator)
1150        throws SystemException {
1151
1152        int orgGroupPermissionsCount =
1153            permissionUserFinder.countByOrgGroupPermissions(
1154                companyId, name, primKey, actionId);
1155
1156        if (orgGroupPermissionsCount > 0) {
1157            return permissionUserFinder.countByUserAndOrgGroupPermission(
1158                companyId, name, primKey, actionId, firstName, middleName,
1159                lastName, emailAddress, andOperator);
1160        }
1161        else {
1162            return permissionUserFinder.countByPermissionAndRole(
1163                companyId, groupId, name, primKey, actionId, firstName,
1164                middleName, lastName, emailAddress, andOperator);
1165        }
1166    }
1167
1168    public long[] getRoleUserIds(long roleId) throws SystemException {
1169        return getUserIds(getRoleUsers(roleId));
1170    }
1171
1172    public List<User> getRoleUsers(long roleId) throws SystemException {
1173        return rolePersistence.getUsers(roleId);
1174    }
1175
1176    public List<User> getRoleUsers(long roleId, int start, int end)
1177        throws SystemException {
1178
1179        return rolePersistence.getUsers(roleId, start, end);
1180    }
1181
1182    public int getRoleUsersCount(long roleId) throws SystemException {
1183        return rolePersistence.getUsersSize(roleId);
1184    }
1185
1186    public int getRoleUsersCount(long roleId, boolean active)
1187        throws PortalException, SystemException {
1188
1189        Role role = rolePersistence.findByPrimaryKey(
1190            roleId);
1191
1192        LinkedHashMap<String, Object> params =
1193            new LinkedHashMap<String, Object>();
1194
1195        params.put("usersRoles", new Long(roleId));
1196
1197        return searchCount(role.getCompanyId(), null, active, params);
1198    }
1199
1200    public List<User> getSocialUsers(
1201            long userId, int start, int end, OrderByComparator obc)
1202        throws PortalException, SystemException {
1203
1204        User user = userPersistence.findByPrimaryKey(userId);
1205
1206        LinkedHashMap<String, Object> params =
1207            new LinkedHashMap<String, Object>();
1208
1209        params.put("socialRelation", new Long[] {userId});
1210
1211        return search(
1212            user.getCompanyId(), null, true, params, start, end, obc);
1213    }
1214
1215    public List<User> getSocialUsers(
1216            long userId, int type, int start, int end, OrderByComparator obc)
1217        throws PortalException, SystemException {
1218
1219        User user = userPersistence.findByPrimaryKey(userId);
1220
1221        LinkedHashMap<String, Object> params =
1222            new LinkedHashMap<String, Object>();
1223
1224        params.put("socialRelationType", new Long[] {userId, new Long(type)});
1225
1226        return search(user.getCompanyId(), null, true, params, start, end, obc);
1227    }
1228
1229    public List<User> getSocialUsers(
1230            long userId1, long userId2, int start, int end,
1231            OrderByComparator obc)
1232        throws PortalException, SystemException {
1233
1234        User user1 = userPersistence.findByPrimaryKey(userId1);
1235
1236        LinkedHashMap<String, Object> params =
1237            new LinkedHashMap<String, Object>();
1238
1239        params.put("socialMutualRelation", new Long[] {userId1, userId2});
1240
1241        return search(
1242            user1.getCompanyId(), null, true, params, start, end, obc);
1243    }
1244
1245    public List<User> getSocialUsers(
1246            long userId1, long userId2, int type, int start, int end,
1247            OrderByComparator obc)
1248        throws PortalException, SystemException {
1249
1250        User user1 = userPersistence.findByPrimaryKey(userId1);
1251
1252        LinkedHashMap<String, Object> params =
1253            new LinkedHashMap<String, Object>();
1254
1255        params.put(
1256            "socialMutualRelationType",
1257            new Long[] {userId1, new Long(type), userId2, new Long(type)});
1258
1259        return search(
1260            user1.getCompanyId(), null, true, params, start, end, obc);
1261    }
1262
1263    public int getSocialUsersCount(long userId)
1264        throws PortalException, SystemException {
1265
1266        User user = userPersistence.findByPrimaryKey(userId);
1267
1268        LinkedHashMap<String, Object> params =
1269            new LinkedHashMap<String, Object>();
1270
1271        params.put("socialRelation", new Long[] {userId});
1272
1273        return searchCount(user.getCompanyId(), null, true, params);
1274    }
1275
1276    public int getSocialUsersCount(long userId, int type)
1277        throws PortalException, SystemException {
1278
1279        User user = userPersistence.findByPrimaryKey(userId);
1280
1281        LinkedHashMap<String, Object> params =
1282            new LinkedHashMap<String, Object>();
1283
1284        params.put("socialRelationType", new Long[] {userId, new Long(type)});
1285
1286        return searchCount(user.getCompanyId(), null, true, params);
1287    }
1288
1289    public int getSocialUsersCount(long userId1, long userId2)
1290        throws PortalException, SystemException {
1291
1292        User user1 = userPersistence.findByPrimaryKey(userId1);
1293
1294        LinkedHashMap<String, Object> params =
1295            new LinkedHashMap<String, Object>();
1296
1297        params.put("socialMutualRelation", new Long[] {userId1, userId2});
1298
1299        return searchCount(user1.getCompanyId(), null, true, params);
1300    }
1301
1302    public int getSocialUsersCount(long userId1, long userId2, int type)
1303        throws PortalException, SystemException {
1304
1305        User user1 = userPersistence.findByPrimaryKey(userId1);
1306
1307        LinkedHashMap<String, Object> params =
1308            new LinkedHashMap<String, Object>();
1309
1310        params.put(
1311            "socialMutualRelationType",
1312            new Long[] {userId1, new Long(type), userId2, new Long(type)});
1313
1314        return searchCount(user1.getCompanyId(), null, true, params);
1315    }
1316
1317    public List<User> getUserGroupUsers(long userGroupId)
1318        throws SystemException {
1319
1320        return userGroupPersistence.getUsers(userGroupId);
1321    }
1322
1323    public int getUserGroupUsersCount(long userGroupId) throws SystemException {
1324        return userGroupPersistence.getUsersSize(userGroupId);
1325    }
1326
1327    public int getUserGroupUsersCount(long userGroupId, boolean active)
1328        throws PortalException, SystemException {
1329
1330        UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
1331            userGroupId);
1332
1333        LinkedHashMap<String, Object> params =
1334            new LinkedHashMap<String, Object>();
1335
1336        params.put("usersUserGroups", new Long(userGroupId));
1337
1338        return searchCount(userGroup.getCompanyId(), null, active, params);
1339    }
1340
1341    public User getUserByContactId(long contactId)
1342        throws PortalException, SystemException {
1343
1344        return userPersistence.findByContactId(contactId);
1345    }
1346
1347    public User getUserByEmailAddress(long companyId, String emailAddress)
1348        throws PortalException, SystemException {
1349
1350        emailAddress = emailAddress.trim().toLowerCase();
1351
1352        return userPersistence.findByC_EA(companyId, emailAddress);
1353    }
1354
1355    public User getUserById(long userId)
1356        throws PortalException, SystemException {
1357
1358        return userPersistence.findByPrimaryKey(userId);
1359    }
1360
1361    public User getUserById(long companyId, long userId)
1362        throws PortalException, SystemException {
1363
1364        return userPersistence.findByC_U(companyId, userId);
1365    }
1366
1367    public User getUserByOpenId(String openId)
1368        throws PortalException, SystemException {
1369
1370        return userPersistence.findByOpenId(openId);
1371    }
1372
1373    public User getUserByPortraitId(long portraitId)
1374        throws PortalException, SystemException {
1375
1376        return userPersistence.findByPortraitId(portraitId);
1377    }
1378
1379    public User getUserByScreenName(long companyId, String screenName)
1380        throws PortalException, SystemException {
1381
1382        screenName = getScreenName(screenName);
1383
1384        return userPersistence.findByC_SN(companyId, screenName);
1385    }
1386
1387    public User getUserByUuid(String uuid)
1388        throws PortalException, SystemException {
1389
1390        List<User> users = userPersistence.findByUuid(uuid);
1391
1392        if (users.isEmpty()) {
1393            throw new NoSuchUserException();
1394        }
1395        else {
1396            return users.get(0);
1397        }
1398    }
1399
1400    public long getUserIdByEmailAddress(long companyId, String emailAddress)
1401        throws PortalException, SystemException {
1402
1403        emailAddress = emailAddress.trim().toLowerCase();
1404
1405        User user = userPersistence.findByC_EA(companyId, emailAddress);
1406
1407        return user.getUserId();
1408    }
1409
1410    public long getUserIdByScreenName(long companyId, String screenName)
1411        throws PortalException, SystemException {
1412
1413        screenName = getScreenName(screenName);
1414
1415        User user = userPersistence.findByC_SN(companyId, screenName);
1416
1417        return user.getUserId();
1418    }
1419
1420    public boolean hasGroupUser(long groupId, long userId)
1421        throws SystemException {
1422
1423        return groupPersistence.containsUser(groupId, userId);
1424    }
1425
1426    public boolean hasOrganizationUser(long organizationId, long userId)
1427        throws SystemException {
1428
1429        return organizationPersistence.containsUser(organizationId, userId);
1430    }
1431
1432    public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
1433        throws SystemException {
1434
1435        return passwordPolicyRelLocalService.hasPasswordPolicyRel(
1436            passwordPolicyId, User.class.getName(), userId);
1437    }
1438
1439    public boolean hasRoleUser(long roleId, long userId)
1440        throws SystemException {
1441
1442        return rolePersistence.containsUser(roleId, userId);
1443    }
1444
1445    /**
1446     * Returns true if the user has the role.
1447     *
1448     * @return true if the user has the role
1449     */
1450    public boolean hasRoleUser(
1451            long companyId, String name, long userId, boolean inherited)
1452        throws PortalException, SystemException {
1453
1454        return roleLocalService.hasUserRole(userId, companyId, name, inherited);
1455    }
1456
1457    public boolean hasUserGroupUser(long userGroupId, long userId)
1458        throws SystemException {
1459
1460        return userGroupPersistence.containsUser(userGroupId, userId);
1461    }
1462
1463    public boolean isPasswordExpired(User user)
1464        throws PortalException, SystemException {
1465
1466        PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1467
1468        if (passwordPolicy.getExpireable()) {
1469            Date now = new Date();
1470
1471            if (user.getPasswordModifiedDate() == null) {
1472                user.setPasswordModifiedDate(now);
1473
1474                userLocalService.updateUser(user, false);
1475            }
1476
1477            long passwordStartTime = user.getPasswordModifiedDate().getTime();
1478            long elapsedTime = now.getTime() - passwordStartTime;
1479
1480            if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
1481                return true;
1482            }
1483            else {
1484                return false;
1485            }
1486        }
1487
1488        return false;
1489    }
1490
1491    public boolean isPasswordExpiringSoon(User user)
1492        throws PortalException, SystemException {
1493
1494        PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1495
1496        if (passwordPolicy.isExpireable()) {
1497            Date now = new Date();
1498
1499            if (user.getPasswordModifiedDate() == null) {
1500                user.setPasswordModifiedDate(now);
1501
1502                userLocalService.updateUser(user, false);
1503            }
1504
1505            long timeModified = user.getPasswordModifiedDate().getTime();
1506            long passwordExpiresOn =
1507                (passwordPolicy.getMaxAge() * 1000) + timeModified;
1508
1509            long timeStartWarning =
1510                passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
1511
1512            if (now.getTime() > timeStartWarning) {
1513                return true;
1514            }
1515            else {
1516                return false;
1517            }
1518        }
1519
1520        return false;
1521    }
1522
1523    public void reIndex(long userId) throws SystemException {
1524        if (SearchEngineUtil.isIndexReadOnly()) {
1525            return;
1526        }
1527
1528        try {
1529            UserIndexer.updateUsers(new long[] {userId});
1530        }
1531        catch (SearchException se) {
1532            throw new SystemException(se);
1533        }
1534    }
1535
1536    public void reIndex(String[] ids) throws SystemException {
1537        if (SearchEngineUtil.isIndexReadOnly()) {
1538            return;
1539        }
1540
1541        long companyId = GetterUtil.getLong(ids[0]);
1542
1543        try {
1544            reIndexUsers(companyId);
1545        }
1546        catch (SystemException se) {
1547            throw se;
1548        }
1549        catch (Exception e) {
1550            throw new SystemException(e);
1551        }
1552    }
1553
1554    public Hits search(
1555            long companyId, String keywords, Boolean active,
1556            LinkedHashMap<String, Object> params, int start, int end, Sort sort)
1557        throws SystemException {
1558
1559        String firstName = null;
1560        String middleName = null;
1561        String lastName = null;
1562        String screenName = null;
1563        String emailAddress = null;
1564        boolean andOperator = false;
1565
1566        if (Validator.isNotNull(keywords)) {
1567            firstName = keywords;
1568            middleName = keywords;
1569            lastName = keywords;
1570            screenName = keywords;
1571            emailAddress = keywords;
1572        }
1573        else {
1574            andOperator = true;
1575        }
1576
1577        return search(
1578            companyId, firstName, middleName, lastName, screenName,
1579            emailAddress, active, params, andOperator, start, end, sort);
1580    }
1581
1582    public Hits search(
1583            long companyId, String firstName, String middleName,
1584            String lastName, String screenName, String emailAddress,
1585            Boolean active, LinkedHashMap<String, Object> params,
1586            boolean andSearch, int start, int end, Sort sort)
1587        throws SystemException {
1588
1589        try {
1590            BooleanQuery contextQuery = BooleanQueryFactoryUtil.create();
1591
1592            contextQuery.addRequiredTerm(
1593                Field.PORTLET_ID, UserIndexer.PORTLET_ID);
1594
1595            if (active != null) {
1596                contextQuery.addRequiredTerm("active", active);
1597            }
1598
1599            BooleanQuery searchQuery = BooleanQueryFactoryUtil.create();
1600
1601            if (Validator.isNotNull(firstName)) {
1602                if (andSearch) {
1603                    searchQuery.addRequiredTerm("firstName", firstName, true);
1604                }
1605                else {
1606                    searchQuery.addTerm("firstName", firstName, true);
1607                }
1608            }
1609
1610            if (Validator.isNotNull(middleName)) {
1611                if (andSearch) {
1612                    searchQuery.addRequiredTerm("middleName", middleName, true);
1613                }
1614                else {
1615                    searchQuery.addTerm("middleName", middleName, true);
1616                }
1617            }
1618
1619            if (Validator.isNotNull(lastName)) {
1620                if (andSearch) {
1621                    searchQuery.addRequiredTerm("lastName", lastName, true);
1622                }
1623                else {
1624                    searchQuery.addTerm("lastName", lastName, true);
1625                }
1626            }
1627
1628            if (Validator.isNotNull(screenName)) {
1629                if (andSearch) {
1630                    searchQuery.addRequiredTerm("screenName", screenName, true);
1631                }
1632                else {
1633                    searchQuery.addTerm("screenName", screenName, true);
1634                }
1635            }
1636
1637            if (Validator.isNotNull(emailAddress)) {
1638                if (andSearch) {
1639                    searchQuery.addRequiredTerm(
1640                        "emailAddress", emailAddress, true);
1641                }
1642                else {
1643                    searchQuery.addTerm("emailAddress", emailAddress, true);
1644                }
1645            }
1646
1647            populateQuery(contextQuery, searchQuery, params, andSearch);
1648
1649            BooleanQuery fullQuery = BooleanQueryFactoryUtil.create();
1650
1651            fullQuery.add(contextQuery, BooleanClauseOccur.MUST);
1652
1653            if (searchQuery.clauses().size() > 0) {
1654                fullQuery.add(searchQuery, BooleanClauseOccur.MUST);
1655            }
1656
1657            return SearchEngineUtil.search(
1658                companyId, fullQuery, sort, start, end);
1659        }
1660        catch (Exception e) {
1661            throw new SystemException(e);
1662        }
1663    }
1664
1665    public List<User> search(
1666            long companyId, String keywords, Boolean active,
1667            LinkedHashMap<String, Object> params, int start, int end,
1668            OrderByComparator obc)
1669        throws SystemException {
1670
1671        return userFinder.findByKeywords(
1672            companyId, keywords, active, params, start, end, obc);
1673    }
1674
1675    public List<User> search(
1676            long companyId, String firstName, String middleName,
1677            String lastName, String screenName, String emailAddress,
1678            Boolean active, LinkedHashMap<String, Object> params,
1679            boolean andSearch, int start, int end, OrderByComparator obc)
1680        throws SystemException {
1681
1682        return userFinder.findByC_FN_MN_LN_SN_EA_A(
1683            companyId, firstName, middleName, lastName, screenName,
1684            emailAddress, active, params, andSearch, start, end, obc);
1685    }
1686
1687    public int searchCount(
1688            long companyId, String keywords, Boolean active,
1689            LinkedHashMap<String, Object> params)
1690        throws SystemException {
1691
1692        return userFinder.countByKeywords(companyId, keywords, active, params);
1693    }
1694
1695    public int searchCount(
1696            long companyId, String firstName, String middleName,
1697            String lastName, String screenName, String emailAddress,
1698            Boolean active, LinkedHashMap<String, Object> params,
1699            boolean andSearch)
1700        throws SystemException {
1701
1702        return userFinder.countByC_FN_MN_LN_SN_EA_A(
1703            companyId, firstName, middleName, lastName, screenName,
1704            emailAddress, active, params, andSearch);
1705    }
1706
1707    public void sendPassword(
1708            long companyId, String emailAddress, String remoteAddr,
1709            String remoteHost, String userAgent, String fromName,
1710            String fromAddress, String subject, String body)
1711        throws PortalException, SystemException {
1712
1713        try {
1714            doSendPassword(
1715                companyId, emailAddress, remoteAddr, remoteHost, userAgent,
1716                fromName, fromAddress, subject, body);
1717        }
1718        catch (IOException ioe) {
1719            throw new SystemException(ioe);
1720        }
1721    }
1722
1723    public void setRoleUsers(long roleId, long[] userIds)
1724        throws SystemException {
1725
1726        rolePersistence.setUsers(roleId, userIds);
1727
1728        try {
1729            UserIndexer.updateUsers(userIds);
1730        }
1731        catch (SearchException se) {
1732            _log.error("Indexing " + StringUtil.merge(userIds), se);
1733        }
1734
1735        PermissionCacheUtil.clearCache();
1736    }
1737
1738    public void setUserGroupUsers(long userGroupId, long[] userIds)
1739        throws PortalException, SystemException {
1740
1741        copyUserGroupLayouts(userGroupId, userIds);
1742
1743        userGroupPersistence.setUsers(userGroupId, userIds);
1744
1745        try {
1746            UserIndexer.updateUsers(userIds);
1747        }
1748        catch (SearchException se) {
1749            _log.error("Indexing " + StringUtil.merge(userIds), se);
1750        }
1751
1752        PermissionCacheUtil.clearCache();
1753    }
1754
1755    public void unsetGroupUsers(long groupId, long[] userIds)
1756        throws SystemException {
1757
1758        userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
1759
1760        groupPersistence.removeUsers(groupId, userIds);
1761
1762        try {
1763            UserIndexer.updateUsers(userIds);
1764        }
1765        catch (SearchException se) {
1766            _log.error("Indexing " + StringUtil.merge(userIds), se);
1767        }
1768
1769        PermissionCacheUtil.clearCache();
1770    }
1771
1772    public void unsetOrganizationUsers(long organizationId, long[] userIds)
1773        throws PortalException, SystemException {
1774
1775        Organization organization = organizationPersistence.findByPrimaryKey(
1776            organizationId);
1777
1778        Group group = organization.getGroup();
1779
1780        long groupId = group.getGroupId();
1781
1782        userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
1783
1784        organizationPersistence.removeUsers(organizationId, userIds);
1785
1786        try {
1787            UserIndexer.updateUsers(userIds);
1788        }
1789        catch (SearchException se) {
1790            _log.error("Indexing " + StringUtil.merge(userIds), se);
1791        }
1792
1793        PermissionCacheUtil.clearCache();
1794    }
1795
1796    public void unsetPasswordPolicyUsers(
1797            long passwordPolicyId, long[] userIds)
1798        throws SystemException {
1799
1800        passwordPolicyRelLocalService.deletePasswordPolicyRels(
1801            passwordPolicyId, User.class.getName(), userIds);
1802    }
1803
1804    public void unsetRoleUsers(long roleId, long[] userIds)
1805        throws PortalException, SystemException {
1806
1807        Role role = rolePersistence.findByPrimaryKey(roleId);
1808
1809        if (role.getName().equals(RoleConstants.USER)) {
1810            return;
1811        }
1812
1813        rolePersistence.removeUsers(roleId, userIds);
1814
1815        try {
1816            UserIndexer.updateUsers(userIds);
1817        }
1818        catch (SearchException se) {
1819            _log.error("Indexing " + StringUtil.merge(userIds), se);
1820        }
1821
1822        PermissionCacheUtil.clearCache();
1823    }
1824
1825    public void unsetRoleUsers(long roleId, List<User> users)
1826        throws PortalException, SystemException {
1827
1828        Role role = rolePersistence.findByPrimaryKey(roleId);
1829
1830        if (role.getName().equals(RoleConstants.USER)) {
1831            return;
1832        }
1833
1834        rolePersistence.removeUsers(roleId, users);
1835
1836        try {
1837            UserIndexer.updateUsers(users);
1838        }
1839        catch (SearchException se) {
1840            _log.error("Indexing " + ListUtil.toString(users, "userId"), se);
1841        }
1842
1843        PermissionCacheUtil.clearCache();
1844    }
1845
1846    public void unsetUserGroupUsers(long userGroupId, long[] userIds)
1847        throws SystemException {
1848
1849        userGroupPersistence.removeUsers(userGroupId, userIds);
1850
1851        try {
1852            UserIndexer.updateUsers(userIds);
1853        }
1854        catch (SearchException se) {
1855            _log.error("Indexing " + StringUtil.merge(userIds), se);
1856        }
1857
1858        PermissionCacheUtil.clearCache();
1859    }
1860
1861    public User updateActive(long userId, boolean active)
1862        throws PortalException, SystemException {
1863
1864        User user = userPersistence.findByPrimaryKey(userId);
1865
1866        user.setActive(active);
1867
1868        userPersistence.update(user, false);
1869
1870        try {
1871            UserIndexer.updateUsers(new long[] {userId});
1872        }
1873        catch (SearchException se) {
1874            _log.error("Indexing " + userId, se);
1875        }
1876
1877        return user;
1878    }
1879
1880    public User updateAgreedToTermsOfUse(
1881            long userId, boolean agreedToTermsOfUse)
1882        throws PortalException, SystemException {
1883
1884        User user = userPersistence.findByPrimaryKey(userId);
1885
1886        user.setAgreedToTermsOfUse(agreedToTermsOfUse);
1887
1888        userPersistence.update(user, false);
1889
1890        return user;
1891    }
1892
1893    public User updateCreateDate(long userId, Date createDate)
1894        throws PortalException, SystemException {
1895
1896        User user = userPersistence.findByPrimaryKey(userId);
1897
1898        user.setCreateDate(createDate);
1899
1900        userPersistence.update(user, false);
1901
1902        return user;
1903    }
1904
1905    public User updateEmailAddress(
1906            long userId, String password, String emailAddress1,
1907            String emailAddress2)
1908        throws PortalException, SystemException {
1909
1910        emailAddress1 = emailAddress1.trim().toLowerCase();
1911        emailAddress2 = emailAddress2.trim().toLowerCase();
1912
1913        if (!emailAddress1.equals(emailAddress2)) {
1914            throw new UserEmailAddressException();
1915        }
1916
1917        User user = userPersistence.findByPrimaryKey(userId);
1918
1919        validateEmailAddress(user.getCompanyId(), emailAddress1);
1920        validateEmailAddress(user.getCompanyId(), emailAddress2);
1921
1922        if (!user.getEmailAddress().equalsIgnoreCase(emailAddress1)) {
1923            if (userPersistence.fetchByC_EA(
1924                    user.getCompanyId(), emailAddress1) != null) {
1925
1926                throw new DuplicateUserEmailAddressException();
1927            }
1928        }
1929
1930        setEmailAddress(
1931            user, password, user.getFirstName(), user.getMiddleName(),
1932            user.getLastName(), emailAddress1);
1933
1934        userPersistence.update(user, false);
1935
1936        return user;
1937    }
1938
1939    public void updateGroups(long userId, long[] newGroupIds)
1940        throws PortalException, SystemException {
1941
1942        if (newGroupIds == null) {
1943            return;
1944        }
1945
1946        List<Group> oldGroups = userPersistence.getGroups(userId);
1947
1948        List<Long> oldGroupIds = new ArrayList<Long>(oldGroups.size());
1949
1950        for (Group oldGroup : oldGroups) {
1951            long oldGroupId = oldGroup.getGroupId();
1952
1953            oldGroupIds.add(oldGroupId);
1954
1955            if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
1956                unsetGroupUsers(oldGroupId, new long[] {userId});
1957            }
1958        }
1959
1960        for (long newGroupId : newGroupIds) {
1961            if (!oldGroupIds.contains(newGroupId)) {
1962                addGroupUsers(newGroupId, new long[] {userId});
1963            }
1964        }
1965
1966        try {
1967            UserIndexer.updateUsers(new long[] {userId});
1968        }
1969        catch (SearchException se) {
1970            _log.error("Indexing " + userId, se);
1971        }
1972
1973        PermissionCacheUtil.clearCache();
1974    }
1975
1976    public User updateLastLogin(long userId, String loginIP)
1977        throws PortalException, SystemException {
1978
1979        User user = userPersistence.findByPrimaryKey(userId);
1980
1981        Date lastLoginDate = user.getLoginDate();
1982
1983        if (lastLoginDate == null) {
1984            lastLoginDate = new Date();
1985        }
1986
1987        user.setLoginDate(new Date());
1988        user.setLoginIP(loginIP);
1989        user.setLastLoginDate(lastLoginDate);
1990        user.setLastLoginIP(user.getLoginIP());
1991        user.setLastFailedLoginDate(null);
1992        user.setFailedLoginAttempts(0);
1993
1994        userPersistence.update(user, false);
1995
1996        return user;
1997    }
1998
1999    public User updateLockout(User user, boolean lockout)
2000        throws PortalException, SystemException {
2001
2002        PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2003
2004        if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
2005            return user;
2006        }
2007
2008        Date lockoutDate = null;
2009
2010        if (lockout) {
2011            lockoutDate = new Date();
2012        }
2013
2014        user.setLockout(lockout);
2015        user.setLockoutDate(lockoutDate);
2016
2017        if (!lockout) {
2018            user.setLastFailedLoginDate(lockoutDate);
2019            user.setFailedLoginAttempts(0);
2020        }
2021
2022        userPersistence.update(user, false);
2023
2024        return user;
2025    }
2026
2027    public User updateLockoutByEmailAddress(
2028            long companyId, String emailAddress, boolean lockout)
2029        throws PortalException, SystemException {
2030
2031        User user = getUserByEmailAddress(companyId, emailAddress);
2032
2033        return updateLockout(user, lockout);
2034    }
2035
2036    public User updateLockoutById(long userId, boolean lockout)
2037        throws PortalException, SystemException {
2038
2039        User user = userPersistence.findByPrimaryKey(userId);
2040
2041        return updateLockout(user, lockout);
2042    }
2043
2044    public User updateLockoutByScreenName(
2045            long companyId, String screenName, boolean lockout)
2046        throws PortalException, SystemException {
2047
2048        User user = getUserByScreenName(companyId, screenName);
2049
2050        return updateLockout(user, lockout);
2051    }
2052
2053    public User updateModifiedDate(long userId, Date modifiedDate)
2054        throws PortalException, SystemException {
2055
2056        User user = userPersistence.findByPrimaryKey(userId);
2057
2058        user.setModifiedDate(modifiedDate);
2059
2060        userPersistence.update(user, false);
2061
2062        return user;
2063    }
2064
2065    public void updateOpenId(long userId, String openId)
2066        throws PortalException, SystemException {
2067
2068        openId = openId.trim();
2069
2070        User user = userPersistence.findByPrimaryKey(userId);
2071
2072        user.setOpenId(openId);
2073
2074        userPersistence.update(user, false);
2075    }
2076
2077    public void updateOrganizations(long userId, long[] newOrganizationIds)
2078        throws PortalException, SystemException {
2079
2080        if (newOrganizationIds == null) {
2081            return;
2082        }
2083
2084        List<Organization> oldOrganizations = userPersistence.getOrganizations(
2085            userId);
2086
2087        List<Long> oldOrganizationIds = new ArrayList<Long>(
2088            oldOrganizations.size());
2089
2090        for (Organization oldOrganization : oldOrganizations) {
2091            long oldOrganizationId = oldOrganization.getOrganizationId();
2092
2093            oldOrganizationIds.add(oldOrganizationId);
2094
2095            if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
2096                unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
2097            }
2098        }
2099
2100        for (long newOrganizationId : newOrganizationIds) {
2101            if (!oldOrganizationIds.contains(newOrganizationId)) {
2102                addOrganizationUsers(newOrganizationId, new long[] {userId});
2103            }
2104        }
2105
2106        try {
2107            UserIndexer.updateUsers(new long[] {userId});
2108        }
2109        catch (SearchException se) {
2110            _log.error("Indexing " + userId, se);
2111        }
2112
2113        PermissionCacheUtil.clearCache();
2114    }
2115
2116    public User updatePassword(
2117            long userId, String password1, String password2,
2118            boolean passwordReset)
2119        throws PortalException, SystemException {
2120
2121        return updatePassword(
2122            userId, password1, password2, passwordReset, false);
2123    }
2124
2125    public User updatePassword(
2126            long userId, String password1, String password2,
2127            boolean passwordReset, boolean silentUpdate)
2128        throws PortalException, SystemException {
2129
2130        User user = userPersistence.findByPrimaryKey(userId);
2131
2132        // Use silentUpdate so that imported user passwords are not exported,
2133        // tracked, or validated
2134
2135        if (!silentUpdate) {
2136            validatePassword(user.getCompanyId(), userId, password1, password2);
2137        }
2138
2139        String oldEncPwd = user.getPassword();
2140
2141        if (!user.isPasswordEncrypted()) {
2142            oldEncPwd = PwdEncryptor.encrypt(user.getPassword());
2143        }
2144
2145        String newEncPwd = PwdEncryptor.encrypt(password1);
2146
2147        if (user.hasCompanyMx()) {
2148            mailService.updatePassword(user.getCompanyId(), userId, password1);
2149        }
2150
2151        user.setPassword(newEncPwd);
2152        user.setPasswordUnencrypted(password1);
2153        user.setPasswordEncrypted(true);
2154        user.setPasswordReset(passwordReset);
2155        user.setPasswordModifiedDate(new Date());
2156        user.setGraceLoginCount(0);
2157
2158        if (!silentUpdate) {
2159            user.setPasswordModified(true);
2160        }
2161
2162        try {
2163            userPersistence.update(user, false);
2164        }
2165        catch (ModelListenerException mle) {
2166            String msg = GetterUtil.getString(mle.getCause().getMessage());
2167
2168            if (PortalLDAPUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
2169                String passwordHistory = PrefsPropsUtil.getString(
2170                    user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
2171
2172                if (msg.indexOf(passwordHistory) != -1) {
2173                    throw new UserPasswordException(
2174                        UserPasswordException.PASSWORD_ALREADY_USED);
2175                }
2176            }
2177
2178            throw new UserPasswordException(
2179                UserPasswordException.PASSWORD_INVALID);
2180        }
2181
2182        if (!silentUpdate) {
2183            user.setPasswordModified(false);
2184
2185            passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
2186        }
2187
2188        return user;
2189    }
2190
2191    public User updatePasswordManually(
2192            long userId, String password, boolean passwordEncrypted,
2193            boolean passwordReset, Date passwordModifiedDate)
2194        throws PortalException, SystemException {
2195
2196        // This method should only be used to manually massage data
2197
2198        User user = userPersistence.findByPrimaryKey(userId);
2199
2200        user.setPassword(password);
2201        user.setPasswordEncrypted(passwordEncrypted);
2202        user.setPasswordReset(passwordReset);
2203        user.setPasswordModifiedDate(passwordModifiedDate);
2204
2205        userPersistence.update(user, false);
2206
2207        return user;
2208    }
2209
2210    public void updatePasswordReset(long userId, boolean passwordReset)
2211        throws PortalException, SystemException {
2212
2213        User user = userPersistence.findByPrimaryKey(userId);
2214
2215        user.setPasswordReset(passwordReset);
2216
2217        userPersistence.update(user, false);
2218    }
2219
2220    public void updatePortrait(long userId, byte[] bytes)
2221        throws PortalException, SystemException {
2222
2223        User user = userPersistence.findByPrimaryKey(userId);
2224
2225        long imageMaxSize = PrefsPropsUtil.getLong(
2226            PropsKeys.USERS_IMAGE_MAX_SIZE);
2227
2228        if ((imageMaxSize > 0) &&
2229            ((bytes == null) || (bytes.length > imageMaxSize))) {
2230
2231            throw new UserPortraitException();
2232        }
2233
2234        long portraitId = user.getPortraitId();
2235
2236        if (portraitId <= 0) {
2237            portraitId = counterLocalService.increment();
2238
2239            user.setPortraitId(portraitId);
2240
2241            userPersistence.update(user, false);
2242        }
2243
2244        imageLocalService.updateImage(portraitId, bytes);
2245    }
2246
2247    public void updateReminderQuery(long userId, String question, String answer)
2248        throws PortalException, SystemException {
2249
2250        validateReminderQuery(question, answer) ;
2251
2252        User user = userPersistence.findByPrimaryKey(userId);
2253
2254        user.setReminderQueryQuestion(question);
2255        user.setReminderQueryAnswer(answer);
2256
2257        userPersistence.update(user, false);
2258    }
2259
2260    public void updateScreenName(long userId, String screenName)
2261        throws PortalException, SystemException {
2262
2263        // User
2264
2265        User user = userPersistence.findByPrimaryKey(userId);
2266
2267        screenName = getScreenName(screenName);
2268
2269        validateScreenName(user.getCompanyId(), userId, screenName);
2270
2271        user.setScreenName(screenName);
2272
2273        userPersistence.update(user, false);
2274
2275        // Group
2276
2277        Group group = groupLocalService.getUserGroup(
2278            user.getCompanyId(), userId);
2279
2280        group.setFriendlyURL(StringPool.SLASH + screenName);
2281
2282        groupPersistence.update(group, false);
2283    }
2284
2285    public User updateUser(
2286            long userId, String oldPassword, String newPassword1,
2287            String newPassword2, boolean passwordReset,
2288            String reminderQueryQuestion, String reminderQueryAnswer,
2289            String screenName, String emailAddress, String openId,
2290            String languageId, String timeZoneId, String greeting,
2291            String comments, String firstName, String middleName,
2292            String lastName, int prefixId, int suffixId, boolean male,
2293            int birthdayMonth, int birthdayDay, int birthdayYear, String smsSn,
2294            String aimSn, String facebookSn, String icqSn, String jabberSn,
2295            String msnSn, String mySpaceSn, String skypeSn, String twitterSn,
2296            String ymSn, String jobTitle, long[] groupIds,
2297            long[] organizationIds, long[] roleIds,
2298            List<UserGroupRole> userGroupRoles, long[] userGroupIds,
2299            ServiceContext serviceContext)
2300        throws PortalException, SystemException {
2301
2302        // User
2303
2304        User user = userPersistence.findByPrimaryKey(userId);
2305        Company company = companyPersistence.findByPrimaryKey(
2306            user.getCompanyId());
2307        String password = oldPassword;
2308        screenName = getScreenName(screenName);
2309        emailAddress = emailAddress.trim().toLowerCase();
2310        openId = openId.trim();
2311        aimSn = aimSn.trim().toLowerCase();
2312        facebookSn = facebookSn.trim().toLowerCase();
2313        icqSn = icqSn.trim().toLowerCase();
2314        jabberSn = jabberSn.trim().toLowerCase();
2315        msnSn = msnSn.trim().toLowerCase();
2316        mySpaceSn = mySpaceSn.trim().toLowerCase();
2317        skypeSn = skypeSn.trim().toLowerCase();
2318        twitterSn = twitterSn.trim().toLowerCase();
2319        ymSn = ymSn.trim().toLowerCase();
2320        Date now = new Date();
2321
2322        EmailAddressGenerator emailAddressGenerator =
2323            (EmailAddressGenerator)InstancePool.get(
2324                PropsValues.USERS_EMAIL_ADDRESS_GENERATOR);
2325
2326        if (emailAddressGenerator.isGenerated(emailAddress)) {
2327            emailAddress = StringPool.BLANK;
2328        }
2329
2330        if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
2331            Validator.isNull(emailAddress)) {
2332
2333            emailAddress = emailAddressGenerator.generate(
2334                user.getCompanyId(), userId);
2335        }
2336
2337        validate(userId, screenName, emailAddress, firstName, lastName, smsSn);
2338
2339        if (Validator.isNotNull(newPassword1) ||
2340            Validator.isNotNull(newPassword2)) {
2341
2342            user = updatePassword(
2343                userId, newPassword1, newPassword2, passwordReset);
2344
2345            password = newPassword1;
2346        }
2347
2348        user.setModifiedDate(now);
2349
2350        if (user.getContactId() <= 0) {
2351            user.setContactId(counterLocalService.increment());
2352        }
2353
2354        user.setPasswordReset(passwordReset);
2355
2356        if (Validator.isNotNull(reminderQueryQuestion) &&
2357            Validator.isNotNull(reminderQueryAnswer)) {
2358
2359            user.setReminderQueryQuestion(reminderQueryQuestion);
2360            user.setReminderQueryAnswer(reminderQueryAnswer);
2361        }
2362
2363        user.setScreenName(screenName);
2364
2365        setEmailAddress(
2366            user, password, firstName, middleName, lastName, emailAddress);
2367
2368        user.setOpenId(openId);
2369        user.setLanguageId(languageId);
2370        user.setTimeZoneId(timeZoneId);
2371        user.setGreeting(greeting);
2372        user.setComments(comments);
2373        user.setFirstName(firstName);
2374        user.setMiddleName(middleName);
2375        user.setLastName(lastName);
2376        user.setJobTitle(jobTitle);
2377
2378        userPersistence.update(user, false);
2379
2380        // Expando
2381
2382        user.setExpandoBridgeAttributes(serviceContext);
2383
2384        // Contact
2385
2386        Date birthday = PortalUtil.getDate(
2387            birthdayMonth, birthdayDay, birthdayYear,
2388            new ContactBirthdayException());
2389
2390        long contactId = user.getContactId();
2391
2392        Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
2393
2394        if (contact == null) {
2395            contact = contactPersistence.create(contactId);
2396
2397            contact.setCompanyId(user.getCompanyId());
2398            contact.setUserName(StringPool.BLANK);
2399            contact.setCreateDate(now);
2400            contact.setAccountId(company.getAccountId());
2401            contact.setParentContactId(
2402                ContactConstants.DEFAULT_PARENT_CONTACT_ID);
2403        }
2404
2405        contact.setModifiedDate(now);
2406        contact.setFirstName(firstName);
2407        contact.setMiddleName(middleName);
2408        contact.setLastName(lastName);
2409        contact.setPrefixId(prefixId);
2410        contact.setSuffixId(suffixId);
2411        contact.setMale(male);
2412        contact.setBirthday(birthday);
2413        contact.setSmsSn(smsSn);
2414        contact.setAimSn(aimSn);
2415        contact.setFacebookSn(facebookSn);
2416        contact.setIcqSn(icqSn);
2417        contact.setJabberSn(jabberSn);
2418        contact.setMsnSn(msnSn);
2419        contact.setMySpaceSn(mySpaceSn);
2420        contact.setSkypeSn(skypeSn);
2421        contact.setTwitterSn(twitterSn);
2422        contact.setYmSn(ymSn);
2423        contact.setJobTitle(jobTitle);
2424
2425        contactPersistence.update(contact, false);
2426
2427        // Group
2428
2429        Group group = groupLocalService.getUserGroup(
2430            user.getCompanyId(), userId);
2431
2432        group.setFriendlyURL(StringPool.SLASH + screenName);
2433
2434        groupPersistence.update(group, false);
2435
2436        // Groups
2437
2438        updateGroups(userId, groupIds);
2439
2440        // Organizations
2441
2442        updateOrganizations(userId, organizationIds);
2443
2444        // Roles
2445
2446        if (roleIds != null) {
2447            roleIds = EnterpriseAdminUtil.addRequiredRoles(userId, roleIds);
2448
2449            userPersistence.setRoles(userId, roleIds);
2450        }
2451
2452        // User group roles
2453
2454        if (userGroupRoles != null) {
2455            List<UserGroupRole> previousUserGroupRoles =
2456                userGroupRolePersistence.findByUserId(userId);
2457
2458            for (UserGroupRole userGroupRole : previousUserGroupRoles) {
2459                if (userGroupRoles.contains(userGroupRole)) {
2460                    userGroupRoles.remove(userGroupRole);
2461                }
2462                else {
2463                    Role role = roleLocalService.getRole(
2464                        userGroupRole.getRoleId());
2465
2466                    String name = role.getName();
2467
2468                    if (!name.equals(RoleConstants.COMMUNITY_MEMBER) &&
2469                        !name.equals(RoleConstants.ORGANIZATION_MEMBER)) {
2470
2471                        userGroupRoleLocalService.deleteUserGroupRole(
2472                            userGroupRole);
2473                    }
2474                }
2475            }
2476
2477            for (UserGroupRole userGroupRole : userGroupRoles) {
2478                userGroupRoleLocalService.addUserGroupRole(userGroupRole);
2479            }
2480        }
2481
2482        // User groups
2483
2484        if (userGroupIds != null) {
2485            copyUserGroupLayouts(userGroupIds, userId);
2486
2487            userPersistence.setUserGroups(userId, userGroupIds);
2488        }
2489
2490        // Announcements
2491
2492        announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
2493
2494        // Tags
2495
2496        if (serviceContext != null) {
2497            updateTagsAsset(userId, user, serviceContext.getTagsEntries());
2498        }
2499
2500        // Indexer
2501
2502        try {
2503            UserIndexer.updateUser(user);
2504        }
2505        catch (SearchException se) {
2506            _log.error("Indexing " + userId, se);
2507        }
2508
2509        // Permission cache
2510
2511        PermissionCacheUtil.clearCache();
2512
2513        return user;
2514    }
2515
2516    public void updateTagsAsset(long userId, User user, String[] tagsEntries)
2517        throws PortalException, SystemException {
2518
2519        tagsAssetLocalService.updateAsset(
2520            userId, 0, User.class.getName(), user.getUserId(), null,
2521            tagsEntries, true, null, null, null, null, null, user.getFullName(),
2522            null, null, null, 0, 0, null, false);
2523    }
2524
2525    protected int authenticate(
2526            long companyId, String login, String password, String authType,
2527            Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
2528        throws PortalException, SystemException {
2529
2530        login = login.trim().toLowerCase();
2531
2532        long userId = GetterUtil.getLong(login);
2533
2534        // User input validation
2535
2536        if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2537            if (!Validator.isEmailAddress(login)) {
2538                throw new UserEmailAddressException();
2539            }
2540        }
2541        else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2542            if (Validator.isNull(login)) {
2543                throw new UserScreenNameException();
2544            }
2545        }
2546        else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2547            if (Validator.isNull(login)) {
2548                throw new UserIdException();
2549            }
2550        }
2551
2552        if (Validator.isNull(password)) {
2553            throw new UserPasswordException(
2554                UserPasswordException.PASSWORD_INVALID);
2555        }
2556
2557        int authResult = Authenticator.FAILURE;
2558
2559        // Pre-authentication pipeline
2560
2561        if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2562            authResult = AuthPipeline.authenticateByEmailAddress(
2563                PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
2564                headerMap, parameterMap);
2565        }
2566        else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2567            authResult = AuthPipeline.authenticateByScreenName(
2568                PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
2569                headerMap, parameterMap);
2570        }
2571        else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2572            authResult = AuthPipeline.authenticateByUserId(
2573                PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
2574                headerMap, parameterMap);
2575        }
2576
2577        // Get user
2578
2579        User user = null;
2580
2581        try {
2582            if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2583                user = userPersistence.findByC_EA(companyId, login);
2584            }
2585            else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2586                user = userPersistence.findByC_SN(companyId, login);
2587            }
2588            else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2589                user = userPersistence.findByC_U(
2590                    companyId, GetterUtil.getLong(login));
2591            }
2592        }
2593        catch (NoSuchUserException nsue) {
2594            return Authenticator.DNE;
2595        }
2596
2597        if (user.isDefaultUser()) {
2598            _log.error(
2599                "The default user should never be allowed to authenticate");
2600
2601            return Authenticator.DNE;
2602        }
2603
2604        if (!user.isPasswordEncrypted()) {
2605            user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
2606            user.setPasswordEncrypted(true);
2607
2608            userPersistence.update(user, false);
2609        }
2610
2611        // Check password policy to see if the is account locked out or if the
2612        // password is expired
2613
2614        checkLockout(user);
2615
2616        checkPasswordExpired(user);
2617
2618        // Authenticate against the User_ table
2619
2620        if (authResult == Authenticator.SUCCESS) {
2621            if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
2622                String encPassword = PwdEncryptor.encrypt(
2623                    password, user.getPassword());
2624
2625                if (user.getPassword().equals(encPassword)) {
2626                    authResult = Authenticator.SUCCESS;
2627                }
2628                else if (GetterUtil.getBoolean(PropsUtil.get(
2629                            PropsKeys.AUTH_MAC_ALLOW))) {
2630
2631                    try {
2632                        MessageDigest digester = MessageDigest.getInstance(
2633                            PropsUtil.get(PropsKeys.AUTH_MAC_ALGORITHM));
2634
2635                        digester.update(login.getBytes("UTF8"));
2636
2637                        String shardKey =
2638                            PropsUtil.get(PropsKeys.AUTH_MAC_SHARED_KEY);
2639
2640                        encPassword = Base64.encode(
2641                            digester.digest(shardKey.getBytes("UTF8")));
2642
2643                        if (password.equals(encPassword)) {
2644                            authResult = Authenticator.SUCCESS;
2645                        }
2646                        else {
2647                            authResult = Authenticator.FAILURE;
2648                        }
2649                    }
2650                    catch (NoSuchAlgorithmException nsae) {
2651                        throw new SystemException(nsae);
2652                    }
2653                    catch (UnsupportedEncodingException uee) {
2654                        throw new SystemException(uee);
2655                    }
2656                }
2657                else {
2658                    authResult = Authenticator.FAILURE;
2659                }
2660            }
2661        }
2662
2663        // Post-authentication pipeline
2664
2665        if (authResult == Authenticator.SUCCESS) {
2666            if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2667                authResult = AuthPipeline.authenticateByEmailAddress(
2668                    PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
2669                    headerMap, parameterMap);
2670            }
2671            else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2672                authResult = AuthPipeline.authenticateByScreenName(
2673                    PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
2674                    headerMap, parameterMap);
2675            }
2676            else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2677                authResult = AuthPipeline.authenticateByUserId(
2678                    PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
2679                    headerMap, parameterMap);
2680            }
2681        }
2682
2683        // Execute code triggered by authentication failure
2684
2685        if (authResult == Authenticator.FAILURE) {
2686            try {
2687                if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2688                    AuthPipeline.onFailureByEmailAddress(
2689                        PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
2690                        parameterMap);
2691                }
2692                else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2693                    AuthPipeline.onFailureByScreenName(
2694                        PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
2695                        parameterMap);
2696                }
2697                else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2698                    AuthPipeline.onFailureByUserId(
2699                        PropsKeys.AUTH_FAILURE, companyId, userId, headerMap,
2700                        parameterMap);
2701                }
2702
2703                // Let LDAP handle max failure event
2704
2705                if (!PortalLDAPUtil.isPasswordPolicyEnabled(
2706                        user.getCompanyId())) {
2707
2708                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2709
2710                    int failedLoginAttempts = user.getFailedLoginAttempts();
2711                    int maxFailures = passwordPolicy.getMaxFailure();
2712
2713                    if ((failedLoginAttempts >= maxFailures) &&
2714                        (maxFailures != 0)) {
2715
2716                        if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2717                            AuthPipeline.onMaxFailuresByEmailAddress(
2718                                PropsKeys.AUTH_MAX_FAILURES, companyId, login,
2719                                headerMap, parameterMap);
2720                        }
2721                        else if (authType.equals(
2722                                    CompanyConstants.AUTH_TYPE_SN)) {
2723
2724                            AuthPipeline.onMaxFailuresByScreenName(
2725                                PropsKeys.AUTH_MAX_FAILURES, companyId, login,
2726                                headerMap, parameterMap);
2727                        }
2728                        else if (authType.equals(
2729                                    CompanyConstants.AUTH_TYPE_ID)) {
2730
2731                            AuthPipeline.onMaxFailuresByUserId(
2732                                PropsKeys.AUTH_MAX_FAILURES, companyId, userId,
2733                                headerMap, parameterMap);
2734                        }
2735                    }
2736                }
2737            }
2738            catch (Exception e) {
2739                _log.error(e, e);
2740            }
2741        }
2742
2743        return authResult;
2744    }
2745
2746    protected void copyUserGroupLayouts(long userGroupId, long userId)
2747        throws PortalException, SystemException {
2748
2749        UserGroup userGroup = userGroupLocalService.getUserGroup(userGroupId);
2750        User user = getUserById(userId);
2751
2752        Map<String, String[]> parameterMap = getLayoutTemplatesParameters();
2753
2754        if (userGroup.hasPrivateLayouts()) {
2755            long sourceGroupId = userGroup.getGroup().getGroupId();
2756            long targetGroupId = user.getGroup().getGroupId();
2757
2758            byte[] bytes = layoutLocalService.exportLayouts(
2759                sourceGroupId, true, parameterMap, null, null);
2760
2761            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
2762
2763            layoutLocalService.importLayouts(
2764                userId, targetGroupId, true, parameterMap, bais);
2765        }
2766
2767        if (userGroup.hasPublicLayouts()) {
2768            long sourceGroupId = userGroup.getGroup().getGroupId();
2769            long targetGroupId = user.getGroup().getGroupId();
2770
2771            byte[] bytes = layoutLocalService.exportLayouts(
2772                sourceGroupId, false, parameterMap, null, null);
2773
2774            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
2775
2776            layoutLocalService.importLayouts(
2777                userId, targetGroupId, false, parameterMap, bais);
2778        }
2779    }
2780
2781    protected void copyUserGroupLayouts(long userGroupId, long userIds[])
2782        throws PortalException, SystemException {
2783
2784        for (long userId : userIds) {
2785            if (!userGroupPersistence.containsUser(userGroupId, userId)) {
2786                copyUserGroupLayouts(userGroupId, userId);
2787            }
2788        }
2789    }
2790
2791    protected void copyUserGroupLayouts(long userGroupIds[], long userId)
2792        throws PortalException, SystemException {
2793
2794        for (long userGroupId : userGroupIds) {
2795            if (!userGroupPersistence.containsUser(userGroupId, userId)) {
2796                copyUserGroupLayouts(userGroupId, userId);
2797            }
2798        }
2799    }
2800
2801    protected void doSendPassword(
2802            long companyId, String emailAddress, String remoteAddr,
2803            String remoteHost, String userAgent, String fromName,
2804            String fromAddress, String subject, String body)
2805        throws IOException, PortalException, SystemException {
2806
2807        if (!PrefsPropsUtil.getBoolean(
2808                companyId, PropsKeys.COMPANY_SECURITY_SEND_PASSWORD) ||
2809            !PrefsPropsUtil.getBoolean(
2810                companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_ENABLED)) {
2811
2812            return;
2813        }
2814
2815        emailAddress = emailAddress.trim().toLowerCase();
2816
2817        if (!Validator.isEmailAddress(emailAddress)) {
2818            throw new UserEmailAddressException();
2819        }
2820
2821        Company company = companyPersistence.findByPrimaryKey(companyId);
2822
2823        User user = userPersistence.findByC_EA(companyId, emailAddress);
2824
2825        PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2826
2827        /*if (user.hasCompanyMx()) {
2828            throw new SendPasswordException();
2829        }*/
2830
2831        String newPassword = null;
2832
2833        if (!PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
2834                PwdEncryptor.TYPE_NONE)) {
2835
2836            newPassword = PwdToolkitUtil.generate();
2837
2838            boolean passwordReset = false;
2839
2840            if (passwordPolicy.getChangeable() &&
2841                passwordPolicy.getChangeRequired()) {
2842
2843                passwordReset = true;
2844            }
2845
2846            user.setPassword(PwdEncryptor.encrypt(newPassword));
2847            user.setPasswordUnencrypted(newPassword);
2848            user.setPasswordEncrypted(true);
2849            user.setPasswordReset(passwordReset);
2850            user.setPasswordModified(true);
2851            user.setPasswordModifiedDate(new Date());
2852
2853            userPersistence.update(user, false);
2854
2855            user.setPasswordModified(false);
2856        }
2857        else {
2858            newPassword = user.getPassword();
2859        }
2860
2861        if (Validator.isNull(fromName)) {
2862            fromName = PrefsPropsUtil.getString(
2863                companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
2864        }
2865
2866        if (Validator.isNull(fromAddress)) {
2867            fromAddress = PrefsPropsUtil.getString(
2868                companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
2869        }
2870
2871        String toName = user.getFullName();
2872        String toAddress = user.getEmailAddress();
2873
2874        if (Validator.isNull(subject)) {
2875            subject = PrefsPropsUtil.getContent(
2876                companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
2877        }
2878
2879        if (Validator.isNull(body)) {
2880            body = PrefsPropsUtil.getContent(
2881                companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
2882        }
2883
2884        subject = StringUtil.replace(
2885            subject,
2886            new String[] {
2887                "[$FROM_ADDRESS$]",
2888                "[$FROM_NAME$]",
2889                "[$PORTAL_URL$]",
2890                "[$REMOTE_ADDRESS$]",
2891                "[$REMOTE_HOST$]",
2892                "[$TO_ADDRESS$]",
2893                "[$TO_NAME$]",
2894                "[$USER_AGENT$]",
2895                "[$USER_ID$]",
2896                "[$USER_PASSWORD$]",
2897                "[$USER_SCREENNAME$]"
2898            },
2899            new String[] {
2900                fromAddress,
2901                fromName,
2902                company.getVirtualHost(),
2903                remoteAddr,
2904                remoteHost,
2905                toAddress,
2906                toName,
2907                HtmlUtil.escape(userAgent),
2908                String.valueOf(user.getUserId()),
2909                newPassword,
2910                user.getScreenName()
2911            });
2912
2913        body = StringUtil.replace(
2914            body,
2915            new String[] {
2916                "[$FROM_ADDRESS$]",
2917                "[$FROM_NAME$]",
2918                "[$PORTAL_URL$]",
2919                "[$REMOTE_ADDRESS$]",
2920                "[$REMOTE_HOST$]",
2921                "[$TO_ADDRESS$]",
2922                "[$TO_NAME$]",
2923                "[$USER_AGENT$]",
2924                "[$USER_ID$]",
2925                "[$USER_PASSWORD$]",
2926                "[$USER_SCREENNAME$]"
2927            },
2928            new String[] {
2929                fromAddress,
2930                fromName,
2931                company.getVirtualHost(),
2932                remoteAddr,
2933                remoteHost,
2934                toAddress,
2935                toName,
2936                HtmlUtil.escape(userAgent),
2937                String.valueOf(user.getUserId()),
2938                newPassword,
2939                user.getScreenName()
2940            });
2941
2942        InternetAddress from = new InternetAddress(fromAddress, fromName);
2943
2944        InternetAddress to = new InternetAddress(toAddress, toName);
2945
2946        MailMessage message = new MailMessage(from, to, subject, body, true);
2947
2948        mailService.sendEmail(message);
2949    }
2950
2951    protected Map<String, String[]> getLayoutTemplatesParameters() {
2952        Map<String, String[]> parameterMap =
2953            new LinkedHashMap<String, String[]>();
2954
2955        parameterMap.put(
2956            PortletDataHandlerKeys.CATEGORIES,
2957            new String[] {Boolean.TRUE.toString()});
2958        parameterMap.put(
2959            PortletDataHandlerKeys.DATA_STRATEGY,
2960            new String[] {PortletDataHandlerKeys.DATA_STRATEGY_MIRROR});
2961        parameterMap.put(
2962            PortletDataHandlerKeys.DELETE_MISSING_LAYOUTS,
2963            new String[] {Boolean.FALSE.toString()});
2964        parameterMap.put(
2965            PortletDataHandlerKeys.DELETE_PORTLET_DATA,
2966            new String[] {Boolean.FALSE.toString()});
2967        parameterMap.put(
2968            PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE,
2969            new String[] {PortletDataHandlerKeys.
2970                LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_NAME});
2971        parameterMap.put(
2972            PortletDataHandlerKeys.PERMISSIONS,
2973            new String[] {Boolean.TRUE.toString()});
2974        parameterMap.put(
2975            PortletDataHandlerKeys.PORTLET_DATA,
2976            new String[] {Boolean.TRUE.toString()});
2977        parameterMap.put(
2978            PortletDataHandlerKeys.PORTLET_DATA_ALL,
2979            new String[] {Boolean.TRUE.toString()});
2980        parameterMap.put(
2981            PortletDataHandlerKeys.PORTLET_SETUP,
2982            new String[] {Boolean.TRUE.toString()});
2983        parameterMap.put(
2984            PortletDataHandlerKeys.PORTLET_USER_PREFERENCES,
2985            new String[] {Boolean.TRUE.toString()});
2986        parameterMap.put(
2987            PortletDataHandlerKeys.PORTLETS_MERGE_MODE,
2988            new String[] {PortletDataHandlerKeys.
2989                PORTLETS_MERGE_MODE_ADD_TO_BOTTOM});
2990        parameterMap.put(
2991            PortletDataHandlerKeys.THEME,
2992            new String[] {Boolean.FALSE.toString()});
2993        parameterMap.put(
2994            PortletDataHandlerKeys.USER_ID_STRATEGY,
2995            new String[] {UserIdStrategy.CURRENT_USER_ID});
2996        parameterMap.put(
2997            PortletDataHandlerKeys.USER_PERMISSIONS,
2998            new String[] {Boolean.FALSE.toString()});
2999
3000        return parameterMap;
3001    }
3002
3003    protected String getScreenName(String screenName) {
3004        return StringUtil.lowerCase(StringUtil.trim(screenName));
3005    }
3006
3007    protected long[] getUserIds(List<User> users) {
3008        long[] userIds = new long[users.size()];
3009
3010        for (int i = 0; i < users.size(); i++) {
3011            User user = users.get(i);
3012
3013            userIds[i] = user.getUserId();
3014        }
3015
3016        return userIds;
3017    }
3018
3019    protected void populateQuery(
3020            BooleanQuery contextQuery, BooleanQuery searchQuery,
3021            LinkedHashMap<String, Object> params, boolean andSearch)
3022        throws ParseException {
3023
3024        if (params == null) {
3025            return;
3026        }
3027
3028        ExpandoBridge expandoBridge = ExpandoBridgeFactoryUtil.getExpandoBridge(
3029            User.class.getName());
3030
3031        Set<String> attributeNames = SetUtil.fromEnumeration(
3032            expandoBridge.getAttributeNames());
3033
3034        for (Map.Entry<String, Object> entry : params.entrySet()) {
3035            String key = entry.getKey();
3036            Object value = entry.getValue();
3037
3038            if (value == null) {
3039                continue;
3040            }
3041
3042            populateQuery(
3043                contextQuery, searchQuery, expandoBridge, attributeNames,
3044                key, value, andSearch);
3045        }
3046    }
3047
3048    protected void populateQuery(
3049            BooleanQuery contextQuery, BooleanQuery searchQuery,
3050            ExpandoBridge expandoBridge, Set<String> attributeNames,
3051            String key, Object value, boolean andSearch)
3052        throws ParseException {
3053
3054        if (key.equals("usersRoles")) {
3055            contextQuery.addRequiredTerm("roleIds", String.valueOf(value));
3056        }
3057        else if (key.equals("usersUserGroups")) {
3058            contextQuery.addRequiredTerm("userGroupIds", String.valueOf(value));
3059        }
3060        else if (key.equals("usersOrgs")) {
3061            if (value instanceof Long[]) {
3062                Long[] values = (Long[])value;
3063
3064                BooleanQuery usersOrgsQuery = BooleanQueryFactoryUtil.create();
3065
3066                for (long organizationId : values) {
3067                    usersOrgsQuery.addTerm("organizationIds", organizationId);
3068                    usersOrgsQuery.addTerm(
3069                        "ancestorOrganizationIds", organizationId);
3070                }
3071
3072                contextQuery.add(usersOrgsQuery, BooleanClauseOccur.MUST);
3073            }
3074            else {
3075                contextQuery.addRequiredTerm(
3076                    "organizationIds", String.valueOf(value));
3077            }
3078        }
3079        else if (attributeNames.contains(key)) {
3080            UnicodeProperties properties = expandoBridge.getAttributeProperties(
3081                key);
3082
3083            if (GetterUtil.getBoolean(
3084                    properties.getProperty(ExpandoBridgeIndexer.INDEXABLE))) {
3085
3086                int type = expandoBridge.getAttributeType(key);
3087
3088                if ((type == ExpandoColumnConstants.STRING) &&
3089                    (Validator.isNotNull((String)value))) {
3090
3091                    if (andSearch) {
3092                        searchQuery.addRequiredTerm(key, (String)value, true);
3093                    }
3094                    else {
3095                        searchQuery.addTerm(key, (String)value, true);
3096                    }
3097                }
3098            }
3099        }
3100        else if (Validator.isNotNull(key) && Validator.isNotNull(value)) {
3101            if (andSearch) {
3102                searchQuery.addRequiredTerm(key, String.valueOf(value));
3103            }
3104            else {
3105                searchQuery.addTerm(key, String.valueOf(value));
3106            }
3107        }
3108    }
3109
3110    protected void reIndexUsers(long companyId) throws SystemException {
3111        int count = userPersistence.countByCompanyId(companyId);
3112
3113        int pages = count / UserIndexer.DEFAULT_INTERVAL;
3114
3115        for (int i = 0; i <= pages; i++) {
3116            int start = (i * UserIndexer.DEFAULT_INTERVAL);
3117            int end = start + UserIndexer.DEFAULT_INTERVAL;
3118
3119            reIndexUsers(companyId, start, end);
3120        }
3121    }
3122
3123    protected void reIndexUsers(long companyId, int start, int end)
3124        throws SystemException {
3125
3126        List<User> users = userPersistence.findByCompanyId(
3127            companyId, start, end);
3128
3129        for (User user : users) {
3130            try {
3131                UserIndexer.updateUser(user);
3132            }
3133            catch (SearchException se) {
3134                _log.error("Reindexing " + user.getUserId(), se);
3135            }
3136        }
3137    }
3138
3139    protected void sendEmail(User user, String password)
3140        throws IOException, PortalException, SystemException {
3141
3142        if (!PrefsPropsUtil.getBoolean(
3143                user.getCompanyId(),
3144                PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
3145
3146            return;
3147        }
3148
3149        long companyId = user.getCompanyId();
3150
3151        Company company = companyPersistence.findByPrimaryKey(companyId);
3152
3153        String fromName = PrefsPropsUtil.getString(
3154            companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3155        String fromAddress = PrefsPropsUtil.getString(
3156            companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3157
3158        String toName = user.getFullName();
3159        String toAddress = user.getEmailAddress();
3160
3161        String subject = PrefsPropsUtil.getContent(
3162            companyId, PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
3163        String body = PrefsPropsUtil.getContent(
3164            companyId, PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
3165
3166        subject = StringUtil.replace(
3167            subject,
3168            new String[] {
3169                "[$FROM_ADDRESS$]",
3170                "[$FROM_NAME$]",
3171                "[$PORTAL_URL$]",
3172                "[$TO_ADDRESS$]",
3173                "[$TO_NAME$]",
3174                "[$USER_ID$]",
3175                "[$USER_PASSWORD$]",
3176                "[$USER_SCREENNAME$]"
3177            },
3178            new String[] {
3179                fromAddress,
3180                fromName,
3181                company.getVirtualHost(),
3182                toAddress,
3183                toName,
3184                String.valueOf(user.getUserId()),
3185                password,
3186                user.getScreenName()
3187            });
3188
3189        body = StringUtil.replace(
3190            body,
3191            new String[] {
3192                "[$FROM_ADDRESS$]",
3193                "[$FROM_NAME$]",
3194                "[$PORTAL_URL$]",
3195                "[$TO_ADDRESS$]",
3196                "[$TO_NAME$]",
3197                "[$USER_ID$]",
3198                "[$USER_PASSWORD$]",
3199                "[$USER_SCREENNAME$]"
3200            },
3201            new String[] {
3202                fromAddress,
3203                fromName,
3204                company.getVirtualHost(),
3205                toAddress,
3206                toName,
3207                String.valueOf(user.getUserId()),
3208                password,
3209                user.getScreenName()
3210            });
3211
3212        InternetAddress from = new InternetAddress(fromAddress, fromName);
3213
3214        InternetAddress to = new InternetAddress(toAddress, toName);
3215
3216        MailMessage message = new MailMessage(from, to, subject, body, true);
3217
3218        mailService.sendEmail(message);
3219    }
3220
3221    protected void setEmailAddress(
3222        User user, String password, String firstName, String middleName,
3223        String lastName, String emailAddress) {
3224
3225        if (emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
3226            return;
3227        }
3228
3229        long userId = user.getUserId();
3230
3231        // test@test.com -> test@liferay.com
3232
3233        if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
3234            mailService.addUser(
3235                user.getCompanyId(), userId, password, firstName, middleName,
3236                lastName, emailAddress);
3237        }
3238
3239        // test@liferay.com -> bob@liferay.com
3240
3241        else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
3242            mailService.updateEmailAddress(
3243                user.getCompanyId(), userId, emailAddress);
3244        }
3245
3246        // test@liferay.com -> test@test.com
3247
3248        else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
3249            mailService.deleteEmailAddress(user.getCompanyId(), userId);
3250        }
3251
3252        user.setEmailAddress(emailAddress);
3253    }
3254
3255    protected void validate(
3256            long userId, String screenName, String emailAddress,
3257            String firstName, String lastName, String smsSn)
3258        throws PortalException, SystemException {
3259
3260        User user = userPersistence.findByPrimaryKey(userId);
3261
3262        if (!user.getScreenName().equalsIgnoreCase(screenName)) {
3263            validateScreenName(user.getCompanyId(), userId, screenName);
3264        }
3265
3266        validateEmailAddress(user.getCompanyId(), emailAddress);
3267
3268        if (!user.isDefaultUser()) {
3269            if (Validator.isNotNull(emailAddress) &&
3270                !user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
3271
3272                if (userPersistence.fetchByC_EA(
3273                        user.getCompanyId(), emailAddress) != null) {
3274
3275                    throw new DuplicateUserEmailAddressException();
3276                }
3277            }
3278
3279            if (Validator.isNull(firstName)) {
3280                throw new ContactFirstNameException();
3281            }
3282            else if (Validator.isNull(lastName)) {
3283                throw new ContactLastNameException();
3284            }
3285        }
3286
3287        if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
3288            throw new UserSmsException();
3289        }
3290    }
3291
3292    protected void validate(
3293            long companyId, long userId, boolean autoPassword, String password1,
3294            String password2, boolean autoScreenName, String screenName,
3295            String emailAddress, String firstName, String lastName,
3296            long[] organizationIds)
3297        throws PortalException, SystemException {
3298
3299        Company company = companyPersistence.findByPrimaryKey(companyId);
3300
3301        if (company.isSystem()) {
3302            return;
3303        }
3304
3305        if (!autoScreenName) {
3306            validateScreenName(companyId, userId, screenName);
3307        }
3308
3309        if (!autoPassword) {
3310            PasswordPolicy passwordPolicy =
3311                passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
3312
3313            PwdToolkitUtil.validate(
3314                companyId, 0, password1, password2, passwordPolicy);
3315        }
3316
3317        validateEmailAddress(companyId, emailAddress);
3318
3319        if (Validator.isNotNull(emailAddress)) {
3320            User user = userPersistence.fetchByC_EA(companyId, emailAddress);
3321
3322            if (user != null) {
3323                throw new DuplicateUserEmailAddressException();
3324            }
3325        }
3326
3327        if (Validator.isNull(firstName)) {
3328            throw new ContactFirstNameException();
3329        }
3330        else if (Validator.isNull(lastName)) {
3331            throw new ContactLastNameException();
3332        }
3333    }
3334
3335    protected void validateEmailAddress(long companyId, String emailAddress)
3336        throws PortalException, SystemException {
3337
3338        if (Validator.isNull(emailAddress) &&
3339            !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
3340
3341            return;
3342        }
3343
3344        if (!Validator.isEmailAddress(emailAddress) ||
3345            emailAddress.startsWith("root@") ||
3346            emailAddress.startsWith("postmaster@")) {
3347
3348            throw new UserEmailAddressException();
3349        }
3350
3351        String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
3352            companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
3353            StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
3354
3355        for (int i = 0; i < reservedEmailAddresses.length; i++) {
3356            if (emailAddress.equalsIgnoreCase(reservedEmailAddresses[i])) {
3357                throw new ReservedUserEmailAddressException();
3358            }
3359        }
3360    }
3361
3362    protected void validatePassword(
3363            long companyId, long userId, String password1, String password2)
3364        throws PortalException, SystemException {
3365
3366        if (Validator.isNull(password1) || Validator.isNull(password2)) {
3367            throw new UserPasswordException(
3368                UserPasswordException.PASSWORD_INVALID);
3369        }
3370
3371        if (!password1.equals(password2)) {
3372            throw new UserPasswordException(
3373                UserPasswordException.PASSWORDS_DO_NOT_MATCH);
3374        }
3375
3376        PasswordPolicy passwordPolicy =
3377            passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
3378
3379        PwdToolkitUtil.validate(
3380            companyId, userId, password1, password2, passwordPolicy);
3381    }
3382
3383    protected void validateReminderQuery(String question, String answer)
3384        throws PortalException {
3385
3386        if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
3387            return;
3388        }
3389
3390        if (Validator.isNull(question)) {
3391            throw new UserReminderQueryException("Question cannot be null");
3392        }
3393
3394        if (Validator.isNull(answer)) {
3395            throw new UserReminderQueryException("Answer cannot be null");
3396        }
3397    }
3398
3399    protected void validateScreenName(
3400            long companyId, long userId, String screenName)
3401        throws PortalException, SystemException {
3402
3403        if (Validator.isNull(screenName)) {
3404            throw new UserScreenNameException();
3405        }
3406
3407        ScreenNameValidator screenNameValidator =
3408            (ScreenNameValidator)InstancePool.get(
3409                PropsValues.USERS_SCREEN_NAME_VALIDATOR);
3410
3411        if (screenNameValidator != null) {
3412            if (!screenNameValidator.validate(companyId, screenName)) {
3413                throw new UserScreenNameException();
3414            }
3415        }
3416
3417        if (Validator.isNumber(screenName) &&
3418            !screenName.equals(String.valueOf(userId))) {
3419
3420            throw new UserScreenNameException();
3421        }
3422
3423        for (char c : screenName.toCharArray()) {
3424            if ((!Validator.isChar(c)) && (!Validator.isDigit(c)) &&
3425                (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
3426                (c != CharPool.UNDERLINE)) {
3427
3428                throw new UserScreenNameException();
3429            }
3430        }
3431
3432        String[] anonymousNames = PrincipalBean.ANONYMOUS_NAMES;
3433
3434        for (int i = 0; i < anonymousNames.length; i++) {
3435            if (screenName.equalsIgnoreCase(anonymousNames[i])) {
3436                throw new UserScreenNameException();
3437            }
3438        }
3439
3440        User user = userPersistence.fetchByC_SN(companyId, screenName);
3441
3442        if (user != null) {
3443            throw new DuplicateUserScreenNameException();
3444        }
3445
3446        String friendlyURL = StringPool.SLASH + screenName;
3447
3448        Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
3449
3450        if (group != null) {
3451            throw new DuplicateUserScreenNameException();
3452        }
3453
3454        int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
3455
3456        if (exceptionType != -1) {
3457            throw new UserScreenNameException(
3458                new GroupFriendlyURLException(exceptionType));
3459        }
3460
3461        String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
3462            companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
3463            StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
3464
3465        for (int i = 0; i < reservedScreenNames.length; i++) {
3466            if (screenName.equalsIgnoreCase(reservedScreenNames[i])) {
3467                throw new ReservedUserScreenNameException();
3468            }
3469        }
3470    }
3471
3472    private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
3473
3474    private static Map<Long, User> _defaultUsers =
3475        new ConcurrentHashMap<Long, User>();
3476
3477}