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