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