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