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