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