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