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 n 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             */
2040            @Override
2041            public User fetchUserByContactId(long contactId) throws SystemException {
2042                    return userPersistence.fetchByContactId(contactId);
2043            }
2044    
2045            /**
2046             * Returns the user with the email address.
2047             *
2048             * @param  companyId the primary key of the user's company
2049             * @param  emailAddress the user's email address
2050             * @return the user with the email address, or <code>null</code> if a user
2051             *         with the email address could not be found
2052             * @throws SystemException if a system exception occurred
2053             */
2054            @Override
2055            public User fetchUserByEmailAddress(long companyId, String emailAddress)
2056                    throws SystemException {
2057    
2058                    emailAddress = getLogin(emailAddress);
2059    
2060                    return userPersistence.fetchByC_EA(companyId, emailAddress);
2061            }
2062    
2063            /**
2064             * Returns the user with the Facebook ID.
2065             *
2066             * @param  companyId the primary key of the user's company
2067             * @param  facebookId the user's Facebook ID
2068             * @return the user with the Facebook ID, or <code>null</code> if a user
2069             *         with the Facebook ID could not be found
2070             * @throws SystemException if a system exception occurred
2071             */
2072            @Override
2073            public User fetchUserByFacebookId(long companyId, long facebookId)
2074                    throws SystemException {
2075    
2076                    return userPersistence.fetchByC_FID(companyId, facebookId);
2077            }
2078    
2079            /**
2080             * Returns the user with the primary key.
2081             *
2082             * @param  userId the primary key of the user
2083             * @return the user with the primary key, or <code>null</code> if a user
2084             *         with the primary key could not be found
2085             * @throws SystemException if a system exception occurred
2086             */
2087            @Override
2088            public User fetchUserById(long userId) throws SystemException {
2089                    return userPersistence.fetchByPrimaryKey(userId);
2090            }
2091    
2092            /**
2093             * Returns the user with the OpenID.
2094             *
2095             * @param  companyId the primary key of the user's company
2096             * @param  openId the user's OpenID
2097             * @return the user with the OpenID, or <code>null</code> if a user with the
2098             *         OpenID could not be found
2099             * @throws SystemException if a system exception occurred
2100             */
2101            @Override
2102            public User fetchUserByOpenId(long companyId, String openId)
2103                    throws SystemException {
2104    
2105                    return userPersistence.fetchByC_O(companyId, openId);
2106            }
2107    
2108            /**
2109             * Returns the user with the screen name.
2110             *
2111             * @param  companyId the primary key of the user's company
2112             * @param  screenName the user's screen name
2113             * @return the user with the screen name, or <code>null</code> if a user
2114             *         with the screen name could not be found
2115             * @throws SystemException if a system exception occurred
2116             */
2117            @Override
2118            public User fetchUserByScreenName(long companyId, String screenName)
2119                    throws SystemException {
2120    
2121                    screenName = getLogin(screenName);
2122    
2123                    return userPersistence.fetchByC_SN(companyId, screenName);
2124            }
2125    
2126            /**
2127             * Returns a range of all the users belonging to the company.
2128             *
2129             * <p>
2130             * Useful when paginating results. Returns a maximum of <code>end -
2131             * start</code> instances. <code>start</code> and <code>end</code> are not
2132             * primary keys, they are indexes in the result set. Thus, <code>0</code>
2133             * refers to the first result in the set. Setting both <code>start</code>
2134             * and <code>end</code> to {@link
2135             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
2136             * result set.
2137             * </p>
2138             *
2139             * @param  companyId the primary key of the company
2140             * @param  start the lower bound of the range of users
2141             * @param  end the upper bound of the range of users (not inclusive)
2142             * @return the range of users belonging to the company
2143             * @throws SystemException if a system exception occurred
2144             */
2145            @Override
2146            public List<User> getCompanyUsers(long companyId, int start, int end)
2147                    throws SystemException {
2148    
2149                    return userPersistence.findByCompanyId(companyId, start, end);
2150            }
2151    
2152            /**
2153             * Returns the number of users belonging to the company.
2154             *
2155             * @param  companyId the primary key of the company
2156             * @return the number of users belonging to the company
2157             * @throws SystemException if a system exception occurred
2158             */
2159            @Override
2160            public int getCompanyUsersCount(long companyId) throws SystemException {
2161                    return userPersistence.countByCompanyId(companyId);
2162            }
2163    
2164            /**
2165             * Returns the default user for the company.
2166             *
2167             * @param  companyId the primary key of the company
2168             * @return the default user for the company
2169             * @throws PortalException if a default user for the company could not be
2170             *         found
2171             * @throws SystemException if a system exception occurred
2172             */
2173            @Override
2174            @Skip
2175            public User getDefaultUser(long companyId)
2176                    throws PortalException, SystemException {
2177    
2178                    User userModel = _defaultUsers.get(companyId);
2179    
2180                    if (userModel == null) {
2181                            userModel = userLocalService.loadGetDefaultUser(companyId);
2182    
2183                            _defaultUsers.put(companyId, userModel);
2184                    }
2185    
2186                    return userModel;
2187            }
2188    
2189            /**
2190             * Returns the primary key of the default user for the company.
2191             *
2192             * @param  companyId the primary key of the company
2193             * @return the primary key of the default user for the company
2194             * @throws PortalException if a default user for the company could not be
2195             *         found
2196             * @throws SystemException if a system exception occurred
2197             */
2198            @Override
2199            @Skip
2200            public long getDefaultUserId(long companyId)
2201                    throws PortalException, SystemException {
2202    
2203                    User user = getDefaultUser(companyId);
2204    
2205                    return user.getUserId();
2206            }
2207    
2208            /**
2209             * Returns the primary keys of all the users belonging to the group.
2210             *
2211             * @param  groupId the primary key of the group
2212             * @return the primary keys of the users belonging to the group
2213             * @throws SystemException if a system exception occurred
2214             */
2215            @Override
2216            public long[] getGroupUserIds(long groupId) throws SystemException {
2217                    return getUserIds(getGroupUsers(groupId));
2218            }
2219    
2220            /**
2221             * Returns the number of users with the status belonging to the group.
2222             *
2223             * @param  groupId the primary key of the group
2224             * @param  status the workflow status
2225             * @return the number of users with the status belonging to the group
2226             * @throws PortalException if a group with the primary key could not be
2227             *         found
2228             * @throws SystemException if a system exception occurred
2229             */
2230            @Override
2231            public int getGroupUsersCount(long groupId, int status)
2232                    throws PortalException, SystemException {
2233    
2234                    Group group = groupPersistence.findByPrimaryKey(groupId);
2235    
2236                    LinkedHashMap<String, Object> params =
2237                            new LinkedHashMap<String, Object>();
2238    
2239                    params.put("usersGroups", new Long(groupId));
2240    
2241                    return searchCount(group.getCompanyId(), null, status, params);
2242            }
2243    
2244            @Override
2245            public List<User> getInheritedRoleUsers(
2246                            long roleId, int start, int end, OrderByComparator obc)
2247                    throws PortalException, SystemException {
2248    
2249                    Role role = rolePersistence.findByPrimaryKey(roleId);
2250    
2251                    LinkedHashMap<String, Object> params =
2252                            new LinkedHashMap<String, Object>();
2253    
2254                    params.put("inherit", Boolean.TRUE);
2255                    params.put("usersRoles", roleId);
2256    
2257                    return search(
2258                            role.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2259                            params, start, end, obc);
2260            }
2261    
2262            /**
2263             * Returns all the users who have not had any announcements of the type
2264             * delivered, excluding the default user.
2265             *
2266             * @param  type the type of announcement
2267             * @return the users who have not had any annoucements of the type delivered
2268             * @throws SystemException if a system exception occurred
2269             */
2270            @Override
2271            public List<User> getNoAnnouncementsDeliveries(String type)
2272                    throws SystemException {
2273    
2274                    return userFinder.findByNoAnnouncementsDeliveries(type);
2275            }
2276    
2277            /**
2278             * Returns all the users who do not have any contacts.
2279             *
2280             * @return the users who do not have any contacts
2281             * @throws SystemException if a system exception occurred
2282             */
2283            @Override
2284            public List<User> getNoContacts() throws SystemException {
2285                    return userFinder.findByNoContacts();
2286            }
2287    
2288            /**
2289             * Returns all the users who do not belong to any groups, excluding the
2290             * default user.
2291             *
2292             * @return the users who do not belong to any groups
2293             * @throws SystemException if a system exception occurred
2294             */
2295            @Override
2296            public List<User> getNoGroups() throws SystemException {
2297                    return userFinder.findByNoGroups();
2298            }
2299    
2300            /**
2301             * Returns the primary keys of all the users belonging to the organization.
2302             *
2303             * @param  organizationId the primary key of the organization
2304             * @return the primary keys of the users belonging to the organization
2305             * @throws SystemException if a system exception occurred
2306             */
2307            @Override
2308            public long[] getOrganizationUserIds(long organizationId)
2309                    throws SystemException {
2310    
2311                    return getUserIds(getOrganizationUsers(organizationId));
2312            }
2313    
2314            /**
2315             * Returns the number of users with the status belonging to the
2316             * organization.
2317             *
2318             * @param  organizationId the primary key of the organization
2319             * @param  status the workflow status
2320             * @return the number of users with the status belonging to the organization
2321             * @throws PortalException if an organization with the primary key could not
2322             *         be found
2323             * @throws SystemException if a system exception occurred
2324             */
2325            @Override
2326            public int getOrganizationUsersCount(long organizationId, int status)
2327                    throws PortalException, SystemException {
2328    
2329                    Organization organization = organizationPersistence.findByPrimaryKey(
2330                            organizationId);
2331    
2332                    LinkedHashMap<String, Object> params =
2333                            new LinkedHashMap<String, Object>();
2334    
2335                    params.put("usersOrgs", new Long(organizationId));
2336    
2337                    return searchCount(organization.getCompanyId(), null, status, params);
2338            }
2339    
2340            /**
2341             * Returns the primary keys of all the users belonging to the role.
2342             *
2343             * @param  roleId the primary key of the role
2344             * @return the primary keys of the users belonging to the role
2345             * @throws SystemException if a system exception occurred
2346             */
2347            @Override
2348            public long[] getRoleUserIds(long roleId) throws SystemException {
2349                    return getUserIds(getRoleUsers(roleId));
2350            }
2351    
2352            /**
2353             * Returns the number of users with the status belonging to the role.
2354             *
2355             * @param  roleId the primary key of the role
2356             * @param  status the workflow status
2357             * @return the number of users with the status belonging to the role
2358             * @throws PortalException if an role with the primary key could not be
2359             *         found
2360             * @throws SystemException if a system exception occurred
2361             */
2362            @Override
2363            public int getRoleUsersCount(long roleId, int status)
2364                    throws PortalException, SystemException {
2365    
2366                    Role role = rolePersistence.findByPrimaryKey(roleId);
2367    
2368                    LinkedHashMap<String, Object> params =
2369                            new LinkedHashMap<String, Object>();
2370    
2371                    params.put("usersRoles", new Long(roleId));
2372    
2373                    return searchCount(role.getCompanyId(), null, status, params);
2374            }
2375    
2376            /**
2377             * Returns an ordered range of all the users with a social relation of the
2378             * type with the user.
2379             *
2380             * <p>
2381             * Useful when paginating results. Returns a maximum of <code>end -
2382             * start</code> instances. <code>start</code> and <code>end</code> are not
2383             * primary keys, they are indexes in the result set. Thus, <code>0</code>
2384             * refers to the first result in the set. Setting both <code>start</code>
2385             * and <code>end</code> to {@link
2386             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
2387             * result set.
2388             * </p>
2389             *
2390             * @param      userId the primary key of the user
2391             * @param      socialRelationType the type of social relation. The possible
2392             *             types can be found in {@link
2393             *             com.liferay.portlet.social.model.SocialRelationConstants}.
2394             * @param      start the lower bound of the range of users
2395             * @param      end the upper bound of the range of users (not inclusive)
2396             * @param      obc the comparator to order the users by (optionally
2397             *             <code>null</code>)
2398             * @return     the ordered range of users with a social relation of the type
2399             *             with the user
2400             * @throws     PortalException if a user with the primary key could not be
2401             *             found
2402             * @throws     SystemException if a system exception occurred
2403             * @deprecated As of 7.0.0, replaced by {@link #getSocialUsers(long, int,
2404             *             String, int, int, OrderByComparator)}
2405             */
2406            @Deprecated
2407            @Override
2408            public List<User> getSocialUsers(
2409                            long userId, int socialRelationType, int start, int end,
2410                            OrderByComparator obc)
2411                    throws PortalException, SystemException {
2412    
2413                    return getSocialUsers(
2414                            userId, socialRelationType, StringPool.EQUAL, start, end, obc);
2415            }
2416    
2417            /**
2418             * Returns an ordered range of all the users with a social relation with the
2419             * user.
2420             *
2421             * <p>
2422             * Useful when paginating results. Returns a maximum of <code>end -
2423             * start</code> instances. <code>start</code> and <code>end</code> are not
2424             * primary keys, they are indexes in the result set. Thus, <code>0</code>
2425             * refers to the first result in the set. Setting both <code>start</code>
2426             * and <code>end</code> to {@link
2427             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
2428             * result set.
2429             * </p>
2430             *
2431             * @param      userId the primary key of the user
2432             * @param      start the lower bound of the range of users
2433             * @param      end the upper bound of the range of users (not inclusive)
2434             * @param      obc the comparator to order the users by (optionally
2435             *             <code>null</code>)
2436             * @return     the ordered range of users with a social relation with the
2437             *             user
2438             * @throws     PortalException if a user with the primary key could not be
2439             *             found
2440             * @throws     SystemException if a system exception occurred
2441             * @deprecated As of 7.0.0, replaced by {@link #getSocialUsers(long, int,
2442             *             boolean, int, int, OrderByComparator)}
2443             */
2444            @Deprecated
2445            @Override
2446            public List<User> getSocialUsers(
2447                            long userId, int start, int end, OrderByComparator obc)
2448                    throws PortalException, SystemException {
2449    
2450                    return getSocialUsers(
2451                            userId, SocialRelationConstants.TYPE_UNI_ENEMY,
2452                            StringPool.NOT_EQUAL, start, end, obc);
2453            }
2454    
2455            @Override
2456            public List<User> getSocialUsers(
2457                            long userId, int socialRelationType,
2458                            String socialRelationTypeComparator, int start, int end,
2459                            OrderByComparator obc)
2460                    throws PortalException, SystemException {
2461    
2462                    if (!socialRelationTypeComparator.equals(StringPool.EQUAL) &&
2463                            !socialRelationTypeComparator.equals(StringPool.NOT_EQUAL)) {
2464    
2465                            throw new IllegalArgumentException(
2466                                    "Invalid social relation type comparator " +
2467                                            socialRelationTypeComparator);
2468                    }
2469    
2470                    if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS)) {
2471                            List<SocialRelation> socialRelations =
2472                                    socialRelationPersistence.findByU1_T(
2473                                            userId, socialRelationType);
2474    
2475                            if (socialRelationTypeComparator.equals(StringPool.NOT_EQUAL)) {
2476                                    socialRelations = ListUtil.remove(
2477                                            socialRelationPersistence.findByUserId1(userId),
2478                                            socialRelations);
2479                            }
2480    
2481                            List<User> users = new ArrayList<User>();
2482    
2483                            for (SocialRelation socialRelation : socialRelations) {
2484                                    User user = userPersistence.findByPrimaryKey(
2485                                            socialRelation.getUserId2());
2486    
2487                                    if (user.isDefaultUser() ||
2488                                            (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {
2489    
2490                                            continue;
2491                                    }
2492    
2493                                    if (!users.contains(user)) {
2494                                            users.add(user);
2495                                    }
2496                            }
2497    
2498                            if (obc != null) {
2499                                    users = ListUtil.sort(users, obc);
2500                            }
2501    
2502                            return users;
2503                    }
2504    
2505                    User user = userPersistence.findByPrimaryKey(userId);
2506    
2507                    return userFinder.findBySocialUsers(
2508                            user.getCompanyId(), userId, socialRelationType,
2509                            socialRelationTypeComparator, WorkflowConstants.STATUS_APPROVED,
2510                            start, end, obc);
2511            }
2512    
2513            /**
2514             * Returns an ordered range of all the users with a mutual social relation
2515             * of the type with both of the given users.
2516             *
2517             * <p>
2518             * Useful when paginating results. Returns a maximum of <code>end -
2519             * start</code> instances. <code>start</code> and <code>end</code> are not
2520             * primary keys, they are indexes in the result set. Thus, <code>0</code>
2521             * refers to the first result in the set. Setting both <code>start</code>
2522             * and <code>end</code> to {@link
2523             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
2524             * result set.
2525             * </p>
2526             *
2527             * @param  userId1 the primary key of the first user
2528             * @param  userId2 the primary key of the second user
2529             * @param  socialRelationType the type of social relation. The possible
2530             *         types can be found in {@link
2531             *         com.liferay.portlet.social.model.SocialRelationConstants}.
2532             * @param  start the lower bound of the range of users
2533             * @param  end the upper bound of the range of users (not inclusive)
2534             * @param  obc the comparator to order the users by (optionally
2535             *         <code>null</code>)
2536             * @return the ordered range of users with a mutual social relation of the
2537             *         type with the user
2538             * @throws PortalException if a user with the primary key could not be found
2539             * @throws SystemException if a system exception occurred
2540             */
2541            @Override
2542            public List<User> getSocialUsers(
2543                            long userId1, long userId2, int socialRelationType, int start,
2544                            int end, OrderByComparator obc)
2545                    throws PortalException, SystemException {
2546    
2547                    User user1 = userPersistence.findByPrimaryKey(userId1);
2548    
2549                    LinkedHashMap<String, Object> params =
2550                            new LinkedHashMap<String, Object>();
2551    
2552                    params.put(
2553                            "socialMutualRelationType",
2554                            new Long[] {userId1, new Long(socialRelationType), userId2,
2555                            new Long(socialRelationType)});
2556    
2557                    return search(
2558                            user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2559                            params, start, end, obc);
2560            }
2561    
2562            /**
2563             * Returns an ordered range of all the users with a mutual social relation
2564             * with both of the given users.
2565             *
2566             * <p>
2567             * Useful when paginating results. Returns a maximum of <code>end -
2568             * start</code> instances. <code>start</code> and <code>end</code> are not
2569             * primary keys, they are indexes in the result set. Thus, <code>0</code>
2570             * refers to the first result in the set. Setting both <code>start</code>
2571             * and <code>end</code> to {@link
2572             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
2573             * result set.
2574             * </p>
2575             *
2576             * @param  userId1 the primary key of the first user
2577             * @param  userId2 the primary key of the second user
2578             * @param  start the lower bound of the range of users
2579             * @param  end the upper bound of the range of users (not inclusive)
2580             * @param  obc the comparator to order the users by (optionally
2581             *         <code>null</code>)
2582             * @return the ordered range of users with a mutual social relation with the
2583             *         user
2584             * @throws PortalException if a user with the primary key could not be found
2585             * @throws SystemException if a system exception occurred
2586             */
2587            @Override
2588            public List<User> getSocialUsers(
2589                            long userId1, long userId2, int start, int end,
2590                            OrderByComparator obc)
2591                    throws PortalException, SystemException {
2592    
2593                    User user1 = userPersistence.findByPrimaryKey(userId1);
2594    
2595                    LinkedHashMap<String, Object> params =
2596                            new LinkedHashMap<String, Object>();
2597    
2598                    params.put("socialMutualRelation", new Long[] {userId1, userId2});
2599    
2600                    return search(
2601                            user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2602                            params, start, end, obc);
2603            }
2604    
2605            /**
2606             * Returns the number of users with a social relation with the user.
2607             *
2608             * @param      userId the primary key of the user
2609             * @return     the number of users with a social relation with the user
2610             * @throws     PortalException if a user with the primary key could not be
2611             *             found
2612             * @throws     SystemException if a system exception occurred
2613             * @deprecated As of 7.0.0, replaced by {@link #getSocialUsersCount(long,
2614             *             int, String)}
2615             */
2616            @Deprecated
2617            @Override
2618            public int getSocialUsersCount(long userId)
2619                    throws PortalException, SystemException {
2620    
2621                    return getSocialUsersCount(
2622                            userId, SocialRelationConstants.TYPE_UNI_ENEMY,
2623                            StringPool.NOT_EQUAL);
2624            }
2625    
2626            /**
2627             * Returns the number of users with a social relation of the type with the
2628             * user.
2629             *
2630             * @param      userId the primary key of the user
2631             * @param      socialRelationType the type of social relation. The possible
2632             *             types can be found in {@link
2633             *             com.liferay.portlet.social.model.SocialRelationConstants}.
2634             * @return     the number of users with a social relation of the type with
2635             *             the user
2636             * @throws     PortalException if a user with the primary key could not be
2637             *             found
2638             * @throws     SystemException if a system exception occurred
2639             * @deprecated As of 7.0.0, replaced by {@link #getSocialUsersCount(long,
2640             *             int, String)}
2641             */
2642            @Deprecated
2643            @Override
2644            public int getSocialUsersCount(long userId, int socialRelationType)
2645                    throws PortalException, SystemException {
2646    
2647                    return getSocialUsersCount(
2648                            userId, socialRelationType, StringPool.EQUAL);
2649            }
2650    
2651            /**
2652             * Returns the number of users with a social relation with the user.
2653             *
2654             * @param  userId the primary key of the user
2655             * @param  socialRelationType the type of social relation. The possible
2656             *         types can be found in {@link
2657             *         com.liferay.portlet.social.model.SocialRelationConstants}.
2658             * @return the number of users with a social relation with the user
2659             * @throws PortalException if a user with the primary key could not be found
2660             * @throws SystemException if a system exception occurred
2661             */
2662            @Override
2663            public int getSocialUsersCount(
2664                            long userId, int socialRelationType,
2665                            String socialRelationTypeComparator)
2666                    throws PortalException, SystemException {
2667    
2668                    User user = userPersistence.findByPrimaryKey(userId);
2669    
2670                    if (!socialRelationTypeComparator.equals(StringPool.EQUAL) &&
2671                            !socialRelationTypeComparator.equals(StringPool.NOT_EQUAL)) {
2672    
2673                            throw new IllegalArgumentException(
2674                                    "Invalid social relation type comparator " +
2675                                            socialRelationTypeComparator);
2676                    }
2677    
2678                    return userFinder.countBySocialUsers(
2679                            user.getCompanyId(), user.getUserId(), socialRelationType,
2680                            socialRelationTypeComparator, WorkflowConstants.STATUS_APPROVED);
2681            }
2682    
2683            /**
2684             * Returns the number of users with a mutual social relation with both of
2685             * the given users.
2686             *
2687             * @param  userId1 the primary key of the first user
2688             * @param  userId2 the primary key of the second user
2689             * @return the number of users with a mutual social relation with the user
2690             * @throws PortalException if a user with the primary key could not be found
2691             * @throws SystemException if a system exception occurred
2692             */
2693            @Override
2694            public int getSocialUsersCount(long userId1, long userId2)
2695                    throws PortalException, SystemException {
2696    
2697                    User user1 = userPersistence.findByPrimaryKey(userId1);
2698    
2699                    LinkedHashMap<String, Object> params =
2700                            new LinkedHashMap<String, Object>();
2701    
2702                    params.put("socialMutualRelation", new Long[] {userId1, userId2});
2703    
2704                    return searchCount(
2705                            user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2706                            params);
2707            }
2708    
2709            /**
2710             * Returns the number of users with a mutual social relation of the type
2711             * with both of the given users.
2712             *
2713             * @param  userId1 the primary key of the first user
2714             * @param  userId2 the primary key of the second user
2715             * @param  socialRelationType the type of social relation. The possible
2716             *         types can be found in {@link
2717             *         com.liferay.portlet.social.model.SocialRelationConstants}.
2718             * @return the number of users with a mutual social relation of the type
2719             *         with the user
2720             * @throws PortalException if a user with the primary key could not be found
2721             * @throws SystemException if a system exception occurred
2722             */
2723            @Override
2724            public int getSocialUsersCount(
2725                            long userId1, long userId2, int socialRelationType)
2726                    throws PortalException, SystemException {
2727    
2728                    User user1 = userPersistence.findByPrimaryKey(userId1);
2729    
2730                    LinkedHashMap<String, Object> params =
2731                            new LinkedHashMap<String, Object>();
2732    
2733                    params.put(
2734                            "socialMutualRelationType",
2735                            new Long[] {userId1, new Long(socialRelationType), userId2,
2736                            new Long(socialRelationType)});
2737    
2738                    return searchCount(
2739                            user1.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
2740                            params);
2741            }
2742    
2743            /**
2744             * Returns the user with the contact ID.
2745             *
2746             * @param  contactId the user's contact ID
2747             * @return the user with the contact ID
2748             * @throws PortalException if a user with the contact ID could not be found
2749             * @throws SystemException if a system exception occurred
2750             */
2751            @Override
2752            public User getUserByContactId(long contactId)
2753                    throws PortalException, SystemException {
2754    
2755                    return userPersistence.findByContactId(contactId);
2756            }
2757    
2758            /**
2759             * Returns the user with the email address.
2760             *
2761             * @param  companyId the primary key of the user's company
2762             * @param  emailAddress the user's email address
2763             * @return the user with the email address
2764             * @throws PortalException if a user with the email address could not be
2765             *         found
2766             * @throws SystemException if a system exception occurred
2767             */
2768            @Override
2769            public User getUserByEmailAddress(long companyId, String emailAddress)
2770                    throws PortalException, SystemException {
2771    
2772                    emailAddress = getLogin(emailAddress);
2773    
2774                    return userPersistence.findByC_EA(companyId, emailAddress);
2775            }
2776    
2777            /**
2778             * Returns the user with the Facebook ID.
2779             *
2780             * @param  companyId the primary key of the user's company
2781             * @param  facebookId the user's Facebook ID
2782             * @return the user with the Facebook ID
2783             * @throws PortalException if a user with the Facebook ID could not be found
2784             * @throws SystemException if a system exception occurred
2785             */
2786            @Override
2787            public User getUserByFacebookId(long companyId, long facebookId)
2788                    throws PortalException, SystemException {
2789    
2790                    return userPersistence.findByC_FID(companyId, facebookId);
2791            }
2792    
2793            /**
2794             * Returns the user with the primary key.
2795             *
2796             * @param  userId the primary key of the user
2797             * @return the user with the primary key
2798             * @throws PortalException if a user with the primary key could not be found
2799             * @throws SystemException if a system exception occurred
2800             */
2801            @Override
2802            public User getUserById(long userId)
2803                    throws PortalException, SystemException {
2804    
2805                    return userPersistence.findByPrimaryKey(userId);
2806            }
2807    
2808            /**
2809             * Returns the user with the primary key from the company.
2810             *
2811             * @param  companyId the primary key of the user's company
2812             * @param  userId the primary key of the user
2813             * @return the user with the primary key
2814             * @throws PortalException if a user with the primary key from the company
2815             *         could not be found
2816             * @throws SystemException if a system exception occurred
2817             */
2818            @Override
2819            public User getUserById(long companyId, long userId)
2820                    throws PortalException, SystemException {
2821    
2822                    return userPersistence.findByC_U(companyId, userId);
2823            }
2824    
2825            /**
2826             * Returns the user with the OpenID.
2827             *
2828             * @param  companyId the primary key of the user's company
2829             * @param  openId the user's OpenID
2830             * @return the user with the OpenID
2831             * @throws PortalException if a user with the OpenID could not be found
2832             * @throws SystemException if a system exception occurred
2833             */
2834            @Override
2835            public User getUserByOpenId(long companyId, String openId)
2836                    throws PortalException, SystemException {
2837    
2838                    return userPersistence.findByC_O(companyId, openId);
2839            }
2840    
2841            /**
2842             * Returns the user with the portrait ID.
2843             *
2844             * @param  portraitId the user's portrait ID
2845             * @return the user with the portrait ID
2846             * @throws PortalException if a user with the portrait ID could not be found
2847             * @throws SystemException if a system exception occurred
2848             */
2849            @Override
2850            public User getUserByPortraitId(long portraitId)
2851                    throws PortalException, SystemException {
2852    
2853                    return userPersistence.findByPortraitId(portraitId);
2854            }
2855    
2856            /**
2857             * Returns the user with the screen name.
2858             *
2859             * @param  companyId the primary key of the user's company
2860             * @param  screenName the user's screen name
2861             * @return the user with the screen name
2862             * @throws PortalException if a user with the screen name could not be found
2863             * @throws SystemException if a system exception occurred
2864             */
2865            @Override
2866            public User getUserByScreenName(long companyId, String screenName)
2867                    throws PortalException, SystemException {
2868    
2869                    screenName = getLogin(screenName);
2870    
2871                    return userPersistence.findByC_SN(companyId, screenName);
2872            }
2873    
2874            /**
2875             * Returns the user with the UUID.
2876             *
2877             * @param      uuid the user's UUID
2878             * @return     the user with the UUID
2879             * @throws     PortalException if a user with the UUID could not be found
2880             * @throws     SystemException if a system exception occurred
2881             * @deprecated As of 6.2.0, replaced by {@link
2882             *             #getUserByUuidAndCompanyId(String, long)}
2883             */
2884            @Override
2885            public User getUserByUuid(String uuid)
2886                    throws PortalException, SystemException {
2887    
2888                    List<User> users = userPersistence.findByUuid(uuid);
2889    
2890                    if (users.isEmpty()) {
2891                            throw new NoSuchUserException("{uuid=" + uuid + "}");
2892                    }
2893                    else {
2894                            return users.get(0);
2895                    }
2896            }
2897    
2898            /**
2899             * Returns the user with the UUID.
2900             *
2901             * @param  uuid the user's UUID
2902             * @param  companyId the primary key of the user's company
2903             * @return the user with the UUID
2904             * @throws PortalException if a user with the UUID could not be found
2905             * @throws SystemException if a system exception occurred
2906             */
2907            @Override
2908            public User getUserByUuidAndCompanyId(String uuid, long companyId)
2909                    throws PortalException, SystemException {
2910    
2911                    List<User> users = userPersistence.findByUuid_C(uuid, companyId);
2912    
2913                    if (users.isEmpty()) {
2914                            StringBundler sb = new StringBundler(5);
2915    
2916                            sb.append("{uuid=");
2917                            sb.append(uuid);
2918                            sb.append(", companyId=");
2919                            sb.append(companyId);
2920                            sb.append("}");
2921    
2922                            throw new NoSuchUserException(sb.toString());
2923                    }
2924                    else {
2925                            return users.get(0);
2926                    }
2927            }
2928    
2929            /**
2930             * Returns the number of users with the status belonging to the user group.
2931             *
2932             * @param  userGroupId the primary key of the user group
2933             * @param  status the workflow status
2934             * @return the number of users with the status belonging to the user group
2935             * @throws PortalException if a user group with the primary key could not be
2936             *         found
2937             * @throws SystemException if a system exception occurred
2938             */
2939            @Override
2940            public int getUserGroupUsersCount(long userGroupId, int status)
2941                    throws PortalException, SystemException {
2942    
2943                    UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
2944                            userGroupId);
2945    
2946                    LinkedHashMap<String, Object> params =
2947                            new LinkedHashMap<String, Object>();
2948    
2949                    params.put("usersUserGroups", new Long(userGroupId));
2950    
2951                    return searchCount(userGroup.getCompanyId(), null, status, params);
2952            }
2953    
2954            /**
2955             * Returns the primary key of the user with the email address.
2956             *
2957             * @param  companyId the primary key of the user's company
2958             * @param  emailAddress the user's email address
2959             * @return the primary key of the user with the email address
2960             * @throws PortalException if a user with the email address could not be
2961             *         found
2962             * @throws SystemException if a system exception occurred
2963             */
2964            @Override
2965            public long getUserIdByEmailAddress(long companyId, String emailAddress)
2966                    throws PortalException, SystemException {
2967    
2968                    emailAddress = StringUtil.toLowerCase(emailAddress.trim());
2969    
2970                    User user = userPersistence.findByC_EA(companyId, emailAddress);
2971    
2972                    return user.getUserId();
2973            }
2974    
2975            /**
2976             * Returns the primary key of the user with the screen name.
2977             *
2978             * @param  companyId the primary key of the user's company
2979             * @param  screenName the user's screen name
2980             * @return the primary key of the user with the screen name
2981             * @throws PortalException if a user with the screen name could not be found
2982             * @throws SystemException if a system exception occurred
2983             */
2984            @Override
2985            public long getUserIdByScreenName(long companyId, String screenName)
2986                    throws PortalException, SystemException {
2987    
2988                    screenName = getLogin(screenName);
2989    
2990                    User user = userPersistence.findByC_SN(companyId, screenName);
2991    
2992                    return user.getUserId();
2993            }
2994    
2995            /**
2996             * Returns <code>true</code> if the password policy has been assigned to the
2997             * user.
2998             *
2999             * @param  passwordPolicyId the primary key of the password policy
3000             * @param  userId the primary key of the user
3001             * @return <code>true</code> if the password policy is assigned to the user;
3002             *         <code>false</code> otherwise
3003             * @throws SystemException if a system exception occurred
3004             */
3005            @Override
3006            public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
3007                    throws SystemException {
3008    
3009                    return passwordPolicyRelLocalService.hasPasswordPolicyRel(
3010                            passwordPolicyId, User.class.getName(), userId);
3011            }
3012    
3013            /**
3014             * Returns <code>true</code> if the user has the role with the name,
3015             * optionally through inheritance.
3016             *
3017             * @param  companyId the primary key of the role's company
3018             * @param  name the name of the role (must be a regular role, not an
3019             *         organization, site or provider role)
3020             * @param  userId the primary key of the user
3021             * @param  inherited whether to include roles inherited from organizations,
3022             *         sites, etc.
3023             * @return <code>true</code> if the user has the role; <code>false</code>
3024             *         otherwise
3025             * @throws PortalException if a role with the name could not be found
3026             * @throws SystemException if a system exception occurred
3027             */
3028            @Override
3029            public boolean hasRoleUser(
3030                            long companyId, String name, long userId, boolean inherited)
3031                    throws PortalException, SystemException {
3032    
3033                    return roleLocalService.hasUserRole(userId, companyId, name, inherited);
3034            }
3035    
3036            /**
3037             * Returns <code>true</code> if the user's password is expired.
3038             *
3039             * @param  user the user
3040             * @return <code>true</code> if the user's password is expired;
3041             *         <code>false</code> otherwise
3042             * @throws PortalException if the password policy for the user could not be
3043             *         found
3044             * @throws SystemException if a system exception occurred
3045             */
3046            @Override
3047            public boolean isPasswordExpired(User user)
3048                    throws PortalException, SystemException {
3049    
3050                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3051    
3052                    if ((passwordPolicy != null) && passwordPolicy.getExpireable()) {
3053                            Date now = new Date();
3054    
3055                            if (user.getPasswordModifiedDate() == null) {
3056                                    user.setPasswordModifiedDate(now);
3057    
3058                                    userLocalService.updateUser(user);
3059                            }
3060    
3061                            long passwordStartTime = user.getPasswordModifiedDate().getTime();
3062                            long elapsedTime = now.getTime() - passwordStartTime;
3063    
3064                            if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
3065                                    return true;
3066                            }
3067                            else {
3068                                    return false;
3069                            }
3070                    }
3071    
3072                    return false;
3073            }
3074    
3075            /**
3076             * Returns <code>true</code> if the password policy is configured to warn
3077             * the user that his password is expiring and the remaining time until
3078             * expiration is equal or less than the configured warning time.
3079             *
3080             * @param  user the user
3081             * @return <code>true</code> if the user's password is expiring soon;
3082             *         <code>false</code> otherwise
3083             * @throws PortalException if the password policy for the user could not be
3084             *         found
3085             * @throws SystemException if a system exception occurred
3086             */
3087            @Override
3088            public boolean isPasswordExpiringSoon(User user)
3089                    throws PortalException, SystemException {
3090    
3091                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3092    
3093                    if ((passwordPolicy != null) && passwordPolicy.isExpireable() &&
3094                            (passwordPolicy.getWarningTime() > 0)) {
3095    
3096                            Date now = new Date();
3097    
3098                            if (user.getPasswordModifiedDate() == null) {
3099                                    user.setPasswordModifiedDate(now);
3100    
3101                                    userLocalService.updateUser(user);
3102                            }
3103    
3104                            long timeModified = user.getPasswordModifiedDate().getTime();
3105                            long passwordExpiresOn =
3106                                    (passwordPolicy.getMaxAge() * 1000) + timeModified;
3107    
3108                            long timeStartWarning =
3109                                    passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
3110    
3111                            if (now.getTime() > timeStartWarning) {
3112                                    return true;
3113                            }
3114                            else {
3115                                    return false;
3116                            }
3117                    }
3118    
3119                    return false;
3120            }
3121    
3122            /**
3123             * Returns the default user for the company.
3124             *
3125             * @param  companyId the primary key of the company
3126             * @return the default user for the company
3127             * @throws PortalException if the user could not be found
3128             * @throws SystemException if a system exception occurred
3129             */
3130            @Override
3131            public User loadGetDefaultUser(long companyId)
3132                    throws PortalException, SystemException {
3133    
3134                    return userPersistence.findByC_DU(companyId, true);
3135            }
3136    
3137            /**
3138             * Returns an ordered range of all the users who match the keywords and
3139             * status, without using the indexer. It is preferable to use the indexed
3140             * version {@link #search(long, String, int, LinkedHashMap, int, int, Sort)}
3141             * instead of this method wherever possible for performance reasons.
3142             *
3143             * <p>
3144             * Useful when paginating results. Returns a maximum of <code>end -
3145             * start</code> instances. <code>start</code> and <code>end</code> are not
3146             * primary keys, they are indexes in the result set. Thus, <code>0</code>
3147             * refers to the first result in the set. Setting both <code>start</code>
3148             * and <code>end</code> to {@link
3149             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
3150             * result set.
3151             * </p>
3152             *
3153             * @param  companyId the primary key of the user's company
3154             * @param  keywords the keywords (space separated), which may occur in the
3155             *         user's first name, middle name, last name, screen name, or email
3156             *         address
3157             * @param  status the workflow status
3158             * @param  params the finder parameters (optionally <code>null</code>). For
3159             *         more information see {@link
3160             *         com.liferay.portal.service.persistence.UserFinder}.
3161             * @param  start the lower bound of the range of users
3162             * @param  end the upper bound of the range of users (not inclusive)
3163             * @param  obc the comparator to order the users by (optionally
3164             *         <code>null</code>)
3165             * @return the matching users
3166             * @throws SystemException if a system exception occurred
3167             * @see    com.liferay.portal.service.persistence.UserFinder
3168             */
3169            @Override
3170            public List<User> search(
3171                            long companyId, String keywords, int status,
3172                            LinkedHashMap<String, Object> params, int start, int end,
3173                            OrderByComparator obc)
3174                    throws SystemException {
3175    
3176                    return userFinder.findByKeywords(
3177                            companyId, keywords, status, params, start, end, obc);
3178            }
3179    
3180            /**
3181             * Returns an ordered range of all the users who match the keywords and
3182             * status, using the indexer. It is preferable to use this method instead of
3183             * the non-indexed version whenever possible for performance reasons.
3184             *
3185             * <p>
3186             * Useful when paginating results. Returns a maximum of <code>end -
3187             * start</code> instances. <code>start</code> and <code>end</code> are not
3188             * primary keys, they are indexes in the result set. Thus, <code>0</code>
3189             * refers to the first result in the set. Setting both <code>start</code>
3190             * and <code>end</code> to {@link
3191             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
3192             * result set.
3193             * </p>
3194             *
3195             * @param  companyId the primary key of the user's company
3196             * @param  keywords the keywords (space separated), which may occur in the
3197             *         user's first name, middle name, last name, screen name, or email
3198             *         address
3199             * @param  status the workflow status
3200             * @param  params the indexer parameters (optionally <code>null</code>). For
3201             *         more information see {@link
3202             *         com.liferay.portlet.usersadmin.util.UserIndexer}.
3203             * @param  start the lower bound of the range of users
3204             * @param  end the upper bound of the range of users (not inclusive)
3205             * @param  sort the field and direction to sort by (optionally
3206             *         <code>null</code>)
3207             * @return the matching users
3208             * @throws SystemException if a system exception occurred
3209             * @see    com.liferay.portlet.usersadmin.util.UserIndexer
3210             */
3211            @Override
3212            public Hits search(
3213                            long companyId, String keywords, int status,
3214                            LinkedHashMap<String, Object> params, int start, int end, Sort sort)
3215                    throws SystemException {
3216    
3217                    String firstName = null;
3218                    String middleName = null;
3219                    String lastName = null;
3220                    String fullName = null;
3221                    String screenName = null;
3222                    String emailAddress = null;
3223                    String street = null;
3224                    String city = null;
3225                    String zip = null;
3226                    String region = null;
3227                    String country = null;
3228                    boolean andOperator = false;
3229    
3230                    if (Validator.isNotNull(keywords)) {
3231                            firstName = keywords;
3232                            middleName = keywords;
3233                            lastName = keywords;
3234                            fullName = keywords;
3235                            screenName = keywords;
3236                            emailAddress = keywords;
3237                            street = keywords;
3238                            city = keywords;
3239                            zip = keywords;
3240                            region = keywords;
3241                            country = keywords;
3242                    }
3243                    else {
3244                            andOperator = true;
3245                    }
3246    
3247                    if (params != null) {
3248                            params.put("keywords", keywords);
3249                    }
3250    
3251                    try {
3252                            SearchContext searchContext = buildSearchContext(
3253                                    companyId, firstName, middleName, lastName, fullName,
3254                                    screenName, emailAddress, street, city, zip, region, country,
3255                                    status, params, andOperator, start, end, sort);
3256    
3257                            Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3258                                    User.class);
3259    
3260                            return indexer.search(searchContext);
3261                    }
3262                    catch (Exception e) {
3263                            throw new SystemException(e);
3264                    }
3265            }
3266    
3267            /**
3268             * Returns an ordered range of all the users with the status, and whose
3269             * first name, middle name, last name, screen name, and email address match
3270             * the keywords specified for them, without using the indexer. It is
3271             * preferable to use the indexed version {@link #search(long, String,
3272             * String, String, String, String, int, LinkedHashMap, boolean, int, int,
3273             * Sort)} instead of this method wherever possible for performance reasons.
3274             *
3275             * <p>
3276             * Useful when paginating results. Returns a maximum of <code>end -
3277             * start</code> instances. <code>start</code> and <code>end</code> are not
3278             * primary keys, they are indexes in the result set. Thus, <code>0</code>
3279             * refers to the first result in the set. Setting both <code>start</code>
3280             * and <code>end</code> to {@link
3281             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
3282             * result set.
3283             * </p>
3284             *
3285             * @param  companyId the primary key of the user's company
3286             * @param  firstName the first name keywords (space separated)
3287             * @param  middleName the middle name keywords
3288             * @param  lastName the last name keywords
3289             * @param  screenName the screen name keywords
3290             * @param  emailAddress the email address keywords
3291             * @param  status the workflow status
3292             * @param  params the finder parameters (optionally <code>null</code>). For
3293             *         more information see {@link
3294             *         com.liferay.portal.service.persistence.UserFinder}.
3295             * @param  andSearch whether every field must match its keywords, or just
3296             *         one field. For example, &quot;users with the first name 'bob' and
3297             *         last name 'smith'&quot; vs &quot;users with the first name 'bob'
3298             *         or the last name 'smith'&quot;.
3299             * @param  start the lower bound of the range of users
3300             * @param  end the upper bound of the range of users (not inclusive)
3301             * @param  obc the comparator to order the users by (optionally
3302             *         <code>null</code>)
3303             * @return the matching users
3304             * @throws SystemException if a system exception occurred
3305             * @see    com.liferay.portal.service.persistence.UserFinder
3306             */
3307            @Override
3308            public List<User> search(
3309                            long companyId, String firstName, String middleName,
3310                            String lastName, String screenName, String emailAddress, int status,
3311                            LinkedHashMap<String, Object> params, boolean andSearch, int start,
3312                            int end, OrderByComparator obc)
3313                    throws SystemException {
3314    
3315                    return userFinder.findByC_FN_MN_LN_SN_EA_S(
3316                            companyId, firstName, middleName, lastName, screenName,
3317                            emailAddress, status, params, andSearch, start, end, obc);
3318            }
3319    
3320            /**
3321             * Returns an ordered range of all the users with the status, and whose
3322             * first name, middle name, last name, screen name, and email address match
3323             * the keywords specified for them, using the indexer. It is preferable to
3324             * use this method instead of the non-indexed version whenever possible for
3325             * performance reasons.
3326             *
3327             * <p>
3328             * Useful when paginating results. Returns a maximum of <code>end -
3329             * start</code> instances. <code>start</code> and <code>end</code> are not
3330             * primary keys, they are indexes in the result set. Thus, <code>0</code>
3331             * refers to the first result in the set. Setting both <code>start</code>
3332             * and <code>end</code> to {@link
3333             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
3334             * result set.
3335             * </p>
3336             *
3337             * @param  companyId the primary key of the user's company
3338             * @param  firstName the first name keywords (space separated)
3339             * @param  middleName the middle name keywords
3340             * @param  lastName the last name keywords
3341             * @param  screenName the screen name keywords
3342             * @param  emailAddress the email address keywords
3343             * @param  status the workflow status
3344             * @param  params the indexer parameters (optionally <code>null</code>). For
3345             *         more information see {@link
3346             *         com.liferay.portlet.usersadmin.util.UserIndexer}.
3347             * @param  andSearch whether every field must match its keywords, or just
3348             *         one field. For example, &quot;users with the first name 'bob' and
3349             *         last name 'smith'&quot; vs &quot;users with the first name 'bob'
3350             *         or the last name 'smith'&quot;.
3351             * @param  start the lower bound of the range of users
3352             * @param  end the upper bound of the range of users (not inclusive)
3353             * @param  sort the field and direction to sort by (optionally
3354             *         <code>null</code>)
3355             * @return the matching users
3356             * @throws SystemException if a system exception occurred
3357             * @see    com.liferay.portlet.usersadmin.util.UserIndexer
3358             */
3359            @Override
3360            public Hits search(
3361                            long companyId, String firstName, String middleName,
3362                            String lastName, String screenName, String emailAddress, int status,
3363                            LinkedHashMap<String, Object> params, boolean andSearch, int start,
3364                            int end, Sort sort)
3365                    throws SystemException {
3366    
3367                    try {
3368                            SearchContext searchContext = buildSearchContext(
3369                                    companyId, firstName, middleName, lastName, null, screenName,
3370                                    emailAddress, null, null, null, null, null, status, params,
3371                                    andSearch, start, end, sort);
3372    
3373                            Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3374                                    User.class);
3375    
3376                            return indexer.search(searchContext);
3377                    }
3378                    catch (Exception e) {
3379                            throw new SystemException(e);
3380                    }
3381            }
3382    
3383            /**
3384             * Returns the number of users who match the keywords and status.
3385             *
3386             * @param  companyId the primary key of the user's company
3387             * @param  keywords the keywords (space separated), which may occur in the
3388             *         user's first name, middle name, last name, screen name, or email
3389             *         address
3390             * @param  status the workflow status
3391             * @param  params the finder parameters (optionally <code>null</code>). For
3392             *         more information see {@link
3393             *         com.liferay.portal.service.persistence.UserFinder}.
3394             * @return the number matching users
3395             * @throws SystemException if a system exception occurred
3396             */
3397            @Override
3398            public int searchCount(
3399                            long companyId, String keywords, int status,
3400                            LinkedHashMap<String, Object> params)
3401                    throws SystemException {
3402    
3403                    if (!PropsValues.USERS_INDEXER_ENABLED ||
3404                            !PropsValues.USERS_SEARCH_WITH_INDEX || isUseCustomSQL(params)) {
3405    
3406                            return userFinder.countByKeywords(
3407                                    companyId, keywords, status, params);
3408                    }
3409    
3410                    try {
3411                            String firstName = null;
3412                            String middleName = null;
3413                            String lastName = null;
3414                            String fullName = null;
3415                            String screenName = null;
3416                            String emailAddress = null;
3417                            String street = null;
3418                            String city = null;
3419                            String zip = null;
3420                            String region = null;
3421                            String country = null;
3422                            boolean andOperator = false;
3423    
3424                            if (Validator.isNotNull(keywords)) {
3425                                    firstName = keywords;
3426                                    middleName = keywords;
3427                                    lastName = keywords;
3428                                    fullName = keywords;
3429                                    screenName = keywords;
3430                                    emailAddress = keywords;
3431                                    street = keywords;
3432                                    city = keywords;
3433                                    zip = keywords;
3434                                    region = keywords;
3435                                    country = keywords;
3436                            }
3437                            else {
3438                                    andOperator = true;
3439                            }
3440    
3441                            if (params != null) {
3442                                    params.put("keywords", keywords);
3443                            }
3444    
3445                            Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3446                                    User.class);
3447    
3448                            SearchContext searchContext = buildSearchContext(
3449                                    companyId, firstName, middleName, lastName, fullName,
3450                                    screenName, emailAddress, street, city, zip, region, country,
3451                                    status, params, andOperator, QueryUtil.ALL_POS,
3452                                    QueryUtil.ALL_POS, null);
3453    
3454                            Hits hits = indexer.search(searchContext);
3455    
3456                            return hits.getLength();
3457                    }
3458                    catch (Exception e) {
3459                            throw new SystemException(e);
3460                    }
3461            }
3462    
3463            /**
3464             * Returns the number of users with the status, and whose first name, middle
3465             * name, last name, screen name, and email address match the keywords
3466             * specified for them.
3467             *
3468             * @param  companyId the primary key of the user's company
3469             * @param  firstName the first name keywords (space separated)
3470             * @param  middleName the middle name keywords
3471             * @param  lastName the last name keywords
3472             * @param  screenName the screen name keywords
3473             * @param  emailAddress the email address keywords
3474             * @param  status the workflow status
3475             * @param  params the finder parameters (optionally <code>null</code>). For
3476             *         more information see {@link
3477             *         com.liferay.portal.service.persistence.UserFinder}.
3478             * @param  andSearch whether every field must match its keywords, or just
3479             *         one field. For example, &quot;users with the first name 'bob' and
3480             *         last name 'smith'&quot; vs &quot;users with the first name 'bob'
3481             *         or the last name 'smith'&quot;.
3482             * @return the number of matching users
3483             * @throws SystemException if a system exception occurred
3484             */
3485            @Override
3486            public int searchCount(
3487                            long companyId, String firstName, String middleName,
3488                            String lastName, String screenName, String emailAddress, int status,
3489                            LinkedHashMap<String, Object> params, boolean andSearch)
3490                    throws SystemException {
3491    
3492                    if (!PropsValues.USERS_INDEXER_ENABLED ||
3493                            !PropsValues.USERS_SEARCH_WITH_INDEX || isUseCustomSQL(params)) {
3494    
3495                            return userFinder.countByC_FN_MN_LN_SN_EA_S(
3496                                    companyId, firstName, middleName, lastName, screenName,
3497                                    emailAddress, status, params, andSearch);
3498                    }
3499    
3500                    try {
3501                            Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
3502                                    User.class);
3503    
3504                            FullNameGenerator fullNameGenerator =
3505                                    FullNameGeneratorFactory.getInstance();
3506    
3507                            String fullName = fullNameGenerator.getFullName(
3508                                    firstName, middleName, lastName);
3509    
3510                            SearchContext searchContext = buildSearchContext(
3511                                    companyId, firstName, middleName, lastName, fullName,
3512                                    screenName, emailAddress, null, null, null, null, null, status,
3513                                    params, true, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
3514    
3515                            Hits hits = indexer.search(searchContext);
3516    
3517                            return hits.getLength();
3518                    }
3519                    catch (Exception e) {
3520                            throw new SystemException(e);
3521                    }
3522            }
3523    
3524            /**
3525             * Sends an email address verification to the user.
3526             *
3527             * @param  user the verification email recipient
3528             * @param  emailAddress the recipient's email address
3529             * @param  serviceContext the service context to be applied. Must set the
3530             *         portal URL, main path, primary key of the layout, remote address,
3531             *         remote host, and agent for the user.
3532             * @throws PortalException if a portal exception occurred
3533             * @throws SystemException if a system exception occurred
3534             */
3535            @Override
3536            public void sendEmailAddressVerification(
3537                            User user, String emailAddress, ServiceContext serviceContext)
3538                    throws PortalException, SystemException {
3539    
3540                    if (user.isEmailAddressVerified() &&
3541                            StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
3542    
3543                            return;
3544                    }
3545    
3546                    Ticket ticket = ticketLocalService.addDistinctTicket(
3547                            user.getCompanyId(), User.class.getName(), user.getUserId(),
3548                            TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3549                            serviceContext);
3550    
3551                    String verifyEmailAddressURL =
3552                            serviceContext.getPortalURL() + serviceContext.getPathMain() +
3553                                    "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3554    
3555                    long plid = serviceContext.getPlid();
3556    
3557                    if (plid > 0) {
3558                            Layout layout = layoutLocalService.fetchLayout(plid);
3559    
3560                            if (layout != null) {
3561                                    Group group = layout.getGroup();
3562    
3563                                    if (!layout.isPrivateLayout() && !group.isUser()) {
3564                                            verifyEmailAddressURL +=
3565                                                    "&p_l_id=" + serviceContext.getPlid();
3566                                    }
3567                            }
3568                    }
3569    
3570                    String fromName = PrefsPropsUtil.getString(
3571                            user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3572                    String fromAddress = PrefsPropsUtil.getString(
3573                            user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3574    
3575                    String toName = user.getFullName();
3576                    String toAddress = emailAddress;
3577    
3578                    String subject = PrefsPropsUtil.getContent(
3579                            user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3580    
3581                    String body = PrefsPropsUtil.getContent(
3582                            user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3583    
3584                    SubscriptionSender subscriptionSender = new SubscriptionSender();
3585    
3586                    subscriptionSender.setBody(body);
3587                    subscriptionSender.setCompanyId(user.getCompanyId());
3588                    subscriptionSender.setContextAttributes(
3589                            "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3590                            "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3591                            "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3592                            "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_ID$]",
3593                            user.getUserId(), "[$USER_SCREENNAME$]", user.getScreenName());
3594                    subscriptionSender.setFrom(fromAddress, fromName);
3595                    subscriptionSender.setHtmlFormat(true);
3596                    subscriptionSender.setMailId("user", user.getUserId());
3597                    subscriptionSender.setServiceContext(serviceContext);
3598                    subscriptionSender.setSubject(subject);
3599                    subscriptionSender.setUserId(user.getUserId());
3600    
3601                    subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3602    
3603                    subscriptionSender.flushNotificationsAsync();
3604            }
3605    
3606            /**
3607             * Sends the password email to the user with the email address. The content
3608             * of this email can be specified in <code>portal.properties</code> with the
3609             * <code>admin.email.password</code> keys.
3610             *
3611             * @param  companyId the primary key of the user's company
3612             * @param  emailAddress the user's email address
3613             * @param  fromName the name of the individual that the email should be from
3614             * @param  fromAddress the address of the individual that the email should
3615             *         be from
3616             * @param  subject the email subject. If <code>null</code>, the subject
3617             *         specified in <code>portal.properties</code> will be used.
3618             * @param  body the email body. If <code>null</code>, the body specified in
3619             *         <code>portal.properties</code> will be used.
3620             * @param  serviceContext the service context to be applied
3621             * @throws PortalException if a user with the email address could not be
3622             *         found
3623             * @throws SystemException if a system exception occurred
3624             */
3625            @Override
3626            public void sendPassword(
3627                            long companyId, String emailAddress, String fromName,
3628                            String fromAddress, String subject, String body,
3629                            ServiceContext serviceContext)
3630                    throws PortalException, SystemException {
3631    
3632                    Company company = companyPersistence.findByPrimaryKey(companyId);
3633    
3634                    if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3635                            return;
3636                    }
3637    
3638                    emailAddress = StringUtil.toLowerCase(emailAddress.trim());
3639    
3640                    if (Validator.isNull(emailAddress)) {
3641                            throw new UserEmailAddressException();
3642                    }
3643    
3644                    User user = userPersistence.findByC_EA(companyId, emailAddress);
3645    
3646                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3647    
3648                    String newPassword = StringPool.BLANK;
3649                    String passwordResetURL = StringPool.BLANK;
3650    
3651                    if (company.isSendPasswordResetLink()) {
3652                            Date expirationDate = null;
3653    
3654                            if ((passwordPolicy != null) &&
3655                                    (passwordPolicy.getResetTicketMaxAge() > 0)) {
3656    
3657                                    expirationDate = new Date(
3658                                            System.currentTimeMillis() +
3659                                                    (passwordPolicy.getResetTicketMaxAge() * 1000));
3660                            }
3661    
3662                            Ticket ticket = ticketLocalService.addDistinctTicket(
3663                                    companyId, User.class.getName(), user.getUserId(),
3664                                    TicketConstants.TYPE_PASSWORD, null, expirationDate,
3665                                    serviceContext);
3666    
3667                            passwordResetURL =
3668                                    serviceContext.getPortalURL() + serviceContext.getPathMain() +
3669                                            "/portal/update_password?p_l_id="+
3670                                                    serviceContext.getPlid() +
3671                                                            "&ticketKey=" + ticket.getKey();
3672                    }
3673                    else {
3674                            if (!PasswordEncryptorUtil.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
3675                                            PasswordEncryptorUtil.TYPE_NONE)) {
3676    
3677                                    if (LDAPSettingsUtil.isPasswordPolicyEnabled(
3678                                                    user.getCompanyId())) {
3679    
3680                                            if (_log.isWarnEnabled()) {
3681                                                    StringBundler sb = new StringBundler(5);
3682    
3683                                                    sb.append("When LDAP password policy is enabled, ");
3684                                                    sb.append("it is possible that portal generated ");
3685                                                    sb.append("passwords will not match the LDAP policy.");
3686                                                    sb.append("Using RegExpToolkit to generate new ");
3687                                                    sb.append("password.");
3688    
3689                                                    _log.warn(sb.toString());
3690                                            }
3691    
3692                                            RegExpToolkit regExpToolkit = new RegExpToolkit();
3693    
3694                                            newPassword = regExpToolkit.generate(null);
3695                                    }
3696                                    else {
3697                                            newPassword = PwdToolkitUtil.generate(passwordPolicy);
3698                                    }
3699    
3700                                    boolean passwordReset = false;
3701    
3702                                    if (passwordPolicy.getChangeable() &&
3703                                            passwordPolicy.getChangeRequired()) {
3704    
3705                                            passwordReset = true;
3706                                    }
3707    
3708                                    user.setPassword(PasswordEncryptorUtil.encrypt(newPassword));
3709                                    user.setPasswordUnencrypted(newPassword);
3710                                    user.setPasswordEncrypted(true);
3711                                    user.setPasswordReset(passwordReset);
3712                                    user.setPasswordModified(true);
3713                                    user.setPasswordModifiedDate(new Date());
3714    
3715                                    userPersistence.update(user);
3716    
3717                                    user.setPasswordModified(false);
3718                            }
3719                            else {
3720                                    newPassword = user.getPassword();
3721                            }
3722                    }
3723    
3724                    if (Validator.isNull(fromName)) {
3725                            fromName = PrefsPropsUtil.getString(
3726                                    companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3727                    }
3728    
3729                    if (Validator.isNull(fromAddress)) {
3730                            fromAddress = PrefsPropsUtil.getString(
3731                                    companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3732                    }
3733    
3734                    String toName = user.getFullName();
3735                    String toAddress = user.getEmailAddress();
3736    
3737                    if (Validator.isNull(subject)) {
3738                            if (company.isSendPasswordResetLink()) {
3739                                    subject = PrefsPropsUtil.getContent(
3740                                            companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
3741                            }
3742                            else {
3743                                    subject = PrefsPropsUtil.getContent(
3744                                            companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
3745                            }
3746                    }
3747    
3748                    if (Validator.isNull(body)) {
3749                            if (company.isSendPasswordResetLink()) {
3750                                    body = PrefsPropsUtil.getContent(
3751                                            companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
3752                            }
3753                            else {
3754                                    body = PrefsPropsUtil.getContent(
3755                                            companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
3756                            }
3757                    }
3758    
3759                    SubscriptionSender subscriptionSender = new SubscriptionSender();
3760    
3761                    subscriptionSender.setBody(body);
3762                    subscriptionSender.setCompanyId(companyId);
3763                    subscriptionSender.setContextAttributes(
3764                            "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
3765                            serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
3766                            serviceContext.getRemoteHost(), "[$USER_ID$]", user.getUserId(),
3767                            "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
3768                            user.getScreenName());
3769                    subscriptionSender.setFrom(fromAddress, fromName);
3770                    subscriptionSender.setHtmlFormat(true);
3771                    subscriptionSender.setMailId("user", user.getUserId());
3772                    subscriptionSender.setServiceContext(serviceContext);
3773                    subscriptionSender.setSubject(subject);
3774                    subscriptionSender.setUserId(user.getUserId());
3775    
3776                    subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3777    
3778                    subscriptionSender.flushNotificationsAsync();
3779            }
3780    
3781            /**
3782             * Sets the users in the role, removing and adding users to the role as
3783             * necessary.
3784             *
3785             * @param  roleId the primary key of the role
3786             * @param  userIds the primary keys of the users
3787             * @throws PortalException if a portal exception occurred
3788             * @throws SystemException if a system exception occurred
3789             */
3790            @Override
3791            public void setRoleUsers(long roleId, long[] userIds)
3792                    throws PortalException, SystemException {
3793    
3794                    List<User> oldUsers = rolePersistence.getUsers(roleId);
3795    
3796                    long[] oldUserIds = new long[oldUsers.size()];
3797    
3798                    for (int i = 0; i < oldUsers.size(); i++) {
3799                            User user = oldUsers.get(i);
3800    
3801                            oldUserIds[i] = user.getUserId();
3802                    }
3803    
3804                    Set<Long> updatedUserIdsSet = SetUtil.symmetricDifference(
3805                            userIds, oldUserIds);
3806    
3807                    long[] updateUserIds = ArrayUtil.toLongArray(updatedUserIdsSet);
3808    
3809                    rolePersistence.setUsers(roleId, userIds);
3810    
3811                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3812    
3813                    indexer.reindex(updateUserIds);
3814    
3815                    PermissionCacheUtil.clearCache(updateUserIds);
3816            }
3817    
3818            /**
3819             * Sets the users in the user group, removing and adding users to the user
3820             * group as necessary.
3821             *
3822             * @param  userGroupId the primary key of the user group
3823             * @param  userIds the primary keys of the users
3824             * @throws PortalException if a portal exception occurred
3825             * @throws SystemException if a system exception occurred
3826             */
3827            @Override
3828            @SuppressWarnings("deprecation")
3829            public void setUserGroupUsers(long userGroupId, long[] userIds)
3830                    throws PortalException, SystemException {
3831    
3832                    if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3833                            userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3834                    }
3835    
3836                    List<User> oldUsers = userGroupPersistence.getUsers(userGroupId);
3837    
3838                    long[] oldUserIds = new long[oldUsers.size()];
3839    
3840                    for (int i = 0; i < oldUsers.size(); i++) {
3841                            User user = oldUsers.get(i);
3842    
3843                            oldUserIds[i] = user.getUserId();
3844                    }
3845    
3846                    Set<Long> updatedUserIdsSet = SetUtil.symmetricDifference(
3847                            userIds, oldUserIds);
3848    
3849                    long[] updateUserIds = ArrayUtil.toLongArray(updatedUserIdsSet);
3850    
3851                    userGroupPersistence.setUsers(userGroupId, userIds);
3852    
3853                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3854    
3855                    indexer.reindex(updateUserIds);
3856    
3857                    PermissionCacheUtil.clearCache(updateUserIds);
3858            }
3859    
3860            /**
3861             * Removes the users from the teams of a group.
3862             *
3863             * @param  groupId the primary key of the group
3864             * @param  userIds the primary keys of the users
3865             * @throws PortalException if a portal exception occurred
3866             * @throws SystemException if a system exception occurred
3867             */
3868            @Override
3869            public void unsetGroupTeamsUsers(long groupId, long[] userIds)
3870                    throws PortalException, SystemException {
3871    
3872                    List<Team> teams = teamPersistence.findByGroupId(groupId);
3873    
3874                    for (Team team : teams) {
3875                            unsetTeamUsers(team.getTeamId(), userIds);
3876                    }
3877    
3878                    PermissionCacheUtil.clearCache(userIds);
3879            }
3880    
3881            /**
3882             * Removes the users from the group.
3883             *
3884             * @param  groupId the primary key of the group
3885             * @param  userIds the primary keys of the users
3886             * @param  serviceContext the service context to be applied (optionally
3887             *         <code>null</code>)
3888             * @throws PortalException if a portal exception occurred
3889             * @throws SystemException if a system exception occurred
3890             */
3891            @Override
3892            public void unsetGroupUsers(
3893                            final long groupId, final long[] userIds,
3894                            ServiceContext serviceContext)
3895                    throws PortalException, SystemException {
3896    
3897                    userGroupRoleLocalService.deleteUserGroupRoles(
3898                            userIds, groupId, RoleConstants.TYPE_SITE);
3899    
3900                    userLocalService.unsetGroupTeamsUsers(groupId, userIds);
3901    
3902                    groupPersistence.removeUsers(groupId, userIds);
3903    
3904                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3905    
3906                    indexer.reindex(userIds);
3907    
3908                    PermissionCacheUtil.clearCache(userIds);
3909    
3910                    Callable<Void> callable = new Callable<Void>() {
3911    
3912                            @Override
3913                            public Void call() throws Exception {
3914                                    Message message = new Message();
3915    
3916                                    message.put("groupId", groupId);
3917                                    message.put("userIds", userIds);
3918    
3919                                    MessageBusUtil.sendMessage(
3920                                            DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
3921    
3922                                    return null;
3923                            }
3924    
3925                    };
3926    
3927                    TransactionCommitCallbackRegistryUtil.registerCallback(callable);
3928            }
3929    
3930            /**
3931             * Removes the users from the organization.
3932             *
3933             * @param  organizationId the primary key of the organization
3934             * @param  userIds the primary keys of the users
3935             * @throws PortalException if a portal exception occurred
3936             * @throws SystemException if a system exception occurred
3937             */
3938            @Override
3939            public void unsetOrganizationUsers(
3940                            long organizationId, final long[] userIds)
3941                    throws PortalException, SystemException {
3942    
3943                    Organization organization = organizationPersistence.findByPrimaryKey(
3944                            organizationId);
3945    
3946                    final Group group = organization.getGroup();
3947    
3948                    userGroupRoleLocalService.deleteUserGroupRoles(
3949                            userIds, group.getGroupId());
3950    
3951                    organizationPersistence.removeUsers(organizationId, userIds);
3952    
3953                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
3954    
3955                    indexer.reindex(userIds);
3956    
3957                    PermissionCacheUtil.clearCache(userIds);
3958    
3959                    Callable<Void> callable = new Callable<Void>() {
3960    
3961                            @Override
3962                            public Void call() throws Exception {
3963                                    Message message = new Message();
3964    
3965                                    message.put("groupId", group.getGroupId());
3966                                    message.put("userIds", userIds);
3967    
3968                                    MessageBusUtil.sendMessage(
3969                                            DestinationNames.SUBSCRIPTION_CLEAN_UP, message);
3970    
3971                                    return null;
3972                            }
3973    
3974                    };
3975    
3976                    TransactionCommitCallbackRegistryUtil.registerCallback(callable);
3977            }
3978    
3979            /**
3980             * Removes the users from the password policy.
3981             *
3982             * @param  passwordPolicyId the primary key of the password policy
3983             * @param  userIds the primary keys of the users
3984             * @throws SystemException if a system exception occurred
3985             */
3986            @Override
3987            public void unsetPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
3988                    throws SystemException {
3989    
3990                    passwordPolicyRelLocalService.deletePasswordPolicyRels(
3991                            passwordPolicyId, User.class.getName(), userIds);
3992            }
3993    
3994            /**
3995             * Removes the users from the role.
3996             *
3997             * @param  roleId the primary key of the role
3998             * @param  users the users
3999             * @throws PortalException if a portal exception occurred
4000             * @throws SystemException if a system exception occurred
4001             */
4002            @Override
4003            public void unsetRoleUsers(long roleId, List<User> users)
4004                    throws PortalException, SystemException {
4005    
4006                    Role role = rolePersistence.findByPrimaryKey(roleId);
4007    
4008                    String roleName = role.getName();
4009    
4010                    if ((roleName.equals(RoleConstants.ADMINISTRATOR) &&
4011                             (getRoleUsersCount(role.getRoleId()) <= 1)) ||
4012                            roleName.equals(RoleConstants.USER)) {
4013    
4014                            return;
4015                    }
4016    
4017                    rolePersistence.removeUsers(roleId, users);
4018    
4019                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
4020    
4021                    indexer.reindex(users);
4022    
4023                    long[] userIds = new long[users.size()];
4024    
4025                    for (int i = 0; i < users.size(); i++) {
4026                            User user = users.get(i);
4027    
4028                            userIds[i] = user.getUserId();
4029                    }
4030    
4031                    PermissionCacheUtil.clearCache(userIds);
4032            }
4033    
4034            /**
4035             * Removes the users from the role.
4036             *
4037             * @param  roleId the primary key of the role
4038             * @param  userIds the primary keys of the users
4039             * @throws PortalException if a portal exception occurred
4040             * @throws SystemException if a system exception occurred
4041             */
4042            @Override
4043            public void unsetRoleUsers(long roleId, long[] userIds)
4044                    throws PortalException, SystemException {
4045    
4046                    Role role = rolePersistence.findByPrimaryKey(roleId);
4047    
4048                    String roleName = role.getName();
4049    
4050                    if (roleName.equals(RoleConstants.USER) ||
4051                            (roleName.equals(RoleConstants.ADMINISTRATOR) &&
4052                             getRoleUsersCount(role.getRoleId()) <= 1)) {
4053    
4054                            return;
4055                    }
4056    
4057                    rolePersistence.removeUsers(roleId, userIds);
4058    
4059                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
4060    
4061                    indexer.reindex(userIds);
4062    
4063                    PermissionCacheUtil.clearCache(userIds);
4064            }
4065    
4066            /**
4067             * Removes the users from the team.
4068             *
4069             * @param  teamId the primary key of the team
4070             * @param  userIds the primary keys of the users
4071             * @throws PortalException if a portal exception occurred
4072             * @throws SystemException if a system exception occurred
4073             */
4074            @Override
4075            public void unsetTeamUsers(long teamId, long[] userIds)
4076                    throws PortalException, SystemException {
4077    
4078                    teamPersistence.removeUsers(teamId, userIds);
4079    
4080                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
4081    
4082                    indexer.reindex(userIds);
4083    
4084                    PermissionCacheUtil.clearCache(userIds);
4085            }
4086    
4087            /**
4088             * Removes the users from the user group.
4089             *
4090             * @param  userGroupId the primary key of the user group
4091             * @param  userIds the primary keys of the users
4092             * @throws PortalException if a portal exception occurred
4093             * @throws SystemException if a system exception occurred
4094             */
4095            @Override
4096            public void unsetUserGroupUsers(long userGroupId, long[] userIds)
4097                    throws PortalException, SystemException {
4098    
4099                    userGroupPersistence.removeUsers(userGroupId, userIds);
4100    
4101                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
4102    
4103                    indexer.reindex(userIds);
4104    
4105                    PermissionCacheUtil.clearCache(userIds);
4106            }
4107    
4108            /**
4109             * Updates whether the user has agreed to the terms of use.
4110             *
4111             * @param  userId the primary key of the user
4112             * @param  agreedToTermsOfUse whether the user has agreet to the terms of
4113             *         use
4114             * @return the user
4115             * @throws PortalException if a user with the primary key could not be found
4116             * @throws SystemException if a system exception occurred
4117             */
4118            @Override
4119            public User updateAgreedToTermsOfUse(
4120                            long userId, boolean agreedToTermsOfUse)
4121                    throws PortalException, SystemException {
4122    
4123                    User user = userPersistence.findByPrimaryKey(userId);
4124    
4125                    user.setAgreedToTermsOfUse(agreedToTermsOfUse);
4126    
4127                    userPersistence.update(user);
4128    
4129                    return user;
4130            }
4131    
4132            /**
4133             * Updates the user's asset with the new asset categories and tag names,
4134             * removing and adding asset categories and tag names as necessary.
4135             *
4136             * @param  userId the primary key of the user
4137             * @param  user ID the primary key of the user
4138             * @param  assetCategoryIds the primary key's of the new asset categories
4139             * @param  assetTagNames the new asset tag names
4140             * @throws PortalException if a user with the primary key could not be found
4141             * @throws SystemException if a system exception occurred
4142             */
4143            @Override
4144            public void updateAsset(
4145                            long userId, User user, long[] assetCategoryIds,
4146                            String[] assetTagNames)
4147                    throws PortalException, SystemException {
4148    
4149                    User owner = userPersistence.findByPrimaryKey(userId);
4150    
4151                    Company company = companyPersistence.findByPrimaryKey(
4152                            owner.getCompanyId());
4153    
4154                    Group companyGroup = company.getGroup();
4155    
4156                    assetEntryLocalService.updateEntry(
4157                            userId, companyGroup.getGroupId(), user.getCreateDate(),
4158                            user.getModifiedDate(), User.class.getName(), user.getUserId(),
4159                            user.getUuid(), 0, assetCategoryIds, assetTagNames, false, null,
4160                            null, null, null, user.getFullName(), null, null, null, null, 0, 0,
4161                            null, false);
4162            }
4163    
4164            /**
4165             * Updates the user's creation date.
4166             *
4167             * @param  userId the primary key of the user
4168             * @param  createDate the new creation date
4169             * @return the user
4170             * @throws PortalException if a user with the primary key could not be found
4171             * @throws SystemException if a system exception occurred
4172             */
4173            @Override
4174            public User updateCreateDate(long userId, Date createDate)
4175                    throws PortalException, SystemException {
4176    
4177                    User user = userPersistence.findByPrimaryKey(userId);
4178    
4179                    user.setCreateDate(createDate);
4180    
4181                    userPersistence.update(user);
4182    
4183                    return user;
4184            }
4185    
4186            /**
4187             * Updates the user's email address.
4188             *
4189             * @param  userId the primary key of the user
4190             * @param  password the user's password
4191             * @param  emailAddress1 the user's new email address
4192             * @param  emailAddress2 the user's new email address confirmation
4193             * @return the user
4194             * @throws PortalException if a user with the primary key could not be found
4195             * @throws SystemException if a system exception occurred
4196             */
4197            @Override
4198            public User updateEmailAddress(
4199                            long userId, String password, String emailAddress1,
4200                            String emailAddress2)
4201                    throws PortalException, SystemException {
4202    
4203                    emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
4204                    emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
4205    
4206                    User user = userPersistence.findByPrimaryKey(userId);
4207    
4208                    validateEmailAddress(user, emailAddress1, emailAddress2);
4209    
4210                    setEmailAddress(
4211                            user, password, user.getFirstName(), user.getMiddleName(),
4212                            user.getLastName(), emailAddress1);
4213    
4214                    userPersistence.update(user);
4215    
4216                    Contact contact = user.getContact();
4217    
4218                    contact.setEmailAddress(user.getEmailAddress());
4219    
4220                    contactPersistence.update(contact);
4221    
4222                    return user;
4223            }
4224    
4225            /**
4226             * Updates the user's email address or sends verification email.
4227             *
4228             * @param  userId the primary key of the user
4229             * @param  password the user's password
4230             * @param  emailAddress1 the user's new email address
4231             * @param  emailAddress2 the user's new email address confirmation
4232             * @param  serviceContext the service context to be applied. Must set the
4233             *         portal URL, main path, primary key of the layout, remote address,
4234             *         remote host, and agent for the user.
4235             * @return the user
4236             * @throws PortalException if a user with the primary key could not be found
4237             * @throws SystemException if a system exception occurred
4238             */
4239            @Override
4240            public User updateEmailAddress(
4241                            long userId, String password, String emailAddress1,
4242                            String emailAddress2, ServiceContext serviceContext)
4243                    throws PortalException, SystemException {
4244    
4245                    emailAddress1 = StringUtil.toLowerCase(emailAddress1.trim());
4246                    emailAddress2 = StringUtil.toLowerCase(emailAddress2.trim());
4247    
4248                    User user = userPersistence.findByPrimaryKey(userId);
4249    
4250                    validateEmailAddress(user, emailAddress1, emailAddress2);
4251    
4252                    Company company = companyPersistence.findByPrimaryKey(
4253                            user.getCompanyId());
4254    
4255                    if (company.isStrangersVerify() &&
4256                            !StringUtil.equalsIgnoreCase(
4257                                    emailAddress1, user.getEmailAddress())) {
4258    
4259                            sendEmailAddressVerification(user, emailAddress1, serviceContext);
4260                    }
4261                    else {
4262                            setEmailAddress(
4263                                    user, password, user.getFirstName(), user.getMiddleName(),
4264                                    user.getLastName(), emailAddress1);
4265    
4266                            userPersistence.update(user);
4267    
4268                            Contact contact = user.getContact();
4269    
4270                            contact.setEmailAddress(user.getEmailAddress());
4271    
4272                            contactPersistence.update(contact);
4273                    }
4274    
4275                    return user;
4276            }
4277    
4278            /**
4279             * Updates whether the user has verified email address.
4280             *
4281             * @param  userId the primary key of the user
4282             * @param  emailAddressVerified whether the user has verified email address
4283             * @return the user
4284             * @throws PortalException if a user with the primary key could not be found
4285             * @throws SystemException if a system exception occurred
4286             */
4287            @Override
4288            public User updateEmailAddressVerified(
4289                            long userId, boolean emailAddressVerified)
4290                    throws PortalException, SystemException {
4291    
4292                    User user = userPersistence.findByPrimaryKey(userId);
4293    
4294                    user.setEmailAddressVerified(emailAddressVerified);
4295    
4296                    userPersistence.update(user);
4297    
4298                    return user;
4299            }
4300    
4301            /**
4302             * Updates the user's Facebook ID.
4303             *
4304             * @param  userId the primary key of the user
4305             * @param  facebookId the user's new Facebook ID
4306             * @return the user
4307             * @throws PortalException if a user with the primary key could not be found
4308             * @throws SystemException if a system exception occurred
4309             */
4310            @Override
4311            public User updateFacebookId(long userId, long facebookId)
4312                    throws PortalException, SystemException {
4313    
4314                    User user = userPersistence.findByPrimaryKey(userId);
4315    
4316                    user.setFacebookId(facebookId);
4317    
4318                    userPersistence.update(user);
4319    
4320                    return user;
4321            }
4322    
4323            /**
4324             * Sets the groups the user is in, removing and adding groups as necessary.
4325             *
4326             * @param  userId the primary key of the user
4327             * @param  newGroupIds the primary keys of the groups
4328             * @param  serviceContext the service context to be applied (optionally
4329             *         <code>null</code>)
4330             * @throws PortalException if a portal exception occurred
4331             * @throws SystemException if a system exception occurred
4332             */
4333            @Override
4334            public void updateGroups(
4335                            long userId, long[] newGroupIds, ServiceContext serviceContext)
4336                    throws PortalException, SystemException {
4337    
4338                    boolean indexingEnabled = true;
4339    
4340                    if (serviceContext != null) {
4341                            indexingEnabled = serviceContext.isIndexingEnabled();
4342                    }
4343    
4344                    updateGroups(userId, newGroupIds, serviceContext, indexingEnabled);
4345            }
4346    
4347            /**
4348             * Updates a user account that was automatically created when a guest user
4349             * participated in an action (e.g. posting a comment) and only provided his
4350             * name and email address.
4351             *
4352             * @param  creatorUserId the primary key of the creator
4353             * @param  companyId the primary key of the user's company
4354             * @param  autoPassword whether a password should be automatically generated
4355             *         for the user
4356             * @param  password1 the user's password
4357             * @param  password2 the user's password confirmation
4358             * @param  autoScreenName whether a screen name should be automatically
4359             *         generated for the user
4360             * @param  screenName the user's screen name
4361             * @param  emailAddress the user's email address
4362             * @param  facebookId the user's facebook ID
4363             * @param  openId the user's OpenID
4364             * @param  locale the user's locale
4365             * @param  firstName the user's first name
4366             * @param  middleName the user's middle name
4367             * @param  lastName the user's last name
4368             * @param  prefixId the user's name prefix ID
4369             * @param  suffixId the user's name suffix ID
4370             * @param  male whether the user is male
4371             * @param  birthdayMonth the user's birthday month (0-based, meaning 0 for
4372             *         January)
4373             * @param  birthdayDay the user's birthday day
4374             * @param  birthdayYear the user's birthday year
4375             * @param  jobTitle the user's job title
4376             * @param  updateUserInformation whether to update the user's information
4377             * @param  sendEmail whether to send the user an email notification about
4378             *         their new account
4379             * @param  serviceContext the service context to be applied (optionally
4380             *         <code>null</code>). Can set expando bridge attributes for the
4381             *         user.
4382             * @return the user
4383             * @throws PortalException if the user's information was invalid
4384             * @throws SystemException if a system exception occurred
4385             */
4386            @Override
4387            public User updateIncompleteUser(
4388                            long creatorUserId, long companyId, boolean autoPassword,
4389                            String password1, String password2, boolean autoScreenName,
4390                            String screenName, String emailAddress, long facebookId,
4391                            String openId, Locale locale, String firstName, String middleName,
4392                            String lastName, int prefixId, int suffixId, boolean male,
4393                            int birthdayMonth, int birthdayDay, int birthdayYear,
4394                            String jobTitle, boolean updateUserInformation, boolean sendEmail,
4395                            ServiceContext serviceContext)
4396                    throws PortalException, SystemException {
4397    
4398                    User user = getUserByEmailAddress(companyId, emailAddress);
4399    
4400                    if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
4401                            throw new PortalException("Invalid user status");
4402                    }
4403    
4404                    User defaultUser = getDefaultUser(companyId);
4405    
4406                    if (facebookId > 0) {
4407                            autoPassword = false;
4408    
4409                            if ((password1 == null) || (password2 == null)) {
4410                                    password1 = PwdGenerator.getPassword();
4411                                    password2 = password1;
4412                            }
4413    
4414                            sendEmail = false;
4415                    }
4416    
4417                    if (updateUserInformation) {
4418                            autoScreenName = false;
4419    
4420                            if (PrefsPropsUtil.getBoolean(
4421                                            companyId,
4422                                            PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
4423    
4424                                    autoScreenName = true;
4425                            }
4426    
4427                            validate(
4428                                    companyId, user.getUserId(), autoPassword, password1, password2,
4429                                    autoScreenName, screenName, emailAddress, openId, firstName,
4430                                    middleName, lastName, null);
4431    
4432                            if (!autoPassword) {
4433                                    if (Validator.isNull(password1) ||
4434                                            Validator.isNull(password2)) {
4435                                                    throw new UserPasswordException(
4436                                                            UserPasswordException.PASSWORD_INVALID);
4437                                    }
4438                            }
4439    
4440                            if (autoScreenName) {
4441                                    ScreenNameGenerator screenNameGenerator =
4442                                            ScreenNameGeneratorFactory.getInstance();
4443    
4444                                    try {
4445                                            screenName = screenNameGenerator.generate(
4446                                                    companyId, user.getUserId(), emailAddress);
4447                                    }
4448                                    catch (Exception e) {
4449                                            throw new SystemException(e);
4450                                    }
4451                            }
4452    
4453                            FullNameGenerator fullNameGenerator =
4454                                    FullNameGeneratorFactory.getInstance();
4455    
4456                            String fullName = fullNameGenerator.getFullName(
4457                                    firstName, middleName, lastName);
4458    
4459                            String greeting = LanguageUtil.format(
4460                                    locale, "welcome-x", " " + fullName, false);
4461    
4462                            if (Validator.isNotNull(password1)) {
4463                                    user.setPassword(PasswordEncryptorUtil.encrypt(password1));
4464                                    user.setPasswordUnencrypted(password1);
4465                            }
4466    
4467                            user.setPasswordEncrypted(true);
4468    
4469                            PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
4470    
4471                            if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
4472                                    passwordPolicy.isChangeRequired()) {
4473    
4474                                    user.setPasswordReset(true);
4475                            }
4476                            else {
4477                                    user.setPasswordReset(false);
4478                            }
4479    
4480                            user.setScreenName(screenName);
4481                            user.setFacebookId(facebookId);
4482                            user.setOpenId(openId);
4483                            user.setLanguageId(locale.toString());
4484                            user.setTimeZoneId(defaultUser.getTimeZoneId());
4485                            user.setGreeting(greeting);
4486                            user.setFirstName(firstName);
4487                            user.setMiddleName(middleName);
4488                            user.setLastName(lastName);
4489                            user.setJobTitle(jobTitle);
4490                            user.setExpandoBridgeAttributes(serviceContext);
4491    
4492                            Date birthday = getBirthday(
4493                                    birthdayMonth, birthdayDay, birthdayYear);
4494    
4495                            Contact contact = user.getContact();
4496    
4497                            contact.setFirstName(firstName);
4498                            contact.setMiddleName(middleName);
4499                            contact.setLastName(lastName);
4500                            contact.setPrefixId(prefixId);
4501                            contact.setSuffixId(suffixId);
4502                            contact.setMale(male);
4503                            contact.setBirthday(birthday);
4504                            contact.setJobTitle(jobTitle);
4505    
4506                            contactPersistence.update(contact, serviceContext);
4507    
4508                            // Indexer
4509    
4510                            Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
4511                                    User.class);
4512    
4513                            indexer.reindex(user);
4514                    }
4515    
4516                    user.setStatus(WorkflowConstants.STATUS_DRAFT);
4517    
4518                    userPersistence.update(user, serviceContext);
4519    
4520                    // Workflow
4521    
4522                    long workflowUserId = creatorUserId;
4523    
4524                    if (workflowUserId == user.getUserId()) {
4525                            workflowUserId = defaultUser.getUserId();
4526                    }
4527    
4528                    ServiceContext workflowServiceContext = serviceContext;
4529    
4530                    if (workflowServiceContext == null) {
4531                            workflowServiceContext = new ServiceContext();
4532                    }
4533    
4534                    workflowServiceContext.setAttribute("autoPassword", autoPassword);
4535                    workflowServiceContext.setAttribute("passwordUnencrypted", password1);
4536                    workflowServiceContext.setAttribute("sendEmail", sendEmail);
4537    
4538                    WorkflowHandlerRegistryUtil.startWorkflowInstance(
4539                            companyId, workflowUserId, User.class.getName(), user.getUserId(),
4540                            user, workflowServiceContext);
4541    
4542                    return getUserByEmailAddress(companyId, emailAddress);
4543            }
4544    
4545            /**
4546             * Updates the user's job title.
4547             *
4548             * @param  userId the primary key of the user
4549             * @param  jobTitle the user's job title
4550             * @return the user
4551             * @throws PortalException if a user with the primary key could not be found
4552             *         or if a contact could not be found matching the user's contact ID
4553             * @throws SystemException if a system exception occurred
4554             */
4555            @Override
4556            public User updateJobTitle(long userId, String jobTitle)
4557                    throws PortalException, SystemException {
4558    
4559                    User user = userPersistence.findByPrimaryKey(userId);
4560    
4561                    user.setJobTitle(jobTitle);
4562    
4563                    userPersistence.update(user);
4564    
4565                    Contact contact = contactPersistence.findByPrimaryKey(
4566                            user.getContactId());
4567    
4568                    contact.setJobTitle(jobTitle);
4569    
4570                    contactPersistence.update(contact);
4571    
4572                    return user;
4573            }
4574    
4575            /**
4576             * Updates the user's last login with the current time and the IP address.
4577             *
4578             * @param  userId the primary key of the user
4579             * @param  loginIP the IP address the user logged in from
4580             * @return the user
4581             * @throws PortalException if a user with the primary key could not be found
4582             * @throws SystemException if a system exception occurred
4583             */
4584            @Override
4585            public User updateLastLogin(long userId, String loginIP)
4586                    throws PortalException, SystemException {
4587    
4588                    User user = userPersistence.findByPrimaryKey(userId);
4589    
4590                    Date lastLoginDate = user.getLoginDate();
4591    
4592                    if (lastLoginDate == null) {
4593                            lastLoginDate = new Date();
4594                    }
4595    
4596                    user.setLoginDate(new Date());
4597                    user.setLoginIP(loginIP);
4598                    user.setLastLoginDate(lastLoginDate);
4599                    user.setLastLoginIP(user.getLoginIP());
4600    
4601                    resetFailedLoginAttempts(user, true);
4602    
4603                    return user;
4604            }
4605    
4606            /**
4607             * Updates whether the user is locked out from logging in.
4608             *
4609             * @param  user the user
4610             * @param  lockout whether the user is locked out
4611             * @return the user
4612             * @throws PortalException if a portal exception occurred
4613             * @throws SystemException if a system exception occurred
4614             */
4615            @Override
4616            public User updateLockout(User user, boolean lockout)
4617                    throws PortalException, SystemException {
4618    
4619                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
4620    
4621                    if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
4622                            return user;
4623                    }
4624    
4625                    Date lockoutDate = null;
4626    
4627                    if (lockout) {
4628                            lockoutDate = new Date();
4629                    }
4630    
4631                    user.setLockout(lockout);
4632                    user.setLockoutDate(lockoutDate);
4633    
4634                    if (!lockout) {
4635                            user.setLastFailedLoginDate(lockoutDate);
4636                            user.setFailedLoginAttempts(0);
4637                    }
4638    
4639                    userPersistence.update(user);
4640    
4641                    return user;
4642            }
4643    
4644            /**
4645             * Updates whether the user is locked out from logging in.
4646             *
4647             * @param  companyId the primary key of the user's company
4648             * @param  emailAddress the user's email address
4649             * @param  lockout whether the user is locked out
4650             * @return the user
4651             * @throws PortalException if a user with the email address could not be
4652             *         found
4653             * @throws SystemException if a system exception occurred
4654             */
4655            @Override
4656            public User updateLockoutByEmailAddress(
4657                            long companyId, String emailAddress, boolean lockout)
4658                    throws PortalException, SystemException {
4659    
4660                    User user = getUserByEmailAddress(companyId, emailAddress);
4661    
4662                    return updateLockout(user, lockout);
4663            }
4664    
4665            /**
4666             * Updates whether the user is locked out from logging in.
4667             *
4668             * @param  userId the primary key of the user
4669             * @param  lockout whether the user is locked out
4670             * @return the user
4671             * @throws PortalException if a user with the primary key could not be found
4672             * @throws SystemException if a system exception occurred
4673             */
4674            @Override
4675            public User updateLockoutById(long userId, boolean lockout)
4676                    throws PortalException, SystemException {
4677    
4678                    User user = userPersistence.findByPrimaryKey(userId);
4679    
4680                    return updateLockout(user, lockout);
4681            }
4682    
4683            /**
4684             * Updates whether the user is locked out from logging in.
4685             *
4686             * @param  companyId the primary key of the user's company
4687             * @param  screenName the user's screen name
4688             * @param  lockout whether the user is locked out
4689             * @return the user
4690             * @throws PortalException if a user with the screen name could not be found
4691             * @throws SystemException if a system exception occurred
4692             */
4693            @Override
4694            public User updateLockoutByScreenName(
4695                            long companyId, String screenName, boolean lockout)
4696                    throws PortalException, SystemException {
4697    
4698                    User user = getUserByScreenName(companyId, screenName);
4699    
4700                    return updateLockout(user, lockout);
4701            }
4702    
4703            /**
4704             * Updates the user's modified date.
4705             *
4706             * @param  userId the primary key of the user
4707             * @param  modifiedDate the new modified date
4708             * @return the user
4709             * @throws PortalException if a user with the primary key could not be found
4710             * @throws SystemException if a system exception occurred
4711             */
4712            @Override
4713            public User updateModifiedDate(long userId, Date modifiedDate)
4714                    throws PortalException, SystemException {
4715    
4716                    User user = userPersistence.findByPrimaryKey(userId);
4717    
4718                    user.setModifiedDate(modifiedDate);
4719    
4720                    userPersistence.update(user);
4721    
4722                    return user;
4723            }
4724    
4725            /**
4726             * Updates the user's OpenID.
4727             *
4728             * @param  userId the primary key of the user
4729             * @param  openId the new OpenID
4730             * @return the user
4731             * @throws PortalException if a user with the primary key could not be found
4732             * @throws SystemException if a system exception occurred
4733             */
4734            @Override
4735            public User updateOpenId(long userId, String openId)
4736                    throws PortalException, SystemException {
4737    
4738                    openId = openId.trim();
4739    
4740                    User user = userPersistence.findByPrimaryKey(userId);
4741    
4742                    user.setOpenId(openId);
4743    
4744                    userPersistence.update(user);
4745    
4746                    return user;
4747            }
4748    
4749            /**
4750             * Sets the organizations that the user is in, removing and adding
4751             * organizations as necessary.
4752             *
4753             * @param  userId the primary key of the user
4754             * @param  newOrganizationIds the primary keys of the organizations
4755             * @param  serviceContext the service context to be applied. Must set
4756             *         whether user indexing is enabled.
4757             * @throws PortalException if a user with the primary key could not be found
4758             * @throws SystemException if a system exception occurred
4759             */
4760            @Override
4761            public void updateOrganizations(
4762                            long userId, long[] newOrganizationIds,
4763                            ServiceContext serviceContext)
4764                    throws PortalException, SystemException {
4765    
4766                    updateOrganizations(
4767                            userId, newOrganizationIds, serviceContext.isIndexingEnabled());
4768            }
4769    
4770            /**
4771             * Updates the user's password without tracking or validation of the change.
4772             *
4773             * @param  userId the primary key of the user
4774             * @param  password1 the user's new password
4775             * @param  password2 the user's new password confirmation
4776             * @param  passwordReset whether the user should be asked to reset their
4777             *         password the next time they log in
4778             * @return the user
4779             * @throws PortalException if a user with the primary key could not be found
4780             * @throws SystemException if a system exception occurred
4781             */
4782            @Override
4783            public User updatePassword(
4784                            long userId, String password1, String password2,
4785                            boolean passwordReset)
4786                    throws PortalException, SystemException {
4787    
4788                    return updatePassword(
4789                            userId, password1, password2, passwordReset, false);
4790            }
4791    
4792            /**
4793             * Updates the user's password, optionally with tracking and validation of
4794             * the change.
4795             *
4796             * @param  userId the primary key of the user
4797             * @param  password1 the user's new password
4798             * @param  password2 the user's new password confirmation
4799             * @param  passwordReset whether the user should be asked to reset their
4800             *         password the next time they login
4801             * @param  silentUpdate whether the password should be updated without being
4802             *         tracked, or validated. Primarily used for password imports.
4803             * @return the user
4804             * @throws PortalException if a user with the primary key could not be found
4805             * @throws SystemException if a system exception occurred
4806             */
4807            @Override
4808            public User updatePassword(
4809                            long userId, String password1, String password2,
4810                            boolean passwordReset, boolean silentUpdate)
4811                    throws PortalException, SystemException {
4812    
4813                    User user = userPersistence.findByPrimaryKey(userId);
4814    
4815                    if (!silentUpdate) {
4816                            validatePassword(user.getCompanyId(), userId, password1, password2);
4817                    }
4818    
4819                    String oldEncPwd = user.getPassword();
4820    
4821                    if (!user.isPasswordEncrypted()) {
4822                            oldEncPwd = PasswordEncryptorUtil.encrypt(user.getPassword());
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                            passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
4871                    }
4872    
4873                    return user;
4874            }
4875    
4876            /**
4877             * Updates the user's password with manually input information. This method
4878             * should only be used when performing maintenance.
4879             *
4880             * @param  userId the primary key of the user
4881             * @param  password the user's new password
4882             * @param  passwordEncrypted the user's new encrypted password
4883             * @param  passwordReset whether the user should be asked to reset their
4884             *         password the next time they login
4885             * @param  passwordModifiedDate the new password modified date
4886             * @return the user
4887             * @throws PortalException if a user with the primary key could not be found
4888             * @throws SystemException if a system exception occurred
4889             */
4890            @Override
4891            public User updatePasswordManually(
4892                            long userId, String password, boolean passwordEncrypted,
4893                            boolean passwordReset, Date passwordModifiedDate)
4894                    throws PortalException, SystemException {
4895    
4896                    // This method should only be used to manually massage data
4897    
4898                    User user = userPersistence.findByPrimaryKey(userId);
4899    
4900                    user.setPassword(password);
4901                    user.setPasswordEncrypted(passwordEncrypted);
4902                    user.setPasswordReset(passwordReset);
4903                    user.setPasswordModifiedDate(passwordModifiedDate);
4904                    user.setDigest(StringPool.BLANK);
4905    
4906                    userPersistence.update(user);
4907    
4908                    return user;
4909            }
4910    
4911            /**
4912             * Updates whether the user should be asked to reset their password the next
4913             * time they login.
4914             *
4915             * @param  userId the primary key of the user
4916             * @param  passwordReset whether the user should be asked to reset their
4917             *         password the next time they login
4918             * @return the user
4919             * @throws PortalException if a user with the primary key could not be found
4920             * @throws SystemException if a system exception occurred
4921             */
4922            @Override
4923            public User updatePasswordReset(long userId, boolean passwordReset)
4924                    throws PortalException, SystemException {
4925    
4926                    User user = userPersistence.findByPrimaryKey(userId);
4927    
4928                    user.setPasswordReset(passwordReset);
4929    
4930                    userPersistence.update(user);
4931    
4932                    return user;
4933            }
4934    
4935            /**
4936             * Updates the user's portrait image.
4937             *
4938             * @param  userId the primary key of the user
4939             * @param  bytes the new portrait image data
4940             * @return the user
4941             * @throws PortalException if a user with the primary key could not be found
4942             *         or if the new portrait was invalid
4943             * @throws SystemException if a system exception occurred
4944             */
4945            @Override
4946            public User updatePortrait(long userId, byte[] bytes)
4947                    throws PortalException, SystemException {
4948    
4949                    User user = userPersistence.findByPrimaryKey(userId);
4950    
4951                    long imageMaxSize = PrefsPropsUtil.getLong(
4952                            PropsKeys.USERS_IMAGE_MAX_SIZE);
4953    
4954                    if ((imageMaxSize > 0) &&
4955                            ((bytes == null) || (bytes.length > imageMaxSize))) {
4956    
4957                            throw new UserPortraitSizeException();
4958                    }
4959    
4960                    long portraitId = user.getPortraitId();
4961    
4962                    if (portraitId <= 0) {
4963                            portraitId = counterLocalService.increment();
4964    
4965                            user.setPortraitId(portraitId);
4966                    }
4967    
4968                    try {
4969                            ImageBag imageBag = ImageToolUtil.read(bytes);
4970    
4971                            RenderedImage renderedImage = imageBag.getRenderedImage();
4972    
4973                            if (renderedImage == null) {
4974                                    throw new UserPortraitTypeException();
4975                            }
4976    
4977                            renderedImage = ImageToolUtil.scale(
4978                                    renderedImage, PropsValues.USERS_IMAGE_MAX_HEIGHT,
4979                                    PropsValues.USERS_IMAGE_MAX_WIDTH);
4980    
4981                            String contentType = imageBag.getType();
4982    
4983                            imageLocalService.updateImage(
4984                                    portraitId,
4985                                    ImageToolUtil.getBytes(renderedImage, contentType));
4986                    }
4987                    catch (IOException ioe) {
4988                            throw new ImageSizeException(ioe);
4989                    }
4990    
4991                    userPersistence.update(user);
4992    
4993                    return user;
4994            }
4995    
4996            /**
4997             * Updates the user's password reset question and answer.
4998             *
4999             * @param  userId the primary key of the user
5000             * @param  question the user's new password reset question
5001             * @param  answer the user's new password reset answer
5002             * @return the user
5003             * @throws PortalException if a user with the primary key could not be found
5004             *         or if the new question or answer were invalid
5005             * @throws SystemException if a system exception occurred
5006             */
5007            @Override
5008            public User updateReminderQuery(long userId, String question, String answer)
5009                    throws PortalException, SystemException {
5010    
5011                    validateReminderQuery(question, answer);
5012    
5013                    User user = userPersistence.findByPrimaryKey(userId);
5014    
5015                    user.setReminderQueryQuestion(question);
5016                    user.setReminderQueryAnswer(answer);
5017    
5018                    userPersistence.update(user);
5019    
5020                    return user;
5021            }
5022    
5023            /**
5024             * Updates the user's screen name.
5025             *
5026             * @param  userId the primary key of the user
5027             * @param  screenName the user's new screen name
5028             * @return the user
5029             * @throws PortalException if a user with the primary key could not be found
5030             *         or if the new screen name was invalid
5031             * @throws SystemException if a system exception occurred
5032             */
5033            @Override
5034            public User updateScreenName(long userId, String screenName)
5035                    throws PortalException, SystemException {
5036    
5037                    // User
5038    
5039                    User user = userPersistence.findByPrimaryKey(userId);
5040    
5041                    screenName = getLogin(screenName);
5042    
5043                    validateScreenName(user.getCompanyId(), userId, screenName);
5044    
5045                    if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
5046                            user.setDigest(StringPool.BLANK);
5047                    }
5048    
5049                    user.setScreenName(screenName);
5050    
5051                    userPersistence.update(user);
5052    
5053                    // Group
5054    
5055                    Group group = groupLocalService.getUserGroup(
5056                            user.getCompanyId(), userId);
5057    
5058                    group.setFriendlyURL(StringPool.SLASH + screenName);
5059    
5060                    groupPersistence.update(group);
5061    
5062                    return user;
5063            }
5064    
5065            /**
5066             * Updates the user's workflow status.
5067             *
5068             * @param      userId the primary key of the user
5069             * @param      status the user's new workflow status
5070             * @return     the user
5071             * @throws     PortalException if a user with the primary key could not be
5072             *             found
5073             * @throws     SystemException if a system exception occurred
5074             * @deprecated As of 7.0.0, replaced by {@link #updateStatus(long, int,
5075             *             ServiceContext)}
5076             */
5077            @Deprecated
5078            @Override
5079            public User updateStatus(long userId, int status)
5080                    throws PortalException, SystemException {
5081    
5082                    return updateStatus(userId, status, new ServiceContext());
5083            }
5084    
5085            /**
5086             * Updates the user's workflow status.
5087             *
5088             * @param  userId the primary key of the user
5089             * @param  status the user's new workflow status
5090             * @param  serviceContext the service context to be applied. You can specify
5091             *         an unencrypted custom password (used by an LDAP listener) for the
5092             *         user via attribute <code>passwordUnencrypted</code>.
5093             * @return the user
5094             * @throws PortalException if a user with the primary key could not be found
5095             * @throws SystemException if a system exception occurred
5096             */
5097            @Override
5098            public User updateStatus(
5099                            long userId, int status, ServiceContext serviceContext)
5100                    throws PortalException, SystemException {
5101    
5102                    User user = userPersistence.findByPrimaryKey(userId);
5103    
5104                    if ((status == WorkflowConstants.STATUS_APPROVED) &&
5105                            (user.getStatus() != WorkflowConstants.STATUS_APPROVED)) {
5106    
5107                            validateCompanyMaxUsers(user.getCompanyId());
5108                    }
5109    
5110                    String passwordUnencrypted = (String)serviceContext.getAttribute(
5111                            "passwordUnencrypted");
5112    
5113                    if (Validator.isNotNull(passwordUnencrypted)) {
5114                            user.setPasswordUnencrypted(passwordUnencrypted);
5115                    }
5116    
5117                    user.setStatus(status);
5118    
5119                    userPersistence.update(user);
5120    
5121                    reindex(user);
5122    
5123                    return user;
5124            }
5125    
5126            /**
5127             * Updates the user.
5128             *
5129             * @param  userId the primary key of the user
5130             * @param  oldPassword the user's old password
5131             * @param  newPassword1 the user's new password (optionally
5132             *         <code>null</code>)
5133             * @param  newPassword2 the user's new password confirmation (optionally
5134             *         <code>null</code>)
5135             * @param  passwordReset whether the user should be asked to reset their
5136             *         password the next time they login
5137             * @param  reminderQueryQuestion the user's new password reset question
5138             * @param  reminderQueryAnswer the user's new password reset answer
5139             * @param  screenName the user's new screen name
5140             * @param  emailAddress the user's new email address
5141             * @param  facebookId the user's new Facebook ID
5142             * @param  openId the user's new OpenID
5143             * @param  languageId the user's new language ID
5144             * @param  timeZoneId the user's new time zone ID
5145             * @param  greeting the user's new greeting
5146             * @param  comments the user's new comments
5147             * @param  firstName the user's new first name
5148             * @param  middleName the user's new middle name
5149             * @param  lastName the user's new last name
5150             * @param  prefixId the user's new name prefix ID
5151             * @param  suffixId the user's new name suffix ID
5152             * @param  male whether user is male
5153             * @param  birthdayMonth the user's new birthday month (0-based, meaning 0
5154             *         for January)
5155             * @param  birthdayDay the user's new birthday day
5156             * @param  birthdayYear the user's birthday year
5157             * @param  smsSn the user's new SMS screen name
5158             * @param  aimSn the user's new AIM screen name
5159             * @param  facebookSn the user's new Facebook screen name
5160             * @param  icqSn the user's new ICQ screen name
5161             * @param  jabberSn the user's new Jabber screen name
5162             * @param  msnSn the user's new MSN screen name
5163             * @param  mySpaceSn the user's new MySpace screen name
5164             * @param  skypeSn the user's new Skype screen name
5165             * @param  twitterSn the user's new Twitter screen name
5166             * @param  ymSn the user's new Yahoo! Messenger screen name
5167             * @param  jobTitle the user's new job title
5168             * @param  groupIds the primary keys of the user's groups
5169             * @param  organizationIds the primary keys of the user's organizations
5170             * @param  roleIds the primary keys of the user's roles
5171             * @param  userGroupRoles the user user's group roles
5172             * @param  userGroupIds the primary keys of the user's user groups
5173             * @param  serviceContext the service context to be applied (optionally
5174             *         <code>null</code>). Can set the UUID (with the <code>uuid</code>
5175             *         attribute), asset category IDs, asset tag names, and expando
5176             *         bridge attributes for the user.
5177             * @return the user
5178             * @throws PortalException if a user with the primary key could not be found
5179             *         or if the new information was invalid
5180             * @throws SystemException if a system exception occurred
5181             */
5182            @Override
5183            @SuppressWarnings("deprecation")
5184            public User updateUser(
5185                            long userId, String oldPassword, String newPassword1,
5186                            String newPassword2, boolean passwordReset,
5187                            String reminderQueryQuestion, String reminderQueryAnswer,
5188                            String screenName, String emailAddress, long facebookId,
5189                            String openId, String languageId, String timeZoneId,
5190                            String greeting, String comments, String firstName,
5191                            String middleName, String lastName, int prefixId, int suffixId,
5192                            boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
5193                            String smsSn, String aimSn, String facebookSn, String icqSn,
5194                            String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
5195                            String twitterSn, String ymSn, String jobTitle, long[] groupIds,
5196                            long[] organizationIds, long[] roleIds,
5197                            List<UserGroupRole> userGroupRoles, long[] userGroupIds,
5198                            ServiceContext serviceContext)
5199                    throws PortalException, SystemException {
5200    
5201                    // User
5202    
5203                    User user = userPersistence.findByPrimaryKey(userId);
5204                    Company company = companyPersistence.findByPrimaryKey(
5205                            user.getCompanyId());
5206                    String password = oldPassword;
5207                    screenName = getLogin(screenName);
5208                    emailAddress = StringUtil.toLowerCase(emailAddress.trim());
5209                    openId = openId.trim();
5210                    String oldFullName = user.getFullName();
5211                    aimSn = StringUtil.toLowerCase(aimSn.trim());
5212                    facebookSn = StringUtil.toLowerCase(facebookSn.trim());
5213                    icqSn = StringUtil.toLowerCase(icqSn.trim());
5214                    jabberSn = StringUtil.toLowerCase(jabberSn.trim());
5215                    msnSn = StringUtil.toLowerCase(msnSn.trim());
5216                    mySpaceSn = StringUtil.toLowerCase(mySpaceSn.trim());
5217                    skypeSn = StringUtil.toLowerCase(skypeSn.trim());
5218                    twitterSn = StringUtil.toLowerCase(twitterSn.trim());
5219                    ymSn = StringUtil.toLowerCase(ymSn.trim());
5220                    Date now = new Date();
5221    
5222                    EmailAddressGenerator emailAddressGenerator =
5223                            EmailAddressGeneratorFactory.getInstance();
5224    
5225                    if (emailAddressGenerator.isGenerated(emailAddress)) {
5226                            emailAddress = StringPool.BLANK;
5227                    }
5228    
5229                    if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
5230                            Validator.isNull(emailAddress)) {
5231    
5232                            emailAddress = emailAddressGenerator.generate(
5233                                    user.getCompanyId(), userId);
5234                    }
5235    
5236                    validate(
5237                            userId, screenName, emailAddress, openId, firstName, middleName,
5238                            lastName, smsSn);
5239    
5240                    if (Validator.isNotNull(newPassword1) ||
5241                            Validator.isNotNull(newPassword2)) {
5242    
5243                            user = updatePassword(
5244                                    userId, newPassword1, newPassword2, passwordReset);
5245    
5246                            password = newPassword1;
5247    
5248                            user.setDigest(StringPool.BLANK);
5249                    }
5250    
5251                    user.setModifiedDate(now);
5252    
5253                    if (user.getContactId() <= 0) {
5254                            user.setContactId(counterLocalService.increment());
5255                    }
5256    
5257                    user.setPasswordReset(passwordReset);
5258    
5259                    if (Validator.isNotNull(reminderQueryQuestion) &&
5260                            Validator.isNotNull(reminderQueryAnswer)) {
5261    
5262                            user.setReminderQueryQuestion(reminderQueryQuestion);
5263                            user.setReminderQueryAnswer(reminderQueryAnswer);
5264                    }
5265    
5266                    if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
5267                            user.setScreenName(screenName);
5268    
5269                            user.setDigest(StringPool.BLANK);
5270                    }
5271    
5272                    boolean sendEmailAddressVerification = false;
5273    
5274                    if (company.isStrangersVerify() &&
5275                            !StringUtil.equalsIgnoreCase(
5276                                    emailAddress, user.getEmailAddress())) {
5277    
5278                            sendEmailAddressVerification = true;
5279                    }
5280                    else {
5281                            setEmailAddress(
5282                                    user, password, firstName, middleName, lastName, emailAddress);
5283                    }
5284    
5285                    if (serviceContext != null) {
5286                            String uuid = serviceContext.getUuid();
5287    
5288                            if (Validator.isNotNull(uuid)) {
5289                                    user.setUuid(uuid);
5290                            }
5291                    }
5292    
5293                    user.setFacebookId(facebookId);
5294    
5295                    Long ldapServerId = null;
5296    
5297                    if (serviceContext != null) {
5298                            ldapServerId = (Long)serviceContext.getAttribute("ldapServerId");
5299                    }
5300    
5301                    if (ldapServerId != null) {
5302                            user.setLdapServerId(ldapServerId);
5303                    }
5304    
5305                    user.setOpenId(openId);
5306                    user.setLanguageId(languageId);
5307                    user.setTimeZoneId(timeZoneId);
5308                    user.setGreeting(greeting);
5309                    user.setComments(comments);
5310                    user.setFirstName(firstName);
5311                    user.setMiddleName(middleName);
5312                    user.setLastName(lastName);
5313                    user.setJobTitle(jobTitle);
5314                    user.setExpandoBridgeAttributes(serviceContext);
5315    
5316                    userPersistence.update(user, serviceContext);
5317    
5318                    // Contact
5319    
5320                    Date birthday = getBirthday(birthdayMonth, birthdayDay, birthdayYear);
5321    
5322                    long contactId = user.getContactId();
5323    
5324                    Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
5325    
5326                    if (contact == null) {
5327                            contact = contactPersistence.create(contactId);
5328    
5329                            contact.setCompanyId(user.getCompanyId());
5330                            contact.setUserName(StringPool.BLANK);
5331                            contact.setCreateDate(now);
5332                            contact.setClassName(User.class.getName());
5333                            contact.setClassPK(user.getUserId());
5334                            contact.setAccountId(company.getAccountId());
5335                            contact.setParentContactId(
5336                                    ContactConstants.DEFAULT_PARENT_CONTACT_ID);
5337                    }
5338    
5339                    contact.setModifiedDate(now);
5340                    contact.setEmailAddress(user.getEmailAddress());
5341                    contact.setFirstName(firstName);
5342                    contact.setMiddleName(middleName);
5343                    contact.setLastName(lastName);
5344                    contact.setPrefixId(prefixId);
5345                    contact.setSuffixId(suffixId);
5346                    contact.setMale(male);
5347                    contact.setBirthday(birthday);
5348                    contact.setSmsSn(smsSn);
5349                    contact.setAimSn(aimSn);
5350                    contact.setFacebookSn(facebookSn);
5351                    contact.setIcqSn(icqSn);
5352                    contact.setJabberSn(jabberSn);
5353                    contact.setMsnSn(msnSn);
5354                    contact.setMySpaceSn(mySpaceSn);
5355                    contact.setSkypeSn(skypeSn);
5356                    contact.setTwitterSn(twitterSn);
5357                    contact.setYmSn(ymSn);
5358                    contact.setJobTitle(jobTitle);
5359    
5360                    contactPersistence.update(contact, serviceContext);
5361    
5362                    // Group
5363    
5364                    Group group = groupLocalService.getUserGroup(
5365                            user.getCompanyId(), userId);
5366    
5367                    group.setFriendlyURL(StringPool.SLASH + screenName);
5368    
5369                    groupPersistence.update(group);
5370    
5371                    // Groups and organizations
5372    
5373                    // See LPS-33205. Cache the user's list of user group roles because
5374                    // adding or removing groups may add or remove user group roles
5375                    // depending on the site default user associations.
5376    
5377                    List<UserGroupRole> previousUserGroupRoles =
5378                            userGroupRolePersistence.findByUserId(userId);
5379    
5380                    updateGroups(userId, groupIds, serviceContext, false);
5381                    updateOrganizations(userId, organizationIds, false);
5382    
5383                    // Roles
5384    
5385                    if (roleIds != null) {
5386                            roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
5387    
5388                            userPersistence.setRoles(userId, roleIds);
5389                    }
5390    
5391                    // User group roles
5392    
5393                    updateUserGroupRoles(
5394                            user, groupIds, organizationIds, userGroupRoles,
5395                            previousUserGroupRoles);
5396    
5397                    // User groups
5398    
5399                    if (userGroupIds != null) {
5400                            if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
5401                                    userGroupLocalService.copyUserGroupLayouts(
5402                                            userGroupIds, userId);
5403                            }
5404    
5405                            userPersistence.setUserGroups(userId, userGroupIds);
5406                    }
5407    
5408                    if (!hasManageLayoutsRolePermission(user) &&
5409                            !hasManageLayoutsOrgPermission(organizationIds, user) &&
5410                            !hasManageLayoutsSitePermission(groupIds, user)) {
5411    
5412                            unsetToggleControlsPreference(userId);
5413                    }
5414    
5415                    // Announcements
5416    
5417                    announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
5418    
5419                    // Asset
5420    
5421                    if (serviceContext != null) {
5422                            updateAsset(
5423                                    userId, user, serviceContext.getAssetCategoryIds(),
5424                                    serviceContext.getAssetTagNames());
5425                    }
5426    
5427                    // Message boards
5428    
5429                    if (GetterUtil.getBoolean(
5430                                    PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
5431                            !oldFullName.equals(user.getFullName())) {
5432    
5433                            mbMessageLocalService.updateUserName(userId, user.getFullName());
5434                    }
5435    
5436                    // Indexer
5437    
5438                    if ((serviceContext == null) || serviceContext.isIndexingEnabled()) {
5439                            Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
5440                                    User.class);
5441    
5442                            indexer.reindex(user);
5443                    }
5444    
5445                    // Email address verification
5446    
5447                    if ((serviceContext != null) && sendEmailAddressVerification) {
5448                            sendEmailAddressVerification(user, emailAddress, serviceContext);
5449                    }
5450    
5451                    // Permission cache
5452    
5453                    PermissionCacheUtil.clearCache(userId);
5454    
5455                    return user;
5456            }
5457    
5458            /**
5459             * Verifies the email address of the ticket.
5460             *
5461             * @param  ticketKey the ticket key
5462             * @throws PortalException if a ticket matching the ticket key could not be
5463             *         found, if the ticket has expired, if the ticket is an email
5464             *         address ticket, or if the email address is invalid
5465             * @throws SystemException if a system exception occurred
5466             */
5467            @Override
5468            public void verifyEmailAddress(String ticketKey)
5469                    throws PortalException, SystemException {
5470    
5471                    Ticket ticket = ticketLocalService.getTicket(ticketKey);
5472    
5473                    if (ticket.isExpired() ||
5474                            (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
5475    
5476                            throw new NoSuchTicketException("{ticketKey=" + ticketKey + "}");
5477                    }
5478    
5479                    User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
5480    
5481                    String emailAddress = ticket.getExtraInfo();
5482    
5483                    emailAddress = StringUtil.toLowerCase(emailAddress).trim();
5484    
5485                    if (!emailAddress.equals(user.getEmailAddress())) {
5486                            if (userPersistence.fetchByC_EA(
5487                                            user.getCompanyId(), emailAddress) != null) {
5488    
5489                                    throw new DuplicateUserEmailAddressException(
5490                                            "{userId=" + user.getUserId() + "}");
5491                            }
5492    
5493                            setEmailAddress(
5494                                    user, StringPool.BLANK, user.getFirstName(),
5495                                    user.getMiddleName(), user.getLastName(), emailAddress);
5496    
5497                            Contact contact = user.getContact();
5498    
5499                            contact.setEmailAddress(user.getEmailAddress());
5500    
5501                            contactPersistence.update(contact);
5502                    }
5503    
5504                    user.setEmailAddressVerified(true);
5505    
5506                    userPersistence.update(user);
5507    
5508                    ticketLocalService.deleteTicket(ticket);
5509            }
5510    
5511            protected void addDefaultRolesAndTeams(long groupId, long[] userIds)
5512                    throws PortalException, SystemException {
5513    
5514                    List<Role> defaultSiteRoles = new ArrayList<Role>();
5515    
5516                    Group group = groupLocalService.getGroup(groupId);
5517    
5518                    UnicodeProperties typeSettingsProperties =
5519                            group.getTypeSettingsProperties();
5520    
5521                    long[] defaultSiteRoleIds = StringUtil.split(
5522                            typeSettingsProperties.getProperty("defaultSiteRoleIds"), 0L);
5523    
5524                    for (long defaultSiteRoleId : defaultSiteRoleIds) {
5525                            Role defaultSiteRole = rolePersistence.fetchByPrimaryKey(
5526                                    defaultSiteRoleId);
5527    
5528                            if (defaultSiteRole == null) {
5529                                    if (_log.isWarnEnabled()) {
5530                                            _log.warn("Unable to find role " + defaultSiteRoleId);
5531                                    }
5532    
5533                                    continue;
5534                            }
5535    
5536                            defaultSiteRoles.add(defaultSiteRole);
5537                    }
5538    
5539                    List<Team> defaultTeams = new ArrayList<Team>();
5540    
5541                    long[] defaultTeamIds = StringUtil.split(
5542                            typeSettingsProperties.getProperty("defaultTeamIds"), 0L);
5543    
5544                    for (long defaultTeamId : defaultTeamIds) {
5545                            Team defaultTeam = teamPersistence.findByPrimaryKey(defaultTeamId);
5546    
5547                            if (defaultTeam == null) {
5548                                    if (_log.isWarnEnabled()) {
5549                                            _log.warn("Unable to find team " + defaultTeamId);
5550                                    }
5551    
5552                                    continue;
5553                            }
5554    
5555                            defaultTeams.add(defaultTeam);
5556                    }
5557    
5558                    for (long userId : userIds) {
5559                            Set<Long> userRoleIdsSet = new HashSet<Long>();
5560    
5561                            for (Role role : defaultSiteRoles) {
5562                                    if (!userPersistence.containsRole(userId, role.getRoleId())) {
5563                                            userRoleIdsSet.add(role.getRoleId());
5564                                    }
5565                            }
5566    
5567                            long[] userRoleIds = ArrayUtil.toArray(
5568                                    userRoleIdsSet.toArray(new Long[userRoleIdsSet.size()]));
5569    
5570                            userGroupRoleLocalService.addUserGroupRoles(
5571                                    userId, groupId, userRoleIds);
5572    
5573                            Set<Long> userTeamIdsSet = new HashSet<Long>();
5574    
5575                            for (Team team : defaultTeams) {
5576                                    if (!userPersistence.containsTeam(userId, team.getTeamId())) {
5577                                            userTeamIdsSet.add(team.getTeamId());
5578                                    }
5579                            }
5580    
5581                            long[] userTeamIds = ArrayUtil.toArray(
5582                                    userTeamIdsSet.toArray(new Long[userTeamIdsSet.size()]));
5583    
5584                            userPersistence.addTeams(userId, userTeamIds);
5585                    }
5586            }
5587    
5588            /**
5589             * Attempts to authenticate the user by their login and password, while
5590             * using the AuthPipeline.
5591             *
5592             * <p>
5593             * Authentication type specifies what <code>login</code> contains.The valid
5594             * values are:
5595             * </p>
5596             *
5597             * <ul>
5598             * <li>
5599             * <code>CompanyConstants.AUTH_TYPE_EA</code> - <code>login</code> is the
5600             * user's email address
5601             * </li>
5602             * <li>
5603             * <code>CompanyConstants.AUTH_TYPE_SN</code> - <code>login</code> is the
5604             * user's screen name
5605             * </li>
5606             * <li>
5607             * <code>CompanyConstants.AUTH_TYPE_ID</code> - <code>login</code> is the
5608             * user's primary key
5609             * </li>
5610             * </ul>
5611             *
5612             * @param  companyId the primary key of the user's company
5613             * @param  login either the user's email address, screen name, or primary
5614             *         key depending on the value of <code>authType</code>
5615             * @param  password the user's password
5616             * @param  authType the type of authentication to perform
5617             * @param  headerMap the header map from the authentication request
5618             * @param  parameterMap the parameter map from the authentication request
5619             * @param  resultsMap the map of authentication results (may be nil). After
5620             *         a succesful authentication the user's primary key will be placed
5621             *         under the key <code>userId</code>.
5622             * @return the authentication status. This can be {@link
5623             *         com.liferay.portal.security.auth.Authenticator#FAILURE}
5624             *         indicating that the user's credentials are invalid, {@link
5625             *         com.liferay.portal.security.auth.Authenticator#SUCCESS}
5626             *         indicating a successful login, or {@link
5627             *         com.liferay.portal.security.auth.Authenticator#DNE} indicating
5628             *         that a user with that login does not exist.
5629             * @throws PortalException if <code>login</code> or <code>password</code>
5630             *         was <code>null</code>
5631             * @throws SystemException if a system exception occurred
5632             * @see    com.liferay.portal.security.auth.AuthPipeline
5633             */
5634            protected int authenticate(
5635                            long companyId, String login, String password, String authType,
5636                            Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
5637                            Map<String, Object> resultsMap)
5638                    throws PortalException, SystemException {
5639    
5640                    if (PropsValues.AUTH_LOGIN_DISABLED) {
5641                            return Authenticator.FAILURE;
5642                    }
5643    
5644                    login = StringUtil.toLowerCase(login.trim());
5645    
5646                    long userId = GetterUtil.getLong(login);
5647    
5648                    // User input validation
5649    
5650                    if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5651                            if (Validator.isNull(login)) {
5652                                    throw new UserEmailAddressException();
5653                            }
5654                    }
5655                    else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5656                            if (Validator.isNull(login)) {
5657                                    throw new UserScreenNameException();
5658                            }
5659                    }
5660                    else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5661                            if (Validator.isNull(login)) {
5662                                    throw new UserIdException();
5663                            }
5664                    }
5665    
5666                    if (Validator.isNull(password)) {
5667                            throw new UserPasswordException(
5668                                    UserPasswordException.PASSWORD_INVALID);
5669                    }
5670    
5671                    int authResult = Authenticator.FAILURE;
5672    
5673                    // Pre-authentication pipeline
5674    
5675                    if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5676                            authResult = AuthPipeline.authenticateByEmailAddress(
5677                                    PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5678                                    headerMap, parameterMap);
5679                    }
5680                    else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5681                            authResult = AuthPipeline.authenticateByScreenName(
5682                                    PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
5683                                    headerMap, parameterMap);
5684                    }
5685                    else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5686                            authResult = AuthPipeline.authenticateByUserId(
5687                                    PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
5688                                    headerMap, parameterMap);
5689                    }
5690    
5691                    // Get user
5692    
5693                    User user = null;
5694    
5695                    if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5696                            user = fetchUserByEmailAddress(companyId, login);
5697                    }
5698                    else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5699                            user = fetchUserByScreenName(companyId, login);
5700                    }
5701                    else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5702                            user = userPersistence.fetchByPrimaryKey(GetterUtil.getLong(login));
5703                    }
5704    
5705                    if (user == null) {
5706                            return Authenticator.DNE;
5707                    }
5708    
5709                    if (!isUserAllowedToAuthenticate(user)) {
5710                            return Authenticator.FAILURE;
5711                    }
5712    
5713                    if (!user.isPasswordEncrypted()) {
5714                            user.setPassword(PasswordEncryptorUtil.encrypt(user.getPassword()));
5715                            user.setPasswordEncrypted(true);
5716    
5717                            userPersistence.update(user);
5718                    }
5719    
5720                    // Authenticate against the User_ table
5721    
5722                    boolean skipLiferayCheck = false;
5723    
5724                    if (authResult == Authenticator.SKIP_LIFERAY_CHECK) {
5725                            authResult = Authenticator.SUCCESS;
5726    
5727                            skipLiferayCheck = true;
5728                    }
5729                    else if ((authResult == Authenticator.SUCCESS) &&
5730                                     PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5731    
5732                            boolean authenticated = PwdAuthenticator.authenticate(
5733                                    login, password, user.getPassword());
5734    
5735                            if (authenticated) {
5736                                    authResult = Authenticator.SUCCESS;
5737                            }
5738                            else {
5739                                    authResult = Authenticator.FAILURE;
5740                            }
5741                    }
5742    
5743                    // Post-authentication pipeline
5744    
5745                    if (authResult == Authenticator.SUCCESS) {
5746                            if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5747                                    authResult = AuthPipeline.authenticateByEmailAddress(
5748                                            PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5749                                            headerMap, parameterMap);
5750                            }
5751                            else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5752                                    authResult = AuthPipeline.authenticateByScreenName(
5753                                            PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5754                                            headerMap, parameterMap);
5755                            }
5756                            else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5757                                    authResult = AuthPipeline.authenticateByUserId(
5758                                            PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5759                                            headerMap, parameterMap);
5760                            }
5761                    }
5762    
5763                    if (resultsMap != null) {
5764                            resultsMap.put("userId", user.getUserId());
5765                    }
5766    
5767                    if (authResult == Authenticator.SUCCESS) {
5768    
5769                            // Update digest
5770    
5771                            if (skipLiferayCheck ||
5772                                    !PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK ||
5773                                    Validator.isNull(user.getDigest())) {
5774    
5775                                    String digest = user.getDigest(password);
5776    
5777                                    user.setDigest(digest);
5778    
5779                                    userPersistence.update(user);
5780                            }
5781                    }
5782    
5783                    // Execute code triggered by authentication failure
5784    
5785                    if (authResult == Authenticator.FAILURE) {
5786                            authResult = handleAuthenticationFailure(
5787                                    login, authType, user, headerMap, parameterMap);
5788                    }
5789                    else {
5790                            resetFailedLoginAttempts(user);
5791                    }
5792    
5793                    // PLACEHOLDER 02
5794    
5795                    return authResult;
5796            }
5797    
5798            protected SearchContext buildSearchContext(
5799                    long companyId, String firstName, String middleName, String lastName,
5800                    String fullName, String screenName, String emailAddress, String street,
5801                    String city, String zip, String region, String country, int status,
5802                    LinkedHashMap<String, Object> params, boolean andSearch, int start,
5803                    int end, Sort sort) {
5804    
5805                    SearchContext searchContext = new SearchContext();
5806    
5807                    searchContext.setAndSearch(andSearch);
5808    
5809                    Map<String, Serializable> attributes =
5810                            new HashMap<String, Serializable>();
5811    
5812                    attributes.put("city", city);
5813                    attributes.put("country", country);
5814                    attributes.put("emailAddress", emailAddress);
5815                    attributes.put("firstName", firstName);
5816                    attributes.put("fullName", fullName);
5817                    attributes.put("lastName", lastName);
5818                    attributes.put("middleName", middleName);
5819                    attributes.put("params", params);
5820                    attributes.put("region", region);
5821                    attributes.put("screenName", screenName);
5822                    attributes.put("street", street);
5823                    attributes.put("status", status);
5824                    attributes.put("zip", zip);
5825    
5826                    searchContext.setAttributes(attributes);
5827    
5828                    searchContext.setCompanyId(companyId);
5829                    searchContext.setEnd(end);
5830    
5831                    if (params != null) {
5832                            String keywords = (String)params.remove("keywords");
5833    
5834                            if (Validator.isNotNull(keywords)) {
5835                                    searchContext.setKeywords(keywords);
5836                            }
5837                    }
5838    
5839                    QueryConfig queryConfig = new QueryConfig();
5840    
5841                    queryConfig.setHighlightEnabled(false);
5842                    queryConfig.setScoreEnabled(false);
5843    
5844                    searchContext.setQueryConfig(queryConfig);
5845    
5846                    if (sort != null) {
5847                            searchContext.setSorts(sort);
5848                    }
5849    
5850                    searchContext.setStart(start);
5851    
5852                    return searchContext;
5853            }
5854    
5855            protected Date getBirthday(
5856                            int birthdayMonth, int birthdayDay, int birthdayYear)
5857                    throws PortalException {
5858    
5859                    Date birthday = PortalUtil.getDate(
5860                            birthdayMonth, birthdayDay, birthdayYear,
5861                            ContactBirthdayException.class);
5862    
5863                    Date now = new Date();
5864    
5865                    if (birthday.after(now)) {
5866                            throw new ContactBirthdayException();
5867                    }
5868    
5869                    return birthday;
5870            }
5871    
5872            protected String getLogin(String login) {
5873                    return StringUtil.lowerCase(StringUtil.trim(login));
5874            }
5875    
5876            protected long[] getUserIds(List<User> users) {
5877                    long[] userIds = new long[users.size()];
5878    
5879                    for (int i = 0; i < users.size(); i++) {
5880                            User user = users.get(i);
5881    
5882                            userIds[i] = user.getUserId();
5883                    }
5884    
5885                    return userIds;
5886            }
5887    
5888            protected int handleAuthenticationFailure(
5889                    String login, String authType, User user,
5890                    Map<String, String[]> headerMap, Map<String, String[]> parameterMap) {
5891    
5892                    if (user == null) {
5893                            return Authenticator.DNE;
5894                    }
5895    
5896                    try {
5897                            if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5898                                    AuthPipeline.onFailureByEmailAddress(
5899                                            PropsKeys.AUTH_FAILURE, user.getCompanyId(), login,
5900                                            headerMap, parameterMap);
5901                            }
5902                            else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5903                                    AuthPipeline.onFailureByScreenName(
5904                                            PropsKeys.AUTH_FAILURE, user.getCompanyId(), login,
5905                                            headerMap, parameterMap);
5906                            }
5907                            else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5908                                    AuthPipeline.onFailureByUserId(
5909                                            PropsKeys.AUTH_FAILURE, user.getCompanyId(),
5910                                            user.getUserId(), headerMap, parameterMap);
5911                            }
5912    
5913                            user = userPersistence.fetchByPrimaryKey(user.getUserId());
5914    
5915                            if (user == null) {
5916                                    return Authenticator.DNE;
5917                            }
5918    
5919                            // Let LDAP handle max failure event
5920    
5921                            if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5922                                            user.getCompanyId())) {
5923    
5924                                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5925    
5926                                    user = userPersistence.fetchByPrimaryKey(user.getUserId());
5927    
5928                                    int failedLoginAttempts = user.getFailedLoginAttempts();
5929                                    int maxFailures = passwordPolicy.getMaxFailure();
5930    
5931                                    if ((failedLoginAttempts >= maxFailures) &&
5932                                            (maxFailures != 0)) {
5933    
5934                                            if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5935                                                    AuthPipeline.onMaxFailuresByEmailAddress(
5936                                                            PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
5937                                                            login, headerMap, parameterMap);
5938                                            }
5939                                            else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5940                                                    AuthPipeline.onMaxFailuresByScreenName(
5941                                                            PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
5942                                                            login, headerMap, parameterMap);
5943                                            }
5944                                            else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5945                                                    AuthPipeline.onMaxFailuresByUserId(
5946                                                            PropsKeys.AUTH_MAX_FAILURES, user.getCompanyId(),
5947                                                            user.getUserId(), headerMap, parameterMap);
5948                                            }
5949                                    }
5950                            }
5951                    }
5952                    catch (Exception e) {
5953                            _log.error(e, e);
5954                    }
5955    
5956                    return Authenticator.FAILURE;
5957            }
5958    
5959            protected boolean hasManageLayoutsPermission(
5960                    long groupId, PermissionChecker permissionChecker)
5961                            throws PortalException, SystemException {
5962    
5963                    return GroupPermissionUtil.contains(
5964                            permissionChecker, groupId, ActionKeys.MANAGE_LAYOUTS);
5965            }
5966    
5967            protected boolean hasManageLayoutsOrgPermission(
5968                    long[] organizationIds, User user)
5969                            throws PortalException, SystemException {
5970    
5971                    if (ArrayUtil.isEmpty(organizationIds)) {
5972                            return false;
5973                    }
5974    
5975                    try {
5976                            PermissionChecker permissionChecker =
5977                                    PermissionCheckerFactoryUtil.create(user);
5978    
5979                            long organizationClassId =
5980                                    ClassNameLocalServiceUtil.fetchClassNameId(
5981                                            Organization.class.getName());
5982    
5983                            for (long organizationId : organizationIds) {
5984                                    Group group = groupPersistence.fetchByC_C_C(
5985                                            user.getCompanyId(), organizationClassId, organizationId);
5986    
5987                                    if (hasManageLayoutsPermission(
5988                                                    group.getGroupId(), permissionChecker)) {
5989    
5990                                            return true;
5991                                    }
5992                            }
5993                    }
5994                    catch (Exception e) {
5995                    }
5996    
5997                    return false;
5998            }
5999    
6000            protected boolean hasManageLayoutsRolePermission(User user)
6001                    throws PortalException, SystemException {
6002    
6003                    try {
6004                            PermissionChecker permissionChecker =
6005                                    PermissionCheckerFactoryUtil.create(user);
6006    
6007                            return GroupPermissionUtil.contains(
6008                                    permissionChecker, ActionKeys.MANAGE_LAYOUTS);
6009                    }
6010                    catch (Exception e) {
6011                    }
6012    
6013                    return false;
6014            }
6015    
6016            protected boolean hasManageLayoutsSitePermission(long[] groupIds, User user)
6017                    throws PortalException, SystemException {
6018    
6019                    if (ArrayUtil.isEmpty(groupIds)) {
6020                            return false;
6021                    }
6022    
6023                    try {
6024                            PermissionChecker permissionChecker =
6025                                    PermissionCheckerFactoryUtil.create(user);
6026    
6027                            for (long groupId : groupIds) {
6028                                    if (hasManageLayoutsPermission(groupId, permissionChecker)) {
6029                                            return true;
6030                                    }
6031                            }
6032                    }
6033                    catch (Exception e) {
6034                    }
6035    
6036                    return false;
6037            }
6038    
6039            protected boolean isUserAllowedToAuthenticate(User user)
6040                    throws PortalException, SystemException {
6041    
6042                    if (user.isDefaultUser()) {
6043                            if (_log.isInfoEnabled()) {
6044                                    _log.info("Authentication is disabled for the default user");
6045                            }
6046    
6047                            return false;
6048                    }
6049                    else if (!user.isActive()) {
6050                            if (_log.isInfoEnabled()) {
6051                                    _log.info(
6052                                            "Authentication is disabled for inactive user " +
6053                                                    user.getUserId());
6054                            }
6055    
6056                            return false;
6057                    }
6058    
6059                    // Check password policy to see if the is account locked out or if the
6060                    // password is expired
6061    
6062                    checkLockout(user);
6063    
6064                    checkPasswordExpired(user);
6065    
6066                    return true;
6067            }
6068    
6069            protected boolean isUseCustomSQL(LinkedHashMap<String, Object> params) {
6070                    if ((params == null) || params.isEmpty()) {
6071                            return false;
6072                    }
6073    
6074                    for (String key : params.keySet()) {
6075                            if (!key.equals("inherit") &&
6076                                    !key.equals("usersGroups") &&
6077                                    !key.equals("usersOrgs") &&
6078                                    !key.equals("usersOrgsCount") &&
6079                                    !key.equals("usersRoles") &&
6080                                    !key.equals("usersTeams") &&
6081                                    !key.equals("usersUserGroups")) {
6082    
6083                                    return true;
6084                            }
6085                    }
6086    
6087                    Boolean inherit = (Boolean)params.get("inherit");
6088    
6089                    if ((inherit != null) && inherit) {
6090                            return true;
6091                    }
6092    
6093                    return false;
6094            }
6095    
6096            protected void reindex(final User user) {
6097                    final Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6098                            User.class);
6099    
6100                    Callable<Void> callable = new ShardCallable<Void>(
6101                            user.getCompanyId()) {
6102    
6103                            @Override
6104                            protected Void doCall() throws Exception {
6105                                    indexer.reindex(user);
6106    
6107                                    return null;
6108                            }
6109    
6110                    };
6111    
6112                    TransactionCommitCallbackRegistryUtil.registerCallback(callable);
6113            }
6114    
6115            protected void resetFailedLoginAttempts(User user) throws SystemException {
6116                    resetFailedLoginAttempts(user, false);
6117            }
6118    
6119            protected void resetFailedLoginAttempts(User user, boolean forceUpdate)
6120                    throws SystemException {
6121    
6122                    if (forceUpdate || (user.getFailedLoginAttempts() > 0)) {
6123                            user.setFailedLoginAttempts(0);
6124    
6125                            userPersistence.update(user);
6126                    }
6127            }
6128    
6129            protected Hits search(
6130                            long companyId, String firstName, String middleName,
6131                            String lastName, String fullName, String screenName,
6132                            String emailAddress, String street, String city, String zip,
6133                            String region, String country, int status,
6134                            LinkedHashMap<String, Object> params, boolean andSearch, int start,
6135                            int end, Sort sort)
6136                    throws SystemException {
6137    
6138                    try {
6139                            SearchContext searchContext = new SearchContext();
6140    
6141                            searchContext.setAndSearch(andSearch);
6142    
6143                            Map<String, Serializable> attributes =
6144                                    new HashMap<String, Serializable>();
6145    
6146                            attributes.put("city", city);
6147                            attributes.put("country", country);
6148                            attributes.put("emailAddress", emailAddress);
6149                            attributes.put("firstName", firstName);
6150                            attributes.put("fullName", fullName);
6151                            attributes.put("lastName", lastName);
6152                            attributes.put("middleName", middleName);
6153                            attributes.put("params", params);
6154                            attributes.put("region", region);
6155                            attributes.put("screenName", screenName);
6156                            attributes.put("street", street);
6157                            attributes.put("status", status);
6158                            attributes.put("zip", zip);
6159    
6160                            searchContext.setAttributes(attributes);
6161    
6162                            searchContext.setCompanyId(companyId);
6163                            searchContext.setEnd(end);
6164    
6165                            if (params != null) {
6166                                    String keywords = (String)params.remove("keywords");
6167    
6168                                    if (Validator.isNotNull(keywords)) {
6169                                            searchContext.setKeywords(keywords);
6170                                    }
6171                            }
6172    
6173                            QueryConfig queryConfig = new QueryConfig();
6174    
6175                            queryConfig.setHighlightEnabled(false);
6176                            queryConfig.setScoreEnabled(false);
6177    
6178                            searchContext.setQueryConfig(queryConfig);
6179    
6180                            if (sort != null) {
6181                                    searchContext.setSorts(sort);
6182                            }
6183    
6184                            searchContext.setStart(start);
6185    
6186                            Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6187                                    User.class);
6188    
6189                            return indexer.search(searchContext);
6190                    }
6191                    catch (Exception e) {
6192                            throw new SystemException(e);
6193                    }
6194            }
6195    
6196            protected void sendEmail(
6197                            User user, String password, ServiceContext serviceContext)
6198                    throws SystemException {
6199    
6200                    if (!PrefsPropsUtil.getBoolean(
6201                                    user.getCompanyId(),
6202                                    PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
6203    
6204                            return;
6205                    }
6206    
6207                    String fromName = PrefsPropsUtil.getString(
6208                            user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
6209                    String fromAddress = PrefsPropsUtil.getString(
6210                            user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
6211    
6212                    String toName = user.getFullName();
6213                    String toAddress = user.getEmailAddress();
6214    
6215                    String subject = PrefsPropsUtil.getContent(
6216                            user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
6217    
6218                    String body = null;
6219    
6220                    if (Validator.isNotNull(password)) {
6221                            body = PrefsPropsUtil.getContent(
6222                                    user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
6223                    }
6224                    else {
6225                            body = PrefsPropsUtil.getContent(
6226                                    user.getCompanyId(),
6227                                    PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
6228                    }
6229    
6230                    SubscriptionSender subscriptionSender = new SubscriptionSender();
6231    
6232                    subscriptionSender.setBody(body);
6233                    subscriptionSender.setCompanyId(user.getCompanyId());
6234                    subscriptionSender.setContextAttributes(
6235                            "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
6236                            "[$USER_SCREENNAME$]", user.getScreenName());
6237                    subscriptionSender.setFrom(fromAddress, fromName);
6238                    subscriptionSender.setHtmlFormat(true);
6239                    subscriptionSender.setMailId("user", user.getUserId());
6240                    subscriptionSender.setServiceContext(serviceContext);
6241                    subscriptionSender.setSubject(subject);
6242                    subscriptionSender.setUserId(user.getUserId());
6243    
6244                    subscriptionSender.addRuntimeSubscribers(toAddress, toName);
6245    
6246                    subscriptionSender.flushNotificationsAsync();
6247            }
6248    
6249            protected void setEmailAddress(
6250                            User user, String password, String firstName, String middleName,
6251                            String lastName, String emailAddress)
6252                    throws PortalException, SystemException {
6253    
6254                    if (StringUtil.equalsIgnoreCase(emailAddress, user.getEmailAddress())) {
6255                            return;
6256                    }
6257    
6258                    long userId = user.getUserId();
6259    
6260                    // test@test.com -> test@liferay.com
6261    
6262                    if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
6263                            Validator.isNotNull(password)) {
6264    
6265                            mailService.addUser(
6266                                    user.getCompanyId(), userId, password, firstName, middleName,
6267                                    lastName, emailAddress);
6268                    }
6269    
6270                    // test@liferay.com -> bob@liferay.com
6271    
6272                    else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
6273                            mailService.updateEmailAddress(
6274                                    user.getCompanyId(), userId, emailAddress);
6275                    }
6276    
6277                    // test@liferay.com -> test@test.com
6278    
6279                    else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
6280                            mailService.deleteEmailAddress(user.getCompanyId(), userId);
6281                    }
6282    
6283                    user.setEmailAddress(emailAddress);
6284                    user.setDigest(StringPool.BLANK);
6285            }
6286    
6287            protected void unsetToggleControlsPreference(long userId)
6288                    throws PortalException, SystemException {
6289    
6290                    PortletPreferencesFactoryImpl portletPreferencesFactory =
6291                            new PortletPreferencesFactoryImpl();
6292    
6293                    PortalPreferences portalPreferences =
6294                            portletPreferencesFactory.getPortalPreferences(userId, false);
6295    
6296                    String toggleControls = portalPreferences.getValue(
6297                            SessionClicks.class.getName(),"liferay_toggle_controls", null);
6298    
6299                    if (Validator.isNotNull(toggleControls) &&
6300                            !toggleControls.equals("visible")) {
6301    
6302                            portalPreferences.setValue(
6303                                    SessionClicks.class.getName(),"liferay_toggle_controls",
6304                                    "visible");
6305    
6306                            String xml = portletPreferencesFactory.toXML(portalPreferences);
6307    
6308                            PortalPreferencesLocalServiceUtil.updatePreferences(
6309                                    userId, PortletKeys.PREFS_OWNER_TYPE_USER, xml);
6310                    }
6311            }
6312    
6313            protected void updateGroups(
6314                            long userId, long[] newGroupIds, ServiceContext serviceContext,
6315                            boolean indexingEnabled)
6316                    throws PortalException, SystemException {
6317    
6318                    if (newGroupIds == null) {
6319                            return;
6320                    }
6321    
6322                    List<Group> oldGroups = userPersistence.getGroups(userId);
6323    
6324                    Set<Long> oldGroupIds = new HashSet<Long>(oldGroups.size());
6325    
6326                    for (Group oldGroup : oldGroups) {
6327                            long oldGroupId = oldGroup.getGroupId();
6328    
6329                            oldGroupIds.add(oldGroupId);
6330    
6331                            if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
6332                                    unsetGroupUsers(
6333                                            oldGroupId, new long[] {userId}, serviceContext);
6334                            }
6335                    }
6336    
6337                    for (long newGroupId : newGroupIds) {
6338                            if (!oldGroupIds.contains(newGroupId)) {
6339                                    addGroupUsers(newGroupId, new long[] {userId});
6340                            }
6341                    }
6342    
6343                    if (indexingEnabled) {
6344                            Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6345                                    User.class);
6346    
6347                            indexer.reindex(new long[] {userId});
6348                    }
6349    
6350                    PermissionCacheUtil.clearCache(userId);
6351            }
6352    
6353            protected void updateOrganizations(
6354                            long userId, long[] newOrganizationIds, boolean indexingEnabled)
6355                    throws PortalException, SystemException {
6356    
6357                    if (newOrganizationIds == null) {
6358                            return;
6359                    }
6360    
6361                    List<Organization> oldOrganizations = userPersistence.getOrganizations(
6362                            userId);
6363    
6364                    Set<Long> oldOrganizationIds = new HashSet<Long>(
6365                            oldOrganizations.size());
6366    
6367                    for (Organization oldOrganization : oldOrganizations) {
6368                            long oldOrganizationId = oldOrganization.getOrganizationId();
6369    
6370                            oldOrganizationIds.add(oldOrganizationId);
6371    
6372                            if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
6373                                    unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
6374                            }
6375                    }
6376    
6377                    for (long newOrganizationId : newOrganizationIds) {
6378                            if (!oldOrganizationIds.contains(newOrganizationId)) {
6379                                    addOrganizationUsers(newOrganizationId, new long[] {userId});
6380                            }
6381                    }
6382    
6383                    if (indexingEnabled) {
6384                            Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
6385                                    User.class);
6386    
6387                            indexer.reindex(new long[] {userId});
6388                    }
6389    
6390                    PermissionCacheUtil.clearCache(userId);
6391            }
6392    
6393            protected void updateUserGroupRoles(
6394                            User user, long[] groupIds, long[] organizationIds,
6395                            List<UserGroupRole> userGroupRoles,
6396                            List<UserGroupRole> previousUserGroupRoles)
6397                    throws PortalException, SystemException {
6398    
6399                    if (userGroupRoles == null) {
6400                            return;
6401                    }
6402    
6403                    userGroupRoles = new ArrayList<UserGroupRole>(userGroupRoles);
6404    
6405                    for (UserGroupRole userGroupRole : previousUserGroupRoles) {
6406                            if (userGroupRoles.contains(userGroupRole)) {
6407                                    userGroupRoles.remove(userGroupRole);
6408                            }
6409                            else {
6410                                    userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
6411                            }
6412                    }
6413    
6414                    if (userGroupRoles.isEmpty()) {
6415                            return;
6416                    }
6417    
6418                    long[] validGroupIds = null;
6419    
6420                    if (groupIds != null) {
6421                            validGroupIds = ArrayUtil.clone(groupIds);
6422                    }
6423                    else {
6424                            validGroupIds = user.getGroupIds();
6425                    }
6426    
6427                    if (organizationIds == null) {
6428                            organizationIds = user.getOrganizationIds();
6429                    }
6430    
6431                    long[] organizationGroupIds = new long[organizationIds.length];
6432    
6433                    for (int i = 0; i < organizationIds.length; i++) {
6434                            long organizationId = organizationIds[i];
6435    
6436                            Organization organization =
6437                                    organizationPersistence.findByPrimaryKey(organizationId);
6438    
6439                            organizationGroupIds[i] = organization.getGroupId();
6440                    }
6441    
6442                    validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
6443    
6444                    Arrays.sort(validGroupIds);
6445    
6446                    for (UserGroupRole userGroupRole : userGroupRoles) {
6447                            if (Arrays.binarySearch(
6448                                            validGroupIds, userGroupRole.getGroupId()) >= 0) {
6449    
6450                                    userGroupRoleLocalService.addUserGroupRole(userGroupRole);
6451                            }
6452                    }
6453            }
6454    
6455            protected void validate(
6456                            long companyId, long userId, boolean autoPassword, String password1,
6457                            String password2, boolean autoScreenName, String screenName,
6458                            String emailAddress, String openId, String firstName,
6459                            String middleName, String lastName, long[] organizationIds)
6460                    throws PortalException, SystemException {
6461    
6462                    validateCompanyMaxUsers(companyId);
6463    
6464                    if (!autoScreenName) {
6465                            validateScreenName(companyId, userId, screenName);
6466                    }
6467    
6468                    if (!autoPassword) {
6469                            PasswordPolicy passwordPolicy =
6470                                    passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
6471    
6472                            PwdToolkitUtil.validate(
6473                                    companyId, 0, password1, password2, passwordPolicy);
6474                    }
6475    
6476                    validateEmailAddress(companyId, emailAddress);
6477    
6478                    if (Validator.isNotNull(emailAddress)) {
6479                            User user = userPersistence.fetchByC_EA(companyId, emailAddress);
6480    
6481                            if ((user != null) && (user.getUserId() != userId)) {
6482                                    throw new DuplicateUserEmailAddressException(
6483                                            "{userId=" + userId + "}");
6484                            }
6485                    }
6486    
6487                    validateOpenId(companyId, userId, openId);
6488    
6489                    validateFullName(companyId, firstName, middleName, lastName);
6490    
6491                    if (organizationIds != null) {
6492                            for (long organizationId : organizationIds) {
6493                                    Organization organization =
6494                                            organizationPersistence.fetchByPrimaryKey(organizationId);
6495    
6496                                    if (organization == null) {
6497                                            throw new NoSuchOrganizationException(
6498                                                    "{organizationId=" + organizationId + "}");
6499                                    }
6500                            }
6501                    }
6502            }
6503    
6504            protected void validate(
6505                            long userId, String screenName, String emailAddress, String openId,
6506                            String firstName, String middleName, String lastName, String smsSn)
6507                    throws PortalException, SystemException {
6508    
6509                    User user = userPersistence.findByPrimaryKey(userId);
6510    
6511                    if (!StringUtil.equalsIgnoreCase(user.getScreenName(), screenName)) {
6512                            validateScreenName(user.getCompanyId(), userId, screenName);
6513                    }
6514    
6515                    validateEmailAddress(user.getCompanyId(), emailAddress);
6516    
6517                    validateOpenId(user.getCompanyId(), userId, openId);
6518    
6519                    if (!user.isDefaultUser()) {
6520                            if (Validator.isNotNull(emailAddress) &&
6521                                    !StringUtil.equalsIgnoreCase(
6522                                            user.getEmailAddress(), emailAddress)) {
6523    
6524                                    if (userPersistence.fetchByC_EA(
6525                                                    user.getCompanyId(), emailAddress) != null) {
6526    
6527                                            throw new DuplicateUserEmailAddressException(
6528                                                    "{userId=" + userId + "}");
6529                                    }
6530                            }
6531    
6532                            validateFullName(
6533                                    user.getCompanyId(), firstName, middleName, lastName);
6534                    }
6535    
6536                    if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
6537                            throw new UserSmsException();
6538                    }
6539            }
6540    
6541            protected void validateCompanyMaxUsers(long companyId)
6542                    throws PortalException, SystemException {
6543    
6544                    Company company = companyPersistence.findByPrimaryKey(companyId);
6545    
6546                    if (company.isSystem() || (company.getMaxUsers() == 0)) {
6547                            return;
6548                    }
6549    
6550                    int userCount = searchCount(
6551                            companyId, null, WorkflowConstants.STATUS_APPROVED, null);
6552    
6553                    if (userCount >= company.getMaxUsers()) {
6554                            throw new CompanyMaxUsersException();
6555                    }
6556            }
6557    
6558            protected void validateEmailAddress(long companyId, String emailAddress)
6559                    throws PortalException, SystemException {
6560    
6561                    if (Validator.isNull(emailAddress) &&
6562                            !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
6563    
6564                            return;
6565                    }
6566    
6567                    EmailAddressValidator emailAddressValidator =
6568                            EmailAddressValidatorFactory.getInstance();
6569    
6570                    if (!emailAddressValidator.validate(companyId, emailAddress)) {
6571                            throw new UserEmailAddressException();
6572                    }
6573    
6574                    String pop3User = PrefsPropsUtil.getString(
6575                            PropsKeys.MAIL_SESSION_MAIL_POP3_USER,
6576                            PropsValues.MAIL_SESSION_MAIL_POP3_USER);
6577    
6578                    if (StringUtil.equalsIgnoreCase(emailAddress, pop3User)) {
6579                            throw new ReservedUserEmailAddressException();
6580                    }
6581    
6582                    String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
6583                            companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
6584                            StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
6585    
6586                    for (String reservedEmailAddress : reservedEmailAddresses) {
6587                            if (StringUtil.equalsIgnoreCase(
6588                                            emailAddress, reservedEmailAddress)) {
6589    
6590                                    throw new ReservedUserEmailAddressException();
6591                            }
6592                    }
6593            }
6594    
6595            protected void validateEmailAddress(
6596                            User user, String emailAddress1, String emailAddress2)
6597                    throws PortalException, SystemException {
6598    
6599                    if (!emailAddress1.equals(emailAddress2)) {
6600                            throw new UserEmailAddressException();
6601                    }
6602    
6603                    validateEmailAddress(user.getCompanyId(), emailAddress1);
6604                    validateEmailAddress(user.getCompanyId(), emailAddress2);
6605    
6606                    if (!StringUtil.equalsIgnoreCase(
6607                                    emailAddress1, user.getEmailAddress())) {
6608    
6609                            if (userPersistence.fetchByC_EA(
6610                                            user.getCompanyId(), emailAddress1) != null) {
6611    
6612                                    throw new DuplicateUserEmailAddressException(
6613                                            "{userId=" + user.getUserId() + "}");
6614                            }
6615                    }
6616            }
6617    
6618            protected void validateFullName(
6619                            long companyId, String firstName, String middleName,
6620                            String lastName)
6621                    throws PortalException, SystemException {
6622    
6623                    if (Validator.isNull(firstName)) {
6624                            throw new ContactFirstNameException();
6625                    }
6626                    else if (Validator.isNull(lastName) &&
6627                                     PrefsPropsUtil.getBoolean(
6628                                             companyId, PropsKeys.USERS_LAST_NAME_REQUIRED,
6629                                             PropsValues.USERS_LAST_NAME_REQUIRED)) {
6630    
6631                            throw new ContactLastNameException();
6632                    }
6633    
6634                    FullNameValidator fullNameValidator =
6635                            FullNameValidatorFactory.getInstance();
6636    
6637                    if (!fullNameValidator.validate(
6638                                    companyId, firstName, middleName, lastName)) {
6639    
6640                            throw new ContactFullNameException();
6641                    }
6642            }
6643    
6644            protected void validateOpenId(long companyId, long userId, String openId)
6645                    throws PortalException, SystemException {
6646    
6647                    if (Validator.isNull(openId)) {
6648                            return;
6649                    }
6650    
6651                    User user = userPersistence.fetchByC_O(companyId, openId);
6652    
6653                    if ((user != null) && (user.getUserId() != userId)) {
6654                            throw new DuplicateOpenIdException("{userId=" + userId + "}");
6655                    }
6656            }
6657    
6658            protected void validatePassword(
6659                            long companyId, long userId, String password1, String password2)
6660                    throws PortalException, SystemException {
6661    
6662                    if (Validator.isNull(password1) || Validator.isNull(password2)) {
6663                            throw new UserPasswordException(
6664                                    UserPasswordException.PASSWORD_INVALID);
6665                    }
6666    
6667                    if (!password1.equals(password2)) {
6668                            throw new UserPasswordException(
6669                                    UserPasswordException.PASSWORDS_DO_NOT_MATCH);
6670                    }
6671    
6672                    PasswordPolicy passwordPolicy =
6673                            passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
6674    
6675                    PwdToolkitUtil.validate(
6676                            companyId, userId, password1, password2, passwordPolicy);
6677            }
6678    
6679            protected void validateReminderQuery(String question, String answer)
6680                    throws PortalException {
6681    
6682                    if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
6683                            return;
6684                    }
6685    
6686                    if (Validator.isNull(question)) {
6687                            throw new UserReminderQueryException("Question is null");
6688                    }
6689    
6690                    if (Validator.isNull(answer)) {
6691                            throw new UserReminderQueryException("Answer is null");
6692                    }
6693            }
6694    
6695            protected void validateScreenName(
6696                            long companyId, long userId, String screenName)
6697                    throws PortalException, SystemException {
6698    
6699                    if (Validator.isNull(screenName)) {
6700                            throw new UserScreenNameException();
6701                    }
6702    
6703                    ScreenNameValidator screenNameValidator =
6704                            ScreenNameValidatorFactory.getInstance();
6705    
6706                    if (!screenNameValidator.validate(companyId, screenName)) {
6707                            throw new UserScreenNameException();
6708                    }
6709    
6710                    if (Validator.isNumber(screenName)) {
6711                            if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
6712                                    throw new UserScreenNameException();
6713                            }
6714    
6715                            if (!screenName.equals(String.valueOf(userId))) {
6716                                    Group group = groupPersistence.fetchByPrimaryKey(
6717                                            GetterUtil.getLong(screenName));
6718    
6719                                    if (group != null) {
6720                                            throw new UserScreenNameException();
6721                                    }
6722                            }
6723                    }
6724    
6725                    for (char c : screenName.toCharArray()) {
6726                            if (!Validator.isChar(c) && !Validator.isDigit(c) &&
6727                                    (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
6728                                    (c != CharPool.UNDERLINE)) {
6729    
6730                                    throw new UserScreenNameException();
6731                            }
6732                    }
6733    
6734                    String[] anonymousNames = BaseServiceImpl.ANONYMOUS_NAMES;
6735    
6736                    for (String anonymousName : anonymousNames) {
6737                            if (StringUtil.equalsIgnoreCase(screenName, anonymousName)) {
6738                                    throw new UserScreenNameException();
6739                            }
6740                    }
6741    
6742                    User user = userPersistence.fetchByC_SN(companyId, screenName);
6743    
6744                    if ((user != null) && (user.getUserId() != userId)) {
6745                            throw new DuplicateUserScreenNameException(
6746                                    "{userId=" + userId + "}");
6747                    }
6748    
6749                    String friendlyURL = StringPool.SLASH + screenName;
6750    
6751                    Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
6752    
6753                    if ((group != null) && (group.getClassPK() != userId)) {
6754                            throw new GroupFriendlyURLException(
6755                                    GroupFriendlyURLException.DUPLICATE);
6756                    }
6757    
6758                    int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
6759    
6760                    if (exceptionType != -1) {
6761                            throw new UserScreenNameException(
6762                                    new GroupFriendlyURLException(exceptionType));
6763                    }
6764    
6765                    String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
6766                            companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
6767                            StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
6768    
6769                    for (String reservedScreenName : reservedScreenNames) {
6770                            if (StringUtil.equalsIgnoreCase(screenName, reservedScreenName)) {
6771                                    throw new ReservedUserScreenNameException();
6772                            }
6773                    }
6774            }
6775    
6776            private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
6777    
6778            private Map<Long, User> _defaultUsers = new ConcurrentHashMap<Long, User>();
6779    
6780    }