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