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