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