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