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