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