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