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