001    /**
002     * Copyright (c) 2000-present 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.ContactNameException;
020    import com.liferay.portal.DuplicateOpenIdException;
021    import com.liferay.portal.GroupFriendlyURLException;
022    import com.liferay.portal.ModelListenerException;
023    import com.liferay.portal.NoSuchImageException;
024    import com.liferay.portal.NoSuchOrganizationException;
025    import com.liferay.portal.NoSuchTicketException;
026    import com.liferay.portal.NoSuchUserException;
027    import com.liferay.portal.PasswordExpiredException;
028    import com.liferay.portal.RequiredUserException;
029    import com.liferay.portal.SendPasswordException;
030    import com.liferay.portal.UserEmailAddressException;
031    import com.liferay.portal.UserIdException;
032    import com.liferay.portal.UserLockoutException;
033    import com.liferay.portal.UserPasswordException;
034    import com.liferay.portal.UserReminderQueryException;
035    import com.liferay.portal.UserScreenNameException;
036    import com.liferay.portal.UserSmsException;
037    import com.liferay.portal.kernel.cache.PortalCache;
038    import com.liferay.portal.kernel.cache.PortalCacheMapSynchronizeUtil;
039    import com.liferay.portal.kernel.cache.PortalCacheMapSynchronizeUtil.Synchronizer;
040    import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
041    import com.liferay.portal.kernel.dao.orm.QueryUtil;
042    import com.liferay.portal.kernel.dao.orm.WildcardMode;
043    import com.liferay.portal.kernel.exception.PortalException;
044    import com.liferay.portal.kernel.exception.SystemException;
045    import com.liferay.portal.kernel.language.LanguageUtil;
046    import com.liferay.portal.kernel.log.Log;
047    import com.liferay.portal.kernel.log.LogFactoryUtil;
048    import com.liferay.portal.kernel.messaging.DestinationNames;
049    import com.liferay.portal.kernel.messaging.Message;
050    import com.liferay.portal.kernel.messaging.MessageBusUtil;
051    import com.liferay.portal.kernel.search.BaseModelSearchResult;
052    import com.liferay.portal.kernel.search.Hits;
053    import com.liferay.portal.kernel.search.Indexer;
054    import com.liferay.portal.kernel.search.IndexerRegistryUtil;
055    import com.liferay.portal.kernel.search.QueryConfig;
056    import com.liferay.portal.kernel.search.SearchContext;
057    import com.liferay.portal.kernel.search.SearchException;
058    import com.liferay.portal.kernel.search.Sort;
059    import com.liferay.portal.kernel.spring.aop.Skip;
060    import com.liferay.portal.kernel.transaction.Propagation;
061    import com.liferay.portal.kernel.transaction.TransactionCommitCallbackUtil;
062    import com.liferay.portal.kernel.transaction.Transactional;
063    import com.liferay.portal.kernel.util.ArrayUtil;
064    import com.liferay.portal.kernel.util.Digester;
065    import com.liferay.portal.kernel.util.DigesterUtil;
066    import com.liferay.portal.kernel.util.GetterUtil;
067    import com.liferay.portal.kernel.util.KeyValuePair;
068    import com.liferay.portal.kernel.util.ListUtil;
069    import com.liferay.portal.kernel.util.LocaleUtil;
070    import com.liferay.portal.kernel.util.LocalizationUtil;
071    import com.liferay.portal.kernel.util.MapUtil;
072    import com.liferay.portal.kernel.util.OrderByComparator;
073    import com.liferay.portal.kernel.util.ParamUtil;
074    import com.liferay.portal.kernel.util.PropsKeys;
075    import com.liferay.portal.kernel.util.PwdGenerator;
076    import com.liferay.portal.kernel.util.SetUtil;
077    import com.liferay.portal.kernel.util.StringBundler;
078    import com.liferay.portal.kernel.util.StringPool;
079    import com.liferay.portal.kernel.util.StringUtil;
080    import com.liferay.portal.kernel.util.UnicodeProperties;
081    import com.liferay.portal.kernel.util.Validator;
082    import com.liferay.portal.kernel.workflow.WorkflowConstants;
083    import com.liferay.portal.kernel.workflow.WorkflowHandlerRegistryUtil;
084    import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
085    import com.liferay.portal.model.Account;
086    import com.liferay.portal.model.Company;
087    import com.liferay.portal.model.CompanyConstants;
088    import com.liferay.portal.model.Contact;
089    import com.liferay.portal.model.ContactConstants;
090    import com.liferay.portal.model.Group;
091    import com.liferay.portal.model.GroupConstants;
092    import com.liferay.portal.model.Layout;
093    import com.liferay.portal.model.Organization;
094    import com.liferay.portal.model.PasswordPolicy;
095    import com.liferay.portal.model.ResourceConstants;
096    import com.liferay.portal.model.Role;
097    import com.liferay.portal.model.RoleConstants;
098    import com.liferay.portal.model.Team;
099    import com.liferay.portal.model.Ticket;
100    import com.liferay.portal.model.TicketConstants;
101    import com.liferay.portal.model.User;
102    import com.liferay.portal.model.UserGroup;
103    import com.liferay.portal.model.UserGroupRole;
104    import com.liferay.portal.model.impl.LayoutImpl;
105    import com.liferay.portal.model.impl.UserCacheModel;
106    import com.liferay.portal.model.impl.UserImpl;
107    import com.liferay.portal.security.auth.AuthPipeline;
108    import com.liferay.portal.security.auth.Authenticator;
109    import com.liferay.portal.security.auth.EmailAddressGenerator;
110    import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
111    import com.liferay.portal.security.auth.EmailAddressValidator;
112    import com.liferay.portal.security.auth.EmailAddressValidatorFactory;
113    import com.liferay.portal.security.auth.FullNameDefinition;
114    import com.liferay.portal.security.auth.FullNameDefinitionFactory;
115    import com.liferay.portal.security.auth.FullNameGenerator;
116    import com.liferay.portal.security.auth.FullNameGeneratorFactory;
117    import com.liferay.portal.security.auth.FullNameValidator;
118    import com.liferay.portal.security.auth.FullNameValidatorFactory;
119    import com.liferay.portal.security.auth.PrincipalException;
120    import com.liferay.portal.security.auth.PrincipalThreadLocal;
121    import com.liferay.portal.security.auth.ScreenNameGenerator;
122    import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
123    import com.liferay.portal.security.auth.ScreenNameValidator;
124    import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
125    import com.liferay.portal.security.ldap.LDAPSettingsUtil;
126    import com.liferay.portal.security.permission.PermissionCacheUtil;
127    import com.liferay.portal.security.pwd.PasswordEncryptorUtil;
128    import com.liferay.portal.security.pwd.PwdAuthenticator;
129    import com.liferay.portal.security.pwd.PwdToolkitUtil;
130    import com.liferay.portal.security.pwd.RegExpToolkit;
131    import com.liferay.portal.service.BaseServiceImpl;
132    import com.liferay.portal.service.ServiceContext;
133    import com.liferay.portal.service.ServiceContextThreadLocal;
134    import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
135    import com.liferay.portal.service.persistence.UserGroupRolePK;
136    import com.liferay.portal.util.PortalUtil;
137    import com.liferay.portal.util.PrefsPropsUtil;
138    import com.liferay.portal.util.PropsValues;
139    import com.liferay.portal.util.SubscriptionSender;
140    import com.liferay.portlet.messageboards.model.MBMessage;
141    import com.liferay.portlet.social.model.SocialRelation;
142    import com.liferay.portlet.social.model.SocialRelationConstants;
143    import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
144    import com.liferay.util.Encryptor;
145    import com.liferay.util.EncryptorException;
146    
147    import java.io.Serializable;
148    
149    import java.util.ArrayList;
150    import java.util.Arrays;
151    import java.util.Calendar;
152    import java.util.Collections;
153    import java.util.Date;
154    import java.util.HashMap;
155    import java.util.HashSet;
156    import java.util.LinkedHashMap;
157    import java.util.LinkedHashSet;
158    import java.util.List;
159    import java.util.Locale;
160    import java.util.Map;
161    import java.util.Set;
162    import java.util.concurrent.Callable;
163    import java.util.concurrent.ConcurrentHashMap;
164    
165    import javax.portlet.PortletPreferences;
166    
167    /**
168     * Provides the local service for accessing, adding, authenticating, deleting,
169     * and updating users.
170     *
171     * @author Brian Wing Shun Chan
172     * @author Scott Lee
173     * @author Raymond Aug??
174     * @author Jorge Ferrer
175     * @author Julio Camarero
176     * @author Wesley Gong
177     * @author Zsigmond Rab
178     */
179    public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
180    
181            /**
182             * Adds a default admin user for the company.
183             *
184             * @param  companyId the primary key of the user's company
185             * @param  screenName the user's screen name
186             * @param  emailAddress the user's email address
187             * @param  locale the user's locale
188             * @param  firstName the user's first name
189             * @param  middleName the user's middle name
190             * @param  lastName the user's last name
191             * @return the new default admin user
192             * @throws PortalException n if a portal exception occurred
193             */
194            @Override
195            public User addDefaultAdminUser(
196                            long companyId, String screenName, String emailAddress,
197                            Locale locale, String firstName, String middleName, String lastName)
198                    throws PortalException {
199    
200                    long creatorUserId = 0;
201                    boolean autoPassword = false;
202                    String password1 = PropsValues.DEFAULT_ADMIN_PASSWORD;
203                    String password2 = password1;
204                    boolean autoScreenName = false;
205    
206                    screenName = getLogin(screenName);
207    
208                    for (int i = 1;; i++) {
209                            User screenNameUser = userPersistence.fetchByC_SN(
210                                    companyId, screenName);
211    
212                            if (screenNameUser == null) {
213                                    break;
214                            }
215    
216                            screenName = screenName + i;
217                    }
218    
219                    long facebookId = 0;
220                    String openId = StringPool.BLANK;
221                    long prefixId = 0;
222                    long suffixId = 0;
223                    boolean male = true;
224                    int birthdayMonth = Calendar.JANUARY;
225                    int birthdayDay = 1;
226                    int birthdayYear = 1970;
227                    String jobTitle = StringPool.BLANK;
228    
229                    Group guestGroup = groupLocalService.getGroup(
230                            companyId, GroupConstants.GUEST);
231    
232                    long[] groupIds = {guestGroup.getGroupId()};
233    
234                    long[] organizationIds = null;
235    
236                    Role adminRole = roleLocalService.getRole(
237                            companyId, RoleConstants.ADMINISTRATOR);
238    
239                    Role powerUserRole = roleLocalService.getRole(
240                            companyId, RoleConstants.POWER_USER);
241    
242                    long[] roleIds = {adminRole.getRoleId(), powerUserRole.getRoleId()};
243    
244                    long[] userGroupIds = null;
245                    boolean sendEmail = false;
246                    ServiceContext serviceContext = new ServiceContext();
247    
248                    User defaultAdminUser = addUser(
249                            creatorUserId, companyId, autoPassword, password1, password2,
250                            autoScreenName, screenName, emailAddress, facebookId, openId,
251                            locale, firstName, middleName, lastName, prefixId, suffixId, male,
252                            birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
253                            organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
254    
255                    updateEmailAddressVerified(defaultAdminUser.getUserId(), true);
256    
257                    updateLastLogin(
258                            defaultAdminUser.getUserId(), defaultAdminUser.getLoginIP());
259    
260                    updatePasswordReset(defaultAdminUser.getUserId(), false);
261    
262                    return defaultAdminUser;
263            }
264    
265            /**
266             * Adds the user to the default groups, unless the user is already in these
267             * groups. The default groups can be specified in
268             * <code>portal.properties</code> with the key
269             * <code>admin.default.group.names</code>.
270             *
271             * @param  userId the primary key of the user
272             * @throws PortalException if a user with the primary key could not be found
273             */
274            @Override
275            public void addDefaultGroups(long userId) throws PortalException {
276                    User user = userPersistence.findByPrimaryKey(userId);
277    
278                    Set<Long> groupIdsSet = new HashSet<>();
279    
280                    String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
281                            user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
282                            StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
283    
284                    for (String defaultGroupName : defaultGroupNames) {
285                            Company company = companyPersistence.findByPrimaryKey(
286                                    user.getCompanyId());
287    
288                            Account account = company.getAccount();
289    
290                            if (StringUtil.equalsIgnoreCase(
291                                            defaultGroupName, account.getName())) {
292    
293                                    defaultGroupName = GroupConstants.GUEST;
294                            }
295    
296                            Group group = groupPersistence.fetchByC_GK(
297                                    user.getCompanyId(), defaultGroupName);
298    
299                            if ((group != null) &&
300                                    !userPersistence.containsGroup(
301                                            userId, group.getGroupId())) {
302    
303                                    groupIdsSet.add(group.getGroupId());
304                            }
305                    }
306    
307                    String[] defaultOrganizationGroupNames = PrefsPropsUtil.getStringArray(
308                            user.getCompanyId(),
309                            PropsKeys.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES,
310                            StringPool.NEW_LINE,
311                            PropsValues.ADMIN_DEFAULT_ORGANIZATION_GROUP_NAMES);
312    
313                    for (String defaultOrganizationGroupName :
314                                    defaultOrganizationGroupNames) {
315    
316                            defaultOrganizationGroupName +=
317                                    GroupLocalServiceImpl.ORGANIZATION_NAME_SUFFIX;
318    
319                            Group group = groupPersistence.fetchByC_GK(
320                                    user.getCompanyId(), defaultOrganizationGroupName);
321    
322                            if ((group != null) &&
323                                    !userPersistence.containsGroup(
324                                            userId, group.getGroupId())) {
325    
326                                    groupIdsSet.add(group.getGroupId());
327                            }
328                    }
329    
330                    long[] groupIds = ArrayUtil.toArray(
331                            groupIdsSet.toArray(new Long[groupIdsSet.size()]));
332    
333                    groupLocalService.addUserGroups(userId, groupIds);
334            }
335    
336            /**
337             * Adds the user to the default roles, unless the user already has these
338             * roles. The default roles can be specified in
339             * <code>portal.properties</code> with the key
340             * <code>admin.default.role.names</code>.
341             *
342             * @param  userId the primary key of the user
343             * @throws PortalException if a user with the primary key could not be found
344             */
345            @Override
346            public void addDefaultRoles(long userId) throws PortalException {
347                    User user = userPersistence.findByPrimaryKey(userId);
348    
349                    Set<Long> roleIdSet = new HashSet<>();
350    
351                    String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
352                            user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
353                            StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
354    
355                    for (String defaultRoleName : defaultRoleNames) {
356                            Role role = rolePersistence.fetchByC_N(
357                                    user.getCompanyId(), defaultRoleName);
358    
359                            if ((role != null) &&
360                                    !userPersistence.containsRole(userId, role.getRoleId())) {
361    
362                                    roleIdSet.add(role.getRoleId());
363                            }
364                    }
365    
366                    Set<Long> groupRoleIdsSet = new HashSet<>();
367                    Set<Long> regularRoleIdsSet = new HashSet<>();
368    
369                    long[] roleIds = ArrayUtil.toLongArray(roleIdSet);
370    
371                    roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
372    
373                    for (long roleId : roleIds) {
374                            Role role = roleLocalService.getRole(roleId);
375    
376                            if (role.getType() == RoleConstants.TYPE_REGULAR) {
377                                    regularRoleIdsSet.add(roleId);
378                            }
379                            else {
380                                    groupRoleIdsSet.add(roleId);
381                            }
382                    }
383    
384                    long[] regularRoleIds = ArrayUtil.toLongArray(regularRoleIdsSet);
385    
386                    userPersistence.addRoles(userId, regularRoleIds);
387    
388                    Set<UserGroupRole> userGroupRolesSet = new LinkedHashSet<>();
389    
390                    long[] groupIds = user.getGroupIds();
391    
392                    for (long groupRoleId : groupRoleIdsSet) {
393                            for (long groupId : groupIds) {
394                                    UserGroupRolePK userGroupRolePK = new UserGroupRolePK(
395                                            userId, groupId, groupRoleId);
396    
397                                    UserGroupRole userGroupRole = userGroupRolePersistence.create(
398                                            userGroupRolePK);
399    
400                                    userGroupRolesSet.add(userGroupRole);
401                            }
402                    }
403    
404                    List<UserGroupRole> previousUserGroupRoles =
405                            userGroupRolePersistence.findByUserId(userId);
406    
407                    updateUserGroupRoles(
408                            user, groupIds, null, new ArrayList<>(userGroupRolesSet),
409                            previousUserGroupRoles);
410            }
411    
412            /**
413             * Adds the user to the default user groups, unless the user is already in
414             * these user groups. The default user groups can be specified in
415             * <code>portal.properties</code> with the property
416             * <code>admin.default.user.group.names</code>.
417             *
418             * @param  userId the primary key of the user
419             * @throws PortalException if a user with the primary key could not be found
420             */
421            @Override
422            @SuppressWarnings("deprecation")
423            public void addDefaultUserGroups(long userId) throws PortalException {
424                    User user = userPersistence.findByPrimaryKey(userId);
425    
426                    Set<Long> userGroupIdSet = new HashSet<>();
427    
428                    String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
429                            user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
430                            StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
431    
432                    for (String defaultUserGroupName : defaultUserGroupNames) {
433                            UserGroup userGroup = userGroupPersistence.fetchByC_N(
434                                    user.getCompanyId(), defaultUserGroupName);
435    
436                            if ((userGroup != null) &&
437                                    !userPersistence.containsUserGroup(
438                                            userId, userGroup.getUserGroupId())) {
439    
440                                    userGroupIdSet.add(userGroup.getUserGroupId());
441                            }
442                    }
443    
444                    long[] userGroupIds = ArrayUtil.toArray(
445                            userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
446    
447                    if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
448                            for (long userGroupId : userGroupIds) {
449                                    userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
450                            }
451                    }
452    
453                    userPersistence.addUserGroups(userId, userGroupIds);
454            }
455    
456            /**
457             * Adds the users to the group.
458             *
459             * @param  groupId the primary key of the group
460             * @param  userIds the primary keys of the users
461             * @throws PortalException if a group or user with the primary key could not
462             *         be found
463             */
464            @Override
465            public void addGroupUsers(long groupId, long[] userIds)
466                    throws PortalException {
467    
468                    groupPersistence.addUsers(groupId, userIds);
469    
470                    reindex(userIds);
471    
472                    PermissionCacheUtil.clearCache(userIds);
473    
474                    addDefaultRolesAndTeams(groupId, userIds);
475            }
476    
477            /**
478             * Adds the users to the organization.
479             *
480             * @param  organizationId the primary key of the organization
481             * @param  userIds the primary keys of the users
482             * @throws PortalException if an organization or user with the primary key
483             *         could not be found
484             */
485            @Override
486            public void addOrganizationUsers(long organizationId, long[] userIds)
487                    throws PortalException {
488    
489                    organizationPersistence.addUsers(organizationId, userIds);
490    
491                    reindex(userIds);
492    
493                    PermissionCacheUtil.clearCache(userIds);
494            }
495    
496            /**
497             * Assigns the password policy to the users, removing any other currently
498             * assigned password policies.
499             *
500             * @param passwordPolicyId the primary key of the password policy
501             * @param userIds the primary keys of the users
502             */
503            @Override
504            public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds) {
505                    passwordPolicyRelLocalService.addPasswordPolicyRels(
506                            passwordPolicyId, User.class.getName(), userIds);
507            }
508    
509            /**
510             * Adds the users to the role.
511             *
512             * @param  roleId the primary key of the role
513             * @param  userIds the primary keys of the users
514             * @throws PortalException if a role or user with the primary key could not
515             *         be found
516             */
517            @Override
518            public void addRoleUsers(long roleId, long[] userIds)
519                    throws PortalException {
520    
521                    rolePersistence.addUsers(roleId, userIds);
522    
523                    reindex(userIds);
524    
525                    PermissionCacheUtil.clearCache(userIds);
526            }
527    
528            /**
529             * Adds the users to the team.
530             *
531             * @param  teamId the primary key of the team
532             * @param  userIds the primary keys of the users
533             * @throws PortalException if a team or user with the primary key could not
534             *         be found
535             */
536            @Override
537            public void addTeamUsers(long teamId, long[] userIds)
538                    throws PortalException {
539    
540                    teamPersistence.addUsers(teamId, userIds);
541    
542                    reindex(userIds);
543    
544                    PermissionCacheUtil.clearCache(userIds);
545            }
546    
547            /**
548             * Adds a user.
549             *
550             * <p>
551             * This method handles the creation and bookkeeping of the user including
552             * its resources, metadata, and internal data structures. It is not
553             * necessary to make subsequent calls to any methods to setup default
554             * groups, resources, etc.
555             * </p>
556             *
557             * @param  creatorUserId the primary key of the creator
558             * @param  companyId the primary key of the user's company
559             * @param  autoPassword whether a password should be automatically generated
560             *         for the user
561             * @param  password1 the user's password
562             * @param  password2 the user's password confirmation
563             * @param  autoScreenName whether a screen name should be automatically
564             *         generated for the user
565             * @param  screenName the user's screen name
566             * @param  emailAddress the user's email address
567             * @param  facebookId the user's facebook ID
568             * @param  openId the user's OpenID
569             * @param  locale the user's locale
570             * @param  firstName the user's first name
571             * @param  middleName the user's middle name
572             * @param  lastName the user's last name
573             * @param  prefixId the user's name prefix ID
574             * @param  suffixId the user's name suffix ID
575             * @param  male whether the user is male
576             * @param  birthdayMonth the user's birthday month (0-based, meaning 0 for
577             *         January)
578             * @param  birthdayDay the user's birthday day
579             * @param  birthdayYear the user's birthday year
580             * @param  jobTitle the user's job title
581             * @param  groupIds the primary keys of the user's groups
582             * @param  organizationIds the primary keys of the user's organizations
583             * @param  roleIds the primary keys of the roles this user possesses
584             * @param  userGroupIds the primary keys of the user's user groups
585             * @param  sendEmail whether to send the user an email notification about
586             *         their new account
587             * @param  serviceContext the service context to be applied (optionally
588             *         <code>null</code>). Can set the UUID (with the <code>uuid</code>
589             *         attribute), asset category IDs, asset tag names, and expando
590             *         bridge attributes for the user.
591             * @return the new user
592             * @throws PortalException if the user's information was invalid
593             */
594            @Override
595            public User addUser(
596                            long creatorUserId, long companyId, boolean autoPassword,
597                            String password1, String password2, boolean autoScreenName,
598                            String screenName, String emailAddress, long facebookId,
599                            String openId, Locale locale, String firstName, String middleName,
600                            String lastName, long prefixId, long suffixId, boolean male,
601                            int birthdayMonth, int birthdayDay, int birthdayYear,
602                            String jobTitle, long[] groupIds, long[] organizationIds,
603                            long[] roleIds, long[] userGroupIds, boolean sendEmail,
604                            ServiceContext serviceContext)
605                    throws PortalException {
606    
607                    boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
608    
609                    try {
610                            WorkflowThreadLocal.setEnabled(false);
611    
612                            if (serviceContext == null) {
613                                    serviceContext = new ServiceContext();
614                            }
615    
616                            if (serviceContext.getWorkflowAction() !=
617                                            WorkflowConstants.ACTION_PUBLISH) {
618    
619                                    serviceContext.setWorkflowAction(
620                                            WorkflowConstants.ACTION_PUBLISH);
621                            }
622    
623                            return addUserWithWorkflow(
624                                    creatorUserId, companyId, autoPassword, password1, password2,
625                                    autoScreenName, screenName, emailAddress, facebookId, openId,
626                                    locale, firstName, middleName, lastName, prefixId, suffixId,
627                                    male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
628                                    groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
629                                    serviceContext);
630                    }
631                    finally {
632                            WorkflowThreadLocal.setEnabled(workflowEnabled);
633                    }
634            }
635    
636            /**
637             * Adds the users to the user group.
638             *
639             * @param  userGroupId the primary key of the user group
640             * @param  userIds the primary keys of the users
641             * @throws PortalException if a user group or user with the primary could
642             *         could not be found
643             */
644            @Override
645            @SuppressWarnings("deprecation")
646            public void addUserGroupUsers(long userGroupId, long[] userIds)
647                    throws PortalException {
648    
649                    if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
650                            userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
651                    }
652    
653                    userGroupPersistence.addUsers(userGroupId, userIds);
654    
655                    reindex(userIds);
656    
657                    PermissionCacheUtil.clearCache(userIds);
658            }
659    
660            /**
661             * Adds a user with workflow.
662             *
663             * <p>
664             * This method handles the creation and bookkeeping of the user including
665             * its resources, metadata, and internal data structures. It is not
666             * necessary to make subsequent calls to any methods to setup default
667             * groups, resources, etc.
668             * </p>
669             *
670             * @param  creatorUserId the primary key of the creator
671             * @param  companyId the primary key of the user's company
672             * @param  autoPassword whether a password should be automatically generated
673             *         for the user
674             * @param  password1 the user's password
675             * @param  password2 the user's password confirmation
676             * @param  autoScreenName whether a screen name should be automatically
677             *         generated for the user
678             * @param  screenName the user's screen name
679             * @param  emailAddress the user's email address
680             * @param  facebookId the user's facebook ID
681             * @param  openId the user's OpenID
682             * @param  locale the user's locale
683             * @param  firstName the user's first name
684             * @param  middleName the user's middle name
685             * @param  lastName the user's last name
686             * @param  prefixId the user's name prefix ID
687             * @param  suffixId the user's name suffix ID
688             * @param  male whether the user is male
689             * @param  birthdayMonth the user's birthday month (0-based, meaning 0 for
690             *         January)
691             * @param  birthdayDay the user's birthday day
692             * @param  birthdayYear the user's birthday year
693             * @param  jobTitle the user's job title
694             * @param  groupIds the primary keys of the user's groups
695             * @param  organizationIds the primary keys of the user's organizations
696             * @param  roleIds the primary keys of the roles this user possesses
697             * @param  userGroupIds the primary keys of the user's user groups
698             * @param  sendEmail whether to send the user an email notification about
699             *         their new account
700             * @param  serviceContext the service context to be applied (optionally
701             *         <code>null</code>). Can set the UUID (with the <code>uuid</code>
702             *         attribute), asset category IDs, asset tag names, and expando
703             *         bridge attributes for the user.
704             * @return the new user
705             * @throws PortalException if the user's information was invalid
706             */
707            @Override
708            @SuppressWarnings("deprecation")
709            public User addUserWithWorkflow(
710                            long creatorUserId, long companyId, boolean autoPassword,
711                            String password1, String password2, boolean autoScreenName,
712                            String screenName, String emailAddress, long facebookId,
713                            String openId, Locale locale, String firstName, String middleName,
714                            String lastName, long prefixId, long suffixId, boolean male,
715                            int birthdayMonth, int birthdayDay, int birthdayYear,
716                            String jobTitle, long[] groupIds, long[] organizationIds,
717                            long[] roleIds, long[] userGroupIds, boolean sendEmail,
718                            ServiceContext serviceContext)
719                    throws PortalException {
720    
721                    // User
722    
723                    Company company = companyPersistence.findByPrimaryKey(companyId);
724                    screenName = getLogin(screenName);
725                    openId = StringUtil.trim(openId);
726    
727                    if (PrefsPropsUtil.getBoolean(
728                                    companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
729    
730                            autoScreenName = true;
731                    }
732    
733                    // PLACEHOLDER 01
734    
735                    long userId = counterLocalService.increment();
736    
737                    EmailAddressGenerator emailAddressGenerator =
738                            EmailAddressGeneratorFactory.getInstance();
739    
740                    if ((emailAddress == null) ||
741                            emailAddressGenerator.isGenerated(emailAddress)) {
742    
743                            emailAddress = StringPool.BLANK;
744                    }
745                    else {
746                            emailAddress = StringUtil.toLowerCase(emailAddress.trim());
747                    }
748    
749                    if (!PrefsPropsUtil.getBoolean(
750                                    companyId, PropsKeys.USERS_EMAIL_ADDRESS_REQUIRED) &&
751                            Validator.isNull(emailAddress)) {
752    
753                            emailAddress = emailAddressGenerator.generate(companyId, userId);
754                    }
755    
756                    validate(
757                            companyId, userId, autoPassword, password1, password2,
758                            autoScreenName, screenName, emailAddress, openId, firstName,
759                            middleName, lastName, organizationIds, locale);
760    
761                    if (!autoPassword) {
762                            if (Validator.isNull(password1) || Validator.isNull(password2)) {
763                                    throw new UserPasswordException.MustNotBeNull(userId);
764                            }
765                    }
766    
767                    if (autoScreenName) {
768                            ScreenNameGenerator screenNameGenerator =
769                                    ScreenNameGeneratorFactory.getInstance();
770    
771                            try {
772                                    screenName = screenNameGenerator.generate(
773                                            companyId, userId, emailAddress);
774                            }
775                            catch (Exception e) {
776                                    throw new SystemException(e);
777                            }
778                    }
779    
780                    User defaultUser = getDefaultUser(companyId);
781    
782                    FullNameGenerator fullNameGenerator =
783                            FullNameGeneratorFactory.getInstance();
784    
785                    String fullName = fullNameGenerator.getFullName(
786                            firstName, middleName, lastName);
787    
788                    String greeting = LanguageUtil.format(
789                            locale, "welcome-x", fullName, false);
790    
791                    User user = userPersistence.create(userId);
792    
793                    if (serviceContext != null) {
794                            String uuid = serviceContext.getUuid();
795    
796                            if (Validator.isNotNull(uuid)) {
797                                    user.setUuid(uuid);
798                            }
799                    }
800    
801                    user.setCompanyId(companyId);
802                    user.setDefaultUser(false);
803                    user.setContactId(counterLocalService.increment());
804    
805                    if (Validator.isNotNull(password1)) {
806                            user.setPassword(PasswordEncryptorUtil.encrypt(password1));
807                            user.setPasswordUnencrypted(password1);
808                    }
809    
810                    user.setPasswordEncrypted(true);
811    
812                    PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
813    
814                    if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
815                            passwordPolicy.isChangeRequired()) {
816    
817                            user.setPasswordReset(true);
818                    }
819                    else {
820                            user.setPasswordReset(false);
821                    }
822    
823                    user.setDigest(StringPool.BLANK);
824                    user.setScreenName(screenName);
825                    user.setEmailAddress(emailAddress);
826                    user.setFacebookId(facebookId);
827    
828                    Long ldapServerId = null;
829    
830                    if (serviceContext != null) {
831                            ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
832                    }
833    
834                    if (ldapServerId != null) {
835                            user.setLdapServerId(ldapServerId);
836                    }
837                    else {
838                            user.setLdapServerId(-1);
839                    }
840    
841                    user.setOpenId(openId);
842                    user.setLanguageId(LocaleUtil.toLanguageId(locale));
843                    user.setTimeZoneId(defaultUser.getTimeZoneId());
844                    user.setGreeting(greeting);
845                    user.setFirstName(firstName);
846                    user.setMiddleName(middleName);
847                    user.setLastName(lastName);
848                    user.setJobTitle(jobTitle);
849                    user.setStatus(WorkflowConstants.STATUS_DRAFT);
850                    user.setExpandoBridgeAttributes(serviceContext);
851    
852                    userPersistence.update(user, serviceContext);
853    
854                    // Contact
855    
856                    String creatorUserName = StringPool.BLANK;
857    
858                    if (creatorUserId <= 0) {
859                            creatorUserId = user.getUserId();
860    
861                            // Don't grab the full name from the User object because it doesn't
862                            // have a corresponding Contact object yet
863    
864                            //creatorUserName = user.getFullName();
865                    }
866                    else {
867                            User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
868    
869                            creatorUserName = creatorUser.getFullName();
870                    }
871    
872                    Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
873    
874                    Contact contact = contactPersistence.create(user.getContactId());
875    
876                    contact.setCompanyId(user.getCompanyId());
877                    contact.setUserId(creatorUserId);
878                    contact.setUserName(creatorUserName);
879                    contact.setClassName(User.class.getName());
880                    contact.setClassPK(user.getUserId());
881                    contact.setAccountId(company.getAccountId());
882                    contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
883                    contact.setEmailAddress(user.getEmailAddress());
884                    contact.setFirstName(firstName);
885                    contact.setMiddleName(middleName);
886                    contact.setLastName(lastName);
887                    contact.setPrefixId(prefixId);
888                    contact.setSuffixId(suffixId);
889                    contact.setMale(male);
890                    contact.setBirthday(birthday);
891                    contact.setJobTitle(jobTitle);
892    
893                    contactPersistence.update(contact, serviceContext);
894    
895                    // Group
896    
897                    groupLocalService.addGroup(
898                            user.getUserId(), GroupConstants.DEFAULT_PARENT_GROUP_ID,
899                            User.class.getName(), user.getUserId(),
900                            GroupConstants.DEFAULT_LIVE_GROUP_ID, (Map<Locale, String>)null,
901                            null, 0, true, GroupConstants.DEFAULT_MEMBERSHIP_RESTRICTION,
902                            StringPool.SLASH + screenName, false, true, null);
903    
904                    // Groups
905    
906                    if (groupIds != null) {
907                            List<Group> groups = new ArrayList<>();
908    
909                            for (long groupId : groupIds) {
910                                    Group group = groupLocalService.fetchGroup(groupId);
911    
912                                    if (group != null) {
913                                            groups.add(group);
914                                    }
915                                    else {
916                                            if (_log.isWarnEnabled()) {
917                                                    _log.warn("Group " + groupId + " does not exist");
918                                            }
919                                    }
920                            }
921    
922                            groupLocalService.addUserGroups(userId, groups);
923                    }
924    
925                    addDefaultGroups(userId);
926    
927                    // Organizations
928    
929                    updateOrganizations(userId, organizationIds, false);
930    
931                    // Roles
932    
933                    if (roleIds != null) {
934                            roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
935    
936                            userPersistence.setRoles(userId, roleIds);
937                    }
938    
939                    addDefaultRoles(userId);
940    
941                    // User groups
942    
943                    if (userGroupIds != null) {
944                            if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
945                                    for (long userGroupId : userGroupIds) {
946                                            userGroupLocalService.copyUserGroupLayouts(
947                                                    userGroupId, new long[] {userId});
948                                    }
949                            }
950    
951                            userPersistence.setUserGroups(userId, userGroupIds);
952                    }
953    
954                    addDefaultUserGroups(userId);
955    
956                    // Resources
957    
958                    resourceLocalService.addResources(
959                            companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
960                            false, false, false);
961    
962                    // Asset
963    
964                    if (serviceContext != null) {
965                            updateAsset(
966                                    creatorUserId, user, serviceContext.getAssetCategoryIds(),
967                                    serviceContext.getAssetTagNames());
968                    }
969    
970                    // Indexer
971    
972                    if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
973                            reindex(user);
974                    }
975    
976                    // Workflow
977    
978                    long workflowUserId = creatorUserId;
979    
980                    if (workflowUserId == userId) {
981                            workflowUserId = defaultUser.getUserId();
982                    }
983    
984                    ServiceContext workflowServiceContext = serviceContext;
985    
986                    if (workflowServiceContext == null) {
987                            workflowServiceContext = new ServiceContext();
988                    }
989    
990                    workflowServiceContext.setAttribute("autoPassword", autoPassword);
991                    workflowServiceContext.setAttribute("passwordUnencrypted", password1);
992                    workflowServiceContext.setAttribute("sendEmail", sendEmail);
993    
994                    WorkflowHandlerRegistryUtil.startWorkflowInstance(
995                            companyId, workflowUserId, User.class.getName(), userId, user,
996                            workflowServiceContext);
997    
998                    if (serviceContext != null) {
999                            String passwordUnencrypted = (String)serviceContext.getAttribute(
1000                                    "passwordUnencrypted");
1001    
1002                            if (Validator.isNotNull(passwordUnencrypted)) {
1003                                    user.setPasswordUnencrypted(passwordUnencrypted);
1004                            }
1005                    }
1006    
1007                    return user;
1008            }
1009    
1010            @Override
1011            public void afterPropertiesSet() {
1012                    super.afterPropertiesSet();
1013    
1014                    PortalCache<Serializable, Serializable> portalCache =
1015                            EntityCacheUtil.getPortalCache(UserImpl.class);
1016    
1017                    PortalCacheMapSynchronizeUtil.synchronize(
1018                            portalCache, _defaultUsers,
1019                            new Synchronizer<Serializable, Serializable>() {
1020    
1021                                    @Override
1022                                    public void onSynchronize(
1023                                            Map<? extends Serializable, ? extends Serializable> map,
1024                                            Serializable key, Serializable value, int timeToLive) {
1025    
1026                                            if (!(value instanceof UserCacheModel)) {
1027                                                    return;
1028                                            }
1029    
1030                                            UserCacheModel userCacheModel = (UserCacheModel)value;
1031    
1032                                            if (userCacheModel.defaultUser) {
1033                                                    _defaultUsers.remove(userCacheModel.companyId);
1034                                            }
1035                                    }
1036    
1037                            });
1038            }
1039    
1040            /**
1041             * Attempts to authenticate the user by their email address and password,
1042             * while using the AuthPipeline.
1043             *
1044             * @param  companyId the primary key of the user's company
1045             * @param  emailAddress the user's email address
1046             * @param  password the user's password
1047             * @param  headerMap the header map from the authentication request
1048             * @param  parameterMap the parameter map from the authentication request
1049             * @param  resultsMap the map of authentication results (may be nil). After
1050             *         a successful authentication the user's primary key will be placed
1051             *         under the key <code>userId</code>.
1052             * @return the authentication status. This can be {@link
1053             *         Authenticator#FAILURE} indicating that the user's credentials are
1054             *         invalid, {@link Authenticator#SUCCESS} indicating a successful
1055             *         login, or {@link Authenticator#DNE} indicating that a user with
1056             *         that login does not exist.
1057             * @throws PortalException if <code>emailAddress</code> or
1058             *         <code>password</code> was <code>null</code>
1059             * @see    AuthPipeline
1060             */
1061            @Override
1062            public int authenticateByEmailAddress(
1063                            long companyId, String emailAddress, String password,
1064                            Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1065                            Map<String, Object> resultsMap)
1066                    throws PortalException {
1067    
1068                    return authenticate(
1069                            companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
1070                            headerMap, parameterMap, resultsMap);
1071            }
1072    
1073            /**
1074             * Attempts to authenticate the user by their screen name and password,
1075             * while using the AuthPipeline.
1076             *
1077             * @param  companyId the primary key of the user's company
1078             * @param  screenName the user's screen name
1079             * @param  password the user's password
1080             * @param  headerMap the header map from the authentication request
1081             * @param  parameterMap the parameter map from the authentication request
1082             * @param  resultsMap the map of authentication results (may be nil). After
1083             *         a successful authentication the user's primary key will be placed
1084             *         under the key <code>userId</code>.
1085             * @return the authentication status. This can be {@link
1086             *         Authenticator#FAILURE} indicating that the user's credentials are
1087             *         invalid, {@link Authenticator#SUCCESS} indicating a successful
1088             *         login, or {@link Authenticator#DNE} indicating that a user with
1089             *         that login does not exist.
1090             * @throws PortalException if <code>screenName</code> or
1091             *         <code>password</code> was <code>null</code>
1092             * @see    AuthPipeline
1093             */
1094            @Override
1095            public int authenticateByScreenName(
1096                            long companyId, String screenName, String password,
1097                            Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1098                            Map<String, Object> resultsMap)
1099                    throws PortalException {
1100    
1101                    return authenticate(
1102                            companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
1103                            headerMap, parameterMap, resultsMap);
1104            }
1105    
1106            /**
1107             * Attempts to authenticate the user by their primary key and password,
1108             * while using the AuthPipeline.
1109             *
1110             * @param  companyId the primary key of the user's company
1111             * @param  userId the user's primary key
1112             * @param  password the user's password
1113             * @param  headerMap the header map from the authentication request
1114             * @param  parameterMap the parameter map from the authentication request
1115             * @param  resultsMap the map of authentication results (may be nil). After
1116             *         a successful authentication the user's primary key will be placed
1117             *         under the key <code>userId</code>.
1118             * @return the authentication status. This can be {@link
1119             *         Authenticator#FAILURE} indicating that the user's credentials are
1120             *         invalid, {@link Authenticator#SUCCESS} indicating a successful
1121             *         login, or {@link Authenticator#DNE} indicating that a user with
1122             *         that login does not exist.
1123             * @throws PortalException if <code>userId</code> or <code>password</code>
1124             *         was <code>null</code>
1125             * @see    AuthPipeline
1126             */
1127            @Override
1128            public int authenticateByUserId(
1129                            long companyId, long userId, String password,
1130                            Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
1131                            Map<String, Object> resultsMap)
1132                    throws PortalException {
1133    
1134                    return authenticate(
1135                            companyId, String.valueOf(userId), password,
1136                            CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap, resultsMap);
1137            }
1138    
1139            /**
1140             * Attempts to authenticate the user using HTTP basic access authentication,
1141             * without using the AuthPipeline. Primarily used for authenticating users
1142             * of <code>tunnel-web</code>.
1143             *
1144             * <p>
1145             * Authentication type specifies what <code>login</code> contains.The valid
1146             * values are:
1147             * </p>
1148             *
1149             * <ul>
1150             * <li>
1151             * <code>CompanyConstants.AUTH_TYPE_EA</code> - <code>login</code> is the
1152             * user's email address
1153             * </li>
1154             * <li>
1155             * <code>CompanyConstants.AUTH_TYPE_SN</code> - <code>login</code> is the
1156             * user's screen name
1157             * </li>
1158             * <li>
1159             * <code>CompanyConstants.AUTH_TYPE_ID</code> - <code>login</code> is the
1160             * user's primary key
1161             * </li>
1162             * </ul>
1163             *
1164             * @param  companyId the primary key of the user's company
1165             * @param  authType the type of authentication to perform
1166             * @param  login either the user's email address, screen name, or primary
1167             *         key depending on the value of <code>authType</code>
1168             * @param  password the user's password
1169             * @return the user's primary key if authentication is successful;
1170             *         <code>0</code> otherwise
1171             * @throws PortalException if a portal exception occurred
1172             */
1173            @Override
1174            @Transactional(propagation = Propagation.SUPPORTS)
1175            public long authenticateForBasic(
1176                            long companyId, String authType, String login, String password)
1177                    throws PortalException {
1178    
1179                    if (PropsValues.AUTH_LOGIN_DISABLED) {
1180                            return 0;
1181                    }
1182    
1183                    User user = null;
1184    
1185                    if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
1186                            user = fetchUserByEmailAddress(companyId, login);
1187                    }
1188                    else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
1189                            user = fetchUserByScreenName(companyId, login);
1190                    }
1191                    else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
1192                            user = userPersistence.fetchByPrimaryKey(GetterUtil.getLong(login));
1193                    }
1194    
1195                    if (user == null) {
1196                            return 0;
1197                    }
1198    
1199                    if (!isUserAllowedToAuthenticate(user)) {
1200                            return 0;
1201                    }
1202    
1203                    if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
1204                            return user.getUserId();
1205                    }
1206    
1207                    String userPassword = user.getPassword();
1208    
1209                    if (!user.isPasswordEncrypted()) {
1210                            userPassword = PasswordEncryptorUtil.encrypt(userPassword);
1211                    }
1212    
1213                    String encPassword = PasswordEncryptorUtil.encrypt(
1214                            password, userPassword);
1215    
1216                    if (userPassword.equals(password) || userPassword.equals(encPassword)) {
1217                            resetFailedLoginAttempts(user);
1218    
1219                            return user.getUserId();
1220                    }
1221    
1222                    handleAuthenticationFailure(
1223                            login, authType, user, Collections.<String, String[]>emptyMap(),
1224                            Collections.<String, String[]>emptyMap());
1225    
1226                    return 0;
1227            }
1228    
1229            /**
1230             * Attempts to authenticate the user using HTTP digest access
1231             * authentication, without using the AuthPipeline. Primarily used for
1232             * authenticating users of <code>tunnel-web</code>.
1233             *
1234             * @param  companyId the primary key of the user's company
1235             * @param  username either the user's email address, screen name, or primary
1236             *         key
1237             * @param  realm unused
1238             * @param  nonce the number used once
1239             * @param  method the request method
1240             * @param  uri the request URI
1241             * @param  response the authentication response hash
1242             * @return the user's primary key if authentication is successful;
1243             *         <code>0</code> otherwise
1244             * @throws PortalException if a portal exception occurred
1245             */
1246            @Override
1247            @Transactional(propagation = Propagation.SUPPORTS)
1248            public long authenticateForDigest(
1249                            long companyId, String username, String realm, String nonce,
1250                            String method, String uri, String response)
1251                    throws PortalException {
1252    
1253                    if (PropsValues.AUTH_LOGIN_DISABLED) {
1254                            return 0;
1255                    }
1256    
1257                    // Get User
1258    
1259                    User user = fetchUserByEmailAddress(companyId, username);
1260    
1261                    if (user == null) {
1262                            user = fetchUserByScreenName(companyId, username);
1263                    }
1264    
1265                    if (user == null) {
1266                            user = userPersistence.fetchByPrimaryKey(
1267                                    GetterUtil.getLong(username));
1268                    }
1269    
1270                    if (user == null) {
1271                            return 0;
1272                    }
1273    
1274                    if (!isUserAllowedToAuthenticate(user)) {
1275                            return 0;
1276                    }
1277    
1278                    // Verify digest
1279    
1280                    String digest = user.getDigest();
1281    
1282                    if (Validator.isNull(digest)) {
1283                            _log.error(
1284                                    "User must first login through the portal " + user.getUserId());
1285    
1286                            return 0;
1287                    }
1288    
1289                    String[] digestArray = StringUtil.split(user.getDigest());
1290    
1291                    for (String ha1 : digestArray) {
1292                            String ha2 = DigesterUtil.digestHex(Digester.MD5, method, uri);
1293    
1294                            String curResponse = DigesterUtil.digestHex(
1295                                    Digester.MD5, ha1, nonce, ha2);
1296    
1297                            if (response.equals(curResponse)) {
1298                                    resetFailedLoginAttempts(user);
1299    
1300                                    return user.getUserId();
1301                            }
1302                    }
1303    
1304                    Company company = companyPersistence.findByPrimaryKey(companyId);
1305    
1306                    handleAuthenticationFailure(
1307                            username, company.getAuthType(), user,
1308                            new HashMap<String, String[]>(), new HashMap<String, String[]>());
1309    
1310                    return 0;
1311            }
1312    
1313            /**
1314             * Attempts to authenticate the user using JAAS credentials, without using
1315             * the AuthPipeline.
1316             *
1317             * @param  userId the primary key of the user
1318             * @param  encPassword the encrypted password
1319             * @return <code>true</code> if authentication is successful;
1320             *         <code>false</code> otherwise
1321             */
1322            @Override
1323            @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1324            public boolean authenticateForJAAS(long userId, String encPassword) {
1325                    if (PropsValues.AUTH_LOGIN_DISABLED) {
1326                            return false;
1327                    }
1328    
1329                    try {
1330                            User user = userPersistence.findByPrimaryKey(userId);
1331    
1332                            if (user.isDefaultUser()) {
1333                                    if (_log.isInfoEnabled()) {
1334                                            _log.info(
1335                                                    "JAAS authentication is disabled for the default user");
1336                                    }
1337    
1338                                    return false;
1339                            }
1340                            else if (!user.isActive()) {
1341                                    if (_log.isInfoEnabled()) {
1342                                            _log.info(
1343                                                    "JAAS authentication is disabled for inactive user " +
1344                                                            userId);
1345                                    }
1346    
1347                                    return false;
1348                            }
1349    
1350                            String userPassword = user.getPassword();
1351    
1352                            if (user.isPasswordEncrypted()) {
1353                                    if (userPassword.equals(encPassword)) {
1354                                            return true;
1355                                    }
1356    
1357                                    if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1358                                            encPassword = PasswordEncryptorUtil.encrypt(
1359                                                    encPassword, userPassword);
1360    
1361                                            if (userPassword.equals(encPassword)) {
1362                                                    return true;
1363                                            }
1364                                    }
1365                            }
1366                            else {
1367                                    if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
1368                                            if (userPassword.equals(encPassword)) {
1369                                                    return true;
1370                                            }
1371                                    }
1372    
1373                                    userPassword = PasswordEncryptorUtil.encrypt(
1374                                            userPassword, encPassword);
1375    
1376                                    if (userPassword.equals(encPassword)) {
1377                                            return true;
1378                                    }
1379                            }
1380                    }
1381                    catch (Exception e) {
1382                            _log.error(e);
1383                    }
1384    
1385                    return false;
1386            }
1387    
1388            /**
1389             * Checks if the user is currently locked out based on the password policy,
1390             * and performs maintenance on the user's lockout and failed login data.
1391             *
1392             * @param  user the user
1393             * @throws PortalException if the user was determined to still be locked out
1394             */
1395            @Override
1396            public void checkLockout(User user) throws PortalException {
1397                    if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1398                            return;
1399                    }
1400    
1401                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1402    
1403                    if (!passwordPolicy.isLockout()) {
1404                            return;
1405                    }
1406    
1407                    // Reset failure count
1408    
1409                    Date now = new Date();
1410                    int failedLoginAttempts = user.getFailedLoginAttempts();
1411    
1412                    if (failedLoginAttempts > 0) {
1413                            long failedLoginTime = user.getLastFailedLoginDate().getTime();
1414                            long elapsedTime = now.getTime() - failedLoginTime;
1415                            long requiredElapsedTime =
1416                                    passwordPolicy.getResetFailureCount() * 1000;
1417    
1418                            if ((requiredElapsedTime != 0) &&
1419                                    (elapsedTime > requiredElapsedTime)) {
1420    
1421                                    user.setFailedLoginAttempts(0);
1422    
1423                                    userPersistence.update(user);
1424                            }
1425                    }
1426    
1427                    // Reset lockout
1428    
1429                    if (user.isLockout()) {
1430                            long lockoutTime = user.getLockoutDate().getTime();
1431                            long elapsedTime = now.getTime() - lockoutTime;
1432                            long requiredElapsedTime =
1433                                    passwordPolicy.getLockoutDuration() * 1000;
1434    
1435                            if ((requiredElapsedTime != 0) &&
1436                                    (elapsedTime > requiredElapsedTime)) {
1437    
1438                                    user.setLockout(false);
1439                                    user.setLockoutDate(null);
1440    
1441                                    userPersistence.update(user);
1442                            }
1443                    }
1444    
1445                    if (user.isLockout()) {
1446                            throw new UserLockoutException.PasswordPolicyLockout(
1447                                    user, passwordPolicy);
1448                    }
1449            }
1450    
1451            /**
1452             * Adds a failed login attempt to the user and updates the user's last
1453             * failed login date.
1454             *
1455             * @param user the user
1456             */
1457            @Override
1458            public void checkLoginFailure(User user) {
1459                    int failedLoginAttempts = user.getFailedLoginAttempts();
1460    
1461                    user.setLastFailedLoginDate(new Date());
1462                    user.setFailedLoginAttempts(++failedLoginAttempts);
1463    
1464                    userPersistence.update(user);
1465            }
1466    
1467            /**
1468             * Adds a failed login attempt to the user with the email address and
1469             * updates the user's last failed login date.
1470             *
1471             * @param  companyId the primary key of the user's company
1472             * @param  emailAddress the user's email address
1473             * @throws PortalException if a user with the email address could not be
1474             *         found
1475             */
1476            @Override
1477            public void checkLoginFailureByEmailAddress(
1478                            long companyId, String emailAddress)
1479                    throws PortalException {
1480    
1481                    User user = getUserByEmailAddress(companyId, emailAddress);
1482    
1483                    checkLoginFailure(user);
1484            }
1485    
1486            /**
1487             * Adds a failed login attempt to the user and updates the user's last
1488             * failed login date.
1489             *
1490             * @param  userId the primary key of the user
1491             * @throws PortalException if a user with the primary key could not be found
1492             */
1493            @Override
1494            public void checkLoginFailureById(long userId) throws PortalException {
1495                    User user = userPersistence.findByPrimaryKey(userId);
1496    
1497                    checkLoginFailure(user);
1498            }
1499    
1500            /**
1501             * Adds a failed login attempt to the user with the screen name and updates
1502             * the user's last failed login date.
1503             *
1504             * @param  companyId the primary key of the user's company
1505             * @param  screenName the user's screen name
1506             * @throws PortalException if a user with the screen name could not be found
1507             */
1508            @Override
1509            public void checkLoginFailureByScreenName(long companyId, String screenName)
1510                    throws PortalException {
1511    
1512                    User user = getUserByScreenName(companyId, screenName);
1513    
1514                    checkLoginFailure(user);
1515            }
1516    
1517            /**
1518             * Checks if the user's password is expired based on the password policy,
1519             * and performs maintenance on the user's grace login and password reset
1520             * data.
1521             *
1522             * @param  user the user
1523             * @throws PortalException if the user's password has expired and the grace
1524             *         login limit has been exceeded
1525             */
1526            @Override
1527            public void checkPasswordExpired(User user) throws PortalException {
1528                    if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1529                            return;
1530                    }
1531    
1532                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1533    
1534                    // Check if password has expired
1535    
1536                    if (isPasswordExpired(user)) {
1537                            int graceLoginCount = user.getGraceLoginCount();
1538    
1539                            if (graceLoginCount < passwordPolicy.getGraceLimit()) {
1540                                    user.setGraceLoginCount(++graceLoginCount);
1541    
1542                                    userPersistence.update(user);
1543                            }
1544                            else {
1545                                    user.setDigest(StringPool.BLANK);
1546    
1547                                    userPersistence.update(user);
1548    
1549                                    throw new PasswordExpiredException();
1550                            }
1551                    }
1552    
1553                    // Check if user should be forced to change password on first login
1554    
1555                    if (passwordPolicy.isChangeable() &&
1556                            passwordPolicy.isChangeRequired()) {
1557    
1558                            if (user.getLastLoginDate() == null) {
1559                                    user.setPasswordReset(true);
1560    
1561                                    userPersistence.update(user);
1562                            }
1563                    }
1564            }
1565    
1566            /**
1567             * Removes all the users from the organization.
1568             *
1569             * @param organizationId the primary key of the organization
1570             */
1571            @Override
1572            public void clearOrganizationUsers(long organizationId) {
1573                    organizationPersistence.clearUsers(organizationId);
1574    
1575                    PermissionCacheUtil.clearCache();
1576            }
1577    
1578            /**
1579             * Removes all the users from the user group.
1580             *
1581             * @param userGroupId the primary key of the user group
1582             */
1583            @Override
1584            public void clearUserGroupUsers(long userGroupId) {
1585                    userGroupPersistence.clearUsers(userGroupId);
1586    
1587                    PermissionCacheUtil.clearCache();
1588            }
1589    
1590            /**
1591             * Completes the user's registration by generating a password and sending
1592             * the confirmation email.
1593             *
1594             * @param  user the user
1595             * @param  serviceContext the service context to be applied. You can specify
1596             *         an unencrypted custom password for the user via attribute
1597             *         <code>passwordUnencrypted</code>. You automatically generate a
1598             *         password for the user by setting attribute
1599             *         <code>autoPassword</code> to <code>true</code>. You can send a
1600             *         confirmation email to the user by setting attribute
1601             *         <code>sendEmail</code> to <code>true</code>.
1602             * @throws PortalException if a portal exception occurred
1603             */
1604            @Override
1605            public void completeUserRegistration(
1606                            User user, ServiceContext serviceContext)
1607                    throws PortalException {
1608    
1609                    boolean autoPassword = ParamUtil.getBoolean(
1610                            serviceContext, "autoPassword");
1611    
1612                    String password = (String)serviceContext.getAttribute(
1613                            "passwordUnencrypted");
1614    
1615                    if (autoPassword) {
1616                            if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
1617                                    if (_log.isWarnEnabled()) {
1618                                            StringBundler sb = new StringBundler(4);
1619    
1620                                            sb.append("When LDAP password policy is enabled, it is ");
1621                                            sb.append("possible that portal generated passwords will ");
1622                                            sb.append("not match the LDAP policy. Using ");
1623                                            sb.append("RegExpToolkit to generate new password.");
1624    
1625                                            _log.warn(sb.toString());
1626                                    }
1627    
1628                                    RegExpToolkit regExpToolkit = new RegExpToolkit();
1629    
1630                                    password = regExpToolkit.generate(null);
1631                            }
1632                            else {
1633                                    PasswordPolicy passwordPolicy =
1634                                            passwordPolicyLocalService.getPasswordPolicy(
1635                                                    user.getCompanyId(), user.getOrganizationIds());
1636    
1637                                    password = PwdToolkitUtil.generate(passwordPolicy);
1638                            }
1639    
1640                            serviceContext.setAttribute("passwordUnencrypted", password);
1641    
1642                            user.setPassword(PasswordEncryptorUtil.encrypt(password));
1643                            user.setPasswordUnencrypted(password);
1644                            user.setPasswordEncrypted(true);
1645                            user.setPasswordModified(true);
1646                            user.setPasswordModifiedDate(new Date());
1647    
1648                            userPersistence.update(user);
1649    
1650                            user.setPasswordModified(false);
1651                    }
1652    
1653                    if (user.hasCompanyMx()) {
1654                            mailService.addUser(
1655                                    user.getCompanyId(), user.getUserId(), password,
1656                                    user.getFirstName(), user.getMiddleName(), user.getLastName(),
1657                                    user.getEmailAddress());
1658                    }
1659    
1660                    boolean sendEmail = ParamUtil.getBoolean(serviceContext, "sendEmail");
1661    
1662                    if (sendEmail) {
1663                            notifyUser(user, password, serviceContext);
1664                    }
1665    
1666                    Company company = companyPersistence.findByPrimaryKey(
1667                            user.getCompanyId());
1668    
1669                    if (company.isStrangersVerify()) {
1670                            sendEmailAddressVerification(
1671                                    user, user.getEmailAddress(), serviceContext);
1672                    }
1673            }
1674    
1675            /**
1676             * Decrypts the user's primary key and password from their encrypted forms.
1677             * Used for decrypting a user's credentials from the values stored in an
1678             * automatic login cookie.
1679             *
1680             * @param  companyId the primary key of the user's company
1681             * @param  name the encrypted primary key of the user
1682             * @param  password the encrypted password of the user
1683             * @return the user's primary key and password
1684             * @throws PortalException if a user with the primary key could not be found
1685             *         or if the user's password was incorrect
1686             */
1687            @Override
1688            public KeyValuePair decryptUserId(
1689                            long companyId, String name, String password)
1690                    throws PortalException {
1691    
1692                    Company company = companyPersistence.findByPrimaryKey(companyId);
1693    
1694                    try {
1695                            name = Encryptor.decrypt(company.getKeyObj(), name);
1696                    }
1697                    catch (EncryptorException ee) {
1698                            throw new SystemException(ee);
1699                    }
1700    
1701                    long userId = GetterUtil.getLong(name);
1702    
1703                    User user = userPersistence.findByPrimaryKey(userId);
1704    
1705                    try {
1706                            password = Encryptor.decrypt(company.getKeyObj(), password);
1707                    }
1708                    catch (EncryptorException ee) {
1709                            throw new SystemException(ee);
1710                    }
1711    
1712                    String userPassword = user.getPassword();
1713                    String encPassword = PasswordEncryptorUtil.encrypt(
1714                            password, userPassword);
1715    
1716                    if (userPassword.equals(encPassword)) {
1717                            if (isPasswordExpired(user)) {
1718                                    user.setPasswordReset(true);
1719    
1720                                    userPersistence.update(user);
1721                            }
1722    
1723                            return new KeyValuePair(name, password);
1724                    }
1725                    else {
1726                            throw new PrincipalException.MustBeAuthenticated(userId);
1727                    }
1728            }
1729    
1730            /**
1731             * Deletes the user's portrait image.
1732             *
1733             * @param  userId the primary key of the user
1734             * @throws PortalException if a user with the primary key could not be found
1735             *         or if the user's portrait could not be found
1736             */
1737            @Override
1738            public void deletePortrait(long userId) throws PortalException {
1739                    User user = userPersistence.findByPrimaryKey(userId);
1740    
1741                    PortalUtil.updateImageId(user, false, null, "portraitId", 0, 0, 0);
1742            }
1743    
1744            /**
1745             * Removes the user from the role.
1746             *
1747             * @param  roleId the primary key of the role
1748             * @param  userId the primary key of the user
1749             * @throws PortalException if a role or user with the primary key could not
1750             *         be found
1751             */
1752            @Override
1753            public void deleteRoleUser(long roleId, long userId)
1754                    throws PortalException {
1755    
1756                    rolePersistence.removeUser(roleId, userId);
1757    
1758                    reindex(userId);
1759    
1760                    PermissionCacheUtil.clearCache(userId);
1761            }
1762    
1763            /**
1764             * Deletes the user.
1765             *
1766             * @param  userId the primary key of the user
1767             * @return the deleted user
1768             * @throws PortalException if a user with the primary key could not be found
1769             */
1770            @Override
1771            public User deleteUser(long userId) throws PortalException {
1772                    User user = userPersistence.findByPrimaryKey(userId);
1773    
1774                    return deleteUser(user);
1775            }
1776    
1777            /**
1778             * Deletes the user.
1779             *
1780             * @param  user the user
1781             * @return the deleted user
1782             * @throws PortalException if a portal exception occurred
1783             */
1784            @Override
1785            public User deleteUser(User user) throws PortalException {
1786                    if (!PropsValues.USERS_DELETE) {
1787                            throw new RequiredUserException();
1788                    }
1789    
1790                    // Browser tracker
1791    
1792                    browserTrackerLocalService.deleteUserBrowserTracker(user.getUserId());
1793    
1794                    // Group
1795    
1796                    Group group = null;
1797    
1798                    if (!user.isDefaultUser()) {
1799                            group = user.getGroup();
1800                    }
1801    
1802                    if (group != null) {
1803                            groupLocalService.deleteGroup(group);
1804                    }
1805    
1806                    // Portrait
1807    
1808                    try {
1809                            imageLocalService.deleteImage(user.getPortraitId());
1810                    }
1811                    catch (NoSuchImageException nsie) {
1812                            if (_log.isWarnEnabled()) {
1813                                    _log.warn(
1814                                            "Unable to delete image " + user.getPortraitId(), nsie);
1815                            }
1816                    }
1817    
1818                    // Password policy relation
1819    
1820                    passwordPolicyRelLocalService.deletePasswordPolicyRel(
1821                            User.class.getName(), user.getUserId());
1822    
1823                    // Old passwords
1824    
1825                    passwordTrackerLocalService.deletePasswordTrackers(user.getUserId());
1826    
1827                    // Subscriptions
1828    
1829                    subscriptionLocalService.deleteSubscriptions(user.getUserId());
1830    
1831                    // External user ids
1832    
1833                    userIdMapperLocalService.deleteUserIdMappers(user.getUserId());
1834    
1835                    // Announcements
1836    
1837                    announcementsDeliveryLocalService.deleteDeliveries(user.getUserId());
1838    
1839                    // Asset
1840    
1841                    assetEntryLocalService.deleteEntry(
1842                            User.class.getName(), user.getUserId());
1843    
1844                    // Blogs
1845    
1846                    blogsStatsUserLocalService.deleteStatsUserByUserId(user.getUserId());
1847    
1848                    // Document library
1849    
1850                    dlFileRankLocalService.deleteFileRanksByUserId(user.getUserId());
1851    
1852                    // Expando
1853    
1854                    expandoRowLocalService.deleteRows(user.getUserId());
1855    
1856                    // Message boards
1857    
1858                    mbBanLocalService.deleteBansByBanUserId(user.getUserId());
1859                    mbStatsUserLocalService.deleteStatsUsersByUserId(user.getUserId());
1860                    mbThreadFlagLocalService.deleteThreadFlagsByUserId(user.getUserId());
1861    
1862                    // Membership requests
1863    
1864                    membershipRequestLocalService.deleteMembershipRequestsByUserId(
1865                            user.getUserId());
1866    
1867                    // Ratings
1868    
1869                    ratingsStatsLocalService.deleteStats(
1870                            User.class.getName(), user.getUserId());
1871    
1872                    // Social
1873    
1874                    socialActivityLocalService.deleteUserActivities(user.getUserId());
1875                    socialRequestLocalService.deleteReceiverUserRequests(user.getUserId());
1876                    socialRequestLocalService.deleteUserRequests(user.getUserId());
1877    
1878                    // Mail
1879    
1880                    mailService.deleteUser(user.getCompanyId(), user.getUserId());
1881    
1882                    // Contact
1883    
1884                    Contact contact = contactLocalService.fetchContact(user.getContactId());
1885    
1886                    if (contact != null) {
1887                            contactLocalService.deleteContact(contact);
1888                    }
1889    
1890                    // Group roles
1891    
1892                    userGroupRoleLocalService.deleteUserGroupRolesByUserId(
1893                            user.getUserId());
1894    
1895                    // Resources
1896    
1897                    resourceLocalService.deleteResource(
1898                            user.getCompanyId(), User.class.getName(),
1899                            ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
1900    
1901                    // User
1902    
1903                    userPersistence.remove(user);
1904    
1905                    // Permission cache
1906    
1907                    PermissionCacheUtil.clearCache(user.getUserId());
1908    
1909                    // Workflow
1910    
1911                    workflowInstanceLinkLocalService.deleteWorkflowInstanceLinks(
1912                            user.getCompanyId(), 0, User.class.getName(), user.getUserId());
1913    
1914                    return user;
1915            }
1916    
1917            /**
1918             * Removes the user from the user group.
1919             *
1920             * @param  userGroupId the primary key of the user group
1921             * @param  userId the primary key of the user
1922             * @throws PortalException if a portal exception occurred
1923             */
1924            @Override
1925            public void deleteUserGroupUser(long userGroupId, long userId)
1926                    throws PortalException {
1927    
1928                    userGroupPersistence.removeUser(userGroupId, userId);
1929    
1930                    reindex(userId);
1931    
1932                    PermissionCacheUtil.clearCache(userId);
1933            }
1934    
1935            /**
1936             * Encrypts the primary key of the user. Used when encrypting the user's
1937             * credentials for storage in an automatic login cookie.
1938             *
1939             * @param  name the primary key of the user
1940             * @return the user's encrypted primary key
1941             * @throws PortalException if a user with the primary key could not be found
1942             */
1943            @Override
1944            @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
1945            public String encryptUserId(String name) throws PortalException {
1946                    long userId = GetterUtil.getLong(name);
1947    
1948                    User user = userPersistence.findByPrimaryKey(userId);
1949    
1950                    Company company = companyPersistence.findByPrimaryKey(
1951                            user.getCompanyId());
1952    
1953                    try {
1954                            return Encryptor.encrypt(company.getKeyObj(), name);
1955                    }
1956                    catch (EncryptorException ee) {
1957                            throw new SystemException(ee);
1958                    }
1959            }
1960    
1961            /**
1962             * Returns the user with the contact ID.
1963             *
1964             * @param  contactId the user's contact ID
1965             * @return the user with the contact ID, or <code>null</code> if a user with
1966             *         the contact ID could not be found
1967             */
1968            @Override
1969            public User fetchUserByContactId(long contactId) {
1970                    return userPersistence.fetchByContactId(contactId);
1971            }
1972    
1973            /**
1974             * Returns the user with the email address.
1975             *
1976             * @param  companyId the primary key of the user's company
1977             * @param  emailAddress the user's email address
1978             * @return the user with the email address, or <code>null</code> if a user
1979             *         with the email address could not be found
1980             */
1981            @Override
1982            public User fetchUserByEmailAddress(long companyId, String emailAddress) {
1983                    emailAddress = getLogin(emailAddress);
1984    
1985                    return userPersistence.fetchByC_EA(companyId, emailAddress);
1986            }
1987    
1988            /**
1989             * Returns the user with the Facebook ID.
1990             *
1991             * @param  companyId the primary key of the user's company
1992             * @param  facebookId the user's Facebook ID
1993             * @return the user with the Facebook ID, or <code>null</code> if a user
1994             *         with the Facebook ID could not be found
1995             */
1996            @Override
1997            public User fetchUserByFacebookId(long companyId, long facebookId) {
1998                    return userPersistence.fetchByC_FID(companyId, facebookId);
1999            }
2000    
2001            /**
2002             * Returns the user with the primary key.
2003             *
2004             * @param  userId the primary key of the user
2005             * @return the user with the primary key, or <code>null</code> if a user
2006             *         with the primary key could not be found
2007             */
2008            @Override
2009            public User fetchUserById(long userId) {
2010                    return userPersistence.fetchByPrimaryKey(userId);
2011            }
2012    
2013            /**
2014             * Returns the user with the OpenID.
2015             *
2016             * @param  companyId the primary key of the user's company
2017             * @param  openId the user's OpenID
2018             * @return the user with the OpenID, or <code>null</code> if a user with the
2019             *         OpenID could not be found
2020             */
2021            @Override
2022            public User fetchUserByOpenId(long companyId, String openId) {
2023                    return userPersistence.fetchByC_O(companyId, openId);
2024            }
2025    
2026            /**
2027             * Returns the user with the portrait ID.
2028             *
2029             * @param  portraitId the user's portrait ID
2030             * @return the user with the portrait ID, or <code>null</code> if a user
2031             *         with the portrait ID could not be found
2032             */
2033            @Override
2034            public User fetchUserByPortraitId(long portraitId) {
2035                    return userPersistence.fetchByPortraitId(portraitId);
2036            }
2037    
2038            /**
2039             * Returns the user with the screen name.
2040             *
2041             * @param  companyId the primary key of the user's company
2042             * @param  screenName the user's screen name
2043             * @return the user with the screen name, or <code>null</code> if a user
2044             *         with the screen name could not be found
2045             */
2046            @Override
2047            public User fetchUserByScreenName(long companyId, String screenName) {
2048                    screenName = getLogin(screenName);
2049    
2050                    return userPersistence.fetchByC_SN(companyId, screenName);
2051            }
2052    
2053            /**
2054             * Returns a range of all the users belonging to the company.
2055             *
2056             * <p>
2057             * Useful when paginating results. Returns a maximum of <code>end -
2058             * start</code> instances. <code>start</code> and <code>end</code> are not
2059             * primary keys, they are indexes in the result set. Thus, <code>0</code>
2060             * refers to the first result in the set. Setting both <code>start</code>
2061             * and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full
2062             * result set.
2063             * </p>
2064             *
2065             * @param  companyId the primary key of the company
2066             * @param  start the lower bound of the range of users
2067             * @param  end the upper bound of the range of users (not inclusive)
2068             * @return the range of users belonging to the company
2069             */
2070            @Override
2071            public List<User> getCompanyUsers(long companyId, int start, int end) {
2072                    return userPersistence.findByCompanyId(companyId, start, end);
2073            }
2074    
2075            /**
2076             * Returns the number of users belonging to the company.
2077             *
2078             * @param  companyId the primary key of the company
2079             * @return the number of users belonging to the company
2080             */
2081            @Override
2082            public int getCompanyUsersCount(long companyId) {
2083                    return userPersistence.countByCompanyId(companyId);
2084            }
2085    
2086            /**
2087             * Returns the default user for the company.
2088             *
2089             * @param  companyId the primary key of the company
2090             * @return the default user for the company
2091             * @throws PortalException if a default user for the company could not be
2092             *         found
2093             */
2094            @Override
2095            @Skip
2096            public User getDefaultUser(long companyId) throws PortalException {
2097                    User userModel = _defaultUsers.get(companyId);
2098    
2099                    if (userModel == null) {
2100                            userModel = userLocalService.loadGetDefaultUser(companyId);
2101    
2102                            _defaultUsers.put(companyId, userModel);
2103                    }
2104    
2105                    return userModel;
2106            }
2107    
2108            /**
2109             * Returns the primary key of the default user for the company.
2110             *
2111             * @param  companyId the primary key of the company
2112             * @return the primary key of the default user for the company
2113             * @throws PortalException if a default user for the company could not be
2114             *         found
2115             */
2116            @Override
2117            @Skip
2118            public long getDefaultUserId(long companyId) throws PortalException {
2119                    User user = getDefaultUser(companyId);
2120    
2121                    return user.getUserId();
2122            }
2123    
2124            /**
2125             * Returns the primary keys of all the users belonging to the group.
2126             *
2127             * @param  groupId the primary key of the group
2128             * @return the primary keys of the users belonging to the group
2129             */
2130            @Override
2131            public long[] getGroupUserIds(long groupId) {
2132                    return groupPersistence.getUserPrimaryKeys(groupId);
2133            }
2134    
2135            /**
2136             * Returns the number of users with the status belonging to the group.
2137             *
2138             * @param  groupId the primary key of the group
2139             * @param  status the workflow status
2140             * @return the number of users with the status belonging to the group
2141             * @throws PortalException if a group with the primary key could not be
2142             *         found
2143             */
2144            @Override
2145            public int getGroupUsersCount(long groupId, int status)
2146                    throws PortalException {
2147    
2148                    Group group = groupPersistence.findByPrimaryKey(groupId);
2149    
2150                    LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2151    
2152                    params.put("usersGroups", Long.valueOf(groupId));
2153    
2154                    return searchCount(group.getCompanyId(), null, status, params);
2155            }
2156    
2157            @Override
2158            public List<User> getInheritedRoleUsers(
2159                            long roleId, int start, int end, OrderByComparator<User> obc)
2160                    throws PortalException {
2161    
2162                    Role role = rolePersistence.findByPrimaryKey(roleId);
2163    
2164                    LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2165    
2166                    params.put("inherit", Boolean.TRUE);
2167                    params.put("usersRoles", roleId);
2168    
2169                    return search(
2170                            role.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2171                            params, start, end, obc);
2172            }
2173    
2174            /**
2175             * Returns all the users who have not had any announcements of the type
2176             * delivered, excluding the default user.
2177             *
2178             * @param  type the type of announcement
2179             * @return the users who have not had any annoucements of the type delivered
2180             */
2181            @Override
2182            public List<User> getNoAnnouncementsDeliveries(String type) {
2183                    return userFinder.findByNoAnnouncementsDeliveries(type);
2184            }
2185    
2186            /**
2187             * Returns all the users who do not have any contacts.
2188             *
2189             * @return the users who do not have any contacts
2190             */
2191            @Override
2192            public List<User> getNoContacts() {
2193                    return userFinder.findByNoContacts();
2194            }
2195    
2196            /**
2197             * Returns all the users who do not belong to any groups, excluding the
2198             * default user.
2199             *
2200             * @return the users who do not belong to any groups
2201             */
2202            @Override
2203            public List<User> getNoGroups() {
2204                    return userFinder.findByNoGroups();
2205            }
2206    
2207            /**
2208             * Returns the primary keys of all the users belonging to the organization.
2209             *
2210             * @param  organizationId the primary key of the organization
2211             * @return the primary keys of the users belonging to the organization
2212             */
2213            @Override
2214            public long[] getOrganizationUserIds(long organizationId) {
2215                    return organizationPersistence.getUserPrimaryKeys(organizationId);
2216            }
2217    
2218            /**
2219             * Returns the number of users with the status belonging to the
2220             * organization.
2221             *
2222             * @param  organizationId the primary key of the organization
2223             * @param  status the workflow status
2224             * @return the number of users with the status belonging to the organization
2225             * @throws PortalException if an organization with the primary key could not
2226             *         be found
2227             */
2228            @Override
2229            public int getOrganizationUsersCount(long organizationId, int status)
2230                    throws PortalException {
2231    
2232                    Organization organization = organizationPersistence.findByPrimaryKey(
2233                            organizationId);
2234    
2235                    LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2236    
2237                    params.put("usersOrgs", Long.valueOf(organizationId));
2238    
2239                    return searchCount(organization.getCompanyId(), null, status, params);
2240            }
2241    
2242            /**
2243             * Returns the primary keys of all the users belonging to the role.
2244             *
2245             * @param  roleId the primary key of the role
2246             * @return the primary keys of the users belonging to the role
2247             */
2248            @Override
2249            public long[] getRoleUserIds(long roleId) {
2250                    return rolePersistence.getUserPrimaryKeys(roleId);
2251            }
2252    
2253            /**
2254             * Returns the number of users with the status belonging to the role.
2255             *
2256             * @param  roleId the primary key of the role
2257             * @param  status the workflow status
2258             * @return the number of users with the status belonging to the role
2259             * @throws PortalException if an role with the primary key could not be
2260             *         found
2261             */
2262            @Override
2263            public int getRoleUsersCount(long roleId, int status)
2264                    throws PortalException {
2265    
2266                    Role role = rolePersistence.findByPrimaryKey(roleId);
2267    
2268                    LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2269    
2270                    params.put("usersRoles", Long.valueOf(roleId));
2271    
2272                    return searchCount(role.getCompanyId(), null, status, params);
2273            }
2274    
2275            /**
2276             * Returns an ordered range of all the users with a social relation of the
2277             * type with the user.
2278             *
2279             * <p>
2280             * Useful when paginating results. Returns a maximum of <code>end -
2281             * start</code> instances. <code>start</code> and <code>end</code> are not
2282             * primary keys, they are indexes in the result set. Thus, <code>0</code>
2283             * refers to the first result in the set. Setting both <code>start</code>
2284             * and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full
2285             * result set.
2286             * </p>
2287             *
2288             * @param      userId the primary key of the user
2289             * @param      socialRelationType the type of social relation. The possible
2290             *             types can be found in {@link SocialRelationConstants}.
2291             * @param      start the lower bound of the range of users
2292             * @param      end the upper bound of the range of users (not inclusive)
2293             * @param      obc the comparator to order the users by (optionally
2294             *             <code>null</code>)
2295             * @return     the ordered range of users with a social relation of the type
2296             *             with the user
2297             * @throws     PortalException if a user with the primary key could not be
2298             *             found
2299             * @deprecated As of 7.0.0, replaced by {@link #getSocialUsers(long, int,
2300             *             String, int, int, OrderByComparator)}
2301             */
2302            @Deprecated
2303            @Override
2304            public List<User> getSocialUsers(
2305                            long userId, int socialRelationType, int start, int end,
2306                            OrderByComparator<User> obc)
2307                    throws PortalException {
2308    
2309                    return getSocialUsers(
2310                            userId, socialRelationType, StringPool.EQUAL, start, end, obc);
2311            }
2312    
2313            /**
2314             * Returns an ordered range of all the users with a social relation with the
2315             * user.
2316             *
2317             * <p>
2318             * Useful when paginating results. Returns a maximum of <code>end -
2319             * start</code> instances. <code>start</code> and <code>end</code> are not
2320             * primary keys, they are indexes in the result set. Thus, <code>0</code>
2321             * refers to the first result in the set. Setting both <code>start</code>
2322             * and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full
2323             * result set.
2324             * </p>
2325             *
2326             * @param      userId the primary key of the user
2327             * @param      start the lower bound of the range of users
2328             * @param      end the upper bound of the range of users (not inclusive)
2329             * @param      obc the comparator to order the users by (optionally
2330             *             <code>null</code>)
2331             * @return     the ordered range of users with a social relation with the
2332             *             user
2333             * @throws     PortalException if a user with the primary key could not be
2334             *             found
2335             * @deprecated As of 7.0.0, replaced by {@link #getSocialUsers(long, int,
2336             *             String, int, int, OrderByComparator)}
2337             */
2338            @Deprecated
2339            @Override
2340            public List<User> getSocialUsers(
2341                            long userId, int start, int end, OrderByComparator<User> obc)
2342                    throws PortalException {
2343    
2344                    return getSocialUsers(
2345                            userId, SocialRelationConstants.TYPE_UNI_ENEMY,
2346                            StringPool.NOT_EQUAL, start, end, obc);
2347            }
2348    
2349            @Override
2350            public List<User> getSocialUsers(
2351                            long userId, int socialRelationType,
2352                            String socialRelationTypeComparator, int start, int end,
2353                            OrderByComparator<User> obc)
2354                    throws PortalException {
2355    
2356                    if (!socialRelationTypeComparator.equals(StringPool.EQUAL) &&
2357                            !socialRelationTypeComparator.equals(StringPool.NOT_EQUAL)) {
2358    
2359                            throw new IllegalArgumentException(
2360                                    "Invalid social relation type comparator " +
2361                                            socialRelationTypeComparator);
2362                    }
2363    
2364                    if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS)) {
2365                            List<SocialRelation> socialRelations =
2366                                    socialRelationPersistence.findByU1_T(
2367                                            userId, socialRelationType);
2368    
2369                            if (socialRelationTypeComparator.equals(StringPool.NOT_EQUAL)) {
2370                                    socialRelations = ListUtil.remove(
2371                                            socialRelationPersistence.findByUserId1(userId),
2372                                            socialRelations);
2373                            }
2374    
2375                            List<User> users = new ArrayList<>();
2376    
2377                            for (SocialRelation socialRelation : socialRelations) {
2378                                    User user = userPersistence.findByPrimaryKey(
2379                                            socialRelation.getUserId2());
2380    
2381                                    if (user.isDefaultUser() ||
2382                                            (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {
2383    
2384                                            continue;
2385                                    }
2386    
2387                                    if (!users.contains(user)) {
2388                                            users.add(user);
2389                                    }
2390                            }
2391    
2392                            if (obc != null) {
2393                                    users = ListUtil.sort(users, obc);
2394                            }
2395    
2396                            return users;
2397                    }
2398    
2399                    User user = userPersistence.findByPrimaryKey(userId);
2400    
2401                    return userFinder.findBySocialUsers(
2402                            user.getCompanyId(), userId, socialRelationType,
2403                            socialRelationTypeComparator, WorkflowConstants.STATUS_APPROVED,
2404                            start, end, obc);
2405            }
2406    
2407            /**
2408             * Returns an ordered range of all the users with a mutual social relation
2409             * of the type with both of the given users.
2410             *
2411             * <p>
2412             * Useful when paginating results. Returns a maximum of <code>end -
2413             * start</code> instances. <code>start</code> and <code>end</code> are not
2414             * primary keys, they are indexes in the result set. Thus, <code>0</code>
2415             * refers to the first result in the set. Setting both <code>start</code>
2416             * and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full
2417             * result set.
2418             * </p>
2419             *
2420             * @param  userId1 the primary key of the first user
2421             * @param  userId2 the primary key of the second user
2422             * @param  socialRelationType the type of social relation. The possible
2423             *         types can be found in {@link SocialRelationConstants}.
2424             * @param  start the lower bound of the range of users
2425             * @param  end the upper bound of the range of users (not inclusive)
2426             * @param  obc the comparator to order the users by (optionally
2427             *         <code>null</code>)
2428             * @return the ordered range of users with a mutual social relation of the
2429             *         type with the user
2430             * @throws PortalException if a user with the primary key could not be found
2431             */
2432            @Override
2433            public List<User> getSocialUsers(
2434                            long userId1, long userId2, int socialRelationType, int start,
2435                            int end, OrderByComparator<User> obc)
2436                    throws PortalException {
2437    
2438                    User user1 = userPersistence.findByPrimaryKey(userId1);
2439    
2440                    LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2441    
2442                    params.put(
2443                            "socialMutualRelationType",
2444                            new Long[] {userId1, Long.valueOf(socialRelationType), userId2,
2445                            Long.valueOf(socialRelationType)
2446                    });
2447    
2448                    return search(
2449                            user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2450                            params, start, end, obc);
2451            }
2452    
2453            /**
2454             * Returns an ordered range of all the users with a mutual social relation
2455             * with both of the given users.
2456             *
2457             * <p>
2458             * Useful when paginating results. Returns a maximum of <code>end -
2459             * start</code> instances. <code>start</code> and <code>end</code> are not
2460             * primary keys, they are indexes in the result set. Thus, <code>0</code>
2461             * refers to the first result in the set. Setting both <code>start</code>
2462             * and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full
2463             * result set.
2464             * </p>
2465             *
2466             * @param  userId1 the primary key of the first user
2467             * @param  userId2 the primary key of the second user
2468             * @param  start the lower bound of the range of users
2469             * @param  end the upper bound of the range of users (not inclusive)
2470             * @param  obc the comparator to order the users by (optionally
2471             *         <code>null</code>)
2472             * @return the ordered range of users with a mutual social relation with the
2473             *         user
2474             * @throws PortalException if a user with the primary key could not be found
2475             */
2476            @Override
2477            public List<User> getSocialUsers(
2478                            long userId1, long userId2, int start, int end,
2479                            OrderByComparator<User> obc)
2480                    throws PortalException {
2481    
2482                    User user1 = userPersistence.findByPrimaryKey(userId1);
2483    
2484                    LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2485    
2486                    params.put("socialMutualRelation", new Long[] {userId1, userId2});
2487    
2488                    return search(
2489                            user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2490                            params, start, end, obc);
2491            }
2492    
2493            /**
2494             * Returns the number of users with a social relation with the user.
2495             *
2496             * @param      userId the primary key of the user
2497             * @return     the number of users with a social relation with the user
2498             * @throws     PortalException if a user with the primary key could not be
2499             *             found
2500             * @deprecated As of 7.0.0, replaced by {@link #getSocialUsersCount(long,
2501             *             int, String)}
2502             */
2503            @Deprecated
2504            @Override
2505            public int getSocialUsersCount(long userId) throws PortalException {
2506                    return getSocialUsersCount(
2507                            userId, SocialRelationConstants.TYPE_UNI_ENEMY,
2508                            StringPool.NOT_EQUAL);
2509            }
2510    
2511            /**
2512             * Returns the number of users with a social relation of the type with the
2513             * user.
2514             *
2515             * @param      userId the primary key of the user
2516             * @param      socialRelationType the type of social relation. The possible
2517             *             types can be found in {@link SocialRelationConstants}.
2518             * @return     the number of users with a social relation of the type with
2519             *             the user
2520             * @throws     PortalException if a user with the primary key could not be
2521             *             found
2522             * @deprecated As of 7.0.0, replaced by {@link #getSocialUsersCount(long,
2523             *             int, String)}
2524             */
2525            @Deprecated
2526            @Override
2527            public int getSocialUsersCount(long userId, int socialRelationType)
2528                    throws PortalException {
2529    
2530                    return getSocialUsersCount(
2531                            userId, socialRelationType, StringPool.EQUAL);
2532            }
2533    
2534            /**
2535             * Returns the number of users with a social relation with the user.
2536             *
2537             * @param  userId the primary key of the user
2538             * @param  socialRelationType the type of social relation. The possible
2539             *         types can be found in {@link SocialRelationConstants}.
2540             * @return the number of users with a social relation with the user
2541             * @throws PortalException if a user with the primary key could not be found
2542             */
2543            @Override
2544            public int getSocialUsersCount(
2545                            long userId, int socialRelationType,
2546                            String socialRelationTypeComparator)
2547                    throws PortalException {
2548    
2549                    User user = userPersistence.findByPrimaryKey(userId);
2550    
2551                    if (!socialRelationTypeComparator.equals(StringPool.EQUAL) &&
2552                            !socialRelationTypeComparator.equals(StringPool.NOT_EQUAL)) {
2553    
2554                            throw new IllegalArgumentException(
2555                                    "Invalid social relation type comparator " +
2556                                            socialRelationTypeComparator);
2557                    }
2558    
2559                    return userFinder.countBySocialUsers(
2560                            user.getCompanyId(), user.getUserId(), socialRelationType,
2561                            socialRelationTypeComparator, WorkflowConstants.STATUS_APPROVED);
2562            }
2563    
2564            /**
2565             * Returns the number of users with a mutual social relation with both of
2566             * the given users.
2567             *
2568             * @param  userId1 the primary key of the first user
2569             * @param  userId2 the primary key of the second user
2570             * @return the number of users with a mutual social relation with the user
2571             * @throws PortalException if a user with the primary key could not be found
2572             */
2573            @Override
2574            public int getSocialUsersCount(long userId1, long userId2)
2575                    throws PortalException {
2576    
2577                    User user1 = userPersistence.findByPrimaryKey(userId1);
2578    
2579                    LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2580    
2581                    params.put("socialMutualRelation", new Long[] {userId1, userId2});
2582    
2583                    return searchCount(
2584                            user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2585                            params);
2586            }
2587    
2588            /**
2589             * Returns the number of users with a mutual social relation of the type
2590             * with both of the given users.
2591             *
2592             * @param  userId1 the primary key of the first user
2593             * @param  userId2 the primary key of the second user
2594             * @param  socialRelationType the type of social relation. The possible
2595             *         types can be found in {@link SocialRelationConstants}.
2596             * @return the number of users with a mutual social relation of the type
2597             *         with the user
2598             * @throws PortalException if a user with the primary key could not be found
2599             */
2600            @Override
2601            public int getSocialUsersCount(
2602                            long userId1, long userId2, int socialRelationType)
2603                    throws PortalException {
2604    
2605                    User user1 = userPersistence.findByPrimaryKey(userId1);
2606    
2607                    LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2608    
2609                    params.put(
2610                            "socialMutualRelationType",
2611                            new Long[] {userId1, Long.valueOf(socialRelationType), userId2,
2612                            Long.valueOf(socialRelationType)
2613                    });
2614    
2615                    return searchCount(
2616                            user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2617                            params);
2618            }
2619    
2620            /**
2621             * Returns the user with the contact ID.
2622             *
2623             * @param  contactId the user's contact ID
2624             * @return the user with the contact ID
2625             * @throws PortalException if a user with the contact ID could not be found
2626             */
2627            @Override
2628            public User getUserByContactId(long contactId) throws PortalException {
2629                    return userPersistence.findByContactId(contactId);
2630            }
2631    
2632            /**
2633             * Returns the user with the email address.
2634             *
2635             * @param  companyId the primary key of the user's company
2636             * @param  emailAddress the user's email address
2637             * @return the user with the email address
2638             * @throws PortalException if a user with the email address could not be
2639             *         found
2640             */
2641            @Override
2642            public User getUserByEmailAddress(long companyId, String emailAddress)
2643                    throws PortalException {
2644    
2645                    emailAddress = getLogin(emailAddress);
2646    
2647                    return userPersistence.findByC_EA(companyId, emailAddress);
2648            }
2649    
2650            /**
2651             * Returns the user with the Facebook ID.
2652             *
2653             * @param  companyId the primary key of the user's company
2654             * @param  facebookId the user's Facebook ID
2655             * @return the user with the Facebook ID
2656             * @throws PortalException if a user with the Facebook ID could not be found
2657             */
2658            @Override
2659            public User getUserByFacebookId(long companyId, long facebookId)
2660                    throws PortalException {
2661    
2662                    return userPersistence.findByC_FID(companyId, facebookId);
2663            }
2664    
2665            /**
2666             * Returns the user with the primary key.
2667             *
2668             * @param  userId the primary key of the user
2669             * @return the user with the primary key
2670             * @throws PortalException if a user with the primary key could not be found
2671             */
2672            @Override
2673            public User getUserById(long userId) throws PortalException {
2674                    return userPersistence.findByPrimaryKey(userId);
2675            }
2676    
2677            /**
2678             * Returns the user with the primary key from the company.
2679             *
2680             * @param  companyId the primary key of the user's company
2681             * @param  userId the primary key of the user
2682             * @return the user with the primary key
2683             * @throws PortalException if a user with the primary key from the company
2684             *         could not be found
2685             */
2686            @Override
2687            public User getUserById(long companyId, long userId)
2688                    throws PortalException {
2689    
2690                    return userPersistence.findByC_U(companyId, userId);
2691            }
2692    
2693            /**
2694             * Returns the user with the OpenID.
2695             *
2696             * @param  companyId the primary key of the user's company
2697             * @param  openId the user's OpenID
2698             * @return the user with the OpenID
2699             * @throws PortalException if a user with the OpenID could not be found
2700             */
2701            @Override
2702            public User getUserByOpenId(long companyId, String openId)
2703                    throws PortalException {
2704    
2705                    return userPersistence.findByC_O(companyId, openId);
2706            }
2707    
2708            /**
2709             * Returns the user with the portrait ID.
2710             *
2711             * @param  portraitId the user's portrait ID
2712             * @return the user with the portrait ID
2713             * @throws PortalException if a user with the portrait ID could not be found
2714             */
2715            @Override
2716            public User getUserByPortraitId(long portraitId) throws PortalException {
2717                    return userPersistence.findByPortraitId(portraitId);
2718            }
2719    
2720            /**
2721             * Returns the user with the screen name.
2722             *
2723             * @param  companyId the primary key of the user's company
2724             * @param  screenName the user's screen name
2725             * @return the user with the screen name
2726             * @throws PortalException if a user with the screen name could not be found
2727             */
2728            @Override
2729            public User getUserByScreenName(long companyId, String screenName)
2730                    throws PortalException {
2731    
2732                    screenName = getLogin(screenName);
2733    
2734                    return userPersistence.findByC_SN(companyId, screenName);
2735            }
2736    
2737            /**
2738             * Returns the user with the UUID.
2739             *
2740             * @param      uuid the user's UUID
2741             * @return     the user with the UUID
2742             * @throws     PortalException if a user with the UUID could not be found
2743             * @deprecated As of 6.2.0, replaced by {@link
2744             *             #getUserByUuidAndCompanyId(String, long)}
2745             */
2746            @Deprecated
2747            @Override
2748            public User getUserByUuid(String uuid) throws PortalException {
2749                    List<User> users = userPersistence.findByUuid(uuid);
2750    
2751                    if (users.isEmpty()) {
2752                            throw new NoSuchUserException("{uuid=" + uuid + "}");
2753                    }
2754                    else {
2755                            return users.get(0);
2756                    }
2757            }
2758    
2759            /**
2760             * Returns the user with the UUID.
2761             *
2762             * @param  uuid the user's UUID
2763             * @param  companyId the primary key of the user's company
2764             * @return the user with the UUID
2765             * @throws PortalException if a user with the UUID could not be found
2766             */
2767            @Override
2768            public User getUserByUuidAndCompanyId(String uuid, long companyId)
2769                    throws PortalException {
2770    
2771                    List<User> users = userPersistence.findByUuid_C(uuid, companyId);
2772    
2773                    if (users.isEmpty()) {
2774                            StringBundler sb = new StringBundler(5);
2775    
2776                            sb.append("{uuid=");
2777                            sb.append(uuid);
2778                            sb.append(", companyId=");
2779                            sb.append(companyId);
2780                            sb.append("}");
2781    
2782                            throw new NoSuchUserException(sb.toString());
2783                    }
2784                    else {
2785                            return users.get(0);
2786                    }
2787            }
2788    
2789            /**
2790             * Returns the number of users with the status belonging to the user group.
2791             *
2792             * @param  userGroupId the primary key of the user group
2793             * @param  status the workflow status
2794             * @return the number of users with the status belonging to the user group
2795             * @throws PortalException if a user group with the primary key could not be
2796             *         found
2797             */
2798            @Override
2799            public int getUserGroupUsersCount(long userGroupId, int status)
2800                    throws PortalException {
2801    
2802                    UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
2803                            userGroupId);
2804    
2805                    LinkedHashMap<String, Object> params = new LinkedHashMap<>();
2806    
2807                    params.put("usersUserGroups", Long.valueOf(userGroupId));
2808    
2809                    return searchCount(userGroup.getCompanyId(), null, status, params);
2810            }
2811    
2812            /**
2813             * Returns the primary key of the user with the email address.
2814             *
2815             * @param  companyId the primary key of the user's company
2816             * @param  emailAddress the user's email address
2817             * @return the primary key of the user with the email address
2818             * @throws PortalException if a user with the email address could not be
2819             *         found
2820             */
2821            @Override
2822            public long getUserIdByEmailAddress(long companyId, String emailAddress)
2823                    throws PortalException {
2824    
2825                    emailAddress = StringUtil.toLowerCase(emailAddress.trim());
2826    
2827                    User user = userPersistence.findByC_EA(companyId, emailAddress);
2828    
2829                    return user.getUserId();
2830            }
2831    
2832            /**
2833             * Returns the primary key of the user with the screen name.
2834             *
2835             * @param  companyId the primary key of the user's company
2836             * @param  screenName the user's screen name
2837             * @return the primary key of the user with the screen name
2838             * @throws PortalException if a user with the screen name could not be found
2839             */
2840            @Override
2841            public long getUserIdByScreenName(long companyId, String screenName)
2842                    throws PortalException {
2843    
2844                    screenName = getLogin(screenName);
2845    
2846                    User user = userPersistence.findByC_SN(companyId, screenName);
2847    
2848                    return user.getUserId();
2849            }
2850    
2851            /**
2852             * Returns <code>true</code> if the password policy has been assigned to the
2853             * user.
2854             *
2855             * @param  passwordPolicyId the primary key of the password policy
2856             * @param  userId the primary key of the user
2857             * @return <code>true</code> if the password policy is assigned to the user;
2858             *         <code>false</code> otherwise
2859             */
2860            @Override
2861            public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId) {
2862                    return passwordPolicyRelLocalService.hasPasswordPolicyRel(
2863                            passwordPolicyId, User.class.getName(), userId);
2864            }
2865    
2866            /**
2867             * Returns <code>true</code> if the user has the role with the name,
2868             * optionally through inheritance.
2869             *
2870             * @param  companyId the primary key of the role's company
2871             * @param  name the name of the role (must be a regular role, not an
2872             *         organization, site or provider role)
2873             * @param  userId the primary key of the user
2874             * @param  inherited whether to include roles inherited from organizations,
2875             *         sites, etc.
2876             * @return <code>true</code> if the user has the role; <code>false</code>
2877             *         otherwise
2878             * @throws PortalException if a role with the name could not be found
2879             */
2880            @Override
2881            public boolean hasRoleUser(
2882                            long companyId, String name, long userId, boolean inherited)
2883                    throws PortalException {
2884    
2885                    return roleLocalService.hasUserRole(userId, companyId, name, inherited);
2886            }
2887    
2888            /**
2889             * Returns <code>true</code> if the user's password is expired.
2890             *
2891             * @param  user the user
2892             * @return <code>true</code> if the user's password is expired;
2893             *         <code>false</code> otherwise
2894             * @throws PortalException if the password policy for the user could not be
2895             *         found
2896             */
2897            @Override
2898            public boolean isPasswordExpired(User user) throws PortalException {
2899                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2900    
2901                    if ((passwordPolicy != null) && passwordPolicy.getExpireable()) {
2902                            Date now = new Date();
2903    
2904                            if (user.getPasswordModifiedDate() == null) {
2905                                    user.setPasswordModifiedDate(now);
2906    
2907                                    userLocalService.updateUser(user);
2908                            }
2909    
2910                            long passwordStartTime = user.getPasswordModifiedDate().getTime();
2911                            long elapsedTime = now.getTime() - passwordStartTime;
2912    
2913                            if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
2914                                    return true;
2915                            }
2916                            else {
2917                                    return false;
2918                            }
2919                    }
2920    
2921                    return false;
2922            }
2923    
2924            /**
2925             * Returns <code>true</code> if the password policy is configured to warn
2926             * the user that his password is expiring and the remaining time until
2927             * expiration is equal or less than the configured warning time.
2928             *
2929             * @param  user the user
2930             * @return <code>true</code> if the user's password is expiring soon;
2931             *         <code>false</code> otherwise
2932             * @throws PortalException if the password policy for the user could not be
2933             *         found
2934             */
2935            @Override
2936            public boolean isPasswordExpiringSoon(User user) throws PortalException {
2937                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2938    
2939                    if ((passwordPolicy != null) && passwordPolicy.isExpireable() &&
2940                            (passwordPolicy.getWarningTime() > 0)) {
2941    
2942                            Date now = new Date();
2943    
2944                            if (user.getPasswordModifiedDate() == null) {
2945                                    user.setPasswordModifiedDate(now);
2946    
2947                                    userLocalService.updateUser(user);
2948                            }
2949    
2950                            long timeModified = user.getPasswordModifiedDate().getTime();
2951                            long passwordExpiresOn =
2952                                    (passwordPolicy.getMaxAge() * 1000) + timeModified;
2953    
2954                            long timeStartWarning =
2955                                    passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
2956    
2957                            if (now.getTime() > timeStartWarning) {
2958                                    return true;
2959                            }
2960                            else {
2961                                    return false;
2962                            }
2963                    }
2964    
2965                    return false;
2966            }
2967    
2968            /**
2969             * Returns the default user for the company.
2970             *
2971             * @param  companyId the primary key of the company
2972             * @return the default user for the company
2973             * @throws PortalException if the user could not be found
2974             */
2975            @Override
2976            public User loadGetDefaultUser(long companyId) throws PortalException {
2977                    return userPersistence.findByC_DU(companyId, true);
2978            }
2979    
2980            /**
2981             * Returns an ordered range of all the users who match the keywords and
2982             * status, without using the indexer. It is preferable to use the indexed
2983             * version {@link #search(long, String, int, LinkedHashMap, int, int, Sort)}
2984             * instead of this method wherever possible for performance reasons.
2985             *
2986             * <p>
2987             * Useful when paginating results. Returns a maximum of <code>end -
2988             * start</code> instances. <code>start</code> and <code>end</code> are not
2989             * primary keys, they are indexes in the result set. Thus, <code>0</code>
2990             * refers to the first result in the set. Setting both <code>start</code>
2991             * and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full
2992             * result set.
2993             * </p>
2994             *
2995             * @param  companyId the primary key of the user's company
2996             * @param  keywords the keywords (space separated), which may occur in the
2997             *         user's first name, middle name, last name, screen name, or email
2998             *         address
2999             * @param  status the workflow status
3000             * @param  params the finder parameters (optionally <code>null</code>). For
3001             *         more information see {@link
3002             *         com.liferay.portal.service.persistence.UserFinder}.
3003             * @param  start the lower bound of the range of users
3004             * @param  end the upper bound of the range of users (not inclusive)
3005             * @param  obc the comparator to order the users by (optionally
3006             *         <code>null</code>)
3007             * @return the matching users
3008             * @see    com.liferay.portal.service.persistence.UserFinder
3009             */
3010            @Override
3011            public List<User> search(
3012                    long companyId, String keywords, int status,
3013                    LinkedHashMap<String, Object> params, int start, int end,
3014                    OrderByComparator<User> obc) {
3015    
3016                    Indexer<?> indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3017    
3018                    if (!indexer.isIndexerEnabled() ||
3019                            !PropsValues.USERS_SEARCH_WITH_INDEX || isUseCustomSQL(params)) {
3020    
3021                            return userFinder.findByKeywords(
3022                                    companyId, keywords, status, params, start, end, obc);
3023                    }
3024    
3025                    try {
3026                            return UsersAdminUtil.getUsers(
3027                                    search(
3028                                            companyId, keywords, status, params, start, end,
3029                                            getSorts(obc)));
3030                    }
3031                    catch (Exception e) {
3032                            throw new SystemException(e);
3033                    }
3034            }
3035    
3036            /**
3037             * Returns an ordered range of all the users who match the keywords and
3038             * status, using the indexer. It is preferable to use this method instead of
3039             * the non-indexed version whenever possible for performance reasons.
3040             *
3041             * <p>
3042             * Useful when paginating results. Returns a maximum of <code>end -
3043             * start</code> instances. <code>start</code> and <code>end</code> are not
3044             * primary keys, they are indexes in the result set. Thus, <code>0</code>
3045             * refers to the first result in the set. Setting both <code>start</code>
3046             * and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full
3047             * result set.
3048             * </p>
3049             *
3050             * @param  companyId the primary key of the user's company
3051             * @param  keywords the keywords (space separated), which may occur in the
3052             *         user's first name, middle name, last name, screen name, or email
3053             *         address
3054             * @param  status the workflow status
3055             * @param  params the indexer parameters (optionally <code>null</code>). For
3056             *         more information see {@link
3057             *         com.liferay.portlet.usersadmin.util.UserIndexer}.
3058             * @param  start the lower bound of the range of users
3059             * @param  end the upper bound of the range of users (not inclusive)
3060             * @param  sort the field and direction to sort by (optionally
3061             *         <code>null</code>)
3062             * @return the matching users
3063             * @see    com.liferay.portlet.usersadmin.util.UserIndexer
3064             */
3065            @Override
3066            public Hits search(
3067                    long companyId, String keywords, int status,
3068                    LinkedHashMap<String, Object> params, int start, int end, Sort sort) {
3069    
3070                    return search(
3071                            companyId, keywords, status, params, start, end, new Sort[] {sort});
3072            }
3073    
3074            @Override
3075            public Hits search(
3076                    long companyId, String keywords, int status,
3077                    LinkedHashMap<String, Object> params, int start, int end,
3078                    Sort[] sorts) {
3079    
3080                    String firstName = null;
3081                    String middleName = null;
3082                    String lastName = null;
3083                    String fullName = null;
3084                    String screenName = null;
3085                    String emailAddress = null;
3086                    String street = null;
3087                    String city = null;
3088                    String zip = null;
3089                    String region = null;
3090                    String country = null;
3091                    boolean andOperator = false;
3092    
3093                    if (Validator.isNotNull(keywords)) {
3094                            firstName = keywords;
3095                            middleName = keywords;
3096                            lastName = keywords;
3097                            fullName = keywords;
3098                            screenName = keywords;
3099                            emailAddress = keywords;
3100                            street = keywords;
3101                            city = keywords;
3102                            zip = keywords;
3103                            region = keywords;
3104                            country = keywords;
3105                    }
3106                    else {
3107                            andOperator = true;
3108                    }
3109    
3110                    if (params != null) {
3111                            params.put("keywords", keywords);
3112                    }
3113    
3114                    try {
3115                            Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3116                                    User.class);
3117    
3118                            SearchContext searchContext = buildSearchContext(
3119                                    companyId, firstName, middleName, lastName, fullName,
3120                                    screenName, emailAddress, street, city, zip, region, country,
3121                                    status, params, andOperator, start, end, sorts);
3122    
3123                            return indexer.search(searchContext);
3124                    }
3125                    catch (Exception e) {
3126                            throw new SystemException(e);
3127                    }
3128            }
3129    
3130            /**
3131             * Returns an ordered range of all the users with the status, and whose
3132             * first name, middle name, last name, screen name, and email address match
3133             * the keywords specified for them, without using the indexer. It is
3134             * preferable to use the indexed version {@link #search(long, String,
3135             * String, String, String, String, int, LinkedHashMap, boolean, int, int,
3136             * Sort)} instead of this method wherever possible for performance reasons.
3137             *
3138             * <p>
3139             * Useful when paginating results. Returns a maximum of <code>end -
3140             * start</code> instances. <code>start</code> and <code>end</code> are not
3141             * primary keys, they are indexes in the result set. Thus, <code>0</code>
3142             * refers to the first result in the set. Setting both <code>start</code>
3143             * and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full
3144             * result set.
3145             * </p>
3146             *
3147             * @param  companyId the primary key of the user's company
3148             * @param  firstName the first name keywords (space separated)
3149             * @param  middleName the middle name keywords
3150             * @param  lastName the last name keywords
3151             * @param  screenName the screen name keywords
3152             * @param  emailAddress the email address keywords
3153             * @param  status the workflow status
3154             * @param  params the finder parameters (optionally <code>null</code>). For
3155             *         more information see {@link
3156             *         com.liferay.portal.service.persistence.UserFinder}.
3157             * @param  andSearch whether every field must match its keywords, or just
3158             *         one field. For example, &quot;users with the first name 'bob' and
3159             *         last name 'smith'&quot; vs &quot;users with the first name 'bob'
3160             *         or the last name 'smith'&quot;.
3161             * @param  start the lower bound of the range of users
3162             * @param  end the upper bound of the range of users (not inclusive)
3163             * @param  obc the comparator to order the users by (optionally
3164             *         <code>null</code>)
3165             * @return the matching users
3166             * @see    com.liferay.portal.service.persistence.UserFinder
3167             */
3168            @Override
3169            public List<User> search(
3170                    long companyId, String firstName, String middleName, String lastName,
3171                    String screenName, String emailAddress, int status,
3172                    LinkedHashMap<String, Object> params, boolean andSearch, int start,
3173                    int end, OrderByComparator<User> obc) {
3174    
3175                    Indexer<?> indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3176    
3177                    if (!indexer.isIndexerEnabled() ||
3178                            !PropsValues.USERS_SEARCH_WITH_INDEX || isUseCustomSQL(params)) {
3179    
3180                            return userFinder.findByC_FN_MN_LN_SN_EA_S(
3181                                    companyId, firstName, middleName, lastName, screenName,
3182                                    emailAddress, status, params, andSearch, start, end, obc);
3183                    }
3184    
3185                    try {
3186                            return UsersAdminUtil.getUsers(
3187                                    search(
3188                                            companyId, firstName, middleName, lastName, screenName,
3189                                            emailAddress, status, params, andSearch, start, end,
3190                                            getSorts(obc)));
3191                    }
3192                    catch (Exception e) {
3193                            throw new SystemException(e);
3194                    }
3195            }
3196    
3197            /**
3198             * Returns an ordered range of all the users with the status, and whose
3199             * first name, middle name, last name, screen name, and email address match
3200             * the keywords specified for them, using the indexer. It is preferable to
3201             * use this method instead of the non-indexed version whenever possible for
3202             * performance reasons.
3203             *
3204             * <p>
3205             * Useful when paginating results. Returns a maximum of <code>end -
3206             * start</code> instances. <code>start</code> and <code>end</code> are not
3207             * primary keys, they are indexes in the result set. Thus, <code>0</code>
3208             * refers to the first result in the set. Setting both <code>start</code>
3209             * and <code>end</code> to {@link QueryUtil#ALL_POS} will return the full
3210             * result set.
3211             * </p>
3212             *
3213             * @param  companyId the primary key of the user's company
3214             * @param  firstName the first name keywords (space separated)
3215             * @param  middleName the middle name keywords
3216             * @param  lastName the last name keywords
3217             * @param  screenName the screen name keywords
3218             * @param  emailAddress the email address keywords
3219             * @param  status the workflow status
3220             * @param  params the indexer parameters (optionally <code>null</code>). For
3221             *         more information see {@link
3222             *         com.liferay.portlet.usersadmin.util.UserIndexer}.
3223             * @param  andSearch whether every field must match its keywords, or just
3224             *         one field. For example, &quot;users with the first name 'bob' and
3225             *         last name 'smith'&quot; vs &quot;users with the first name 'bob'
3226             *         or the last name 'smith'&quot;.
3227             * @param  start the lower bound of the range of users
3228             * @param  end the upper bound of the range of users (not inclusive)
3229             * @param  sort the field and direction to sort by (optionally
3230             *         <code>null</code>)
3231             * @return the matching users
3232             * @see    com.liferay.portlet.usersadmin.util.UserIndexer
3233             */
3234            @Override
3235            public Hits search(
3236                    long companyId, String firstName, String middleName, String lastName,
3237                    String screenName, String emailAddress, int status,
3238                    LinkedHashMap<String, Object> params, boolean andSearch, int start,
3239                    int end, Sort sort) {
3240    
3241                    return search(
3242                            companyId, firstName, middleName, lastName, screenName,
3243                            emailAddress, status, params, andSearch, start, end,
3244                            new Sort[] {sort});
3245            }
3246    
3247            @Override
3248            public Hits search(
3249                    long companyId, String firstName, String middleName, String lastName,
3250                    String screenName, String emailAddress, int status,
3251                    LinkedHashMap<String, Object> params, boolean andSearch, int start,
3252                    int end, Sort[] sorts) {
3253    
3254                    try {
3255                            Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3256                                    User.class);
3257    
3258                            SearchContext searchContext = buildSearchContext(
3259                                    companyId, firstName, middleName, lastName, null, screenName,
3260                                    emailAddress, null, null, null, null, null, status, params,
3261                                    andSearch, start, end, sorts);
3262    
3263                            return indexer.search(searchContext);
3264                    }
3265                    catch (Exception e) {
3266                            throw new SystemException(e);
3267                    }
3268            }
3269    
3270            /**
3271             * Returns the number of users who match the keywords and status.
3272             *
3273             * @param  companyId the primary key of the user's company
3274             * @param  keywords the keywords (space separated), which may occur in the
3275             *         user's first name, middle name, last name, screen name, or email
3276             *         address
3277             * @param  status the workflow status
3278             * @param  params the finder parameters (optionally <code>null</code>). For
3279             *         more information see {@link
3280             *         com.liferay.portal.service.persistence.UserFinder}.
3281             * @return the number matching users
3282             */
3283            @Override
3284            public int searchCount(
3285                    long companyId, String keywords, int status,
3286                    LinkedHashMap<String, Object> params) {
3287    
3288                    Indexer<?> indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3289    
3290                    if (!indexer.isIndexerEnabled() ||
3291                            !PropsValues.USERS_SEARCH_WITH_INDEX || isUseCustomSQL(params)) {
3292    
3293                            return userFinder.countByKeywords(
3294                                    companyId, keywords, status, params);
3295                    }
3296    
3297                    try {
3298                            String firstName = null;
3299                            String middleName = null;
3300                            String lastName = null;
3301                            String fullName = null;
3302                            String screenName = null;
3303                            String emailAddress = null;
3304                            String street = null;
3305                            String city = null;
3306                            String zip = null;
3307                            String region = null;
3308                            String country = null;
3309                            boolean andOperator = false;
3310    
3311                            if (Validator.isNotNull(keywords)) {
3312                                    firstName = keywords;
3313                                    middleName = keywords;
3314                                    lastName = keywords;
3315                                    fullName = keywords;
3316                                    screenName = keywords;
3317                                    emailAddress = keywords;
3318                                    street = keywords;
3319                                    city = keywords;
3320                                    zip = keywords;
3321                                    region = keywords;
3322                                    country = keywords;
3323                            }
3324                            else {
3325                                    andOperator = true;
3326                            }
3327    
3328                            if (params != null) {
3329                                    params.put("keywords", keywords);
3330                            }
3331    
3332                            SearchContext searchContext = buildSearchContext(
3333                                    companyId, firstName, middleName, lastName, fullName,
3334                                    screenName, emailAddress, street, city, zip, region, country,
3335                                    status, params, andOperator, QueryUtil.ALL_POS,
3336                                    QueryUtil.ALL_POS, null);
3337    
3338                            return (int)indexer.searchCount(searchContext);
3339                    }
3340                    catch (Exception e) {
3341                            throw new SystemException(e);
3342                    }
3343            }
3344    
3345            /**
3346             * Returns the number of users with the status, and whose first name, middle
3347             * name, last name, screen name, and email address match the keywords
3348             * specified for them.
3349             *
3350             * @param  companyId the primary key of the user's company
3351             * @param  firstName the first name keywords (space separated)
3352             * @param  middleName the middle name keywords
3353             * @param  lastName the last name keywords
3354             * @param  screenName the screen name keywords
3355             * @param  emailAddress the email address keywords
3356             * @param  status the workflow status
3357             * @param  params the finder parameters (optionally <code>null</code>). For
3358             *         more information see {@link
3359             *         com.liferay.portal.service.persistence.UserFinder}.
3360             * @param  andSearch whether every field must match its keywords, or just
3361             *         one field. For example, &quot;users with the first name 'bob' and
3362             *         last name 'smith'&quot; vs &quot;users with the first name 'bob'
3363             *         or the last name 'smith'&quot;.
3364             * @return the number of matching users
3365             */
3366            @Override
3367            public int searchCount(
3368                    long companyId, String firstName, String middleName, String lastName,
3369                    String screenName, String emailAddress, int status,
3370                    LinkedHashMap<String, Object> params, boolean andSearch) {
3371    
3372                    Indexer<?> indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3373    
3374                    if (!indexer.isIndexerEnabled() ||
3375                            !PropsValues.USERS_SEARCH_WITH_INDEX || isUseCustomSQL(params)) {
3376    
3377                            return userFinder.countByC_FN_MN_LN_SN_EA_S(
3378                                    companyId, firstName, middleName, lastName, screenName,
3379                                    emailAddress, status, params, andSearch);
3380                    }
3381    
3382                    try {
3383                            FullNameGenerator fullNameGenerator =
3384                                    FullNameGeneratorFactory.getInstance();
3385    
3386                            String fullName = fullNameGenerator.getFullName(
3387                                    firstName, middleName, lastName);
3388    
3389                            SearchContext searchContext = buildSearchContext(
3390                                    companyId, firstName, middleName, lastName, fullName,
3391                                    screenName, emailAddress, null, null, null, null, null, status,
3392                                    params, true, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
3393    
3394                            return (int)indexer.searchCount(searchContext);
3395                    }
3396                    catch (Exception e) {
3397                            throw new SystemException(e);
3398                    }
3399            }
3400    
3401            @Override
3402            public Map<Long, Integer> searchCounts(
3403                    long companyId, int status, long[] groupIds) {
3404    
3405                    return userFinder.countByGroups(companyId, status, groupIds);
3406            }
3407    
3408            @Override
3409            public List<User> searchSocial(
3410                            long userId, int[] socialRelationTypes, String keywords, int start,
3411                            int end)
3412                    throws PortalException {
3413    
3414                    User user = userPersistence.findByPrimaryKey(userId);
3415    
3416                    LinkedHashMap<String, Object> params = new LinkedHashMap<>();
3417    
3418                    params.put(
3419                            "socialRelationType",
3420                            new Long[][] {
3421                                    new Long[] {userId}, ArrayUtil.toLongArray(socialRelationTypes)
3422                            });
3423                    params.put("wildcardMode", WildcardMode.TRAILING);
3424    
3425                    return userFinder.findByKeywords(
3426                            user.getCompanyId(), keywords, WorkflowConstants.STATUS_APPROVED,
3427                            params, start, end, null);
3428            }
3429    
3430            @Override
3431            public List<User> searchSocial(
3432                    long companyId, long[] groupIds, String keywords, int start, int end) {
3433    
3434                    LinkedHashMap<String, Object> params = new LinkedHashMap<>();
3435    
3436                    params.put("usersGroups", ArrayUtil.toLongArray(groupIds));
3437                    params.put("wildcardMode", WildcardMode.TRAILING);
3438    
3439                    return userFinder.findByKeywords(
3440                            companyId, keywords, WorkflowConstants.STATUS_APPROVED, params,
3441                            start, end, null);
3442            }
3443    
3444            @Override
3445            public List<User> searchSocial(
3446                            long[] groupIds, long userId, int[] socialRelationTypes,
3447                            String keywords, int start, int end)
3448                    throws PortalException {
3449    
3450                    User user = userPersistence.findByPrimaryKey(userId);
3451    
3452                    LinkedHashMap<String, Object> params = new LinkedHashMap<>();
3453    
3454                    params.put(
3455                            "socialRelationType",
3456                            new Long[][] {
3457                                    new Long[] {userId}, ArrayUtil.toLongArray(socialRelationTypes)
3458                            });
3459                    params.put("socialRelationTypeUnionUserGroups", true);
3460                    params.put("usersGroups", ArrayUtil.toLongArray(groupIds));
3461                    params.put("wildcardMode", WildcardMode.TRAILING);
3462    
3463                    return userFinder.findByKeywords(
3464                            user.getCompanyId(), keywords, WorkflowConstants.STATUS_APPROVED,
3465                            params, start, end, null);
3466            }
3467    
3468            @Override
3469            public BaseModelSearchResult<User> searchUsers(
3470                            long companyId, String keywords, int status,
3471                            LinkedHashMap<String, Object> params, int start, int end, Sort sort)
3472                    throws PortalException {
3473    
3474                    return searchUsers(
3475                            companyId, keywords, status, params, start, end, new Sort[] {sort});
3476            }
3477    
3478            @Override
3479            public BaseModelSearchResult<User> searchUsers(
3480                            long companyId, String keywords, int status,
3481                            LinkedHashMap<String, Object> params, int start, int end,
3482                            Sort[] sorts)
3483                    throws PortalException {
3484    
3485                    String firstName = null;
3486                    String middleName = null;
3487                    String lastName = null;
3488                    String fullName = null;
3489                    String screenName = null;
3490                    String emailAddress = null;
3491                    String street = null;
3492                    String city = null;
3493                    String zip = null;
3494                    String region = null;
3495                    String country = null;
3496                    boolean andOperator = false;
3497    
3498                    if (Validator.isNotNull(keywords)) {
3499                            firstName = keywords;
3500                            middleName = keywords;
3501                            lastName = keywords;
3502                            fullName = keywords;
3503                            screenName = keywords;
3504                            emailAddress = keywords;
3505                            street = keywords;
3506                            city = keywords;
3507                            zip = keywords;
3508                            region = keywords;
3509                            country = keywords;
3510                    }
3511                    else {
3512                            andOperator = true;
3513                    }
3514    
3515                    if (params != null) {
3516                            params.put("keywords", keywords);
3517                    }
3518    
3519                    SearchContext searchContext = buildSearchContext(
3520                            companyId, firstName, middleName, lastName, fullName, screenName,
3521                            emailAddress, street, city, zip, region, country, status, params,
3522                            andOperator, start, end, sorts);
3523    
3524                    return searchUsers(searchContext);
3525            }
3526    
3527            @Override
3528            public BaseModelSearchResult<User> searchUsers(
3529                            long companyId, String firstName, String middleName,
3530                            String lastName, String screenName, String emailAddress, int status,
3531                            LinkedHashMap<String, Object> params, boolean andSearch, int start,
3532                            int end, Sort sort)
3533                    throws PortalException {
3534    
3535                    return searchUsers(
3536                            companyId, firstName, middleName, lastName, screenName,
3537                            emailAddress, status, params, andSearch, start, end,
3538                            new Sort[] {sort});
3539            }
3540    
3541            @Override
3542            public BaseModelSearchResult<User> searchUsers(
3543                            long companyId, String firstName, String middleName,
3544                            String lastName, String screenName, String emailAddress, int status,
3545                            LinkedHashMap<String, Object> params, boolean andSearch, int start,
3546                            int end, Sort[] sorts)
3547                    throws PortalException {
3548    
3549                    SearchContext searchContext = buildSearchContext(
3550                            companyId, firstName, middleName, lastName, null, screenName,
3551                            emailAddress, null, null, null, null, null, status, params,
3552                            andSearch, start, end, sorts);
3553    
3554                    return searchUsers(searchContext);
3555            }
3556    
3557            /**
3558             * Sends an email address verification to the user.
3559             *
3560             * @param  user the verification email recipient
3561             * @param  emailAddress the recipient's email address
3562             * @param  serviceContext the service context to be applied. Must set the
3563             *         portal URL, main path, primary key of the layout, remote address,
3564             *         remote host, and agent for the user.
3565             * @throws PortalException if a portal exception occurred
3566             */
3567            @Override
3568            public void sendEmailAddressVerification(
3569                            User user, String emailAddress, ServiceContext serviceContext)
3570                    throws PortalException {
3571    
3572                    if (user.isEmailAddressVerified() &&
3573                            StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
3574    
3575                            return;
3576                    }
3577    
3578                    Ticket ticket = ticketLocalService.addDistinctTicket(
3579                            user.getCompanyId(), User.class.getName(), user.getUserId(),
3580                            TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3581                            serviceContext);
3582    
3583                    String verifyEmailAddressURL =
3584                            serviceContext.getPortalURL() + serviceContext.getPathMain() +
3585                                    "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3586    
3587                    long plid = serviceContext.getPlid();
3588    
3589                    if (plid > 0) {
3590                            Layout layout = layoutLocalService.fetchLayout(plid);
3591    
3592                            if (layout != null) {
3593                                    Group group = layout.getGroup();
3594    
3595                                    if (!layout.isPrivateLayout() && !group.isUser()) {
3596                                            verifyEmailAddressURL +=
3597                                                    "&p_l_id=" + serviceContext.getPlid();
3598                                    }
3599                            }
3600                    }
3601    
3602                    String fromName = PrefsPropsUtil.getString(
3603                            user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3604                    String fromAddress = PrefsPropsUtil.getString(
3605                            user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3606    
3607                    String toName = user.getFullName();
3608                    String toAddress = emailAddress;
3609    
3610                    PortletPreferences companyPortletPreferences =
3611                            PrefsPropsUtil.getPreferences(user.getCompanyId(), true);
3612    
3613                    Map<Locale, String> localizedSubjectMap =
3614                            LocalizationUtil.getLocalizationMap(
3615                                    companyPortletPreferences, "adminEmailVerificationSubject",
3616                                    PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3617                    Map<Locale, String> localizedBodyMap =
3618                            LocalizationUtil.getLocalizationMap(
3619                                    companyPortletPreferences, "adminEmailVerificationBody",
3620                                    PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3621    
3622                    SubscriptionSender subscriptionSender = new SubscriptionSender();
3623    
3624                    subscriptionSender.setCompanyId(user.getCompanyId());
3625                    subscriptionSender.setContextAttributes(
3626                            "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3627                            "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3628                            "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3629                            "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_ID$]",
3630                            user.getUserId(), "[$USER_SCREENNAME$]", user.getScreenName());
3631                    subscriptionSender.setFrom(fromAddress, fromName);
3632                    subscriptionSender.setHtmlFormat(true);
3633                    subscriptionSender.setLocalizedBodyMap(localizedBodyMap);
3634                    subscriptionSender.setLocalizedSubjectMap(localizedSubjectMap);
3635                    subscriptionSender.setMailId("user", user.getUserId());
3636                    subscriptionSender.setServiceContext(serviceContext);
3637    
3638                    subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3639    
3640                    subscriptionSender.flushNotificationsAsync();
3641            }
3642    
3643            /**
3644             * Sends the password email to the user with the email address. The content
3645             * of this email can be specified in <code>portal.properties</code> with the
3646             * <code>admin.email.password</code> keys.
3647             *
3648             * @param  companyId the primary key of the user's company
3649             * @param  emailAddress the user's email address
3650             * @param  fromName the name of the individual that the email should be from
3651             * @param  fromAddress the address of the individual that the email should
3652             *         be from
3653             * @param  subject the email subject. If <code>null</code>, the subject
3654             *         specified in <code>portal.properties</code> will be used.
3655             * @param  body the email body. If <code>null</code>, the body specified in
3656             *         <code>portal.properties</code> will be used.
3657             * @param  serviceContext the service context to be applied
3658             * @throws PortalException if a user with the email address could not be
3659             *         found
3660             */
3661            @Override
3662            public boolean sendPassword(
3663                            long companyId, String emailAddress, String fromName,
3664                            String fromAddress, String subject, String body,
3665                            ServiceContext serviceContext)
3666                    throws PortalException {
3667    
3668                    Company company = companyPersistence.findByPrimaryKey(companyId);
3669    
3670                    if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3671                            throw new SendPasswordException.MustBeEnabled(company);
3672                    }
3673    
3674                    emailAddress = StringUtil.toLowerCase(emailAddress.trim());
3675    
3676                    if (Validator.isNull(emailAddress)) {
3677                            throw new UserEmailAddressException.MustNotBeNull();
3678                    }
3679    
3680                    User user = userPersistence.findByC_EA(companyId, emailAddress);
3681    
3682                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3683    
3684                    String newPassword = StringPool.BLANK;
3685                    String passwordResetURL = StringPool.BLANK;
3686    
3687                    if (company.isSendPasswordResetLink()) {
3688                            Date expirationDate = null;
3689    
3690                            if ((passwordPolicy != null) &&
3691                                    (passwordPolicy.getResetTicketMaxAge() > 0)) {
3692    
3693                                    expirationDate = new Date(
3694                                            System.currentTimeMillis() +
3695                                                    (passwordPolicy.getResetTicketMaxAge() * 1000));
3696                            }
3697    
3698                            Ticket ticket = ticketLocalService.addDistinctTicket(
3699                                    companyId, User.class.getName(), user.getUserId(),
3700                                    TicketConstants.TYPE_PASSWORD, null, expirationDate,
3701                                    serviceContext);
3702    
3703                            passwordResetURL =
3704                                    serviceContext.getPortalURL() + serviceContext.getPathMain() +
3705                                            "/portal/update_password?p_l_id="+
3706                                                    serviceContext.getPlid() +
3707                                                            "&ticketKey=" + ticket.getKey();
3708                    }
3709                    else {
3710                            if (!Validator.equals(
3711                                            PasswordEncryptorUtil.getDefaultPasswordAlgorithmType(),
3712                                            PasswordEncryptorUtil.TYPE_NONE)) {
3713    
3714                                    if (LDAPSettingsUtil.isPasswordPolicyEnabled(
3715                                                    user.getCompanyId())) {
3716    
3717                                            if (_log.isWarnEnabled()) {
3718                                                    StringBundler sb = new StringBundler(5);
3719    
3720                                                    sb.append("When LDAP password policy is enabled, ");
3721                                                    sb.append("it is possible that portal generated ");
3722                                                    sb.append("passwords will not match the LDAP policy.");
3723                                                    sb.append("Using RegExpToolkit to generate new ");
3724                                                    sb.append("password.");
3725    
3726                                                    _log.warn(sb.toString());
3727                                            }
3728    
3729                                            RegExpToolkit regExpToolkit = new RegExpToolkit();
3730    
3731                                            newPassword = regExpToolkit.generate(null);
3732                                    }
3733                                    else {
3734                                            newPassword = PwdToolkitUtil.generate(passwordPolicy);
3735                                    }
3736    
3737                                    boolean passwordReset = false;
3738    
3739                                    if (passwordPolicy.getChangeable() &&
3740                                            passwordPolicy.getChangeRequired()) {
3741    
3742                                            passwordReset = true;
3743                                    }
3744    
3745                                    user.setPassword(PasswordEncryptorUtil.encrypt(newPassword));
3746                                    user.setPasswordUnencrypted(newPassword);
3747                                    user.setPasswordEncrypted(true);
3748                                    user.setPasswordReset(passwordReset);
3749                                    user.setPasswordModified(true);
3750                                    user.setPasswordModifiedDate(new Date());
3751    
3752                                    userPersistence.update(user);
3753    
3754                                    user.setPasswordModified(false);
3755                            }
3756                            else {
3757                                    newPassword = user.getPassword();
3758                            }
3759                    }
3760    
3761                    sendPasswordNotification(
3762                            user, companyId, newPassword, passwordResetURL, fromName,
3763                            fromAddress, subject, body, serviceContext);
3764    
3765                    return company.isSendPassword();
3766            }
3767    
3768            /**
3769             * Sends a password notification email to the user matching the email
3770             * address. The portal's settings determine whether a password is sent
3771             * explicitly or whether a link for resetting the user's password is sent.
3772             * The method sends the email asynchronously and returns before the email is
3773             * sent.
3774             *
3775             * <p>
3776             * The content of the notification email is specified with the
3777             * <code>admin.email.password</code> portal property keys. They can be
3778             * overridden via a <code>portal-ext.properties</code> file or modified
3779             * through the Portal Settings UI.
3780             * </p>
3781             *
3782             * @param  companyId the primary key of the user's company
3783             * @param  emailAddress the user's email address
3784             * @return <code>true</code> if the notification email includes a new
3785             *         password; <code>false</code> if the notification email only
3786             *         contains a reset link
3787             * @throws PortalException if a user with the email address could not be
3788             *         found
3789             */
3790            @Override
3791            public boolean sendPasswordByEmailAddress(
3792                            long companyId, String emailAddress)
3793                    throws PortalException {
3794    
3795                    User user = userPersistence.findByC_EA(companyId, emailAddress);
3796    
3797                    return sendPassword(
3798                            user.getCompanyId(), user.getEmailAddress(), null, null, null, null,
3799                            ServiceContextThreadLocal.getServiceContext());
3800            }
3801    
3802            /**
3803             * Sends a password notification email to the user matching the screen name.
3804             * The portal's settings determine whether a password is sent explicitly or
3805             * whether a link for resetting the user's password is sent. The method
3806             * sends the email asynchronously and returns before the email is sent.
3807             *
3808             * <p>
3809             * The content of the notification email is specified with the
3810             * <code>admin.email.password</code> portal property keys. They can be
3811             * overridden via a <code>portal-ext.properties</code> file or modified
3812             * through the Portal Settings UI.
3813             * </p>
3814             *
3815             * @param  companyId the primary key of the user's company
3816             * @param  screenName the user's screen name
3817             * @return <code>true</code> if the notification email includes a new
3818             *         password; <code>false</code> if the notification email only
3819             *         contains a reset link
3820             * @throws PortalException if a user with the screen name could not be found
3821             */
3822            @Override
3823            public boolean sendPasswordByScreenName(long companyId, String screenName)
3824                    throws PortalException {
3825    
3826                    User user = userPersistence.findByC_SN(companyId, screenName);
3827    
3828                    return sendPassword(
3829                            user.getCompanyId(), user.getEmailAddress(), null, null, null, null,
3830                            ServiceContextThreadLocal.getServiceContext());
3831            }
3832    
3833            /**
3834             * Sends a password notification email to the user matching the ID. The
3835             * portal's settings determine whether a password is sent explicitly or
3836             * whether a link for resetting the user's password is sent. The method
3837             * sends the email asynchronously and returns before the email is sent.
3838             *
3839             * <p>
3840             * The content of the notification email is specified with the
3841             * <code>admin.email.password</code> portal property keys. They can be
3842             * overridden via a <code>portal-ext.properties</code> file or modified
3843             * through the Portal Settings UI.
3844             * </p>
3845             *
3846             * @param  userId the user's primary key
3847             * @return <code>true</code> if the notification email includes a new
3848             *         password; <code>false</code> if the notification email only
3849             *         contains a reset link
3850             * @throws PortalException if a user with the user ID could not be found
3851             */
3852            @Override
3853            public boolean sendPasswordByUserId(long userId) throws PortalException {
3854                    User user = userPersistence.findByPrimaryKey(userId);
3855    
3856                    return sendPassword(
3857                            user.getCompanyId(), user.getEmailAddress(), null, null, null, null,
3858                            ServiceContextThreadLocal.getServiceContext());
3859            }
3860    
3861            /**
3862             * Sets the users in the role, removing and adding users to the role as
3863             * necessary.
3864             *
3865             * @param  roleId the primary key of the role
3866             * @param  userIds the primary keys of the users
3867             * @throws PortalException if a portal exception occurred
3868             */
3869            @Override
3870            public void setRoleUsers(long roleId, long[] userIds)
3871                    throws PortalException {
3872    
3873                    long[] oldUserIds = rolePersistence.getUserPrimaryKeys(roleId);
3874    
3875                    Set<Long> updatedUserIdsSet = SetUtil.symmetricDifference(
3876                            userIds, oldUserIds);
3877    
3878                    long[] updateUserIds = ArrayUtil.toLongArray(updatedUserIdsSet);
3879    
3880                    rolePersistence.setUsers(roleId, userIds);
3881    
3882                    reindex(updateUserIds);
3883    
3884                    PermissionCacheUtil.clearCache(updateUserIds);
3885            }
3886    
3887            /**
3888             * Sets the users in the user group, removing and adding users to the user
3889             * group as necessary.
3890             *
3891             * @param  userGroupId the primary key of the user group
3892             * @param  userIds the primary keys of the users
3893             * @throws PortalException if a portal exception occurred
3894             */
3895            @Override
3896            @SuppressWarnings("deprecation")
3897            public void setUserGroupUsers(long userGroupId, long[] userIds)
3898                    throws PortalException {
3899    
3900                    if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3901                            userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3902                    }
3903    
3904                    long[] oldUserIds = userGroupPersistence.getUserPrimaryKeys(
3905                            userGroupId);
3906    
3907                    Set<Long> updatedUserIdsSet = SetUtil.symmetricDifference(
3908                            userIds, oldUserIds);
3909    
3910                    long[] updateUserIds = ArrayUtil.toLongArray(updatedUserIdsSet);
3911    
3912                    userGroupPersistence.setUsers(userGroupId, userIds);
3913    
3914                    reindex(updateUserIds);
3915    
3916                    PermissionCacheUtil.clearCache(updateUserIds);
3917            }
3918    
3919            /**
3920             * Removes the users from the teams of a group.
3921             *
3922             * @param  groupId the primary key of the group
3923             * @param  userIds the primary keys of the users
3924             * @throws PortalException if a portal exception occurred
3925             */
3926            @Override
3927            public void unsetGroupTeamsUsers(long groupId, long[] userIds)
3928                    throws PortalException {
3929    
3930                    List<Team> teams = teamPersistence.findByGroupId(groupId);
3931    
3932                    for (Team team : teams) {
3933                            unsetTeamUsers(team.getTeamId(), userIds);
3934                    }
3935    
3936                    PermissionCacheUtil.clearCache(userIds);
3937            }
3938    
3939            /**
3940             * Removes the users from the group.
3941             *
3942             * @param  groupId the primary key of the group
3943             * @param  userIds the primary keys of the users
3944             * @param  serviceContext the service context to be applied (optionally
3945             *         <code>null</code>)
3946             * @throws PortalException if a portal exception occurred
3947             */
3948            @Override
3949            public void unsetGroupUsers(
3950                            final long groupId, final long[] userIds,
3951                            ServiceContext serviceContext)
3952                    throws PortalException {
3953    
3954                    userGroupRoleLocalService.deleteUserGroupRoles(
3955                            userIds, groupId, RoleConstants.TYPE_SITE);
3956    
3957                    unsetGroupTeamsUsers(groupId, userIds);
3958    
3959                    groupPersistence.removeUsers(groupId, userIds);
3960    
3961                    reindex(userIds);
3962    
3963                    PermissionCacheUtil.clearCache(userIds);
3964    
3965                    Callable<Void> callable = new Callable<Void>() {
3966    
3967                            @Override
3968                            public Void call() throws Exception {
3969                                    Message message = new Message();
3970    
3971                                    message.put("groupId", groupId);
3972                                    message.put("userIds", userIds);
3973    
3974                                    MessageBusUtil.sendMessage(
3975                                            DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
3976    
3977                                    return null;
3978                            }
3979    
3980                    };
3981    
3982                    TransactionCommitCallbackUtil.registerCallback(callable);
3983            }
3984    
3985            /**
3986             * Removes the users from the organization.
3987             *
3988             * @param  organizationId the primary key of the organization
3989             * @param  userIds the primary keys of the users
3990             * @throws PortalException if a portal exception occurred
3991             */
3992            @Override
3993            public void unsetOrganizationUsers(
3994                            long organizationId, final long[] userIds)
3995                    throws PortalException {
3996    
3997                    Organization organization = organizationPersistence.findByPrimaryKey(
3998                            organizationId);
3999    
4000                    final Group group = organization.getGroup();
4001    
4002                    userGroupRoleLocalService.deleteUserGroupRoles(
4003                            userIds, group.getGroupId());
4004    
4005                    organizationPersistence.removeUsers(organizationId, userIds);
4006    
4007                    reindex(userIds);
4008    
4009                    PermissionCacheUtil.clearCache(userIds);
4010    
4011                    Callable<Void> callable = new Callable<Void>() {
4012    
4013                            @Override
4014                            public Void call() throws Exception {
4015                                    Message message = new Message();
4016    
4017                                    message.put("groupId", group.getGroupId());
4018                                    message.put("userIds", userIds);
4019    
4020                                    MessageBusUtil.sendMessage(
4021                                            DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
4022    
4023                                    return null;
4024                            }
4025    
4026                    };
4027    
4028                    TransactionCommitCallbackUtil.registerCallback(callable);
4029            }
4030    
4031            /**
4032             * Removes the users from the password policy.
4033             *
4034             * @param passwordPolicyId the primary key of the password policy
4035             * @param userIds the primary keys of the users
4036             */
4037            @Override
4038            public void unsetPasswordPolicyUsers(
4039                    long passwordPolicyId, long[] userIds) {
4040    
4041                    passwordPolicyRelLocalService.deletePasswordPolicyRels(
4042                            passwordPolicyId, User.class.getName(), userIds);
4043            }
4044    
4045            /**
4046             * Removes the users from the role.
4047             *
4048             * @param  roleId the primary key of the role
4049             * @param  users the users
4050             * @throws PortalException if a portal exception occurred
4051             */
4052            @Override
4053            public void unsetRoleUsers(long roleId, List<User> users)
4054                    throws PortalException {
4055    
4056                    Role role = rolePersistence.findByPrimaryKey(roleId);
4057    
4058                    String roleName = role.getName();
4059    
4060                    if ((roleName.equals(RoleConstants.ADMINISTRATOR) &&
4061                             (getRoleUsersCount(role.getRoleId()) <= 1)) ||
4062                            roleName.equals(RoleConstants.USER)) {
4063    
4064                            return;
4065                    }
4066    
4067                    rolePersistence.removeUsers(roleId, users);
4068    
4069                    Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4070                            User.class);
4071    
4072                    indexer.reindex(users);
4073    
4074                    long[] userIds = new long[users.size()];
4075    
4076                    for (int i = 0; i < users.size(); i++) {
4077                            User user = users.get(i);
4078    
4079                            userIds[i] = user.getUserId();
4080                    }
4081    
4082                    PermissionCacheUtil.clearCache(userIds);
4083            }
4084    
4085            /**
4086             * Removes the users from the role.
4087             *
4088             * @param  roleId the primary key of the role
4089             * @param  userIds the primary keys of the users
4090             * @throws PortalException if a portal exception occurred
4091             */
4092            @Override
4093            public void unsetRoleUsers(long roleId, long[] userIds)
4094                    throws PortalException {
4095    
4096                    Role role = rolePersistence.findByPrimaryKey(roleId);
4097    
4098                    String roleName = role.getName();
4099    
4100                    if (roleName.equals(RoleConstants.USER) ||
4101                            (roleName.equals(RoleConstants.ADMINISTRATOR) &&
4102                             getRoleUsersCount(role.getRoleId()) <= 1)) {
4103    
4104                            return;
4105                    }
4106    
4107                    rolePersistence.removeUsers(roleId, userIds);
4108    
4109                    reindex(userIds);
4110    
4111                    PermissionCacheUtil.clearCache(userIds);
4112            }
4113    
4114            /**
4115             * Removes the users from the team.
4116             *
4117             * @param  teamId the primary key of the team
4118             * @param  userIds the primary keys of the users
4119             * @throws PortalException if a portal exception occurred
4120             */
4121            @Override
4122            public void unsetTeamUsers(long teamId, long[] userIds)
4123                    throws PortalException {
4124    
4125                    teamPersistence.removeUsers(teamId, userIds);
4126    
4127                    reindex(userIds);
4128    
4129                    PermissionCacheUtil.clearCache(userIds);
4130            }
4131    
4132            /**
4133             * Removes the users from the user group.
4134             *
4135             * @param  userGroupId the primary key of the user group
4136             * @param  userIds the primary keys of the users
4137             * @throws PortalException if a portal exception occurred
4138             */
4139            @Override
4140            public void unsetUserGroupUsers(long userGroupId, long[] userIds)
4141                    throws PortalException {
4142    
4143                    userGroupPersistence.removeUsers(userGroupId, userIds);
4144    
4145                    reindex(userIds);
4146    
4147                    PermissionCacheUtil.clearCache(userIds);
4148            }
4149    
4150            /**
4151             * Updates whether the user has agreed to the terms of use.
4152             *
4153             * @param  userId the primary key of the user
4154             * @param  agreedToTermsOfUse whether the user has agreet to the terms of
4155             *         use
4156             * @return the user
4157             * @throws PortalException if a user with the primary key could not be found
4158             */
4159            @Override
4160            public User updateAgreedToTermsOfUse(
4161                            long userId, boolean agreedToTermsOfUse)
4162                    throws PortalException {
4163    
4164                    User user = userPersistence.findByPrimaryKey(userId);
4165    
4166                    user.setAgreedToTermsOfUse(agreedToTermsOfUse);
4167    
4168                    userPersistence.update(user);
4169    
4170                    return user;
4171            }
4172    
4173            /**
4174             * Updates the user's asset with the new asset categories and tag names,
4175             * removing and adding asset categories and tag names as necessary.
4176             *
4177             * @param  userId the primary key of the user
4178             * @param  user ID the primary key of the user
4179             * @param  assetCategoryIds the primary key's of the new asset categories
4180             * @param  assetTagNames the new asset tag names
4181             * @throws PortalException if a user with the primary key could not be found
4182             */
4183            @Override
4184            public void updateAsset(
4185                            long userId, User user, long[] assetCategoryIds,
4186                            String[] assetTagNames)
4187                    throws PortalException {
4188    
4189                    User owner = userPersistence.findByPrimaryKey(userId);
4190    
4191                    Company company = companyPersistence.findByPrimaryKey(
4192                            owner.getCompanyId());
4193    
4194                    Group companyGroup = company.getGroup();
4195    
4196                    assetEntryLocalService.updateEntry(
4197                            userId, companyGroup.getGroupId(), user.getCreateDate(),
4198                            user.getModifiedDate(), User.class.getName(), user.getUserId(),
4199                            user.getUuid(), 0, assetCategoryIds, assetTagNames, false, null,
4200                            null, null, null, user.getFullName(), null, null, null, null, 0, 0,
4201                            null);
4202            }
4203    
4204            /**
4205             * Updates the user's creation date.
4206             *
4207             * @param  userId the primary key of the user
4208             * @param  createDate the new creation date
4209             * @return the user
4210             * @throws PortalException if a user with the primary key could not be found
4211             */
4212            @Override
4213            public User updateCreateDate(long userId, Date createDate)
4214                    throws PortalException {
4215    
4216                    User user = userPersistence.findByPrimaryKey(userId);
4217    
4218                    user.setCreateDate(createDate);
4219    
4220                    userPersistence.update(user);
4221    
4222                    return user;
4223            }
4224    
4225            /**
4226             * Updates the user's email address.
4227             *
4228             * @param  userId the primary key of the user
4229             * @param  password the user's password
4230             * @param  emailAddress1 the user's new email address
4231             * @param  emailAddress2 the user's new email address confirmation
4232             * @return the user
4233             * @throws PortalException if a user with the primary key could not be found
4234             */
4235            @Override
4236            public User updateEmailAddress(
4237                            long userId, String password, String emailAddress1,
4238                            String emailAddress2)
4239                    throws PortalException {
4240    
4241                    emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
4242                    emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
4243    
4244                    User user = userPersistence.findByPrimaryKey(userId);
4245    
4246                    validateEmailAddress(user, emailAddress1, emailAddress2);
4247    
4248                    setEmailAddress(
4249                            user, password, user.getFirstName(), user.getMiddleName(),
4250                            user.getLastName(), emailAddress1);
4251    
4252                    userPersistence.update(user);
4253    
4254                    Contact contact = user.getContact();
4255    
4256                    contact.setEmailAddress(user.getEmailAddress());
4257    
4258                    contactPersistence.update(contact);
4259    
4260                    return user;
4261            }
4262    
4263            /**
4264             * Updates the user's email address or sends verification email.
4265             *
4266             * @param  userId the primary key of the user
4267             * @param  password the user's password
4268             * @param  emailAddress1 the user's new email address
4269             * @param  emailAddress2 the user's new email address confirmation
4270             * @param  serviceContext the service context to be applied. Must set the
4271             *         portal URL, main path, primary key of the layout, remote address,
4272             *         remote host, and agent for the user.
4273             * @return the user
4274             * @throws PortalException if a user with the primary key could not be found
4275             */
4276            @Override
4277            public User updateEmailAddress(
4278                            long userId, String password, String emailAddress1,
4279                            String emailAddress2, ServiceContext serviceContext)
4280                    throws PortalException {
4281    
4282                    emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
4283                    emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
4284    
4285                    User user = userPersistence.findByPrimaryKey(userId);
4286    
4287                    validateEmailAddress(user, emailAddress1, emailAddress2);
4288    
4289                    Company company = companyPersistence.findByPrimaryKey(
4290                            user.getCompanyId());
4291    
4292                    if (company.isStrangersVerify() &&
4293                            !StringUtil.equalsIgnoreCase(
4294                                    emailAddress1, user.getEmailAddress())) {
4295    
4296                            sendEmailAddressVerification(user, emailAddress1, serviceContext);
4297                    }
4298                    else {
4299                            setEmailAddress(
4300                                    user, password, user.getFirstName(), user.getMiddleName(),
4301                                    user.getLastName(), emailAddress1);
4302    
4303                            userPersistence.update(user);
4304    
4305                            Contact contact = user.getContact();
4306    
4307                            contact.setEmailAddress(user.getEmailAddress());
4308    
4309                            contactPersistence.update(contact);
4310                    }
4311    
4312                    return user;
4313            }
4314    
4315            /**
4316             * Updates whether the user has verified email address.
4317             *
4318             * @param  userId the primary key of the user
4319             * @param  emailAddressVerified whether the user has verified email address
4320             * @return the user
4321             * @throws PortalException if a user with the primary key could not be found
4322             */
4323            @Override
4324            public User updateEmailAddressVerified(
4325                            long userId, boolean emailAddressVerified)
4326                    throws PortalException {
4327    
4328                    User user = userPersistence.findByPrimaryKey(userId);
4329    
4330                    user.setEmailAddressVerified(emailAddressVerified);
4331    
4332                    userPersistence.update(user);
4333    
4334                    return user;
4335            }
4336    
4337            /**
4338             * Updates the user's Facebook ID.
4339             *
4340             * @param  userId the primary key of the user
4341             * @param  facebookId the user's new Facebook ID
4342             * @return the user
4343             * @throws PortalException if a user with the primary key could not be found
4344             */
4345            @Override
4346            public User updateFacebookId(long userId, long facebookId)
4347                    throws PortalException {
4348    
4349                    User user = userPersistence.findByPrimaryKey(userId);
4350    
4351                    user.setFacebookId(facebookId);
4352    
4353                    userPersistence.update(user);
4354    
4355                    return user;
4356            }
4357    
4358            /**
4359             * Sets the groups the user is in, removing and adding groups as necessary.
4360             *
4361             * @param  userId the primary key of the user
4362             * @param  newGroupIds the primary keys of the groups
4363             * @param  serviceContext the service context to be applied (optionally
4364             *         <code>null</code>)
4365             * @throws PortalException if a portal exception occurred
4366             */
4367            @Override
4368            public void updateGroups(
4369                            long userId, long[] newGroupIds, ServiceContext serviceContext)
4370                    throws PortalException {
4371    
4372                    boolean indexingEnabled = true;
4373    
4374                    if (serviceContext != null) {
4375                            indexingEnabled = serviceContext.isIndexingEnabled();
4376                    }
4377    
4378                    updateGroups(userId, newGroupIds, serviceContext, indexingEnabled);
4379            }
4380    
4381            /**
4382             * Updates a user account that was automatically created when a guest user
4383             * participated in an action (e.g. posting a comment) and only provided his
4384             * name and email address.
4385             *
4386             * @param  creatorUserId the primary key of the creator
4387             * @param  companyId the primary key of the user's company
4388             * @param  autoPassword whether a password should be automatically generated
4389             *         for the user
4390             * @param  password1 the user's password
4391             * @param  password2 the user's password confirmation
4392             * @param  autoScreenName whether a screen name should be automatically
4393             *         generated for the user
4394             * @param  screenName the user's screen name
4395             * @param  emailAddress the user's email address
4396             * @param  facebookId the user's facebook ID
4397             * @param  openId the user's OpenID
4398             * @param  locale the user's locale
4399             * @param  firstName the user's first name
4400             * @param  middleName the user's middle name
4401             * @param  lastName the user's last name
4402             * @param  prefixId the user's name prefix ID
4403             * @param  suffixId the user's name suffix ID
4404             * @param  male whether the user is male
4405             * @param  birthdayMonth the user's birthday month (0-based, meaning 0 for
4406             *         January)
4407             * @param  birthdayDay the user's birthday day
4408             * @param  birthdayYear the user's birthday year
4409             * @param  jobTitle the user's job title
4410             * @param  updateUserInformation whether to update the user's information
4411             * @param  sendEmail whether to send the user an email notification about
4412             *         their new account
4413             * @param  serviceContext the service context to be applied (optionally
4414             *         <code>null</code>). Can set expando bridge attributes for the
4415             *         user.
4416             * @return the user
4417             * @throws PortalException if the user's information was invalid
4418             */
4419            @Override
4420            public User updateIncompleteUser(
4421                            long creatorUserId, long companyId, boolean autoPassword,
4422                            String password1, String password2, boolean autoScreenName,
4423                            String screenName, String emailAddress, long facebookId,
4424                            String openId, Locale locale, String firstName, String middleName,
4425                            String lastName, long prefixId, long suffixId, boolean male,
4426                            int birthdayMonth, int birthdayDay, int birthdayYear,
4427                            String jobTitle, boolean updateUserInformation, boolean sendEmail,
4428                            ServiceContext serviceContext)
4429                    throws PortalException {
4430    
4431                    User user = getUserByEmailAddress(companyId, emailAddress);
4432    
4433                    if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
4434                            throw new PortalException("Invalid user status");
4435                    }
4436    
4437                    User defaultUser = getDefaultUser(companyId);
4438    
4439                    if (facebookId > 0) {
4440                            autoPassword = false;
4441    
4442                            if ((password1 == null) || (password2 == null)) {
4443                                    password1 = PwdGenerator.getPassword();
4444                                    password2 = password1;
4445                            }
4446    
4447                            sendEmail = false;
4448                    }
4449    
4450                    if (updateUserInformation) {
4451                            autoScreenName = false;
4452    
4453                            if (PrefsPropsUtil.getBoolean(
4454                                            companyId,
4455                                            PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
4456    
4457                                    autoScreenName = true;
4458                            }
4459    
4460                            validate(
4461                                    companyId, user.getUserId(), autoPassword, password1, password2,
4462                                    autoScreenName, screenName, emailAddress, openId, firstName,
4463                                    middleName, lastName, null, locale);
4464    
4465                            if (!autoPassword) {
4466                                    if (Validator.isNull(password1) ||
4467                                            Validator.isNull(password2)) {
4468                                                    throw new UserPasswordException.MustNotBeNull(
4469                                                            user.getUserId());
4470                                    }
4471                            }
4472    
4473                            if (autoScreenName) {
4474                                    ScreenNameGenerator screenNameGenerator =
4475                                            ScreenNameGeneratorFactory.getInstance();
4476    
4477                                    try {
4478                                            screenName = screenNameGenerator.generate(
4479                                                    companyId, user.getUserId(), emailAddress);
4480                                    }
4481                                    catch (Exception e) {
4482                                            throw new SystemException(e);
4483                                    }
4484                            }
4485    
4486                            FullNameGenerator fullNameGenerator =
4487                                    FullNameGeneratorFactory.getInstance();
4488    
4489                            String fullName = fullNameGenerator.getFullName(
4490                                    firstName, middleName, lastName);
4491    
4492                            String greeting = LanguageUtil.format(
4493                                    locale, "welcome-x", fullName, false);
4494    
4495                            if (Validator.isNotNull(password1)) {
4496                                    user.setPassword(PasswordEncryptorUtil.encrypt(password1));
4497                                    user.setPasswordUnencrypted(password1);
4498                            }
4499    
4500                            user.setPasswordEncrypted(true);
4501    
4502                            PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
4503    
4504                            if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
4505                                    passwordPolicy.isChangeRequired()) {
4506    
4507                                    user.setPasswordReset(true);
4508                            }
4509                            else {
4510                                    user.setPasswordReset(false);
4511                            }
4512    
4513                            user.setScreenName(screenName);
4514                            user.setFacebookId(facebookId);
4515                            user.setOpenId(openId);
4516                            user.setLanguageId(locale.toString());
4517                            user.setTimeZoneId(defaultUser.getTimeZoneId());
4518                            user.setGreeting(greeting);
4519                            user.setFirstName(firstName);
4520                            user.setMiddleName(middleName);
4521                            user.setLastName(lastName);
4522                            user.setJobTitle(jobTitle);
4523                            user.setExpandoBridgeAttributes(serviceContext);
4524    
4525                            Date birthday = getBirthday(
4526                                    birthdayMonth, birthdayDay, birthdayYear);
4527    
4528                            Contact contact = user.getContact();
4529    
4530                            contact.setFirstName(firstName);
4531                            contact.setMiddleName(middleName);
4532                            contact.setLastName(lastName);
4533                            contact.setPrefixId(prefixId);
4534                            contact.setSuffixId(suffixId);
4535                            contact.setMale(male);
4536                            contact.setBirthday(birthday);
4537                            contact.setJobTitle(jobTitle);
4538    
4539                            contactPersistence.update(contact, serviceContext);
4540    
4541                            // Indexer
4542    
4543                            Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4544                                    User.class);
4545    
4546                            indexer.reindex(user);
4547                    }
4548    
4549                    user.setStatus(WorkflowConstants.STATUS_DRAFT);
4550    
4551                    userPersistence.update(user, serviceContext);
4552    
4553                    // Workflow
4554    
4555                    long workflowUserId = creatorUserId;
4556    
4557                    if (workflowUserId == user.getUserId()) {
4558                            workflowUserId = defaultUser.getUserId();
4559                    }
4560    
4561                    ServiceContext workflowServiceContext = serviceContext;
4562    
4563                    if (workflowServiceContext == null) {
4564                            workflowServiceContext = new ServiceContext();
4565                    }
4566    
4567                    workflowServiceContext.setAttribute("autoPassword", autoPassword);
4568                    workflowServiceContext.setAttribute("passwordUnencrypted", password1);
4569                    workflowServiceContext.setAttribute("sendEmail", sendEmail);
4570    
4571                    WorkflowHandlerRegistryUtil.startWorkflowInstance(
4572                            companyId, workflowUserId, User.class.getName(), user.getUserId(),
4573                            user, workflowServiceContext);
4574    
4575                    return getUserByEmailAddress(companyId, emailAddress);
4576            }
4577    
4578            /**
4579             * Updates the user's job title.
4580             *
4581             * @param  userId the primary key of the user
4582             * @param  jobTitle the user's job title
4583             * @return the user
4584             * @throws PortalException if a user with the primary key could not be found
4585             *         or if a contact could not be found matching the user's contact ID
4586             */
4587            @Override
4588            public User updateJobTitle(long userId, String jobTitle)
4589                    throws PortalException {
4590    
4591                    User user = userPersistence.findByPrimaryKey(userId);
4592    
4593                    user.setJobTitle(jobTitle);
4594    
4595                    userPersistence.update(user);
4596    
4597                    Contact contact = contactPersistence.findByPrimaryKey(
4598                            user.getContactId());
4599    
4600                    contact.setJobTitle(jobTitle);
4601    
4602                    contactPersistence.update(contact);
4603    
4604                    return user;
4605            }
4606    
4607            /**
4608             * Updates the user's last login with the current time and the IP address.
4609             *
4610             * @param  userId the primary key of the user
4611             * @param  loginIP the IP address the user logged in from
4612             * @return the user
4613             * @throws PortalException if a user with the primary key could not be found
4614             */
4615            @Override
4616            public User updateLastLogin(long userId, String loginIP)
4617                    throws PortalException {
4618    
4619                    User user = userPersistence.findByPrimaryKey(userId);
4620    
4621                    Date lastLoginDate = user.getLoginDate();
4622    
4623                    if (lastLoginDate == null) {
4624                            lastLoginDate = new Date();
4625                    }
4626    
4627                    String lastLoginIP = user.getLoginIP();
4628    
4629                    if (lastLoginIP == null) {
4630                            lastLoginIP = loginIP;
4631                    }
4632    
4633                    user.setLoginDate(new Date());
4634                    user.setLoginIP(loginIP);
4635                    user.setLastLoginDate(lastLoginDate);
4636                    user.setLastLoginIP(lastLoginIP);
4637    
4638                    resetFailedLoginAttempts(user, true);
4639    
4640                    return user;
4641            }
4642    
4643            /**
4644             * Updates whether the user is locked out from logging in.
4645             *
4646             * @param  user the user
4647             * @param  lockout whether the user is locked out
4648             * @return the user
4649             * @throws PortalException if a portal exception occurred
4650             */
4651            @Override
4652            public User updateLockout(User user, boolean lockout)
4653                    throws PortalException {
4654    
4655                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
4656    
4657                    if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
4658                            return user;
4659                    }
4660    
4661                    Date lockoutDate = null;
4662    
4663                    if (lockout) {
4664                            lockoutDate = new Date();
4665                    }
4666    
4667                    user.setLockout(lockout);
4668                    user.setLockoutDate(lockoutDate);
4669    
4670                    if (!lockout) {
4671                            user.setFailedLoginAttempts(0);
4672                    }
4673    
4674                    userPersistence.update(user);
4675    
4676                    return user;
4677            }
4678    
4679            /**
4680             * Updates whether the user is locked out from logging in.
4681             *
4682             * @param  companyId the primary key of the user's company
4683             * @param  emailAddress the user's email address
4684             * @param  lockout whether the user is locked out
4685             * @return the user
4686             * @throws PortalException if a user with the email address could not be
4687             *         found
4688             */
4689            @Override
4690            public User updateLockoutByEmailAddress(
4691                            long companyId, String emailAddress, boolean lockout)
4692                    throws PortalException {
4693    
4694                    User user = getUserByEmailAddress(companyId, emailAddress);
4695    
4696                    return updateLockout(user, lockout);
4697            }
4698    
4699            /**
4700             * Updates whether the user is locked out from logging in.
4701             *
4702             * @param  userId the primary key of the user
4703             * @param  lockout whether the user is locked out
4704             * @return the user
4705             * @throws PortalException if a user with the primary key could not be found
4706             */
4707            @Override
4708            public User updateLockoutById(long userId, boolean lockout)
4709                    throws PortalException {
4710    
4711                    User user = userPersistence.findByPrimaryKey(userId);
4712    
4713                    return updateLockout(user, lockout);
4714            }
4715    
4716            /**
4717             * Updates whether the user is locked out from logging in.
4718             *
4719             * @param  companyId the primary key of the user's company
4720             * @param  screenName the user's screen name
4721             * @param  lockout whether the user is locked out
4722             * @return the user
4723             * @throws PortalException if a user with the screen name could not be found
4724             */
4725            @Override
4726            public User updateLockoutByScreenName(
4727                            long companyId, String screenName, boolean lockout)
4728                    throws PortalException {
4729    
4730                    User user = getUserByScreenName(companyId, screenName);
4731    
4732                    return updateLockout(user, lockout);
4733            }
4734    
4735            /**
4736             * Updates the user's modified date.
4737             *
4738             * @param  userId the primary key of the user
4739             * @param  modifiedDate the new modified date
4740             * @return the user
4741             * @throws PortalException if a user with the primary key could not be found
4742             */
4743            @Override
4744            public User updateModifiedDate(long userId, Date modifiedDate)
4745                    throws PortalException {
4746    
4747                    User user = userPersistence.findByPrimaryKey(userId);
4748    
4749                    userPersistence.update(user);
4750    
4751                    return user;
4752            }
4753    
4754            /**
4755             * Updates the user's OpenID.
4756             *
4757             * @param  userId the primary key of the user
4758             * @param  openId the new OpenID
4759             * @return the user
4760             * @throws PortalException if a user with the primary key could not be found
4761             */
4762            @Override
4763            public User updateOpenId(long userId, String openId)
4764                    throws PortalException {
4765    
4766                    openId = openId.trim();
4767    
4768                    User user = userPersistence.findByPrimaryKey(userId);
4769    
4770                    user.setOpenId(openId);
4771    
4772                    userPersistence.update(user);
4773    
4774                    return user;
4775            }
4776    
4777            /**
4778             * Sets the organizations that the user is in, removing and adding
4779             * organizations as necessary.
4780             *
4781             * @param  userId the primary key of the user
4782             * @param  newOrganizationIds the primary keys of the organizations
4783             * @param  serviceContext the service context to be applied. Must set
4784             *         whether user indexing is enabled.
4785             * @throws PortalException if a user with the primary key could not be found
4786             */
4787            @Override
4788            public void updateOrganizations(
4789                            long userId, long[] newOrganizationIds,
4790                            ServiceContext serviceContext)
4791                    throws PortalException {
4792    
4793                    updateOrganizations(
4794                            userId, newOrganizationIds, serviceContext.isIndexingEnabled());
4795            }
4796    
4797            /**
4798             * Updates the user's password without tracking or validation of the change.
4799             *
4800             * @param  userId the primary key of the user
4801             * @param  password1 the user's new password
4802             * @param  password2 the user's new password confirmation
4803             * @param  passwordReset whether the user should be asked to reset their
4804             *         password the next time they log in
4805             * @return the user
4806             * @throws PortalException if a user with the primary key could not be found
4807             */
4808            @Override
4809            public User updatePassword(
4810                            long userId, String password1, String password2,
4811                            boolean passwordReset)
4812                    throws PortalException {
4813    
4814                    return updatePassword(
4815                            userId, password1, password2, passwordReset, false);
4816            }
4817    
4818            /**
4819             * Updates the user's password, optionally with tracking and validation of
4820             * the change.
4821             *
4822             * @param  userId the primary key of the user
4823             * @param  password1 the user's new password
4824             * @param  password2 the user's new password confirmation
4825             * @param  passwordReset whether the user should be asked to reset their
4826             *         password the next time they login
4827             * @param  silentUpdate whether the password should be updated without being
4828             *         tracked, or validated. Primarily used for password imports.
4829             * @return the user
4830             * @throws PortalException if a user with the primary key could not be found
4831             */
4832            @Override
4833            public User updatePassword(
4834                            long userId, String password1, String password2,
4835                            boolean passwordReset, boolean silentUpdate)
4836                    throws PortalException {
4837    
4838                    User user = userPersistence.findByPrimaryKey(userId);
4839    
4840                    if (!silentUpdate) {
4841                            validatePassword(user.getCompanyId(), userId, password1, password2);
4842                    }
4843    
4844                    String oldEncPwd = user.getPassword();
4845    
4846                    if (!user.isPasswordEncrypted()) {
4847                            oldEncPwd = PasswordEncryptorUtil.encrypt(user.getPassword());
4848                    }
4849    
4850                    String newEncPwd = PasswordEncryptorUtil.encrypt(password1);
4851    
4852                    if (user.hasCompanyMx()) {
4853                            mailService.updatePassword(user.getCompanyId(), userId, password1);
4854                    }
4855    
4856                    user.setPassword(newEncPwd);
4857                    user.setPasswordUnencrypted(password1);
4858                    user.setPasswordEncrypted(true);
4859                    user.setPasswordReset(passwordReset);
4860    
4861                    if (!silentUpdate || (user.getPasswordModifiedDate() == null)) {
4862                            user.setPasswordModifiedDate(new Date());
4863                    }
4864    
4865                    user.setDigest(StringPool.BLANK);
4866                    user.setGraceLoginCount(0);
4867    
4868                    if (!silentUpdate) {
4869                            user.setPasswordModified(true);
4870                    }
4871    
4872                    try {
4873                            userPersistence.update(user);
4874                    }
4875                    catch (ModelListenerException mle) {
4876                            String msg = GetterUtil.getString(mle.getCause().getMessage());
4877    
4878                            if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
4879                                    String passwordHistory = PrefsPropsUtil.getString(
4880                                            user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
4881    
4882                                    if (msg.contains(passwordHistory)) {
4883                                            throw new UserPasswordException.MustNotBeRecentlyUsed(
4884                                                    userId);
4885                                    }
4886                            }
4887    
4888                            throw new UserPasswordException.MustComplyWithModelListeners(
4889                                    userId, mle);
4890                    }
4891    
4892                    if (!silentUpdate) {
4893                            user.setPasswordModified(false);
4894    
4895                            passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
4896                    }
4897    
4898                    if (!silentUpdate && (PrincipalThreadLocal.getUserId() != userId)) {
4899                            sendPasswordNotification(
4900                                    user, user.getCompanyId(), password1, null, null, null, null,
4901                                    null, ServiceContextThreadLocal.getServiceContext());
4902                    }
4903    
4904                    return user;
4905            }
4906    
4907            /**
4908             * Updates the user's password with manually input information. This method
4909             * should only be used when performing maintenance.
4910             *
4911             * @param  userId the primary key of the user
4912             * @param  password the user's new password
4913             * @param  passwordEncrypted the user's new encrypted password
4914             * @param  passwordReset whether the user should be asked to reset their
4915             *         password the next time they login
4916             * @param  passwordModifiedDate the new password modified date
4917             * @return the user
4918             * @throws PortalException if a user with the primary key could not be found
4919             */
4920            @Override
4921            public User updatePasswordManually(
4922                            long userId, String password, boolean passwordEncrypted,
4923                            boolean passwordReset, Date passwordModifiedDate)
4924                    throws PortalException {
4925    
4926                    // This method should only be used to manually massage data
4927    
4928                    User user = userPersistence.findByPrimaryKey(userId);
4929    
4930                    user.setPassword(password);
4931                    user.setPasswordEncrypted(passwordEncrypted);
4932                    user.setPasswordReset(passwordReset);
4933                    user.setPasswordModifiedDate(passwordModifiedDate);
4934                    user.setDigest(StringPool.BLANK);
4935    
4936                    userPersistence.update(user);
4937    
4938                    return user;
4939            }
4940    
4941            /**
4942             * Updates whether the user should be asked to reset their password the next
4943             * time they login.
4944             *
4945             * @param  userId the primary key of the user
4946             * @param  passwordReset whether the user should be asked to reset their
4947             *         password the next time they login
4948             * @return the user
4949             * @throws PortalException if a user with the primary key could not be found
4950             */
4951            @Override
4952            public User updatePasswordReset(long userId, boolean passwordReset)
4953                    throws PortalException {
4954    
4955                    User user = userPersistence.findByPrimaryKey(userId);
4956    
4957                    user.setPasswordReset(passwordReset);
4958    
4959                    userPersistence.update(user);
4960    
4961                    return user;
4962            }
4963    
4964            /**
4965             * Updates the user's portrait image.
4966             *
4967             * @param  userId the primary key of the user
4968             * @param  bytes the new portrait image data
4969             * @return the user
4970             * @throws PortalException if a user with the primary key could not be found
4971             *         or if the new portrait was invalid
4972             */
4973            @Override
4974            public User updatePortrait(long userId, byte[] bytes)
4975                    throws PortalException {
4976    
4977                    User user = userPersistence.findByPrimaryKey(userId);
4978    
4979                    PortalUtil.updateImageId(
4980                            user, true, bytes, "portraitId",
4981                            PrefsPropsUtil.getLong(PropsKeys.USERS_IMAGE_MAX_SIZE),
4982                            PropsValues.USERS_IMAGE_MAX_HEIGHT,
4983                            PropsValues.USERS_IMAGE_MAX_WIDTH);
4984    
4985                    return userPersistence.update(user);
4986            }
4987    
4988            /**
4989             * Updates the user's password reset question and answer.
4990             *
4991             * @param  userId the primary key of the user
4992             * @param  question the user's new password reset question
4993             * @param  answer the user's new password reset answer
4994             * @return the user
4995             * @throws PortalException if a user with the primary key could not be found
4996             *         or if the new question or answer were invalid
4997             */
4998            @Override
4999            public User updateReminderQuery(long userId, String question, String answer)
5000                    throws PortalException {
5001    
5002                    validateReminderQuery(question, answer);
5003    
5004                    User user = userPersistence.findByPrimaryKey(userId);
5005    
5006                    user.setReminderQueryQuestion(question);
5007                    user.setReminderQueryAnswer(answer);
5008    
5009                    userPersistence.update(user);
5010    
5011                    return user;
5012            }
5013    
5014            /**
5015             * Updates the user's screen name.
5016             *
5017             * @param  userId the primary key of the user
5018             * @param  screenName the user's new screen name
5019             * @return the user
5020             * @throws PortalException if a user with the primary key could not be found
5021             *         or if the new screen name was invalid
5022             */
5023            @Override
5024            public User updateScreenName(long userId, String screenName)
5025                    throws PortalException {
5026    
5027                    // User
5028    
5029                    User user = userPersistence.findByPrimaryKey(userId);
5030    
5031                    screenName = getLogin(screenName);
5032    
5033                    validateScreenName(user.getCompanyId(), userId, screenName);
5034    
5035                    if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
5036                            user.setDigest(StringPool.BLANK);
5037                    }
5038    
5039                    user.setScreenName(screenName);
5040    
5041                    userPersistence.update(user);
5042    
5043                    // Group
5044    
5045                    Group group = groupLocalService.getUserGroup(
5046                            user.getCompanyId(), userId);
5047    
5048                    group.setFriendlyURL(StringPool.SLASH + screenName);
5049    
5050                    groupPersistence.update(group);
5051    
5052                    return user;
5053            }
5054    
5055            /**
5056             * Updates the user's workflow status.
5057             *
5058             * @param      userId the primary key of the user
5059             * @param      status the user's new workflow status
5060             * @return     the user
5061             * @throws     PortalException if a user with the primary key could not be
5062             *             found
5063             * @deprecated As of 7.0.0, replaced by {@link #updateStatus(long, int,
5064             *             ServiceContext)}
5065             */
5066            @Deprecated
5067            @Override
5068            public User updateStatus(long userId, int status) throws PortalException {
5069                    return updateStatus(userId, status, new ServiceContext());
5070            }
5071    
5072            /**
5073             * Updates the user's workflow status.
5074             *
5075             * @param  userId the primary key of the user
5076             * @param  status the user's new workflow status
5077             * @param  serviceContext the service context to be applied. You can specify
5078             *         an unencrypted custom password (used by an LDAP listener) for the
5079             *         user via attribute <code>passwordUnencrypted</code>.
5080             * @return the user
5081             * @throws PortalException if a user with the primary key could not be found
5082             */
5083            @Override
5084            public User updateStatus(
5085                            long userId, int status, ServiceContext serviceContext)
5086                    throws PortalException {
5087    
5088                    User user = userPersistence.findByPrimaryKey(userId);
5089    
5090                    if ((status == WorkflowConstants.STATUS_APPROVED) &&
5091                            (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {
5092    
5093                            validateCompanyMaxUsers(user.getCompanyId());
5094                    }
5095    
5096                    String passwordUnencrypted = (String)serviceContext.getAttribute(
5097                            "passwordUnencrypted");
5098    
5099                    if (Validator.isNotNull(passwordUnencrypted)) {
5100                            user.setPasswordUnencrypted(passwordUnencrypted);
5101                    }
5102    
5103                    user.setStatus(status);
5104    
5105                    userPersistence.update(user);
5106    
5107                    reindex(user);
5108    
5109                    return user;
5110            }
5111    
5112            /**
5113             * Updates the user.
5114             *
5115             * @param  userId the primary key of the user
5116             * @param  oldPassword the user's old password
5117             * @param  newPassword1 the user's new password (optionally
5118             *         <code>null</code>)
5119             * @param  newPassword2 the user's new password confirmation (optionally
5120             *         <code>null</code>)
5121             * @param  passwordReset whether the user should be asked to reset their
5122             *         password the next time they login
5123             * @param  reminderQueryQuestion the user's new password reset question
5124             * @param  reminderQueryAnswer the user's new password reset answer
5125             * @param  screenName the user's new screen name
5126             * @param  emailAddress the user's new email address
5127             * @param  facebookId the user's new Facebook ID
5128             * @param  openId the user's new OpenID
5129             * @param  portrait whether to update the user's portrait image
5130             * @param  portraitBytes the new portrait image data
5131             * @param  languageId the user's new language ID
5132             * @param  timeZoneId the user's new time zone ID
5133             * @param  greeting the user's new greeting
5134             * @param  comments the user's new comments
5135             * @param  firstName the user's new first name
5136             * @param  middleName the user's new middle name
5137             * @param  lastName the user's new last name
5138             * @param  prefixId the user's new name prefix ID
5139             * @param  suffixId the user's new name suffix ID
5140             * @param  male whether user is male
5141             * @param  birthdayMonth the user's new birthday month (0-based, meaning 0
5142             *         for January)
5143             * @param  birthdayDay the user's new birthday day
5144             * @param  birthdayYear the user's birthday year
5145             * @param  smsSn the user's new SMS screen name
5146             * @param  aimSn the user's new AIM screen name
5147             * @param  facebookSn the user's new Facebook screen name
5148             * @param  icqSn the user's new ICQ screen name
5149             * @param  jabberSn the user's new Jabber screen name
5150             * @param  mySpaceSn the user's new MySpace screen name
5151             * @param  skypeSn the user's new Skype screen name
5152             * @param  twitterSn the user's new Twitter screen name
5153             * @param  ymSn the user's new Yahoo! Messenger screen name
5154             * @param  jobTitle the user's new job title
5155             * @param  groupIds the primary keys of the user's groups
5156             * @param  organizationIds the primary keys of the user's organizations
5157             * @param  roleIds the primary keys of the user's roles
5158             * @param  userGroupRoles the user user's group roles
5159             * @param  userGroupIds the primary keys of the user's user groups
5160             * @param  serviceContext the service context to be applied (optionally
5161             *         <code>null</code>). Can set the UUID (with the <code>uuid</code>
5162             *         attribute), asset category IDs, asset tag names, and expando
5163             *         bridge attributes for the user.
5164             * @return the user
5165             * @throws PortalException if a user with the primary key could not be found
5166             *         or if the new information was invalid
5167             */
5168            @Override
5169            @SuppressWarnings("deprecation")
5170            public User updateUser(
5171                            long userId, String oldPassword, String newPassword1,
5172                            String newPassword2, boolean passwordReset,
5173                            String reminderQueryQuestion, String reminderQueryAnswer,
5174                            String screenName, String emailAddress, long facebookId,
5175                            String openId, boolean portrait, byte[] portraitBytes,
5176                            String languageId, String timeZoneId, String greeting,
5177                            String comments, String firstName, String middleName,
5178                            String lastName, long prefixId, long suffixId, boolean male,
5179                            int birthdayMonth, int birthdayDay, int birthdayYear, String smsSn,
5180                            String aimSn, String facebookSn, String icqSn, String jabberSn,
5181                            String mySpaceSn, String skypeSn, String twitterSn, String ymSn,
5182                            String jobTitle, long[] groupIds, long[] organizationIds,
5183                            long[] roleIds, List<UserGroupRole> userGroupRoles,
5184                            long[] userGroupIds, ServiceContext serviceContext)
5185                    throws PortalException {
5186    
5187                    // User
5188    
5189                    User user = userPersistence.findByPrimaryKey(userId);
5190                    Company company = companyPersistence.findByPrimaryKey(
5191                            user.getCompanyId());
5192                    String password = oldPassword;
5193                    screenName = getLogin(screenName);
5194                    emailAddress = StringUtil.toLowerCase(emailAddress.trim());
5195                    openId = openId.trim();
5196                    String oldFullName = user.getFullName();
5197                    aimSn = StringUtil.toLowerCase(aimSn.trim());
5198                    facebookSn = StringUtil.toLowerCase(facebookSn.trim());
5199                    icqSn = StringUtil.toLowerCase(icqSn.trim());
5200                    jabberSn = StringUtil.toLowerCase(jabberSn.trim());
5201                    mySpaceSn = StringUtil.toLowerCase(mySpaceSn.trim());
5202                    skypeSn = StringUtil.toLowerCase(skypeSn.trim());
5203                    twitterSn = StringUtil.toLowerCase(twitterSn.trim());
5204                    ymSn = StringUtil.toLowerCase(ymSn.trim());
5205    
5206                    EmailAddressGenerator emailAddressGenerator =
5207                            EmailAddressGeneratorFactory.getInstance();
5208    
5209                    if (emailAddressGenerator.isGenerated(emailAddress)) {
5210                            emailAddress = StringPool.BLANK;
5211                    }
5212    
5213                    if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
5214                            Validator.isNull(emailAddress)) {
5215    
5216                            emailAddress = emailAddressGenerator.generate(
5217                                    user.getCompanyId(), userId);
5218                    }
5219    
5220                    Locale locale = LocaleUtil.fromLanguageId(languageId);
5221    
5222                    validate(
5223                            userId, screenName, emailAddress, openId, firstName, middleName,
5224                            lastName, smsSn, locale);
5225    
5226                    if (Validator.isNotNull(newPassword1) ||
5227                            Validator.isNotNull(newPassword2)) {
5228    
5229                            user = updatePassword(
5230                                    userId, newPassword1, newPassword2, passwordReset);
5231    
5232                            password = newPassword1;
5233    
5234                            user.setDigest(StringPool.BLANK);
5235                    }
5236    
5237                    if (user.getContactId() <= 0) {
5238                            user.setContactId(counterLocalService.increment());
5239                    }
5240    
5241                    user.setPasswordReset(passwordReset);
5242    
5243                    if (Validator.isNotNull(reminderQueryQuestion) &&
5244                            Validator.isNotNull(reminderQueryAnswer)) {
5245    
5246                            user.setReminderQueryQuestion(reminderQueryQuestion);
5247                            user.setReminderQueryAnswer(reminderQueryAnswer);
5248                    }
5249    
5250                    if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
5251                            user.setScreenName(screenName);
5252    
5253                            user.setDigest(StringPool.BLANK);
5254                    }
5255    
5256                    boolean sendEmailAddressVerification = false;
5257    
5258                    if (company.isStrangersVerify() &&
5259                            !StringUtil.equalsIgnoreCase(
5260                                    emailAddress, user.getEmailAddress())) {
5261    
5262                            sendEmailAddressVerification = true;
5263                    }
5264                    else {
5265                            setEmailAddress(
5266                                    user, password, firstName, middleName, lastName, emailAddress);
5267                    }
5268    
5269                    if (serviceContext != null) {
5270                            String uuid = serviceContext.getUuid();
5271    
5272                            if (Validator.isNotNull(uuid)) {
5273                                    user.setUuid(uuid);
5274                            }
5275                    }
5276    
5277                    user.setFacebookId(facebookId);
5278    
5279                    Long ldapServerId = null;
5280    
5281                    if (serviceContext != null) {
5282                            ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
5283                    }
5284    
5285                    if (ldapServerId != null) {
5286                            user.setLdapServerId(ldapServerId);
5287                    }
5288    
5289                    user.setOpenId(openId);
5290    
5291                    PortalUtil.updateImageId(
5292                            user, portrait, portraitBytes, "portraitId",
5293                            PrefsPropsUtil.getLong(PropsKeys.USERS_IMAGE_MAX_SIZE),
5294                            PropsValues.USERS_IMAGE_MAX_HEIGHT,
5295                            PropsValues.USERS_IMAGE_MAX_WIDTH);
5296    
5297                    user.setLanguageId(languageId);
5298                    user.setTimeZoneId(timeZoneId);
5299                    user.setGreeting(greeting);
5300                    user.setComments(comments);
5301                    user.setFirstName(firstName);
5302                    user.setMiddleName(middleName);
5303                    user.setLastName(lastName);
5304                    user.setJobTitle(jobTitle);
5305                    user.setExpandoBridgeAttributes(serviceContext);
5306    
5307                    userPersistence.update(user, serviceContext);
5308    
5309                    // Contact
5310    
5311                    Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
5312    
5313                    long contactId = user.getContactId();
5314    
5315                    Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
5316    
5317                    if (contact == null) {
5318                            contact = contactPersistence.create(contactId);
5319    
5320                            contact.setCompanyId(user.getCompanyId());
5321                            contact.setUserName(StringPool.BLANK);
5322                            contact.setClassName(User.class.getName());
5323                            contact.setClassPK(user.getUserId());
5324                            contact.setAccountId(company.getAccountId());
5325                            contact.setParentContactId(
5326                                    ContactConstants.DEFAULT_PARENT_CONTACT_ID);
5327                    }
5328    
5329                    contact.setEmailAddress(user.getEmailAddress());
5330                    contact.setFirstName(firstName);
5331                    contact.setMiddleName(middleName);
5332                    contact.setLastName(lastName);
5333                    contact.setPrefixId(prefixId);
5334                    contact.setSuffixId(suffixId);
5335                    contact.setMale(male);
5336                    contact.setBirthday(birthday);
5337                    contact.setSmsSn(smsSn);
5338                    contact.setAimSn(aimSn);
5339                    contact.setFacebookSn(facebookSn);
5340                    contact.setIcqSn(icqSn);
5341                    contact.setJabberSn(jabberSn);
5342                    contact.setMySpaceSn(mySpaceSn);
5343                    contact.setSkypeSn(skypeSn);
5344                    contact.setTwitterSn(twitterSn);
5345                    contact.setYmSn(ymSn);
5346                    contact.setJobTitle(jobTitle);
5347    
5348                    contactPersistence.update(contact, serviceContext);
5349    
5350                    // Group
5351    
5352                    Group group = groupLocalService.getUserGroup(
5353                            user.getCompanyId(), userId);
5354    
5355                    group.setFriendlyURL(StringPool.SLASH + screenName);
5356    
5357                    groupPersistence.update(group);
5358    
5359                    // Groups and organizations
5360    
5361                    // See LPS-33205. Cache the user's list of user group roles because
5362                    // adding or removing groups may add or remove user group roles
5363                    // depending on the site default user associations.
5364    
5365                    List<UserGroupRole> previousUserGroupRoles =
5366                            userGroupRolePersistence.findByUserId(userId);
5367    
5368                    updateGroups(userId, groupIds, serviceContext, false);
5369                    updateOrganizations(userId, organizationIds, false);
5370    
5371                    // Roles
5372    
5373                    if (roleIds != null) {
5374                            roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
5375    
5376                            userPersistence.setRoles(userId, roleIds);
5377                    }
5378    
5379                    // User group roles
5380    
5381                    updateUserGroupRoles(
5382                            user, groupIds, organizationIds, userGroupRoles,
5383                            previousUserGroupRoles);
5384    
5385                    // User groups
5386    
5387                    if (userGroupIds != null) {
5388                            if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
5389                                    userGroupLocalService.copyUserGroupLayouts(
5390                                            userGroupIds, userId);
5391                            }
5392    
5393                            userPersistence.setUserGroups(userId, userGroupIds);
5394                    }
5395    
5396                    // Announcements
5397    
5398                    announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
5399    
5400                    // Asset
5401    
5402                    if (serviceContext != null) {
5403                            updateAsset(
5404                                    userId, user, serviceContext.getAssetCategoryIds(),
5405                                    serviceContext.getAssetTagNames());
5406                    }
5407    
5408                    // Message boards
5409    
5410                    if (GetterUtil.getBoolean(
5411                                    PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
5412                            !oldFullName.equals(user.getFullName())) {
5413    
5414                            mbMessageLocalService.updateUserName(userId, user.getFullName());
5415                    }
5416    
5417                    // Indexer
5418    
5419                    if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
5420                            Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5421                                    User.class);
5422    
5423                            indexer.reindex(user);
5424                    }
5425    
5426                    // Email address verification
5427    
5428                    if ((serviceContext != null) && sendEmailAddressVerification) {
5429                            sendEmailAddressVerification(user, emailAddress, serviceContext);
5430                    }
5431    
5432                    // Permission cache
5433    
5434                    PermissionCacheUtil.clearCache(userId);
5435    
5436                    return user;
5437            }
5438    
5439            /**
5440             * Updates the user.
5441             *
5442             * @param      userId the primary key of the user
5443             * @param      oldPassword the user's old password
5444             * @param      newPassword1 the user's new password (optionally
5445             *             <code>null</code>)
5446             * @param      newPassword2 the user's new password confirmation (optionally
5447             *             <code>null</code>)
5448             * @param      passwordReset whether the user should be asked to reset their
5449             *             password the next time they login
5450             * @param      reminderQueryQuestion the user's new password reset question
5451             * @param      reminderQueryAnswer the user's new password reset answer
5452             * @param      screenName the user's new screen name
5453             * @param      emailAddress the user's new email address
5454             * @param      facebookId the user's new Facebook ID
5455             * @param      openId the user's new OpenID
5456             * @param      languageId the user's new language ID
5457             * @param      timeZoneId the user's new time zone ID
5458             * @param      greeting the user's new greeting
5459             * @param      comments the user's new comments
5460             * @param      firstName the user's new first name
5461             * @param      middleName the user's new middle name
5462             * @param      lastName the user's new last name
5463             * @param      prefixId the user's new name prefix ID
5464             * @param      suffixId the user's new name suffix ID
5465             * @param      male whether user is male
5466             * @param      birthdayMonth the user's new birthday month (0-based, meaning
5467             *             0 for January)
5468             * @param      birthdayDay the user's new birthday day
5469             * @param      birthdayYear the user's birthday year
5470             * @param      smsSn the user's new SMS screen name
5471             * @param      aimSn the user's new AIM screen name
5472             * @param      facebookSn the user's new Facebook screen name
5473             * @param      icqSn the user's new ICQ screen name
5474             * @param      jabberSn the user's new Jabber screen name
5475             * @param      mySpaceSn the user's new MySpace screen name
5476             * @param      skypeSn the user's new Skype screen name
5477             * @param      twitterSn the user's new Twitter screen name
5478             * @param      ymSn the user's new Yahoo! Messenger screen name
5479             * @param      jobTitle the user's new job title
5480             * @param      groupIds the primary keys of the user's groups
5481             * @param      organizationIds the primary keys of the user's organizations
5482             * @param      roleIds the primary keys of the user's roles
5483             * @param      userGroupRoles the user user's group roles
5484             * @param      userGroupIds the primary keys of the user's user groups
5485             * @param      serviceContext the service context to be applied (optionally
5486             *             <code>null</code>). Can set the UUID (with the
5487             *             <code>uuid</code> attribute), asset category IDs, asset tag
5488             *             names, and expando bridge attributes for the user.
5489             * @return     the user
5490             * @throws     PortalException if a user with the primary key could not be
5491             *             found or if the new information was invalid
5492             * @deprecated As of 7.0.0, replaced by {@link #updateUser(long, String,
5493             *             String, String, boolean, String, String, String, String,
5494             *             long, String, boolean, byte[], String, String, String,
5495             *             String, String, String, String, int, int, boolean, int, int,
5496             *             int, String, String, String, String, String, String, String,
5497             *             String, String, String, String, long[], long[], long[], List,
5498             *             long[], ServiceContext)}
5499             */
5500            @Deprecated
5501            @Override
5502            public User updateUser(
5503                            long userId, String oldPassword, String newPassword1,
5504                            String newPassword2, boolean passwordReset,
5505                            String reminderQueryQuestion, String reminderQueryAnswer,
5506                            String screenName, String emailAddress, long facebookId,
5507                            String openId, String languageId, String timeZoneId,
5508                            String greeting, String comments, String firstName,
5509                            String middleName, String lastName, long prefixId, long suffixId,
5510                            boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
5511                            String smsSn, String aimSn, String facebookSn, String icqSn,
5512                            String jabberSn, String mySpaceSn, String skypeSn, String twitterSn,
5513                            String ymSn, String jobTitle, long[] groupIds,
5514                            long[] organizationIds, long[] roleIds,
5515                            List<UserGroupRole> userGroupRoles, long[] userGroupIds,
5516                            ServiceContext serviceContext)
5517                    throws PortalException {
5518    
5519                    return updateUser(
5520                            userId, oldPassword, newPassword1, newPassword2, passwordReset,
5521                            reminderQueryQuestion, reminderQueryAnswer, screenName,
5522                            emailAddress, facebookId, openId, true, null, languageId,
5523                            timeZoneId, greeting, comments, firstName, middleName, lastName,
5524                            prefixId, suffixId, male, birthdayMonth, birthdayDay, birthdayYear,
5525                            smsSn, aimSn, facebookSn, icqSn, jabberSn, mySpaceSn, skypeSn,
5526                            twitterSn, ymSn, jobTitle, groupIds, organizationIds, roleIds,
5527                            userGroupRoles, userGroupIds, serviceContext);
5528            }
5529    
5530            /**
5531             * Verifies the email address of the ticket.
5532             *
5533             * @param  ticketKey the ticket key
5534             * @throws PortalException if a ticket matching the ticket key could not be
5535             *         found, if the ticket has expired, if the ticket is an email
5536             *         address ticket, or if the email address is invalid
5537             */
5538            @Override
5539            public void verifyEmailAddress(String ticketKey) throws PortalException {
5540                    Ticket ticket = ticketLocalService.getTicket(ticketKey);
5541    
5542                    if (ticket.isExpired() ||
5543                            (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
5544    
5545                            throw new NoSuchTicketException("{ticketKey=" + ticketKey + "}");
5546                    }
5547    
5548                    User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
5549    
5550                    String emailAddress = ticket.getExtraInfo();
5551    
5552                    emailAddress = StringUtil.toLowerCase(emailAddress).trim();
5553    
5554                    if (!emailAddress.equals(user.getEmailAddress())) {
5555                            if (userPersistence.fetchByC_EA(
5556                                            user.getCompanyId(), emailAddress) != null) {
5557    
5558                                    throw new UserEmailAddressException.MustNotBeDuplicate(
5559                                            user.getUserId(), emailAddress);
5560                            }
5561    
5562                            setEmailAddress(
5563                                    user, StringPool.BLANK, user.getFirstName(),
5564                                    user.getMiddleName(), user.getLastName(), emailAddress);
5565    
5566                            Contact contact = user.getContact();
5567    
5568                            contact.setEmailAddress(user.getEmailAddress());
5569    
5570                            contactPersistence.update(contact);
5571                    }
5572    
5573                    user.setEmailAddressVerified(true);
5574    
5575                    userPersistence.update(user);
5576    
5577                    ticketLocalService.deleteTicket(ticket);
5578            }
5579    
5580            protected void addDefaultRolesAndTeams(long groupId, long[] userIds)
5581                    throws PortalException {
5582    
5583                    List<Role> defaultSiteRoles = new ArrayList<>();
5584    
5585                    Group group = groupLocalService.getGroup(groupId);
5586    
5587                    UnicodeProperties typeSettingsProperties =
5588                            group.getTypeSettingsProperties();
5589    
5590                    long[] defaultSiteRoleIds = StringUtil.split(
5591                            typeSettingsProperties.getProperty("defaultSiteRoleIds"), 0L);
5592    
5593                    for (long defaultSiteRoleId : defaultSiteRoleIds) {
5594                            Role defaultSiteRole = rolePersistence.fetchByPrimaryKey(
5595                                    defaultSiteRoleId);
5596    
5597                            if (defaultSiteRole == null) {
5598                                    if (_log.isWarnEnabled()) {
5599                                            _log.warn("Unable to find role " + defaultSiteRoleId);
5600                                    }
5601    
5602                                    continue;
5603                            }
5604    
5605                            defaultSiteRoles.add(defaultSiteRole);
5606                    }
5607    
5608                    List<Team> defaultTeams = new ArrayList<>();
5609    
5610                    long[] defaultTeamIds = StringUtil.split(
5611                            typeSettingsProperties.getProperty("defaultTeamIds"), 0L);
5612    
5613                    for (long defaultTeamId : defaultTeamIds) {
5614                            Team defaultTeam = teamPersistence.findByPrimaryKey(defaultTeamId);
5615    
5616                            if (defaultTeam == null) {
5617                                    if (_log.isWarnEnabled()) {
5618                                            _log.warn("Unable to find team " + defaultTeamId);
5619                                    }
5620    
5621                                    continue;
5622                            }
5623    
5624                            defaultTeams.add(defaultTeam);
5625                    }
5626    
5627                    for (long userId : userIds) {
5628                            Set<Long> userRoleIdsSet = new HashSet<>();
5629    
5630                            for (Role role : defaultSiteRoles) {
5631                                    if (!userPersistence.containsRole(userId, role.getRoleId())) {
5632                                            userRoleIdsSet.add(role.getRoleId());
5633                                    }
5634                            }
5635    
5636                            long[] userRoleIds = ArrayUtil.toArray(
5637                                    userRoleIdsSet.toArray(new Long[userRoleIdsSet.size()]));
5638    
5639                            userGroupRoleLocalService.addUserGroupRoles(
5640                                    userId, groupId, userRoleIds);
5641    
5642                            Set<Long> userTeamIdsSet = new HashSet<>();
5643    
5644                            for (Team team : defaultTeams) {
5645                                    if (!userPersistence.containsTeam(userId, team.getTeamId())) {
5646                                            userTeamIdsSet.add(team.getTeamId());
5647                                    }
5648                            }
5649    
5650                            long[] userTeamIds = ArrayUtil.toArray(
5651                                    userTeamIdsSet.toArray(new Long[userTeamIdsSet.size()]));
5652    
5653                            userPersistence.addTeams(userId, userTeamIds);
5654                    }
5655            }
5656    
5657            /**
5658             * Attempts to authenticate the user by their login and password, while
5659             * using the AuthPipeline.
5660             *
5661             * <p>
5662             * Authentication type specifies what <code>login</code> contains.The valid
5663             * values are:
5664             * </p>
5665             *
5666             * <ul>
5667             * <li>
5668             * <code>CompanyConstants.AUTH_TYPE_EA</code> - <code>login</code> is the
5669             * user's email address
5670             * </li>
5671             * <li>
5672             * <code>CompanyConstants.AUTH_TYPE_SN</code> - <code>login</code> is the
5673             * user's screen name
5674             * </li>
5675             * <li>
5676             * <code>CompanyConstants.AUTH_TYPE_ID</code> - <code>login</code> is the
5677             * user's primary key
5678             * </li>
5679             * </ul>
5680             *
5681             * @param  companyId the primary key of the user's company
5682             * @param  login either the user's email address, screen name, or primary
5683             *         key depending on the value of <code>authType</code>
5684             * @param  password the user's password
5685             * @param  authType the type of authentication to perform
5686             * @param  headerMap the header map from the authentication request
5687             * @param  parameterMap the parameter map from the authentication request
5688             * @param  resultsMap the map of authentication results (may be nil). After
5689             *         a successful authentication the user's primary key will be placed
5690             *         under the key <code>userId</code>.
5691             * @return the authentication status. This can be {@link
5692             *         Authenticator#FAILURE} indicating that the user's credentials are
5693             *         invalid, {@link Authenticator#SUCCESS} indicating a successful
5694             *         login, or {@link Authenticator#DNE} indicating that a user with
5695             *         that login does not exist.
5696             * @throws PortalException if <code>login</code> or <code>password</code>
5697             *         was <code>null</code>
5698             * @see    AuthPipeline
5699             */
5700            protected int authenticate(
5701                            long companyId, String login, String password, String authType,
5702                            Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
5703                            Map<String, Object> resultsMap)
5704                    throws PortalException {
5705    
5706                    if (PropsValues.AUTH_LOGIN_DISABLED) {
5707                            return Authenticator.FAILURE;
5708                    }
5709    
5710                    login = StringUtil.toLowerCase(login.trim());
5711    
5712                    long userId = GetterUtil.getLong(login);
5713    
5714                    // User input validation
5715    
5716                    if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5717                            if (Validator.isNull(login)) {
5718                                    throw new UserEmailAddressException.MustNotBeNull();
5719                            }
5720                    }
5721                    else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5722                            if (Validator.isNull(login)) {
5723                                    throw new UserScreenNameException.MustNotBeNull();
5724                            }
5725                    }
5726                    else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5727                            if (Validator.isNull(login)) {
5728                                    throw new UserIdException.MustNotBeNull();
5729                            }
5730                    }
5731    
5732                    if (Validator.isNull(password)) {
5733                            throw new UserPasswordException.MustNotBeNull(userId);
5734                    }
5735    
5736                    int authResult = Authenticator.FAILURE;
5737    
5738                    // Pre-authentication pipeline
5739    
5740                    if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5741                            authResult = AuthPipeline.authenticateByEmailAddress(
5742                                    PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5743                                    headerMap, parameterMap);
5744                    }
5745                    else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5746                            authResult = AuthPipeline.authenticateByScreenName(
5747                                    PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5748                                    headerMap, parameterMap);
5749                    }
5750                    else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5751                            authResult = AuthPipeline.authenticateByUserId(
5752                                    PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
5753                                    headerMap, parameterMap);
5754                    }
5755    
5756                    // Get user
5757    
5758                    User user = null;
5759    
5760                    if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5761                            user = fetchUserByEmailAddress(companyId, login);
5762                    }
5763                    else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5764                            user = fetchUserByScreenName(companyId, login);
5765                    }
5766                    else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5767                            user = userPersistence.fetchByPrimaryKey(GetterUtil.getLong(login));
5768                    }
5769    
5770                    if (user == null) {
5771                            return Authenticator.DNE;
5772                    }
5773    
5774                    if (!isUserAllowedToAuthenticate(user)) {
5775                            return Authenticator.FAILURE;
5776                    }
5777    
5778                    if (!user.isPasswordEncrypted()) {
5779                            user.setPassword(PasswordEncryptorUtil.encrypt(user.getPassword()));
5780                            user.setPasswordEncrypted(true);
5781    
5782                            userPersistence.update(user);
5783                    }
5784    
5785                    // Authenticate against the User_ table
5786    
5787                    boolean skipLiferayCheck = false;
5788    
5789                    if (authResult == Authenticator.SKIP_LIFERAY_CHECK) {
5790                            authResult = Authenticator.SUCCESS;
5791    
5792                            skipLiferayCheck = true;
5793                    }
5794                    else if ((authResult == Authenticator.SUCCESS) &&
5795                                     PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5796    
5797                            boolean authenticated = PwdAuthenticator.authenticate(
5798                                    login, password, user.getPassword());
5799    
5800                            if (authenticated) {
5801                                    authResult = Authenticator.SUCCESS;
5802                            }
5803                            else {
5804                                    authResult = Authenticator.FAILURE;
5805                            }
5806                    }
5807    
5808                    // Post-authentication pipeline
5809    
5810                    if (authResult == Authenticator.SUCCESS) {
5811                            if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5812                                    authResult = AuthPipeline.authenticateByEmailAddress(
5813                                            PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5814                                            headerMap, parameterMap);
5815                            }
5816                            else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5817                                    authResult = AuthPipeline.authenticateByScreenName(
5818                                            PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5819                                            headerMap, parameterMap);
5820                            }
5821                            else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5822                                    authResult = AuthPipeline.authenticateByUserId(
5823                                            PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5824                                            headerMap, parameterMap);
5825                            }
5826                    }
5827    
5828                    if (resultsMap != null) {
5829                            resultsMap.put("userId", user.getUserId());
5830                    }
5831    
5832                    if (authResult == Authenticator.SUCCESS) {
5833    
5834                            // Update digest
5835    
5836                            if (skipLiferayCheck ||
5837                                    !PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK ||
5838                                    Validator.isNull(user.getDigest())) {
5839    
5840                                    user = userPersistence.fetchByPrimaryKey(user.getUserId());
5841    
5842                                    String digest = user.getDigest(password);
5843    
5844                                    user.setDigest(digest);
5845    
5846                                    userPersistence.update(user);
5847                            }
5848                    }
5849    
5850                    // Execute code triggered by authentication failure
5851    
5852                    if (authResult == Authenticator.FAILURE) {
5853                            authResult = handleAuthenticationFailure(
5854                                    login, authType, user, headerMap, parameterMap);
5855                    }
5856                    else {
5857                            resetFailedLoginAttempts(user);
5858                    }
5859    
5860                    // PLACEHOLDER 02
5861    
5862                    return authResult;
5863            }
5864    
5865            protected SearchContext buildSearchContext(
5866                    long companyId, String firstName, String middleName, String lastName,
5867                    String fullName, String screenName, String emailAddress, String street,
5868                    String city, String zip, String region, String country, int status,
5869                    LinkedHashMap<String, Object> params, boolean andSearch, int start,
5870                    int end, Sort[] sorts) {
5871    
5872                    SearchContext searchContext = new SearchContext();
5873    
5874                    searchContext.setAndSearch(andSearch);
5875    
5876                    Map<String, Serializable> attributes = new HashMap<>();
5877    
5878                    attributes.put("city", city);
5879                    attributes.put("country", country);
5880                    attributes.put("emailAddress", emailAddress);
5881                    attributes.put("firstName", firstName);
5882                    attributes.put("fullName", fullName);
5883                    attributes.put("lastName", lastName);
5884                    attributes.put("middleName", middleName);
5885                    attributes.put("params", params);
5886                    attributes.put("region", region);
5887                    attributes.put("screenName", screenName);
5888                    attributes.put("street", street);
5889                    attributes.put("status", status);
5890                    attributes.put("zip", zip);
5891    
5892                    searchContext.setAttributes(attributes);
5893    
5894                    searchContext.setCompanyId(companyId);
5895                    searchContext.setEnd(end);
5896    
5897                    if (params != null) {
5898                            String keywords = (String)params.remove("keywords");
5899    
5900                            if (Validator.isNotNull(keywords)) {
5901                                    searchContext.setKeywords(keywords);
5902                            }
5903                    }
5904    
5905                    if (sorts != null) {
5906                            searchContext.setSorts(sorts);
5907                    }
5908    
5909                    searchContext.setStart(start);
5910    
5911                    QueryConfig queryConfig = searchContext.getQueryConfig();
5912    
5913                    queryConfig.setHighlightEnabled(false);
5914                    queryConfig.setScoreEnabled(false);
5915    
5916                    return searchContext;
5917            }
5918    
5919            protected Date getBirthday(
5920                            int birthdayMonth, int birthdayDay, int birthdayYear)
5921                    throws PortalException {
5922    
5923                    Date birthday = PortalUtil.getDate(
5924                            birthdayMonth, birthdayDay, birthdayYear,
5925                            ContactBirthdayException.class);
5926    
5927                    if (birthday.after(new Date())) {
5928                            throw new ContactBirthdayException();
5929                    }
5930    
5931                    return birthday;
5932            }
5933    
5934            protected String getLogin(String login) {
5935                    return StringUtil.lowerCase(StringUtil.trim(login));
5936            }
5937    
5938            protected Sort[] getSorts(OrderByComparator<User> obc) {
5939                    if (obc == null) {
5940                            return new Sort[0];
5941                    }
5942    
5943                    String[] orderByClauses = StringUtil.split(obc.getOrderBy());
5944                    String[] orderByFields = obc.getOrderByFields();
5945    
5946                    Sort[] sorts = new Sort[orderByFields.length];
5947    
5948                    for (int i = 0; i < orderByFields.length; i++) {
5949                            boolean reverse = orderByClauses[i].contains("DESC");
5950    
5951                            sorts[i] = new Sort(orderByFields[i], reverse);
5952                    }
5953    
5954                    return sorts;
5955            }
5956    
5957            protected int handleAuthenticationFailure(
5958                    String login, String authType, User user,
5959                    Map<String, String[]> headerMap, Map<String, String[]> parameterMap) {
5960    
5961                    if (user == null) {
5962                            return Authenticator.DNE;
5963                    }
5964    
5965                    try {
5966                            if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5967                                    AuthPipeline.onFailureByEmailAddress(
5968                                            PropsKeys.AUTH_FAILURE, user.getCompanyId(), login,
5969                                            headerMap, parameterMap);
5970                            }
5971                            else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5972                                    AuthPipeline.onFailureByScreenName(
5973                                            PropsKeys.AUTH_FAILURE, user.getCompanyId(), login,
5974                                            headerMap, parameterMap);
5975                            }
5976                            else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5977                                    AuthPipeline.onFailureByUserId(
5978                                            PropsKeys.AUTH_FAILURE, user.getCompanyId(),
5979                                            user.getUserId(), headerMap, parameterMap);
5980                            }
5981    
5982                            user = userPersistence.fetchByPrimaryKey(user.getUserId());
5983    
5984                            if (user == null) {
5985                                    return Authenticator.DNE;
5986                            }
5987    
5988                            // Let LDAP handle max failure event
5989    
5990                            if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5991                                            user.getCompanyId())) {
5992    
5993                                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5994    
5995                                    user = userPersistence.fetchByPrimaryKey(user.getUserId());
5996    
5997                                    int failedLoginAttempts = user.getFailedLoginAttempts();
5998                                    int maxFailures = passwordPolicy.getMaxFailure();
5999    
6000                                    if ((failedLoginAttempts >= maxFailures) &&
6001                                            (maxFailures != 0)) {
6002    
6003                                            if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
6004                                                    AuthPipeline.onMaxFailuresByEmailAddress(
6005                                                            PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
6006                                                            login, headerMap, parameterMap);
6007                                            }
6008                                            else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
6009                                                    AuthPipeline.onMaxFailuresByScreenName(
6010                                                            PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
6011                                                            login, headerMap, parameterMap);
6012                                            }
6013                                            else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
6014                                                    AuthPipeline.onMaxFailuresByUserId(
6015                                                            PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
6016                                                            user.getUserId(), headerMap, parameterMap);
6017                                            }
6018                                    }
6019                            }
6020                    }
6021                    catch (Exception e) {
6022                            _log.error(e, e);
6023                    }
6024    
6025                    return Authenticator.FAILURE;
6026            }
6027    
6028            protected boolean isUseCustomSQL(LinkedHashMap<String, Object> params) {
6029                    if (MapUtil.isEmpty(params)) {
6030                            return false;
6031                    }
6032    
6033                    for (String key : params.keySet()) {
6034                            if (!key.equals("inherit") && !key.equals("usersGroups") &&
6035                                    !key.equals("usersOrgs") && !key.equals("usersOrgsCount") &&
6036                                    !key.equals("usersRoles") && !key.equals("usersTeams") &&
6037                                    !key.equals("usersUserGroups")) {
6038    
6039                                    return true;
6040                            }
6041                    }
6042    
6043                    Boolean inherit = (Boolean)params.get("inherit");
6044    
6045                    if ((inherit != null) && inherit) {
6046                            return true;
6047                    }
6048    
6049                    return false;
6050            }
6051    
6052            protected boolean isUserAllowedToAuthenticate(User user)
6053                    throws PortalException {
6054    
6055                    if (user.isDefaultUser()) {
6056                            if (_log.isInfoEnabled()) {
6057                                    _log.info("Authentication is disabled for the default user");
6058                            }
6059    
6060                            return false;
6061                    }
6062                    else if (!user.isActive()) {
6063                            if (_log.isInfoEnabled()) {
6064                                    _log.info(
6065                                            "Authentication is disabled for inactive user " +
6066                                                    user.getUserId());
6067                            }
6068    
6069                            return false;
6070                    }
6071    
6072                    // Check password policy to see if the is account locked out or if the
6073                    // password is expired
6074    
6075                    checkLockout(user);
6076    
6077                    checkPasswordExpired(user);
6078    
6079                    return true;
6080            }
6081    
6082            protected void notifyUser(
6083                    User user, String password, ServiceContext serviceContext) {
6084    
6085                    if (!PrefsPropsUtil.getBoolean(
6086                                    user.getCompanyId(),
6087                                    PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
6088    
6089                            return;
6090                    }
6091    
6092                    String fromName = PrefsPropsUtil.getString(
6093                            user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
6094                    String fromAddress = PrefsPropsUtil.getString(
6095                            user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
6096    
6097                    String toName = user.getFullName();
6098                    String toAddress = user.getEmailAddress();
6099    
6100                    PortletPreferences companyPortletPreferences =
6101                            PrefsPropsUtil.getPreferences(user.getCompanyId(), true);
6102    
6103                    Map<Locale, String> localizedSubjectMap =
6104                            LocalizationUtil.getLocalizationMap(
6105                                    companyPortletPreferences, "adminEmailUserAddedSubject",
6106                                    PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
6107    
6108                    Map<Locale, String> localizedBodyMap = null;
6109    
6110                    if (Validator.isNotNull(password)) {
6111                            localizedBodyMap = LocalizationUtil.getLocalizationMap(
6112                                    companyPortletPreferences, "adminEmailUserAddedBody",
6113                                    PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
6114                    }
6115                    else {
6116                            localizedBodyMap = LocalizationUtil.getLocalizationMap(
6117                                    companyPortletPreferences, "adminEmailUserAddedNoPasswordBody",
6118                                    PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
6119                    }
6120    
6121                    SubscriptionSender subscriptionSender = new SubscriptionSender();
6122    
6123                    subscriptionSender.setCompanyId(user.getCompanyId());
6124                    subscriptionSender.setContextAttributes(
6125                            "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
6126                            "[$USER_SCREENNAME$]", user.getScreenName());
6127                    subscriptionSender.setFrom(fromAddress, fromName);
6128                    subscriptionSender.setHtmlFormat(true);
6129                    subscriptionSender.setLocalizedBodyMap(localizedBodyMap);
6130                    subscriptionSender.setLocalizedSubjectMap(localizedSubjectMap);
6131                    subscriptionSender.setMailId("user", user.getUserId());
6132                    subscriptionSender.setServiceContext(serviceContext);
6133    
6134                    subscriptionSender.addRuntimeSubscribers(toAddress, toName);
6135    
6136                    subscriptionSender.flushNotificationsAsync();
6137            }
6138    
6139            protected void reindex(long userId) throws SearchException {
6140                    Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6141                            User.class);
6142    
6143                    User user = userLocalService.fetchUser(userId);
6144    
6145                    indexer.reindex(user);
6146            }
6147    
6148            protected void reindex(long[] userIds) throws SearchException {
6149                    Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6150                            User.class);
6151    
6152                    List<User> users = new ArrayList<>(userIds.length);
6153    
6154                    for (Long userId : userIds) {
6155                            User user = userLocalService.fetchUser(userId);
6156    
6157                            users.add(user);
6158                    }
6159    
6160                    indexer.reindex(users);
6161            }
6162    
6163            protected void reindex(final User user) throws SearchException {
6164                    Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6165                            User.class);
6166    
6167                    indexer.reindex(user);
6168            }
6169    
6170            protected void resetFailedLoginAttempts(User user) {
6171                    resetFailedLoginAttempts(user, false);
6172            }
6173    
6174            protected void resetFailedLoginAttempts(User user, boolean forceUpdate) {
6175                    if (forceUpdate || (user.getFailedLoginAttempts() > 0)) {
6176                            user.setFailedLoginAttempts(0);
6177    
6178                            userPersistence.update(user);
6179                    }
6180            }
6181    
6182            protected BaseModelSearchResult<User> searchUsers(
6183                            SearchContext searchContext)
6184                    throws PortalException {
6185    
6186                    Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6187                            User.class);
6188    
6189                    for (int i = 0; i < 10; i++) {
6190                            Hits hits = indexer.search(searchContext);
6191    
6192                            List<User> users = UsersAdminUtil.getUsers(hits);
6193    
6194                            if (users != null) {
6195                                    return new BaseModelSearchResult<>(users, hits.getLength());
6196                            }
6197                    }
6198    
6199                    throw new SearchException(
6200                            "Unable to fix the search index after 10 attempts");
6201            }
6202    
6203            protected void sendPasswordNotification(
6204                    User user, long companyId, String newPassword, String passwordResetURL,
6205                    String fromName, String fromAddress, String subject, String body,
6206                    ServiceContext serviceContext) {
6207    
6208                    if (Validator.isNull(fromName)) {
6209                            fromName = PrefsPropsUtil.getString(
6210                                    companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
6211                    }
6212    
6213                    if (Validator.isNull(fromAddress)) {
6214                            fromAddress = PrefsPropsUtil.getString(
6215                                    companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
6216                    }
6217    
6218                    String toName = user.getFullName();
6219                    String toAddress = user.getEmailAddress();
6220    
6221                    PortletPreferences companyPortletPreferences =
6222                            PrefsPropsUtil.getPreferences(companyId, true);
6223    
6224                    Map<Locale, String> localizedSubjectMap = null;
6225                    Map<Locale, String> localizedBodyMap = null;
6226    
6227                    String bodyProperty = null;
6228                    String prefix = null;
6229                    String subjectProperty = null;
6230    
6231                    if (Validator.isNotNull(passwordResetURL)) {
6232                            bodyProperty = PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY;
6233                            prefix = "adminEmailPasswordReset";
6234                            subjectProperty = PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT;
6235                    }
6236                    else {
6237                            bodyProperty = PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY;
6238                            prefix = "adminEmailPasswordSent";
6239                            subjectProperty = PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT;
6240                    }
6241    
6242                    if (Validator.isNull(body)) {
6243                            localizedBodyMap = LocalizationUtil.getLocalizationMap(
6244                                    companyPortletPreferences, prefix + "Body", bodyProperty);
6245                    }
6246    
6247                    if (Validator.isNull(subject)) {
6248                            localizedSubjectMap = LocalizationUtil.getLocalizationMap(
6249                                    companyPortletPreferences, prefix + "Subject", subjectProperty);
6250                    }
6251    
6252                    SubscriptionSender subscriptionSender = new SubscriptionSender();
6253    
6254                    subscriptionSender.setCompanyId(companyId);
6255                    subscriptionSender.setContextAttributes(
6256                            "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
6257                            serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
6258                            serviceContext.getRemoteHost(), "[$USER_ID$]", user.getUserId(),
6259                            "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
6260                            user.getScreenName());
6261                    subscriptionSender.setFrom(fromAddress, fromName);
6262                    subscriptionSender.setHtmlFormat(true);
6263                    subscriptionSender.setLocalizedBodyMap(localizedBodyMap);
6264                    subscriptionSender.setLocalizedSubjectMap(localizedSubjectMap);
6265                    subscriptionSender.setMailId("user", user.getUserId());
6266                    subscriptionSender.setServiceContext(serviceContext);
6267    
6268                    subscriptionSender.addRuntimeSubscribers(toAddress, toName);
6269    
6270                    subscriptionSender.flushNotificationsAsync();
6271            }
6272    
6273            protected void setEmailAddress(
6274                            User user, String password, String firstName, String middleName,
6275                            String lastName, String emailAddress)
6276                    throws PortalException {
6277    
6278                    if (StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
6279                            return;
6280                    }
6281    
6282                    long userId = user.getUserId();
6283    
6284                    // test@test.com -> test@liferay.com
6285    
6286                    if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
6287                            Validator.isNotNull(password)) {
6288    
6289                            mailService.addUser(
6290                                    user.getCompanyId(), userId, password, firstName, middleName,
6291                                    lastName, emailAddress);
6292                    }
6293    
6294                    // test@liferay.com -> bob@liferay.com
6295    
6296                    else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
6297                            mailService.updateEmailAddress(
6298                                    user.getCompanyId(), userId, emailAddress);
6299                    }
6300    
6301                    // test@liferay.com -> test@test.com
6302    
6303                    else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
6304                            mailService.deleteEmailAddress(user.getCompanyId(), userId);
6305                    }
6306    
6307                    user.setEmailAddress(emailAddress);
6308                    user.setDigest(StringPool.BLANK);
6309            }
6310    
6311            protected void updateGroups(
6312                            long userId, long[] newGroupIds, ServiceContext serviceContext,
6313                            boolean indexingEnabled)
6314                    throws PortalException {
6315    
6316                    if (newGroupIds == null) {
6317                            return;
6318                    }
6319    
6320                    long[] oldGroupIds = getGroupPrimaryKeys(userId);
6321    
6322                    for (long oldGroupId : oldGroupIds) {
6323                            if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
6324                                    unsetGroupUsers(
6325                                            oldGroupId, new long[] {userId}, serviceContext);
6326                            }
6327                    }
6328    
6329                    for (long newGroupId : newGroupIds) {
6330                            if (!ArrayUtil.contains(oldGroupIds, newGroupId)) {
6331                                    addGroupUsers(newGroupId, new long[] {userId});
6332                            }
6333                    }
6334    
6335                    if (indexingEnabled) {
6336                            reindex(userId);
6337                    }
6338    
6339                    PermissionCacheUtil.clearCache(userId);
6340            }
6341    
6342            protected void updateOrganizations(
6343                            long userId, long[] newOrganizationIds, boolean indexingEnabled)
6344                    throws PortalException {
6345    
6346                    if (newOrganizationIds == null) {
6347                            return;
6348                    }
6349    
6350                    long[] oldOrganizationIds = getOrganizationPrimaryKeys(userId);
6351    
6352                    for (long oldOrganizationId : oldOrganizationIds) {
6353                            if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
6354                                    unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
6355                            }
6356                    }
6357    
6358                    for (long newOrganizationId : newOrganizationIds) {
6359                            if (!ArrayUtil.contains(oldOrganizationIds, newOrganizationId)) {
6360                                    addOrganizationUsers(newOrganizationId, new long[] {userId});
6361                            }
6362                    }
6363    
6364                    if (indexingEnabled) {
6365                            reindex(userId);
6366                    }
6367    
6368                    PermissionCacheUtil.clearCache(userId);
6369            }
6370    
6371            protected void updateUserGroupRoles(
6372                            User user, long[] groupIds, long[] organizationIds,
6373                            List<UserGroupRole> userGroupRoles,
6374                            List<UserGroupRole> previousUserGroupRoles)
6375                    throws PortalException {
6376    
6377                    if (userGroupRoles == null) {
6378                            return;
6379                    }
6380    
6381                    userGroupRoles = new ArrayList<>(userGroupRoles);
6382    
6383                    for (UserGroupRole userGroupRole : previousUserGroupRoles) {
6384                            if (userGroupRoles.contains(userGroupRole)) {
6385                                    userGroupRoles.remove(userGroupRole);
6386                            }
6387                            else {
6388                                    userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
6389                            }
6390                    }
6391    
6392                    if (ListUtil.isEmpty(userGroupRoles)) {
6393                            return;
6394                    }
6395    
6396                    long[] validGroupIds = null;
6397    
6398                    if (groupIds != null) {
6399                            validGroupIds = ArrayUtil.clone(groupIds);
6400                    }
6401                    else {
6402                            validGroupIds = user.getGroupIds();
6403                    }
6404    
6405                    if (organizationIds == null) {
6406                            organizationIds = user.getOrganizationIds();
6407                    }
6408    
6409                    for (long organizationId : organizationIds) {
6410                            Organization organization =
6411                                    organizationPersistence.findByPrimaryKey(organizationId);
6412    
6413                            validGroupIds = ArrayUtil.append(
6414                                    validGroupIds, organization.getGroupId());
6415                    }
6416    
6417                    Arrays.sort(validGroupIds);
6418    
6419                    for (UserGroupRole userGroupRole : userGroupRoles) {
6420                            if (Arrays.binarySearch(
6421                                            validGroupIds, userGroupRole.getGroupId()) >= 0) {
6422    
6423                                    userGroupRoleLocalService.addUserGroupRole(userGroupRole);
6424                            }
6425                    }
6426            }
6427    
6428            protected void validate(
6429                            long companyId, long userId, boolean autoPassword, String password1,
6430                            String password2, boolean autoScreenName, String screenName,
6431                            String emailAddress, String openId, String firstName,
6432                            String middleName, String lastName, long[] organizationIds,
6433                            Locale locale)
6434                    throws PortalException {
6435    
6436                    validateCompanyMaxUsers(companyId);
6437    
6438                    if (!autoScreenName) {
6439                            validateScreenName(companyId, userId, screenName);
6440                    }
6441    
6442                    if (!autoPassword) {
6443                            PasswordPolicy passwordPolicy =
6444                                    passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
6445    
6446                            PwdToolkitUtil.validate(
6447                                    companyId, 0, password1, password2, passwordPolicy);
6448                    }
6449    
6450                    validateEmailAddress(companyId, emailAddress);
6451    
6452                    if (Validator.isNotNull(emailAddress)) {
6453                            User user = userPersistence.fetchByC_EA(companyId, emailAddress);
6454    
6455                            if ((user != null) && (user.getUserId() != userId)) {
6456                                    throw new UserEmailAddressException.MustNotBeDuplicate(
6457                                            userId, emailAddress);
6458                            }
6459                    }
6460    
6461                    validateOpenId(companyId, userId, openId);
6462    
6463                    validateFullName(companyId, firstName, middleName, lastName, locale);
6464    
6465                    if (organizationIds != null) {
6466                            for (long organizationId : organizationIds) {
6467                                    Organization organization =
6468                                            organizationPersistence.fetchByPrimaryKey(organizationId);
6469    
6470                                    if (organization == null) {
6471                                            throw new NoSuchOrganizationException(
6472                                                    "{organizationId=" + organizationId + "}");
6473                                    }
6474                            }
6475                    }
6476            }
6477    
6478            protected void validate(
6479                            long userId, String screenName, String emailAddress, String openId,
6480                            String firstName, String middleName, String lastName, String smsSn,
6481                            Locale locale)
6482                    throws PortalException {
6483    
6484                    User user = userPersistence.findByPrimaryKey(userId);
6485    
6486                    if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
6487                            validateScreenName(user.getCompanyId(), userId, screenName);
6488                    }
6489    
6490                    validateEmailAddress(user.getCompanyId(), emailAddress);
6491    
6492                    validateOpenId(user.getCompanyId(), userId, openId);
6493    
6494                    if (!user.isDefaultUser()) {
6495                            if (Validator.isNotNull(emailAddress) &&
6496                                    !StringUtil.equalsIgnoreCase(
6497                                            user.getEmailAddress(), emailAddress)) {
6498    
6499                                    if (userPersistence.fetchByC_EA(
6500                                                    user.getCompanyId(), emailAddress) != null) {
6501    
6502                                            throw new UserEmailAddressException.MustNotBeDuplicate(
6503                                                    userId, emailAddress);
6504                                    }
6505                            }
6506    
6507                            validateFullName(
6508                                    user.getCompanyId(), firstName, middleName, lastName, locale);
6509                    }
6510    
6511                    if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
6512                            throw new UserSmsException.MustBeEmailAddress(smsSn);
6513                    }
6514            }
6515    
6516            protected void validateCompanyMaxUsers(long companyId)
6517                    throws PortalException {
6518    
6519                    Company company = companyPersistence.findByPrimaryKey(companyId);
6520    
6521                    if (company.isSystem() || (company.getMaxUsers() == 0)) {
6522                            return;
6523                    }
6524    
6525                    int userCount = searchCount(
6526                            companyId, null, WorkflowConstants.STATUS_APPROVED, null);
6527    
6528                    if (userCount >= company.getMaxUsers()) {
6529                            throw new CompanyMaxUsersException();
6530                    }
6531            }
6532    
6533            protected void validateEmailAddress(long companyId, String emailAddress)
6534                    throws PortalException {
6535    
6536                    if (Validator.isNull(emailAddress) &&
6537                            !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
6538    
6539                            return;
6540                    }
6541    
6542                    EmailAddressValidator emailAddressValidator =
6543                            EmailAddressValidatorFactory.getInstance();
6544    
6545                    if (!emailAddressValidator.validate(companyId, emailAddress)) {
6546                            throw new UserEmailAddressException.MustValidate(
6547                                    emailAddress, emailAddressValidator);
6548                    }
6549    
6550                    String pop3User = PrefsPropsUtil.getString(
6551                            PropsKeys.MAIL_SESSION_MAIL_POP3_USER,
6552                            PropsValues.MAIL_SESSION_MAIL_POP3_USER);
6553    
6554                    if (StringUtil.equalsIgnoreCase(emailAddress, pop3User)) {
6555                            throw new UserEmailAddressException.MustNotBePOP3User(emailAddress);
6556                    }
6557    
6558                    String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
6559                            companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
6560                            StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
6561    
6562                    for (String reservedEmailAddress : reservedEmailAddresses) {
6563                            if (StringUtil.equalsIgnoreCase(
6564                                            emailAddress, reservedEmailAddress)) {
6565    
6566                                    throw new UserEmailAddressException.MustNotBeReserved(
6567                                            emailAddress, reservedEmailAddresses);
6568                            }
6569                    }
6570            }
6571    
6572            protected void validateEmailAddress(
6573                            User user, String emailAddress1, String emailAddress2)
6574                    throws PortalException {
6575    
6576                    if (!emailAddress1.equals(emailAddress2)) {
6577                            throw new UserEmailAddressException.MustBeEqual(
6578                                    user, emailAddress1, emailAddress2);
6579                    }
6580    
6581                    validateEmailAddress(user.getCompanyId(), emailAddress1);
6582                    validateEmailAddress(user.getCompanyId(), emailAddress2);
6583    
6584                    if (!StringUtil.equalsIgnoreCase(
6585                                    emailAddress1, user.getEmailAddress())) {
6586    
6587                            if (userPersistence.fetchByC_EA(
6588                                            user.getCompanyId(), emailAddress1) != null) {
6589    
6590                                    throw new UserEmailAddressException.MustNotBeDuplicate(
6591                                            user.getUserId(), emailAddress1);
6592                            }
6593                    }
6594            }
6595    
6596            protected void validateFullName(
6597                            long companyId, String firstName, String middleName,
6598                            String lastName, Locale locale)
6599                    throws PortalException {
6600    
6601                    FullNameDefinition fullNameDefinition =
6602                            FullNameDefinitionFactory.getInstance(locale);
6603    
6604                    if (Validator.isNull(firstName)) {
6605                            throw new ContactNameException.MustHaveFirstName();
6606                    }
6607                    else if (Validator.isNull(middleName) &&
6608                                     fullNameDefinition.isFieldRequired("middle-name")) {
6609    
6610                            throw new ContactNameException.MustHaveMiddleName();
6611                    }
6612                    else if (Validator.isNull(lastName) &&
6613                                     fullNameDefinition.isFieldRequired("last-name")) {
6614    
6615                            throw new ContactNameException.MustHaveLastName();
6616                    }
6617    
6618                    FullNameValidator fullNameValidator =
6619                            FullNameValidatorFactory.getInstance();
6620    
6621                    if (!fullNameValidator.validate(
6622                                    companyId, firstName, middleName, lastName)) {
6623    
6624                            throw new ContactNameException.MustHaveValidFullName(
6625                                    fullNameValidator);
6626                    }
6627            }
6628    
6629            protected void validateOpenId(long companyId, long userId, String openId)
6630                    throws PortalException {
6631    
6632                    if (Validator.isNull(openId)) {
6633                            return;
6634                    }
6635    
6636                    User user = userPersistence.fetchByC_O(companyId, openId);
6637    
6638                    if ((user != null) && (user.getUserId() != userId)) {
6639                            throw new DuplicateOpenIdException("{userId=" + userId + "}");
6640                    }
6641            }
6642    
6643            protected void validatePassword(
6644                            long companyId, long userId, String password1, String password2)
6645                    throws PortalException {
6646    
6647                    if (Validator.isNull(password1) || Validator.isNull(password2)) {
6648                            throw new UserPasswordException.MustNotBeNull(userId);
6649                    }
6650    
6651                    if (!password1.equals(password2)) {
6652                            throw new UserPasswordException.MustMatch(userId);
6653                    }
6654    
6655                    PasswordPolicy passwordPolicy =
6656                            passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
6657    
6658                    PwdToolkitUtil.validate(
6659                            companyId, userId, password1, password2, passwordPolicy);
6660            }
6661    
6662            protected void validateReminderQuery(String question, String answer)
6663                    throws PortalException {
6664    
6665                    if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
6666                            return;
6667                    }
6668    
6669                    if (Validator.isNull(question)) {
6670                            throw new UserReminderQueryException("Question is null");
6671                    }
6672    
6673                    if (Validator.isNull(answer)) {
6674                            throw new UserReminderQueryException("Answer is null");
6675                    }
6676            }
6677    
6678            protected void validateScreenName(
6679                            long companyId, long userId, String screenName)
6680                    throws PortalException {
6681    
6682                    if (Validator.isNull(screenName)) {
6683                            throw new UserScreenNameException.MustNotBeNull(userId);
6684                    }
6685    
6686                    ScreenNameValidator screenNameValidator =
6687                            ScreenNameValidatorFactory.getInstance();
6688    
6689                    if (!screenNameValidator.validate(companyId, screenName)) {
6690                            throw new UserScreenNameException.MustValidate(
6691                                    userId, screenName, screenNameValidator);
6692                    }
6693    
6694                    if (Validator.isNumber(screenName)) {
6695                            if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
6696                                    throw new UserScreenNameException.MustNotBeNumeric(
6697                                            userId, screenName);
6698                            }
6699    
6700                            if (!screenName.equals(String.valueOf(userId))) {
6701                                    Group group = groupPersistence.fetchByPrimaryKey(
6702                                            GetterUtil.getLong(screenName));
6703    
6704                                    if (group != null) {
6705                                            throw new UserScreenNameException.MustNotBeUsedByGroup(
6706                                                    userId, screenName, group);
6707                                    }
6708                            }
6709                    }
6710    
6711                    String[] anonymousNames = BaseServiceImpl.ANONYMOUS_NAMES;
6712    
6713                    for (String anonymousName : anonymousNames) {
6714                            if (StringUtil.equalsIgnoreCase(screenName, anonymousName)) {
6715                                    throw new UserScreenNameException.MustNotBeReservedForAnonymous(
6716                                            userId, screenName, anonymousNames);
6717                            }
6718                    }
6719    
6720                    User user = userPersistence.fetchByC_SN(companyId, screenName);
6721    
6722                    if ((user != null) && (user.getUserId() != userId)) {
6723                            throw new UserScreenNameException.MustNotBeDuplicate(
6724                                    user.getUserId(), screenName);
6725                    }
6726    
6727                    String friendlyURL = StringPool.SLASH + screenName;
6728    
6729                    Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
6730    
6731                    if ((group != null) && (group.getClassPK() != userId)) {
6732                            GroupFriendlyURLException gfurle = new GroupFriendlyURLException(
6733                                    GroupFriendlyURLException.DUPLICATE);
6734    
6735                            gfurle.setDuplicateClassPK(group.getGroupId());
6736                            gfurle.setDuplicateClassName(Group.class.getName());
6737    
6738                            throw gfurle;
6739                    }
6740    
6741                    int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
6742    
6743                    if (exceptionType != -1) {
6744                            throw new UserScreenNameException.MustProduceValidFriendlyURL(
6745                                    userId, screenName, exceptionType);
6746                    }
6747    
6748                    String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
6749                            companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
6750                            StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
6751    
6752                    for (String reservedScreenName : reservedScreenNames) {
6753                            if (StringUtil.equalsIgnoreCase(screenName, reservedScreenName)) {
6754                                    throw new UserScreenNameException.MustNotBeReserved(
6755                                            userId, screenName, reservedScreenNames);
6756                            }
6757                    }
6758            }
6759    
6760            private static final Log _log = LogFactoryUtil.getLog(
6761                    UserLocalServiceImpl.class);
6762    
6763            private final Map<Long, User> _defaultUsers = new ConcurrentHashMap<>();
6764    
6765    }