001    /**
002     * Copyright (c) 2000-2011 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.ImageProcessorUtil;
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.util.PortalUtil;
116    import com.liferay.portal.util.PrefsPropsUtil;
117    import com.liferay.portal.util.PropsValues;
118    import com.liferay.portal.util.SubscriptionSender;
119    import com.liferay.portlet.documentlibrary.ImageSizeException;
120    import com.liferay.portlet.messageboards.model.MBMessage;
121    import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
122    import com.liferay.util.Encryptor;
123    import com.liferay.util.EncryptorException;
124    
125    import java.awt.image.RenderedImage;
126    
127    import java.io.IOException;
128    import java.io.Serializable;
129    
130    import java.util.ArrayList;
131    import java.util.Arrays;
132    import java.util.Date;
133    import java.util.HashMap;
134    import java.util.HashSet;
135    import java.util.LinkedHashMap;
136    import java.util.List;
137    import java.util.Locale;
138    import java.util.Map;
139    import java.util.Set;
140    import java.util.concurrent.ConcurrentHashMap;
141    
142    /**
143     * The implementation of the user local service.
144     *
145     * @author Brian Wing Shun Chan
146     * @author Scott Lee
147     * @author Raymond Augé
148     * @author Jorge Ferrer
149     * @author Julio Camarero
150     * @author Wesley Gong
151     * @author Zsigmond Rab
152     */
153    public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
154    
155            /**
156             * Adds the user to the default groups, unless the user is already in these
157             * groups. The default groups can be specified in
158             * <code>portal.properties</code> with the key
159             * <code>admin.default.group.names</code>.
160             *
161             * @param  userId the primary key of the user
162             * @throws PortalException if a user with the primary key could not be found
163             * @throws SystemException if a system exception occurred
164             */
165            public void addDefaultGroups(long userId)
166                    throws PortalException, SystemException {
167    
168                    User user = userPersistence.findByPrimaryKey(userId);
169    
170                    Set<Long> groupIdsSet = new HashSet<Long>();
171    
172                    String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
173                            user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
174                            StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
175    
176                    for (String defaultGroupName : defaultGroupNames) {
177                            Company company = companyPersistence.findByPrimaryKey(
178                                    user.getCompanyId());
179    
180                            Account account = company.getAccount();
181    
182                            if (defaultGroupName.equalsIgnoreCase(account.getName())) {
183                                    defaultGroupName = GroupConstants.GUEST;
184                            }
185    
186                            try {
187                                    Group group = groupPersistence.findByC_N(
188                                            user.getCompanyId(), defaultGroupName);
189    
190                                    if (!userPersistence.containsGroup(
191                                                    userId, group.getGroupId())) {
192    
193                                            groupIdsSet.add(group.getGroupId());
194                                    }
195                            }
196                            catch (NoSuchGroupException nsge) {
197                            }
198                    }
199    
200                    long[] groupIds = ArrayUtil.toArray(
201                            groupIdsSet.toArray(new Long[groupIdsSet.size()]));
202    
203                    groupLocalService.addUserGroups(userId, groupIds);
204            }
205    
206            /**
207             * Adds the user to the default roles, unless the user already has these
208             * roles. The default roles can be specified in
209             * <code>portal.properties</code> with the key
210             * <code>admin.default.role.names</code>.
211             *
212             * @param  userId the primary key of the user
213             * @throws PortalException if a user with the primary key could not be found
214             * @throws SystemException if a system exception occurred
215             */
216            public void addDefaultRoles(long userId)
217                    throws PortalException, SystemException {
218    
219                    User user = userPersistence.findByPrimaryKey(userId);
220    
221                    Set<Long> roleIdSet = new HashSet<Long>();
222    
223                    String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
224                            user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
225                            StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
226    
227                    for (String defaultRoleName : defaultRoleNames) {
228                            try {
229                                    Role role = rolePersistence.findByC_N(
230                                            user.getCompanyId(), defaultRoleName);
231    
232                                    if (!userPersistence.containsRole(userId, role.getRoleId())) {
233                                            roleIdSet.add(role.getRoleId());
234                                    }
235                            }
236                            catch (NoSuchRoleException nsre) {
237                            }
238                    }
239    
240                    long[] roleIds = ArrayUtil.toArray(
241                            roleIdSet.toArray(new Long[roleIdSet.size()]));
242    
243                    roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
244    
245                    userPersistence.addRoles(userId, roleIds);
246            }
247    
248            /**
249             * Adds the user to the default user groups, unless the user is already in
250             * these user groups. The default user groups can be specified in
251             * <code>portal.properties</code> with the property
252             * <code>admin.default.user.group.names</code>.
253             *
254             * @param  userId the primary key of the user
255             * @throws PortalException if a user with the primary key could not be found
256             * @throws SystemException if a system exception occurred
257             */
258            @SuppressWarnings("deprecation")
259            public void addDefaultUserGroups(long userId)
260                    throws PortalException, SystemException {
261    
262                    User user = userPersistence.findByPrimaryKey(userId);
263    
264                    Set<Long> userGroupIdSet = new HashSet<Long>();
265    
266                    String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
267                            user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
268                            StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
269    
270                    for (String defaultUserGroupName : defaultUserGroupNames) {
271                            try {
272                                    UserGroup userGroup = userGroupPersistence.findByC_N(
273                                            user.getCompanyId(), defaultUserGroupName);
274    
275                                    if (!userPersistence.containsUserGroup(
276                                                    userId, userGroup.getUserGroupId())) {
277    
278                                            userGroupIdSet.add(userGroup.getUserGroupId());
279                                    }
280                            }
281                            catch (NoSuchUserGroupException nsuge) {
282                            }
283                    }
284    
285                    long[] userGroupIds = ArrayUtil.toArray(
286                            userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
287    
288                    if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
289                            for (long userGroupId : userGroupIds) {
290                                    userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
291                            }
292                    }
293    
294                    userPersistence.addUserGroups(userId, userGroupIds);
295            }
296    
297            /**
298             * Adds the users to the group.
299             *
300             * @param  groupId the primary key of the group
301             * @param  userIds the primary keys of the users
302             * @throws PortalException if a group or user with the primary key could not
303             *         be found
304             * @throws SystemException if a system exception occurred
305             */
306            public void addGroupUsers(long groupId, long[] userIds)
307                    throws PortalException, SystemException {
308    
309                    groupPersistence.addUsers(groupId, userIds);
310    
311                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
312    
313                    indexer.reindex(userIds);
314    
315                    PermissionCacheUtil.clearCache();
316            }
317    
318            /**
319             * Adds the users to the organization.
320             *
321             * @param  organizationId the primary key of the organization
322             * @param  userIds the primary keys of the users
323             * @throws PortalException if an organization or user with the primary key
324             *         could not be found
325             * @throws SystemException if a system exception occurred
326             */
327            public void addOrganizationUsers(long organizationId, long[] userIds)
328                    throws PortalException, SystemException {
329    
330                    organizationPersistence.addUsers(organizationId, userIds);
331    
332                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
333    
334                    indexer.reindex(userIds);
335    
336                    PermissionCacheUtil.clearCache();
337            }
338    
339            /**
340             * Assigns the password policy to the users, removing any other currently
341             * assigned password policies.
342             *
343             * @param  passwordPolicyId the primary key of the password policy
344             * @param  userIds the primary keys of the users
345             * @throws SystemException if a system exception occurred
346             */
347            public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
348                    throws SystemException {
349    
350                    passwordPolicyRelLocalService.addPasswordPolicyRels(
351                            passwordPolicyId, User.class.getName(), userIds);
352            }
353    
354            /**
355             * Adds the users to the role.
356             *
357             * @param  roleId the primary key of the role
358             * @param  userIds the primary keys of the users
359             * @throws PortalException if a role or user with the primary key could not
360             *         be found
361             * @throws SystemException if a system exception occurred
362             */
363            public void addRoleUsers(long roleId, long[] userIds)
364                    throws PortalException, SystemException {
365    
366                    rolePersistence.addUsers(roleId, userIds);
367    
368                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
369    
370                    indexer.reindex(userIds);
371    
372                    PermissionCacheUtil.clearCache();
373            }
374    
375            /**
376             * Adds the users to the team.
377             *
378             * @param  teamId the primary key of the team
379             * @param  userIds the primary keys of the users
380             * @throws PortalException if a team or user with the primary key could not
381             *         be found
382             * @throws SystemException if a system exception occurred
383             */
384            public void addTeamUsers(long teamId, long[] userIds)
385                    throws PortalException, SystemException {
386    
387                    teamPersistence.addUsers(teamId, userIds);
388    
389                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
390    
391                    indexer.reindex(userIds);
392    
393                    PermissionCacheUtil.clearCache();
394            }
395    
396            /**
397             * Adds a user.
398             *
399             * <p>
400             * This method handles the creation and bookkeeping of the user including
401             * its resources, metadata, and internal data structures. It is not
402             * necessary to make subsequent calls to any methods to setup default
403             * groups, resources, etc.
404             * </p>
405             *
406             * @param  creatorUserId the primary key of the creator
407             * @param  companyId the primary key of the user's company
408             * @param  autoPassword whether a password should be automatically generated
409             *         for the user
410             * @param  password1 the user's password
411             * @param  password2 the user's password confirmation
412             * @param  autoScreenName whether a screen name should be automatically
413             *         generated for the user
414             * @param  screenName the user's screen name
415             * @param  emailAddress the user's email address
416             * @param  facebookId the user's facebook ID
417             * @param  openId the user's OpenID
418             * @param  locale the user's locale
419             * @param  firstName the user's first name
420             * @param  middleName the user's middle name
421             * @param  lastName the user's last name
422             * @param  prefixId the user's name prefix ID
423             * @param  suffixId the user's name suffix ID
424             * @param  male whether the user is male
425             * @param  birthdayMonth the user's birthday month (0-based, meaning 0 for
426             *         January)
427             * @param  birthdayDay the user's birthday day
428             * @param  birthdayYear the user's birthday year
429             * @param  jobTitle the user's job title
430             * @param  groupIds the primary keys of the user's groups
431             * @param  organizationIds the primary keys of the user's organizations
432             * @param  roleIds the primary keys of the roles this user possesses
433             * @param  userGroupIds the primary keys of the user's user groups
434             * @param  sendEmail whether to send the user an email notification about
435             *         their new account
436             * @param  serviceContext the user's service context (optionally
437             *         <code>null</code>). Can set the universally unique identifier
438             *         (with the <code>uuid</code> attribute), asset category IDs, asset
439             *         tag names, and expando bridge attributes for the user.
440             * @return the new user
441             * @throws PortalException if the user's information was invalid
442             * @throws SystemException if a system exception occurred
443             */
444            public User addUser(
445                            long creatorUserId, long companyId, boolean autoPassword,
446                            String password1, String password2, boolean autoScreenName,
447                            String screenName, String emailAddress, long facebookId,
448                            String openId, Locale locale, String firstName, String middleName,
449                            String lastName, int prefixId, int suffixId, boolean male,
450                            int birthdayMonth, int birthdayDay, int birthdayYear,
451                            String jobTitle, long[] groupIds, long[] organizationIds,
452                            long[] roleIds, long[] userGroupIds, boolean sendEmail,
453                            ServiceContext serviceContext)
454                    throws PortalException, SystemException {
455    
456                    boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
457    
458                    try {
459                            WorkflowThreadLocal.setEnabled(false);
460    
461                            return addUserWithWorkflow(
462                                    creatorUserId, companyId, autoPassword, password1, password2,
463                                    autoScreenName, screenName, emailAddress, facebookId, openId,
464                                    locale, firstName, middleName, lastName, prefixId, suffixId,
465                                    male, birthdayMonth, birthdayDay, birthdayYear, jobTitle,
466                                    groupIds, organizationIds, roleIds, userGroupIds, sendEmail,
467                                    serviceContext);
468                    }
469                    finally {
470                            WorkflowThreadLocal.setEnabled(workflowEnabled);
471                    }
472            }
473    
474            /**
475             * Adds the users to the user group.
476             *
477             * @param  userGroupId the primary key of the user group
478             * @param  userIds the primary keys of the users
479             * @throws PortalException if a user group or user with the primary could
480             *         could not be found
481             * @throws SystemException if a system exception occurred
482             */
483            @SuppressWarnings("deprecation")
484            public void addUserGroupUsers(long userGroupId, long[] userIds)
485                    throws PortalException, SystemException {
486    
487                    if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
488                            userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
489                    }
490    
491                    userGroupPersistence.addUsers(userGroupId, userIds);
492    
493                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
494    
495                    indexer.reindex(userIds);
496    
497                    PermissionCacheUtil.clearCache();
498            }
499    
500            /**
501             * Adds a user with workflow.
502             *
503             * <p>
504             * This method handles the creation and bookkeeping of the user including
505             * its resources, metadata, and internal data structures. It is not
506             * necessary to make subsequent calls to any methods to setup default
507             * groups, resources, etc.
508             * </p>
509             *
510             * @param  creatorUserId the primary key of the creator
511             * @param  companyId the primary key of the user's company
512             * @param  autoPassword whether a password should be automatically generated
513             *         for the user
514             * @param  password1 the user's password
515             * @param  password2 the user's password confirmation
516             * @param  autoScreenName whether a screen name should be automatically
517             *         generated for the user
518             * @param  screenName the user's screen name
519             * @param  emailAddress the user's email address
520             * @param  facebookId the user's facebook ID
521             * @param  openId the user's OpenID
522             * @param  locale the user's locale
523             * @param  firstName the user's first name
524             * @param  middleName the user's middle name
525             * @param  lastName the user's last name
526             * @param  prefixId the user's name prefix ID
527             * @param  suffixId the user's name suffix ID
528             * @param  male whether the user is male
529             * @param  birthdayMonth the user's birthday month (0-based, meaning 0 for
530             *         January)
531             * @param  birthdayDay the user's birthday day
532             * @param  birthdayYear the user's birthday year
533             * @param  jobTitle the user's job title
534             * @param  groupIds the primary keys of the user's groups
535             * @param  organizationIds the primary keys of the user's organizations
536             * @param  roleIds the primary keys of the roles this user possesses
537             * @param  userGroupIds the primary keys of the user's user groups
538             * @param  sendEmail whether to send the user an email notification about
539             *         their new account
540             * @param  serviceContext the user's service context (optionally
541             *         <code>null</code>). Can set the universally unique identifier
542             *         (with the <code>uuid</code> attribute), asset category IDs, asset
543             *         tag names, and expando bridge attributes for the user.
544             * @return the new user
545             * @throws PortalException if the user's information was invalid
546             * @throws SystemException if a system exception occurred
547             */
548            @SuppressWarnings("deprecation")
549            public User addUserWithWorkflow(
550                            long creatorUserId, long companyId, boolean autoPassword,
551                            String password1, String password2, boolean autoScreenName,
552                            String screenName, String emailAddress, long facebookId,
553                            String openId, Locale locale, String firstName, String middleName,
554                            String lastName, int prefixId, int suffixId, boolean male,
555                            int birthdayMonth, int birthdayDay, int birthdayYear,
556                            String jobTitle, long[] groupIds, long[] organizationIds,
557                            long[] roleIds, long[] userGroupIds, boolean sendEmail,
558                            ServiceContext serviceContext)
559                    throws PortalException, SystemException {
560    
561                    // User
562    
563                    Company company = companyPersistence.findByPrimaryKey(companyId);
564                    screenName = getScreenName(screenName);
565                    emailAddress = emailAddress.trim().toLowerCase();
566                    openId = openId.trim();
567                    Date now = new Date();
568    
569                    if (PrefsPropsUtil.getBoolean(
570                                    companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
571    
572                            autoScreenName = true;
573                    }
574    
575                    long userId = counterLocalService.increment();
576    
577                    EmailAddressGenerator emailAddressGenerator =
578                            EmailAddressGeneratorFactory.getInstance();
579    
580                    if (emailAddressGenerator.isGenerated(emailAddress)) {
581                            emailAddress = StringPool.BLANK;
582                    }
583    
584                    if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
585                            Validator.isNull(emailAddress)) {
586    
587                            emailAddress = emailAddressGenerator.generate(companyId, userId);
588                    }
589    
590                    validate(
591                            companyId, userId, autoPassword, password1, password2,
592                            autoScreenName, screenName, emailAddress, firstName, middleName,
593                            lastName, organizationIds);
594    
595                    if (!autoPassword) {
596                            if (Validator.isNull(password1) || Validator.isNull(password2)) {
597                                    throw new UserPasswordException(
598                                            UserPasswordException.PASSWORD_INVALID);
599                            }
600                    }
601    
602                    if (autoScreenName) {
603                            ScreenNameGenerator screenNameGenerator =
604                                    ScreenNameGeneratorFactory.getInstance();
605    
606                            try {
607                                    screenName = screenNameGenerator.generate(
608                                            companyId, userId, emailAddress);
609                            }
610                            catch (Exception e) {
611                                    throw new SystemException(e);
612                            }
613                    }
614    
615                    User defaultUser = getDefaultUser(companyId);
616    
617                    FullNameGenerator fullNameGenerator =
618                            FullNameGeneratorFactory.getInstance();
619    
620                    String fullName = fullNameGenerator.getFullName(
621                            firstName, middleName, lastName);
622    
623                    String greeting = LanguageUtil.format(
624                            locale, "welcome-x", " " + fullName, false);
625    
626                    User user = userPersistence.create(userId);
627    
628                    if (serviceContext != null) {
629                            String uuid = serviceContext.getUuid();
630    
631                            if (Validator.isNotNull(uuid)) {
632                                    user.setUuid(uuid);
633                            }
634                    }
635    
636                    user.setCompanyId(companyId);
637                    user.setCreateDate(now);
638                    user.setModifiedDate(now);
639                    user.setDefaultUser(false);
640                    user.setContactId(counterLocalService.increment());
641    
642                    if (Validator.isNotNull(password1)) {
643                            user.setPassword(PwdEncryptor.encrypt(password1));
644                            user.setPasswordUnencrypted(password1);
645                    }
646    
647                    user.setPasswordEncrypted(true);
648    
649                    PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
650    
651                    if ((passwordPolicy != null) && passwordPolicy.isChangeable() &&
652                            passwordPolicy.isChangeRequired()) {
653    
654                            user.setPasswordReset(true);
655                    }
656                    else {
657                            user.setPasswordReset(false);
658                    }
659    
660                    user.setDigest(StringPool.BLANK);
661                    user.setScreenName(screenName);
662                    user.setEmailAddress(emailAddress);
663                    user.setFacebookId(facebookId);
664                    user.setOpenId(openId);
665                    user.setLanguageId(locale.toString());
666                    user.setTimeZoneId(defaultUser.getTimeZoneId());
667                    user.setGreeting(greeting);
668                    user.setFirstName(firstName);
669                    user.setMiddleName(middleName);
670                    user.setLastName(lastName);
671                    user.setJobTitle(jobTitle);
672                    user.setStatus(WorkflowConstants.STATUS_DRAFT);
673    
674                    userPersistence.update(user, false, serviceContext);
675    
676                    // Resources
677    
678                    String creatorUserName = StringPool.BLANK;
679    
680                    if (creatorUserId <= 0) {
681                            creatorUserId = user.getUserId();
682    
683                            // Don't grab the full name from the User object because it doesn't
684                            // have a corresponding Contact object yet
685    
686                            //creatorUserName = user.getFullName();
687                    }
688                    else {
689                            User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
690    
691                            creatorUserName = creatorUser.getFullName();
692                    }
693    
694                    resourceLocalService.addResources(
695                            companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
696                            false, false, false);
697    
698                    // Contact
699    
700                    Date birthday = PortalUtil.getDate(
701                            birthdayMonth, birthdayDay, birthdayYear,
702                            new ContactBirthdayException());
703    
704                    Contact contact = contactPersistence.create(user.getContactId());
705    
706                    contact.setCompanyId(user.getCompanyId());
707                    contact.setUserId(creatorUserId);
708                    contact.setUserName(creatorUserName);
709                    contact.setCreateDate(now);
710                    contact.setModifiedDate(now);
711                    contact.setAccountId(company.getAccountId());
712                    contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
713                    contact.setFirstName(firstName);
714                    contact.setMiddleName(middleName);
715                    contact.setLastName(lastName);
716                    contact.setPrefixId(prefixId);
717                    contact.setSuffixId(suffixId);
718                    contact.setMale(male);
719                    contact.setBirthday(birthday);
720                    contact.setJobTitle(jobTitle);
721    
722                    contactPersistence.update(contact, false, serviceContext);
723    
724                    // Group
725    
726                    groupLocalService.addGroup(
727                            user.getUserId(), User.class.getName(), user.getUserId(), null,
728                            null, 0, StringPool.SLASH + screenName, false, true, null);
729    
730                    // Groups
731    
732                    if (groupIds != null) {
733                            groupLocalService.addUserGroups(userId, groupIds);
734                    }
735    
736                    addDefaultGroups(userId);
737    
738                    // Organizations
739    
740                    boolean indexingEnabled = serviceContext.isIndexingEnabled();
741    
742                    serviceContext.setIndexingEnabled(false);
743    
744                    try {
745                            updateOrganizations(userId, organizationIds, serviceContext);
746                    }
747                    finally {
748                            serviceContext.setIndexingEnabled(indexingEnabled);
749                    }
750    
751                    // Roles
752    
753                    if (roleIds != null) {
754                            roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
755    
756                            userPersistence.setRoles(userId, roleIds);
757                    }
758    
759                    addDefaultRoles(userId);
760    
761                    // User groups
762    
763                    if (userGroupIds != null) {
764                            if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
765                                    for (long userGroupId : userGroupIds) {
766                                            userGroupLocalService.copyUserGroupLayouts(
767                                                    userGroupId, new long[] {userId});
768                                    }
769                            }
770    
771                            userPersistence.setUserGroups(userId, userGroupIds);
772                    }
773    
774                    addDefaultUserGroups(userId);
775    
776                    // Asset
777    
778                    if (serviceContext != null) {
779                            updateAsset(
780                                    creatorUserId, user, serviceContext.getAssetCategoryIds(),
781                                    serviceContext.getAssetTagNames());
782                    }
783    
784                    // Expando
785    
786                    user.setExpandoBridgeAttributes(serviceContext);
787    
788                    // Indexer
789    
790                    if (serviceContext.isIndexingEnabled()) {
791                            Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
792    
793                            indexer.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 screen name.
1777             *
1778             * @param  companyId the primary key of the user's company
1779             * @param  screenName the user's screen name
1780             * @return the user with the screen name, or <code>null</code> if a user
1781             *         with the screen name could not be found
1782             * @throws SystemException if a system exception occurred
1783             */
1784            public User fetchUserByScreenName(long companyId, String screenName)
1785                    throws SystemException {
1786    
1787                    screenName = getScreenName(screenName);
1788    
1789                    return userPersistence.fetchByC_SN(companyId, screenName);
1790            }
1791    
1792            /**
1793             * Returns the user with the primary key.
1794             *
1795             * @param  userId the primary key of the user
1796             * @return the user with the primary key, or <code>null</code> if a user
1797             *         with the primary key could not be found
1798             * @throws SystemException if a system exception occurred
1799             */
1800            public User fetchUserById(long userId) throws SystemException {
1801                    return userPersistence.fetchByPrimaryKey(userId);
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             * Updates a user account that was automatically created when a guest user
2826             * participated in an action (e.g. posting a comment) and only provided his
2827             * name and email address.
2828             *
2829             * @param  creatorUserId the primary key of the creator
2830             * @param  companyId the primary key of the user's company
2831             * @param  autoPassword whether a password should be automatically generated
2832             *         for the user
2833             * @param  password1 the user's password
2834             * @param  password2 the user's password confirmation
2835             * @param  autoScreenName whether a screen name should be automatically
2836             *         generated for the user
2837             * @param  screenName the user's screen name
2838             * @param  emailAddress the user's email address
2839             * @param  facebookId the user's facebook ID
2840             * @param  openId the user's OpenID
2841             * @param  locale the user's locale
2842             * @param  firstName the user's first name
2843             * @param  middleName the user's middle name
2844             * @param  lastName the user's last name
2845             * @param  prefixId the user's name prefix ID
2846             * @param  suffixId the user's name suffix ID
2847             * @param  male whether the user is male
2848             * @param  birthdayMonth the user's birthday month (0-based, meaning 0 for
2849             *         January)
2850             * @param  birthdayDay the user's birthday day
2851             * @param  birthdayYear the user's birthday year
2852             * @param  jobTitle the user's job title
2853             * @param  updateUserInformation whether to update the user's information
2854             * @param  sendEmail whether to send the user an email notification about
2855             *         their new account
2856             * @param  serviceContext the user's service context (optionally
2857             *         <code>null</code>). Can set expando bridge attributes for the
2858             *         user.
2859             * @return the user
2860             * @throws PortalException if the user's information was invalid
2861             * @throws SystemException if a system exception occurred
2862             */
2863            public User updateIncompleteUser(
2864                            long creatorUserId, long companyId, boolean autoPassword,
2865                            String password1, String password2, boolean autoScreenName,
2866                            String screenName, String emailAddress, long facebookId,
2867                            String openId, Locale locale, String firstName, String middleName,
2868                            String lastName, int prefixId, int suffixId, boolean male,
2869                            int birthdayMonth, int birthdayDay, int birthdayYear,
2870                            String jobTitle, boolean updateUserInformation, boolean sendEmail,
2871                            ServiceContext serviceContext)
2872                    throws PortalException, SystemException {
2873    
2874                    User user = getUserByEmailAddress(companyId, emailAddress);
2875    
2876                    if (user.getStatus() != WorkflowConstants.STATUS_INCOMPLETE) {
2877                            throw new PortalException("Invalid user status");
2878                    }
2879    
2880                    User defaultUser = getDefaultUser(companyId);
2881    
2882                    if (updateUserInformation) {
2883                            autoScreenName = false;
2884    
2885                            if (PrefsPropsUtil.getBoolean(
2886                                            companyId,
2887                                            PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
2888    
2889                                    autoScreenName = true;
2890                            }
2891    
2892                            validate(
2893                                    companyId, user.getUserId(), autoPassword, password1, password2,
2894                                    autoScreenName, screenName, emailAddress, firstName, middleName,
2895                                    lastName, null);
2896    
2897                            if (!autoPassword) {
2898                                    if (Validator.isNull(password1) ||
2899                                            Validator.isNull(password2)) {
2900                                                    throw new UserPasswordException(
2901                                                            UserPasswordException.PASSWORD_INVALID);
2902                                    }
2903                            }
2904    
2905                            if (autoScreenName) {
2906                                    ScreenNameGenerator screenNameGenerator =
2907                                            ScreenNameGeneratorFactory.getInstance();
2908    
2909                                    try {
2910                                            screenName = screenNameGenerator.generate(
2911                                                    companyId, user.getUserId(), emailAddress);
2912                                    }
2913                                    catch (Exception e) {
2914                                            throw new SystemException(e);
2915                                    }
2916                            }
2917    
2918                            FullNameGenerator fullNameGenerator =
2919                                    FullNameGeneratorFactory.getInstance();
2920    
2921                            String fullName = fullNameGenerator.getFullName(
2922                                    firstName, middleName, lastName);
2923    
2924                            String greeting = LanguageUtil.format(
2925                                    locale, "welcome-x", " " + fullName, false);
2926    
2927                            if (Validator.isNotNull(password1)) {
2928                                    user.setPassword(PwdEncryptor.encrypt(password1));
2929                                    user.setPasswordUnencrypted(password1);
2930                            }
2931    
2932                            user.setPasswordEncrypted(true);
2933    
2934                            PasswordPolicy passwordPolicy = defaultUser.getPasswordPolicy();
2935    
2936                            if (passwordPolicy.isChangeable() &&
2937                                    passwordPolicy.isChangeRequired()) {
2938    
2939                                    user.setPasswordReset(true);
2940                            }
2941                            else {
2942                                    user.setPasswordReset(false);
2943                            }
2944    
2945                            user.setScreenName(screenName);
2946                            user.setFacebookId(facebookId);
2947                            user.setOpenId(openId);
2948                            user.setLanguageId(locale.toString());
2949                            user.setTimeZoneId(defaultUser.getTimeZoneId());
2950                            user.setGreeting(greeting);
2951                            user.setFirstName(firstName);
2952                            user.setMiddleName(middleName);
2953                            user.setLastName(lastName);
2954                            user.setJobTitle(jobTitle);
2955    
2956                            Date birthday = PortalUtil.getDate(
2957                                    birthdayMonth, birthdayDay, birthdayYear,
2958                                    new ContactBirthdayException());
2959    
2960                            Contact contact = user.getContact();
2961    
2962                            contact.setFirstName(firstName);
2963                            contact.setMiddleName(middleName);
2964                            contact.setLastName(lastName);
2965                            contact.setPrefixId(prefixId);
2966                            contact.setSuffixId(suffixId);
2967                            contact.setMale(male);
2968                            contact.setBirthday(birthday);
2969                            contact.setJobTitle(jobTitle);
2970    
2971                            contactPersistence.update(contact, false, serviceContext);
2972    
2973                            // Expando
2974    
2975                            user.setExpandoBridgeAttributes(serviceContext);
2976    
2977                            // Indexer
2978    
2979                            Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
2980    
2981                            indexer.reindex(user);
2982                    }
2983    
2984                    user.setStatus(WorkflowConstants.STATUS_DRAFT);
2985    
2986                    userPersistence.update(user, false, serviceContext);
2987    
2988                    // Workflow
2989    
2990                    long workflowUserId = creatorUserId;
2991    
2992                    if (workflowUserId == user.getUserId()) {
2993                            workflowUserId = defaultUser.getUserId();
2994                    }
2995    
2996                    serviceContext.setAttribute("autoPassword", autoPassword);
2997                    serviceContext.setAttribute("sendEmail", sendEmail);
2998    
2999                    WorkflowHandlerRegistryUtil.startWorkflowInstance(
3000                            companyId, workflowUserId, User.class.getName(), user.getUserId(),
3001                            user, serviceContext);
3002    
3003                    return getUserByEmailAddress(companyId, emailAddress);
3004            }
3005    
3006            /**
3007             * Returns an ordered range of all the users who match the keywords and
3008             * status, without using the indexer. It is preferable to use the indexed
3009             * version {@link #search(long, String, int, LinkedHashMap, int, int, Sort)}
3010             * instead of this method wherever possible for performance reasons.
3011             *
3012             * <p>
3013             * Useful when paginating results. Returns a maximum of <code>end -
3014             * start</code> instances. <code>start</code> and <code>end</code> are not
3015             * primary keys, they are indexes in the result set. Thus, <code>0</code>
3016             * refers to the first result in the set. Setting both <code>start</code>
3017             * and <code>end</code> to {@link
3018             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
3019             * result set.
3020             * </p>
3021             *
3022             * @param  companyId the primary key of the user's company
3023             * @param  keywords the keywords (space separated), which may occur in the
3024             *         user's first name, middle name, last name, screen name, or email
3025             *         address
3026             * @param  status the workflow status
3027             * @param  params the finder parameters (optionally <code>null</code>). For
3028             *         more information see {@link
3029             *         com.liferay.portal.service.persistence.UserFinder}.
3030             * @param  start the lower bound of the range of users
3031             * @param  end the upper bound of the range of users (not inclusive)
3032             * @param  obc the comparator to order the users by (optionally
3033             *         <code>null</code>)
3034             * @return the matching users
3035             * @throws SystemException if a system exception occurred
3036             * @see    com.liferay.portal.service.persistence.UserFinder
3037             */
3038            public List<User> search(
3039                            long companyId, String keywords, int status,
3040                            LinkedHashMap<String, Object> params, int start, int end,
3041                            OrderByComparator obc)
3042                    throws SystemException {
3043    
3044                    return userFinder.findByKeywords(
3045                            companyId, keywords, status, params, start, end, obc);
3046            }
3047    
3048            /**
3049             * Returns an ordered range of all the users who match the keywords and
3050             * status, using the indexer. It is preferable to use this method instead of
3051             * the non-indexed version whenever possible for performance reasons.
3052             *
3053             * <p>
3054             * Useful when paginating results. Returns a maximum of <code>end -
3055             * start</code> instances. <code>start</code> and <code>end</code> are not
3056             * primary keys, they are indexes in the result set. Thus, <code>0</code>
3057             * refers to the first result in the set. Setting both <code>start</code>
3058             * and <code>end</code> to {@link
3059             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
3060             * result set.
3061             * </p>
3062             *
3063             * @param  companyId the primary key of the user's company
3064             * @param  keywords the keywords (space separated), which may occur in the
3065             *         user's first name, middle name, last name, screen name, or email
3066             *         address
3067             * @param  status the workflow status
3068             * @param  params the indexer parameters (optionally <code>null</code>). For
3069             *         more information see {@link
3070             *         com.liferay.portlet.usersadmin.util.UserIndexer}.
3071             * @param  start the lower bound of the range of users
3072             * @param  end the upper bound of the range of users (not inclusive)
3073             * @param  sort the field and direction to sort by (optionally
3074             *         <code>null</code>)
3075             * @return the matching users
3076             * @throws SystemException if a system exception occurred
3077             * @see    com.liferay.portlet.usersadmin.util.UserIndexer
3078             */
3079            public Hits search(
3080                            long companyId, String keywords, int status,
3081                            LinkedHashMap<String, Object> params, int start, int end, Sort sort)
3082                    throws SystemException {
3083    
3084                    String firstName = null;
3085                    String middleName = null;
3086                    String lastName = null;
3087                    String fullName = null;
3088                    String screenName = null;
3089                    String emailAddress = null;
3090                    String street = null;
3091                    String city = null;
3092                    String zip = null;
3093                    String region = null;
3094                    String country = null;
3095                    boolean andOperator = false;
3096    
3097                    if (Validator.isNotNull(keywords)) {
3098                            firstName = keywords;
3099                            middleName = keywords;
3100                            lastName = keywords;
3101                            fullName = keywords;
3102                            screenName = keywords;
3103                            emailAddress = keywords;
3104                            street = keywords;
3105                            city = keywords;
3106                            zip = keywords;
3107                            region = keywords;
3108                            country = keywords;
3109                    }
3110                    else {
3111                            andOperator = true;
3112                    }
3113    
3114                    params.put("keywords", keywords);
3115    
3116                    return search(
3117                            companyId, firstName, middleName, lastName, fullName, screenName,
3118                            emailAddress, street, city, zip, region, country, status, params,
3119                            andOperator, start, end, sort);
3120            }
3121    
3122            /**
3123             * Returns an ordered range of all the users with the status, and whose
3124             * first name, middle name, last name, screen name, and email address match
3125             * the keywords specified for them, without using the indexer. It is
3126             * preferable to use the indexed version {@link #search(long, String,
3127             * String, String, String, String, int, LinkedHashMap, boolean, int, int,
3128             * Sort)} instead of this method wherever possible for performance reasons.
3129             *
3130             * <p>
3131             * Useful when paginating results. Returns a maximum of <code>end -
3132             * start</code> instances. <code>start</code> and <code>end</code> are not
3133             * primary keys, they are indexes in the result set. Thus, <code>0</code>
3134             * refers to the first result in the set. Setting both <code>start</code>
3135             * and <code>end</code> to {@link
3136             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
3137             * result set.
3138             * </p>
3139             *
3140             * @param  companyId the primary key of the user's company
3141             * @param  firstName the first name keywords (space separated)
3142             * @param  middleName the middle name keywords
3143             * @param  lastName the last name keywords
3144             * @param  screenName the screen name keywords
3145             * @param  emailAddress the email address keywords
3146             * @param  status the workflow status
3147             * @param  params the finder parameters (optionally <code>null</code>). For
3148             *         more information see {@link
3149             *         com.liferay.portal.service.persistence.UserFinder}.
3150             * @param  andSearch whether every field must match its keywords, or just
3151             *         one field. For example, &quot;users with the first name 'bob' and
3152             *         last name 'smith'&quot; vs &quot;users with the first name 'bob'
3153             *         or the last name 'smith'&quot;.
3154             * @param  start the lower bound of the range of users
3155             * @param  end the upper bound of the range of users (not inclusive)
3156             * @param  obc the comparator to order the users by (optionally
3157             *         <code>null</code>)
3158             * @return the matching users
3159             * @throws SystemException if a system exception occurred
3160             * @see    com.liferay.portal.service.persistence.UserFinder
3161             */
3162            public List<User> search(
3163                            long companyId, String firstName, String middleName,
3164                            String lastName, String screenName, String emailAddress,
3165                            int status, LinkedHashMap<String, Object> params,
3166                            boolean andSearch, int start, int end, OrderByComparator obc)
3167                    throws SystemException {
3168    
3169                    return userFinder.findByC_FN_MN_LN_SN_EA_S(
3170                            companyId, firstName, middleName, lastName, screenName,
3171                            emailAddress, status, params, andSearch, start, end, obc);
3172            }
3173    
3174            /**
3175             * Returns an ordered range of all the users with the status, and whose
3176             * first name, middle name, last name, screen name, and email address match
3177             * the keywords specified for them, using the indexer. It is preferable to
3178             * use this method instead of the non-indexed version whenever possible for
3179             * performance reasons.
3180             *
3181             * <p>
3182             * Useful when paginating results. Returns a maximum of <code>end -
3183             * start</code> instances. <code>start</code> and <code>end</code> are not
3184             * primary keys, they are indexes in the result set. Thus, <code>0</code>
3185             * refers to the first result in the set. Setting both <code>start</code>
3186             * and <code>end</code> to {@link
3187             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
3188             * result set.
3189             * </p>
3190             *
3191             * @param  companyId the primary key of the user's company
3192             * @param  firstName the first name keywords (space separated)
3193             * @param  middleName the middle name keywords
3194             * @param  lastName the last name keywords
3195             * @param  screenName the screen name keywords
3196             * @param  emailAddress the email address keywords
3197             * @param  status the workflow status
3198             * @param  params the indexer parameters (optionally <code>null</code>). For
3199             *         more information see {@link
3200             *         com.liferay.portlet.usersadmin.util.UserIndexer}.
3201             * @param  andSearch whether every field must match its keywords, or just
3202             *         one field. For example, &quot;users with the first name 'bob' and
3203             *         last name 'smith'&quot; vs &quot;users with the first name 'bob'
3204             *         or the last name 'smith'&quot;.
3205             * @param  start the lower bound of the range of users
3206             * @param  end the upper bound of the range of users (not inclusive)
3207             * @param  sort the field and direction to sort by (optionally
3208             *         <code>null</code>)
3209             * @return the matching users
3210             * @throws SystemException if a system exception occurred
3211             * @see    com.liferay.portlet.usersadmin.util.UserIndexer
3212             */
3213            public Hits search(
3214                            long companyId, String firstName, String middleName,
3215                            String lastName, String screenName, String emailAddress,
3216                            int status, LinkedHashMap<String, Object> params,
3217                            boolean andSearch, int start, int end, Sort sort)
3218                    throws SystemException {
3219    
3220                    return search(
3221                            companyId, firstName, middleName, lastName, null, screenName,
3222                            emailAddress, null, null, null, null, null, status, params,
3223                            andSearch, start, end, sort);
3224            }
3225    
3226            /**
3227             * Returns the number of users who match the keywords and status.
3228             *
3229             * @param  companyId the primary key of the user's company
3230             * @param  keywords the keywords (space separated), which may occur in the
3231             *         user's first name, middle name, last name, screen name, or email
3232             *         address
3233             * @param  status the workflow status
3234             * @param  params the finder parameters (optionally <code>null</code>). For
3235             *         more information see {@link
3236             *         com.liferay.portal.service.persistence.UserFinder}.
3237             * @return the number matching users
3238             * @throws SystemException if a system exception occurred
3239             */
3240            public int searchCount(
3241                            long companyId, String keywords, int status,
3242                            LinkedHashMap<String, Object> params)
3243                    throws SystemException {
3244    
3245                    return userFinder.countByKeywords(companyId, keywords, status, params);
3246            }
3247    
3248            /**
3249             * Returns the number of users with the status, and whose first name, middle
3250             * name, last name, screen name, and email address match the keywords
3251             * specified for them.
3252             *
3253             * @param  companyId the primary key of the user's company
3254             * @param  firstName the first name keywords (space separated)
3255             * @param  middleName the middle name keywords
3256             * @param  lastName the last name keywords
3257             * @param  screenName the screen name keywords
3258             * @param  emailAddress the email address keywords
3259             * @param  status the workflow status
3260             * @param  params the finder parameters (optionally <code>null</code>). For
3261             *         more information see {@link
3262             *         com.liferay.portal.service.persistence.UserFinder}.
3263             * @param  andSearch whether every field must match its keywords, or just
3264             *         one field. For example, &quot;users with the first name 'bob' and
3265             *         last name 'smith'&quot; vs &quot;users with the first name 'bob'
3266             *         or the last name 'smith'&quot;.
3267             * @return the number of matching users
3268             * @throws SystemException if a system exception occurred
3269             */
3270            public int searchCount(
3271                            long companyId, String firstName, String middleName,
3272                            String lastName, String screenName, String emailAddress,
3273                            int status, LinkedHashMap<String, Object> params,
3274                            boolean andSearch)
3275                    throws SystemException {
3276    
3277                    return userFinder.countByC_FN_MN_LN_SN_EA_S(
3278                            companyId, firstName, middleName, lastName, screenName,
3279                            emailAddress, status, params, andSearch);
3280            }
3281    
3282            /**
3283             * Sends an email address verification to the user.
3284             *
3285             * @param  user the verification email recipient
3286             * @param  emailAddress the recipient's email address
3287             * @param  serviceContext the service context. Must set the portal URL, main
3288             *         path, primary key of the layout, remote address, remote host, and
3289             *         agent for the user.
3290             * @throws PortalException if a portal exception occurred
3291             * @throws SystemException if a system exception occurred
3292             */
3293            public void sendEmailAddressVerification(
3294                            User user, String emailAddress, ServiceContext serviceContext)
3295                    throws PortalException, SystemException {
3296    
3297                    if (user.isEmailAddressVerified() &&
3298                            emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
3299    
3300                            return;
3301                    }
3302    
3303                    Ticket ticket = ticketLocalService.addTicket(
3304                            user.getCompanyId(), User.class.getName(), user.getUserId(),
3305                            TicketConstants.TYPE_EMAIL_ADDRESS, emailAddress, null,
3306                            serviceContext);
3307    
3308                    String verifyEmailAddressURL =
3309                            serviceContext.getPortalURL() + serviceContext.getPathMain() +
3310                                    "/portal/verify_email_address?ticketKey=" + ticket.getKey();
3311    
3312                    Layout layout = layoutLocalService.getLayout(serviceContext.getPlid());
3313    
3314                    Group group = layout.getGroup();
3315    
3316                    if (!layout.isPrivateLayout() && !group.isUser()) {
3317                            verifyEmailAddressURL += "&p_l_id=" + serviceContext.getPlid();
3318                    }
3319    
3320                    String fromName = PrefsPropsUtil.getString(
3321                            user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
3322                    String fromAddress = PrefsPropsUtil.getString(
3323                            user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3324    
3325                    String toName = user.getFullName();
3326                    String toAddress = emailAddress;
3327    
3328                    String subject = PrefsPropsUtil.getContent(
3329                            user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_SUBJECT);
3330    
3331                    String body = PrefsPropsUtil.getContent(
3332                            user.getCompanyId(), PropsKeys.ADMIN_EMAIL_VERIFICATION_BODY);
3333    
3334                    SubscriptionSender subscriptionSender = new SubscriptionSender();
3335    
3336                    subscriptionSender.setBody(body);
3337                    subscriptionSender.setCompanyId(user.getCompanyId());
3338                    subscriptionSender.setContextAttributes(
3339                            "[$EMAIL_VERIFICATION_CODE$]", ticket.getKey(),
3340                            "[$EMAIL_VERIFICATION_URL$]", verifyEmailAddressURL,
3341                            "[$REMOTE_ADDRESS$]", serviceContext.getRemoteAddr(),
3342                            "[$REMOTE_HOST$]", serviceContext.getRemoteHost(), "[$USER_AGENT$]",
3343                            serviceContext.getUserAgent(), "[$USER_ID$]", user.getUserId(),
3344                            "[$USER_SCREENNAME$]", user.getScreenName());
3345                    subscriptionSender.setFrom(fromAddress, fromName);
3346                    subscriptionSender.setHtmlFormat(true);
3347                    subscriptionSender.setMailId("user", user.getUserId());
3348                    subscriptionSender.setServiceContext(serviceContext);
3349                    subscriptionSender.setSubject(subject);
3350                    subscriptionSender.setUserId(user.getUserId());
3351    
3352                    subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3353    
3354                    subscriptionSender.flushNotificationsAsync();
3355            }
3356    
3357            /**
3358             * Sends the password email to the user with the email address. The content
3359             * of this email can be specified in <code>portal.properties</code> with the
3360             * <code>admin.email.password</code> keys.
3361             *
3362             * @param  companyId the primary key of the user's company
3363             * @param  emailAddress the user's email address
3364             * @param  fromName the name of the individual that the email should be from
3365             * @param  fromAddress the address of the individual that the email should
3366             *         be from
3367             * @param  subject the email subject. If <code>null</code>, the subject
3368             *         specified in <code>portal.properties</code> will be used.
3369             * @param  body the email body. If <code>null</code>, the body specified in
3370             *         <code>portal.properties</code> will be used.
3371             * @param  serviceContext the user's service context
3372             * @throws PortalException if a user with the email address could not be
3373             *         found
3374             * @throws SystemException if a system exception occurred
3375             */
3376            public void sendPassword(
3377                            long companyId, String emailAddress, String fromName,
3378                            String fromAddress, String subject, String body,
3379                            ServiceContext serviceContext)
3380                    throws PortalException, SystemException {
3381    
3382                    Company company = companyPersistence.findByPrimaryKey(companyId);
3383    
3384                    if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
3385                            return;
3386                    }
3387    
3388                    emailAddress = emailAddress.trim().toLowerCase();
3389    
3390                    if (Validator.isNull(emailAddress)) {
3391                            throw new UserEmailAddressException();
3392                    }
3393    
3394                    User user = userPersistence.findByC_EA(companyId, emailAddress);
3395    
3396                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
3397    
3398                    String newPassword = StringPool.BLANK;
3399                    String passwordResetURL = StringPool.BLANK;
3400    
3401                    if (company.isSendPasswordResetLink()) {
3402                            Date expirationDate = new Date(
3403                                    System.currentTimeMillis() +
3404                                            (passwordPolicy.getResetTicketMaxAge() * 1000));
3405    
3406                            Ticket ticket = ticketLocalService.addTicket(
3407                                    companyId, User.class.getName(), user.getUserId(),
3408                                    TicketConstants.TYPE_PASSWORD, null, expirationDate,
3409                                    serviceContext);
3410    
3411                            passwordResetURL =
3412                                    serviceContext.getPortalURL() + serviceContext.getPathMain() +
3413                                            "/portal/update_password?p_l_id="+
3414                                                    serviceContext.getPlid() +
3415                                                            "&ticketKey=" + ticket.getKey();
3416                    }
3417                    else {
3418                            if (!PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
3419                                            PwdEncryptor.TYPE_NONE)) {
3420    
3421                                    newPassword = PwdToolkitUtil.generate(passwordPolicy);
3422    
3423                                    boolean passwordReset = false;
3424    
3425                                    if (passwordPolicy.getChangeable() &&
3426                                            passwordPolicy.getChangeRequired()) {
3427    
3428                                            passwordReset = true;
3429                                    }
3430    
3431                                    user.setPassword(PwdEncryptor.encrypt(newPassword));
3432                                    user.setPasswordUnencrypted(newPassword);
3433                                    user.setPasswordEncrypted(true);
3434                                    user.setPasswordReset(passwordReset);
3435                                    user.setPasswordModified(true);
3436                                    user.setPasswordModifiedDate(new Date());
3437    
3438                                    userPersistence.update(user, false);
3439    
3440                                    user.setPasswordModified(false);
3441                            }
3442                            else {
3443                                    newPassword = user.getPassword();
3444                            }
3445                    }
3446    
3447                    if (Validator.isNull(fromName)) {
3448                            fromName = PrefsPropsUtil.getString(
3449                                    companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
3450                    }
3451    
3452                    if (Validator.isNull(fromAddress)) {
3453                            fromAddress = PrefsPropsUtil.getString(
3454                                    companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
3455                    }
3456    
3457                    String toName = user.getFullName();
3458                    String toAddress = user.getEmailAddress();
3459    
3460                    if (Validator.isNull(subject)) {
3461                            if (company.isSendPasswordResetLink()) {
3462                                    subject = PrefsPropsUtil.getContent(
3463                                            companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
3464                            }
3465                            else {
3466                                    subject = PrefsPropsUtil.getContent(
3467                                            companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
3468                            }
3469                    }
3470    
3471                    if (Validator.isNull(body)) {
3472                            if (company.isSendPasswordResetLink()) {
3473                                    body = PrefsPropsUtil.getContent(
3474                                            companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
3475                            }
3476                            else {
3477                                    body = PrefsPropsUtil.getContent(
3478                                            companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
3479                            }
3480                    }
3481    
3482                    SubscriptionSender subscriptionSender = new SubscriptionSender();
3483    
3484                    subscriptionSender.setBody(body);
3485                    subscriptionSender.setCompanyId(companyId);
3486                    subscriptionSender.setContextAttributes(
3487                            "[$PASSWORD_RESET_URL$]", passwordResetURL, "[$REMOTE_ADDRESS$]",
3488                            serviceContext.getRemoteAddr(), "[$REMOTE_HOST$]",
3489                            serviceContext.getRemoteHost(), "[$USER_AGENT$]",
3490                            serviceContext.getUserAgent(), "[$USER_ID$]", user.getUserId(),
3491                            "[$USER_PASSWORD$]", newPassword, "[$USER_SCREENNAME$]",
3492                            user.getScreenName());
3493                    subscriptionSender.setFrom(fromAddress, fromName);
3494                    subscriptionSender.setHtmlFormat(true);
3495                    subscriptionSender.setMailId("user", user.getUserId());
3496                    subscriptionSender.setServiceContext(serviceContext);
3497                    subscriptionSender.setSubject(subject);
3498                    subscriptionSender.setUserId(user.getUserId());
3499    
3500                    subscriptionSender.addRuntimeSubscribers(toAddress, toName);
3501    
3502                    subscriptionSender.flushNotificationsAsync();
3503            }
3504    
3505            /**
3506             * Sets the users in the role, removing and adding users to the role as
3507             * necessary.
3508             *
3509             * @param  roleId the primary key of the role
3510             * @param  userIds the primary keys of the users
3511             * @throws PortalException if a portal exception occurred
3512             * @throws SystemException if a system exception occurred
3513             */
3514            public void setRoleUsers(long roleId, long[] userIds)
3515                    throws PortalException, SystemException {
3516    
3517                    rolePersistence.setUsers(roleId, userIds);
3518    
3519                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3520    
3521                    indexer.reindex(userIds);
3522    
3523                    PermissionCacheUtil.clearCache();
3524            }
3525    
3526            /**
3527             * Sets the users in the user group, removing and adding users to the user
3528             * group as necessary.
3529             *
3530             * @param  userGroupId the primary key of the user group
3531             * @param  userIds the primary keys of the users
3532             * @throws PortalException if a portal exception occurred
3533             * @throws SystemException if a system exception occurred
3534             */
3535            @SuppressWarnings("deprecation")
3536            public void setUserGroupUsers(long userGroupId, long[] userIds)
3537                    throws PortalException, SystemException {
3538    
3539                    if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
3540                            userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
3541                    }
3542    
3543                    userGroupPersistence.setUsers(userGroupId, userIds);
3544    
3545                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3546    
3547                    indexer.reindex(userIds);
3548    
3549                    PermissionCacheUtil.clearCache();
3550            }
3551    
3552            /**
3553             * Removes the users from the group.
3554             *
3555             * @param  groupId the primary key of the group
3556             * @param  userIds the primary keys of the users
3557             * @throws PortalException if a portal exception occurred
3558             * @throws SystemException if a system exception occurred
3559             */
3560            public void unsetGroupUsers(
3561                            long groupId, long[] userIds, ServiceContext serviceContext)
3562                    throws PortalException, SystemException {
3563    
3564                    userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
3565    
3566                    groupPersistence.removeUsers(groupId, userIds);
3567    
3568                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3569    
3570                    indexer.reindex(userIds);
3571    
3572                    PermissionCacheUtil.clearCache();
3573            }
3574    
3575            /**
3576             * Removes the users from the organization.
3577             *
3578             * @param  organizationId the primary key of the organization
3579             * @param  userIds the primary keys of the users
3580             * @throws PortalException if a portal exception occurred
3581             * @throws SystemException if a system exception occurred
3582             */
3583            public void unsetOrganizationUsers(long organizationId, long[] userIds)
3584                    throws PortalException, SystemException {
3585    
3586                    Organization organization = organizationPersistence.findByPrimaryKey(
3587                            organizationId);
3588    
3589                    Group group = organization.getGroup();
3590    
3591                    long groupId = group.getGroupId();
3592    
3593                    userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
3594    
3595                    organizationPersistence.removeUsers(organizationId, userIds);
3596    
3597                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3598    
3599                    indexer.reindex(userIds);
3600    
3601                    PermissionCacheUtil.clearCache();
3602            }
3603    
3604            /**
3605             * Removes the users from the password policy.
3606             *
3607             * @param  passwordPolicyId the primary key of the password policy
3608             * @param  userIds the primary keys of the users
3609             * @throws SystemException if a system exception occurred
3610             */
3611            public void unsetPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
3612                    throws SystemException {
3613    
3614                    passwordPolicyRelLocalService.deletePasswordPolicyRels(
3615                            passwordPolicyId, User.class.getName(), userIds);
3616            }
3617    
3618            /**
3619             * Removes the users from the role.
3620             *
3621             * @param  roleId the primary key of the role
3622             * @param  users the users
3623             * @throws PortalException if a portal exception occurred
3624             * @throws SystemException if a system exception occurred
3625             */
3626            public void unsetRoleUsers(long roleId, List<User> users)
3627                    throws PortalException, SystemException {
3628    
3629                    Role role = rolePersistence.findByPrimaryKey(roleId);
3630    
3631                    if (role.getName().equals(RoleConstants.USER)) {
3632                            return;
3633                    }
3634    
3635                    rolePersistence.removeUsers(roleId, users);
3636    
3637                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3638    
3639                    indexer.reindex(users);
3640    
3641                    PermissionCacheUtil.clearCache();
3642            }
3643    
3644            /**
3645             * Removes the users from the role.
3646             *
3647             * @param  roleId the primary key of the role
3648             * @param  userIds the primary keys of the users
3649             * @throws PortalException if a portal exception occurred
3650             * @throws SystemException if a system exception occurred
3651             */
3652            public void unsetRoleUsers(long roleId, long[] userIds)
3653                    throws PortalException, SystemException {
3654    
3655                    Role role = rolePersistence.findByPrimaryKey(roleId);
3656    
3657                    if (role.getName().equals(RoleConstants.USER)) {
3658                            return;
3659                    }
3660    
3661                    rolePersistence.removeUsers(roleId, userIds);
3662    
3663                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3664    
3665                    indexer.reindex(userIds);
3666    
3667                    PermissionCacheUtil.clearCache();
3668            }
3669    
3670            /**
3671             * Removes the users from the team.
3672             *
3673             * @param  teamId the primary key of the team
3674             * @param  userIds the primary keys of the users
3675             * @throws PortalException if a portal exception occurred
3676             * @throws SystemException if a system exception occurred
3677             */
3678            public void unsetTeamUsers(long teamId, long[] userIds)
3679                    throws PortalException, SystemException {
3680    
3681                    teamPersistence.removeUsers(teamId, userIds);
3682    
3683                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3684    
3685                    indexer.reindex(userIds);
3686    
3687                    PermissionCacheUtil.clearCache();
3688            }
3689    
3690            /**
3691             * Removes the users from the user group.
3692             *
3693             * @param  userGroupId the primary key of the user group
3694             * @param  userIds the primary keys of the users
3695             * @throws PortalException if a portal exception occurred
3696             * @throws SystemException if a system exception occurred
3697             */
3698            public void unsetUserGroupUsers(long userGroupId, long[] userIds)
3699                    throws PortalException, SystemException {
3700    
3701                    userGroupPersistence.removeUsers(userGroupId, userIds);
3702    
3703                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3704    
3705                    indexer.reindex(userIds);
3706    
3707                    PermissionCacheUtil.clearCache();
3708            }
3709    
3710            /**
3711             * Updates whether the user has agreed to the terms of use.
3712             *
3713             * @param  userId the primary key of the user
3714             * @param  agreedToTermsOfUse whether the user has agreet to the terms of
3715             *         use
3716             * @return the user
3717             * @throws PortalException if a user with the primary key could not be found
3718             * @throws SystemException if a system exception occurred
3719             */
3720            public User updateAgreedToTermsOfUse(
3721                            long userId, boolean agreedToTermsOfUse)
3722                    throws PortalException, SystemException {
3723    
3724                    User user = userPersistence.findByPrimaryKey(userId);
3725    
3726                    user.setAgreedToTermsOfUse(agreedToTermsOfUse);
3727    
3728                    userPersistence.update(user, false);
3729    
3730                    return user;
3731            }
3732    
3733            /**
3734             * Updates the user's asset with the new asset categories and tag names,
3735             * removing and adding asset categories and tag names as necessary.
3736             *
3737             * @param  userId the primary key of the user
3738             * @param  user ID the primary key of the user
3739             * @param  assetCategoryIds the primary key's of the new asset categories
3740             * @param  assetTagNames the new asset tag names
3741             * @throws PortalException if a user with the primary key could not be found
3742             * @throws SystemException if a system exception occurred
3743             */
3744            public void updateAsset(
3745                            long userId, User user, long[] assetCategoryIds,
3746                            String[] assetTagNames)
3747                    throws PortalException, SystemException {
3748    
3749                    User owner = userPersistence.findByPrimaryKey(userId);
3750    
3751                    Company company = companyPersistence.findByPrimaryKey(
3752                            owner.getCompanyId());
3753    
3754                    Group companyGroup = company.getGroup();
3755    
3756                    assetEntryLocalService.updateEntry(
3757                            userId, companyGroup.getGroupId(), User.class.getName(),
3758                            user.getUserId(), user.getUuid(), 0, assetCategoryIds,
3759                            assetTagNames, false, null, null, null, null, null,
3760                            user.getFullName(), null, null, null, null, 0, 0, null, false);
3761            }
3762    
3763            /**
3764             * Updates the user's creation date.
3765             *
3766             * @param  userId the primary key of the user
3767             * @param  createDate the new creation date
3768             * @return the user
3769             * @throws PortalException if a user with the primary key could not be found
3770             * @throws SystemException if a system exception occurred
3771             */
3772            public User updateCreateDate(long userId, Date createDate)
3773                    throws PortalException, SystemException {
3774    
3775                    User user = userPersistence.findByPrimaryKey(userId);
3776    
3777                    user.setCreateDate(createDate);
3778    
3779                    userPersistence.update(user, false);
3780    
3781                    return user;
3782            }
3783    
3784            /**
3785             * Updates the user's email address.
3786             *
3787             * @param  userId the primary key of the user
3788             * @param  password the user's password
3789             * @param  emailAddress1 the user's new email address
3790             * @param  emailAddress2 the user's new email address confirmation
3791             * @return the user
3792             * @throws PortalException if a user with the primary key could not be found
3793             * @throws SystemException if a system exception occurred
3794             */
3795            public User updateEmailAddress(
3796                            long userId, String password, String emailAddress1,
3797                            String emailAddress2)
3798                    throws PortalException, SystemException {
3799    
3800                    emailAddress1 = emailAddress1.trim().toLowerCase();
3801                    emailAddress2 = emailAddress2.trim().toLowerCase();
3802    
3803                    User user = userPersistence.findByPrimaryKey(userId);
3804    
3805                    validateEmailAddress(user, emailAddress1, emailAddress2);
3806    
3807                    setEmailAddress(
3808                            user, password, user.getFirstName(), user.getMiddleName(),
3809                            user.getLastName(), emailAddress1);
3810    
3811                    userPersistence.update(user, false);
3812    
3813                    return user;
3814            }
3815    
3816            /**
3817             * Updates the user's email address or sends verification email.
3818             *
3819             * @param  userId the primary key of the user
3820             * @param  password the user's password
3821             * @param  emailAddress1 the user's new email address
3822             * @param  emailAddress2 the user's new email address confirmation
3823             * @return the user
3824             * @throws PortalException if a user with the primary key could not be found
3825             * @throws SystemException if a system exception occurred
3826             */
3827            public User updateEmailAddress(
3828                            long userId, String password, String emailAddress1,
3829                            String emailAddress2, ServiceContext serviceContext)
3830                    throws PortalException, SystemException {
3831    
3832                    emailAddress1 = emailAddress1.trim().toLowerCase();
3833                    emailAddress2 = emailAddress2.trim().toLowerCase();
3834    
3835                    User user = userPersistence.findByPrimaryKey(userId);
3836    
3837                    validateEmailAddress(user, emailAddress1, emailAddress2);
3838    
3839                    Company company = companyPersistence.findByPrimaryKey(
3840                            user.getCompanyId());
3841    
3842                    if (!company.isStrangersVerify()) {
3843                            setEmailAddress(
3844                                    user, password, user.getFirstName(), user.getMiddleName(),
3845                                    user.getLastName(), emailAddress1);
3846    
3847                            userPersistence.update(user, false);
3848                    }
3849                    else {
3850                            sendEmailAddressVerification(user, emailAddress1, serviceContext);
3851                    }
3852    
3853                    return user;
3854            }
3855    
3856            /**
3857             * Updates whether the user has verified email address.
3858             *
3859             * @param  userId the primary key of the user
3860             * @param  emailAddressVerified whether the user has verified email address
3861             * @return the user
3862             * @throws PortalException if a user with the primary key could not be found
3863             * @throws SystemException if a system exception occurred
3864             */
3865            public User updateEmailAddressVerified(
3866                            long userId, boolean emailAddressVerified)
3867                    throws PortalException, SystemException {
3868    
3869                    User user = userPersistence.findByPrimaryKey(userId);
3870    
3871                    user.setEmailAddressVerified(emailAddressVerified);
3872    
3873                    userPersistence.update(user, false);
3874    
3875                    return user;
3876            }
3877    
3878            /**
3879             * Updates the user's Facebook ID.
3880             *
3881             * @param  userId the primary key of the user
3882             * @param  facebookId the user's new Facebook ID
3883             * @return the user
3884             * @throws PortalException if a user with the primary key could not be found
3885             * @throws SystemException if a system exception occurred
3886             */
3887            public User updateFacebookId(long userId, long facebookId)
3888                    throws PortalException, SystemException {
3889    
3890                    User user = userPersistence.findByPrimaryKey(userId);
3891    
3892                    user.setFacebookId(facebookId);
3893    
3894                    userPersistence.update(user, false);
3895    
3896                    return user;
3897            }
3898    
3899            /**
3900             * Sets the groups the user is in, removing and adding groups as necessary.
3901             *
3902             * @param  userId the primary key of the user
3903             * @param  newGroupIds the primary keys of the groups
3904             * @throws PortalException if a portal exception occurred
3905             * @throws SystemException if a system exception occurred
3906             */
3907            public void updateGroups(
3908                            long userId, long[] newGroupIds, ServiceContext serviceContext)
3909                    throws PortalException, SystemException {
3910    
3911                    if (newGroupIds == null) {
3912                            return;
3913                    }
3914    
3915                    List<Group> oldGroups = userPersistence.getGroups(userId);
3916    
3917                    List<Long> oldGroupIds = new ArrayList<Long>(oldGroups.size());
3918    
3919                    for (Group oldGroup : oldGroups) {
3920                            long oldGroupId = oldGroup.getGroupId();
3921    
3922                            oldGroupIds.add(oldGroupId);
3923    
3924                            if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
3925                                    unsetGroupUsers(
3926                                            oldGroupId, new long[] {userId}, serviceContext);
3927                            }
3928                    }
3929    
3930                    for (long newGroupId : newGroupIds) {
3931                            if (!oldGroupIds.contains(newGroupId)) {
3932                                    addGroupUsers(newGroupId, new long[] {userId});
3933                            }
3934                    }
3935    
3936                    if (serviceContext.isIndexingEnabled()) {
3937                            Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
3938    
3939                            indexer.reindex(new long[] {userId});
3940                    }
3941    
3942                    PermissionCacheUtil.clearCache();
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 = ImageProcessorUtil.read(bytes);
4383    
4384                            RenderedImage renderedImage = imageBag.getRenderedImage();
4385    
4386                            if (renderedImage == null) {
4387                                    throw new UserPortraitTypeException();
4388                            }
4389    
4390                            renderedImage = ImageProcessorUtil.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                                    ImageProcessorUtil.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                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
4495    
4496                    indexer.reindex(user);
4497    
4498                    return user;
4499            }
4500    
4501            /**
4502             * Updates the user.
4503             *
4504             * @param  userId the primary key of the user
4505             * @param  oldPassword the user's old password
4506             * @param  newPassword1 the user's new password (optionally
4507             *         <code>null</code>)
4508             * @param  newPassword2 the user's new password confirmation (optionally
4509             *         <code>null</code>)
4510             * @param  passwordReset whether the user should be asked to reset their
4511             *         password the next time they login
4512             * @param  reminderQueryQuestion the user's new password reset question
4513             * @param  reminderQueryAnswer the user's new password reset answer
4514             * @param  screenName the user's new screen name
4515             * @param  emailAddress the user's new email address
4516             * @param  facebookId the user's new Facebook ID
4517             * @param  openId the user's new OpenID
4518             * @param  languageId the user's new language ID
4519             * @param  timeZoneId the user's new time zone ID
4520             * @param  greeting the user's new greeting
4521             * @param  comments the user's new comments
4522             * @param  firstName the user's new first name
4523             * @param  middleName the user's new middle name
4524             * @param  lastName the user's new last name
4525             * @param  prefixId the user's new name prefix ID
4526             * @param  suffixId the user's new name suffix ID
4527             * @param  male whether user is male
4528             * @param  birthdayMonth the user's new birthday month (0-based, meaning 0
4529             *         for January)
4530             * @param  birthdayDay the user's new birthday day
4531             * @param  birthdayYear the user's birthday year
4532             * @param  smsSn the user's new SMS screen name
4533             * @param  aimSn the user's new AIM screen name
4534             * @param  facebookSn the user's new Facebook screen name
4535             * @param  icqSn the user's new ICQ screen name
4536             * @param  jabberSn the user's new Jabber screen name
4537             * @param  msnSn the user's new MSN screen name
4538             * @param  mySpaceSn the user's new MySpace screen name
4539             * @param  skypeSn the user's new Skype screen name
4540             * @param  twitterSn the user's new Twitter screen name
4541             * @param  ymSn the user's new Yahoo! Messenger screen name
4542             * @param  jobTitle the user's new job title
4543             * @param  groupIds the primary keys of the user's groups
4544             * @param  organizationIds the primary keys of the user's organizations
4545             * @param  roleIds the primary keys of the user's roles
4546             * @param  userGroupRoles the user user's group roles
4547             * @param  userGroupIds the primary keys of the user's user groups
4548             * @param  serviceContext the user's service context (optionally
4549             *         <code>null</code>). Can set the universally unique identifier
4550             *         (with the <code>uuid</code> attribute), asset category IDs, asset
4551             *         tag names, and expando bridge attributes for the user.
4552             * @return the user
4553             * @throws PortalException if a user with the primary key could not be found
4554             *         or if the new information was invalid
4555             * @throws SystemException if a system exception occurred
4556             */
4557            @SuppressWarnings("deprecation")
4558            public User updateUser(
4559                            long userId, String oldPassword, String newPassword1,
4560                            String newPassword2, boolean passwordReset,
4561                            String reminderQueryQuestion, String reminderQueryAnswer,
4562                            String screenName, String emailAddress, long facebookId,
4563                            String openId, String languageId, String timeZoneId,
4564                            String greeting, String comments, String firstName,
4565                            String middleName, String lastName, int prefixId, int suffixId,
4566                            boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
4567                            String smsSn, String aimSn, String facebookSn, String icqSn,
4568                            String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
4569                            String twitterSn, String ymSn, String jobTitle, long[] groupIds,
4570                            long[] organizationIds, long[] roleIds,
4571                            List<UserGroupRole> userGroupRoles, long[] userGroupIds,
4572                            ServiceContext serviceContext)
4573                    throws PortalException, SystemException {
4574    
4575                    // User
4576    
4577                    User user = userPersistence.findByPrimaryKey(userId);
4578                    Company company = companyPersistence.findByPrimaryKey(
4579                            user.getCompanyId());
4580                    String password = oldPassword;
4581                    screenName = getScreenName(screenName);
4582                    emailAddress = emailAddress.trim().toLowerCase();
4583                    openId = openId.trim();
4584                    String oldFullName = user.getFullName();
4585                    aimSn = aimSn.trim().toLowerCase();
4586                    facebookSn = facebookSn.trim().toLowerCase();
4587                    icqSn = icqSn.trim().toLowerCase();
4588                    jabberSn = jabberSn.trim().toLowerCase();
4589                    msnSn = msnSn.trim().toLowerCase();
4590                    mySpaceSn = mySpaceSn.trim().toLowerCase();
4591                    skypeSn = skypeSn.trim().toLowerCase();
4592                    twitterSn = twitterSn.trim().toLowerCase();
4593                    ymSn = ymSn.trim().toLowerCase();
4594                    Date now = new Date();
4595    
4596                    EmailAddressGenerator emailAddressGenerator =
4597                            EmailAddressGeneratorFactory.getInstance();
4598    
4599                    if (emailAddressGenerator.isGenerated(emailAddress)) {
4600                            emailAddress = StringPool.BLANK;
4601                    }
4602    
4603                    if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
4604                            Validator.isNull(emailAddress)) {
4605    
4606                            emailAddress = emailAddressGenerator.generate(
4607                                    user.getCompanyId(), userId);
4608                    }
4609    
4610                    validate(
4611                            userId, screenName, emailAddress, firstName, middleName, lastName,
4612                            smsSn);
4613    
4614                    if (Validator.isNotNull(newPassword1) ||
4615                            Validator.isNotNull(newPassword2)) {
4616    
4617                            user = updatePassword(
4618                                    userId, newPassword1, newPassword2, passwordReset);
4619    
4620                            password = newPassword1;
4621    
4622                            user.setDigest(StringPool.BLANK);
4623                    }
4624    
4625                    user.setModifiedDate(now);
4626    
4627                    if (user.getContactId() <= 0) {
4628                            user.setContactId(counterLocalService.increment());
4629                    }
4630    
4631                    user.setPasswordReset(passwordReset);
4632    
4633                    if (Validator.isNotNull(reminderQueryQuestion) &&
4634                            Validator.isNotNull(reminderQueryAnswer)) {
4635    
4636                            user.setReminderQueryQuestion(reminderQueryQuestion);
4637                            user.setReminderQueryAnswer(reminderQueryAnswer);
4638                    }
4639    
4640                    if (!user.getScreenName().equalsIgnoreCase(screenName)) {
4641                            user.setScreenName(screenName);
4642    
4643                            user.setDigest(StringPool.BLANK);
4644                    }
4645    
4646                    boolean sendEmailAddressVerification = false;
4647    
4648                    if (!company.isStrangersVerify()) {
4649                            setEmailAddress(
4650                                    user, password, firstName, middleName, lastName, emailAddress);
4651                    }
4652                    else {
4653                            sendEmailAddressVerification = true;
4654                    }
4655    
4656                    if (serviceContext != null) {
4657                            String uuid = serviceContext.getUuid();
4658    
4659                            if (Validator.isNotNull(uuid)) {
4660                                    user.setUuid(uuid);
4661                            }
4662                    }
4663    
4664                    user.setFacebookId(facebookId);
4665                    user.setOpenId(openId);
4666                    user.setLanguageId(languageId);
4667                    user.setTimeZoneId(timeZoneId);
4668                    user.setGreeting(greeting);
4669                    user.setComments(comments);
4670                    user.setFirstName(firstName);
4671                    user.setMiddleName(middleName);
4672                    user.setLastName(lastName);
4673                    user.setJobTitle(jobTitle);
4674    
4675                    userPersistence.update(user, false, serviceContext);
4676    
4677                    // Contact
4678    
4679                    Date birthday = PortalUtil.getDate(
4680                            birthdayMonth, birthdayDay, birthdayYear,
4681                            new ContactBirthdayException());
4682    
4683                    long contactId = user.getContactId();
4684    
4685                    Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
4686    
4687                    if (contact == null) {
4688                            contact = contactPersistence.create(contactId);
4689    
4690                            contact.setCompanyId(user.getCompanyId());
4691                            contact.setUserName(StringPool.BLANK);
4692                            contact.setCreateDate(now);
4693                            contact.setAccountId(company.getAccountId());
4694                            contact.setParentContactId(
4695                                    ContactConstants.DEFAULT_PARENT_CONTACT_ID);
4696                    }
4697    
4698                    contact.setModifiedDate(now);
4699                    contact.setFirstName(firstName);
4700                    contact.setMiddleName(middleName);
4701                    contact.setLastName(lastName);
4702                    contact.setPrefixId(prefixId);
4703                    contact.setSuffixId(suffixId);
4704                    contact.setMale(male);
4705                    contact.setBirthday(birthday);
4706                    contact.setSmsSn(smsSn);
4707                    contact.setAimSn(aimSn);
4708                    contact.setFacebookSn(facebookSn);
4709                    contact.setIcqSn(icqSn);
4710                    contact.setJabberSn(jabberSn);
4711                    contact.setMsnSn(msnSn);
4712                    contact.setMySpaceSn(mySpaceSn);
4713                    contact.setSkypeSn(skypeSn);
4714                    contact.setTwitterSn(twitterSn);
4715                    contact.setYmSn(ymSn);
4716                    contact.setJobTitle(jobTitle);
4717    
4718                    contactPersistence.update(contact, false, serviceContext);
4719    
4720                    // Group
4721    
4722                    Group group = groupLocalService.getUserGroup(
4723                            user.getCompanyId(), userId);
4724    
4725                    group.setFriendlyURL(StringPool.SLASH + screenName);
4726    
4727                    groupPersistence.update(group, false);
4728    
4729                    // Groups and organizations
4730    
4731                    boolean indexingEnabled = serviceContext.isIndexingEnabled();
4732    
4733                    serviceContext.setIndexingEnabled(false);
4734    
4735                    try {
4736                            updateGroups(userId, groupIds, serviceContext);
4737                            updateOrganizations(userId, organizationIds, serviceContext);
4738                    }
4739                    finally {
4740                            serviceContext.setIndexingEnabled(indexingEnabled);
4741                    }
4742    
4743                    // Roles
4744    
4745                    if (roleIds != null) {
4746                            roleIds = UsersAdminUtil.addRequiredRoles(user, roleIds);
4747    
4748                            userPersistence.setRoles(userId, roleIds);
4749                    }
4750    
4751                    // User group roles
4752    
4753                    updateUserGroupRoles(user, groupIds, organizationIds, userGroupRoles);
4754    
4755                    // User groups
4756    
4757                    if (userGroupIds != null) {
4758                            if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
4759                                    userGroupLocalService.copyUserGroupLayouts(
4760                                            userGroupIds, userId);
4761                            }
4762    
4763                            userPersistence.setUserGroups(userId, userGroupIds);
4764                    }
4765    
4766                    // Announcements
4767    
4768                    announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
4769    
4770                    // Asset
4771    
4772                    if (serviceContext != null) {
4773                            updateAsset(
4774                                    userId, user, serviceContext.getAssetCategoryIds(),
4775                                    serviceContext.getAssetTagNames());
4776                    }
4777    
4778                    // Expando
4779    
4780                    user.setExpandoBridgeAttributes(serviceContext);
4781    
4782                    // Message boards
4783    
4784                    if (GetterUtil.getBoolean(
4785                                    PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
4786                            !oldFullName.equals(user.getFullName())) {
4787    
4788                            mbMessageLocalService.updateUserName(userId, user.getFullName());
4789                    }
4790    
4791                    // Indexer
4792    
4793                    if (serviceContext.isIndexingEnabled()) {
4794                            Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
4795    
4796                            indexer.reindex(user);
4797                    }
4798    
4799                    // Email address verification
4800    
4801                    if (sendEmailAddressVerification) {
4802                            sendEmailAddressVerification(user, emailAddress, serviceContext);
4803                    }
4804    
4805                    // Permission cache
4806    
4807                    PermissionCacheUtil.clearCache();
4808    
4809                    return user;
4810            }
4811    
4812            /**
4813             * Verifies the email address of the ticket.
4814             *
4815             * @param  ticketKey the ticket key
4816             * @throws PortalException if a ticket matching the ticket key could not be
4817             *         found, if the ticket has expired, if the ticket is an email
4818             *         address ticket, or if the email address is invalid
4819             * @throws SystemException if a system exception occurred
4820             */
4821            public void verifyEmailAddress(String ticketKey)
4822                    throws PortalException, SystemException {
4823    
4824                    Ticket ticket = ticketLocalService.getTicket(ticketKey);
4825    
4826                    if (ticket.isExpired() ||
4827                            (ticket.getType() != TicketConstants.TYPE_EMAIL_ADDRESS)) {
4828    
4829                            throw new NoSuchTicketException();
4830                    }
4831    
4832                    User user = userPersistence.findByPrimaryKey(ticket.getClassPK());
4833    
4834                    String emailAddress = ticket.getExtraInfo();
4835    
4836                    emailAddress = emailAddress.toLowerCase().trim();
4837    
4838                    if (!emailAddress.equals(user.getEmailAddress())) {
4839                            if (userPersistence.fetchByC_EA(
4840                                            user.getCompanyId(), emailAddress) != null) {
4841    
4842                                    throw new DuplicateUserEmailAddressException();
4843                            }
4844    
4845                            setEmailAddress(
4846                                    user, StringPool.BLANK, user.getFirstName(),
4847                                    user.getMiddleName(), user.getLastName(), emailAddress);
4848                    }
4849    
4850                    user.setEmailAddressVerified(true);
4851    
4852                    userPersistence.update(user, false);
4853    
4854                    ticketLocalService.deleteTicket(ticket);
4855            }
4856    
4857            /**
4858             * Attempts to authenticate the user by their login and password, while
4859             * using the AuthPipeline.
4860             *
4861             * <p>
4862             * Authentication type specifies what <code>login</code> contains.The valid
4863             * values are:
4864             * </p>
4865             *
4866             * <ul>
4867             * <li>
4868             * <code>CompanyConstants.AUTH_TYPE_EA</code> - <code>login</code> is the
4869             * user's email address
4870             * </li>
4871             * <li>
4872             * <code>CompanyConstants.AUTH_TYPE_SN</code> - <code>login</code> is the
4873             * user's screen name
4874             * </li>
4875             * <li>
4876             * <code>CompanyConstants.AUTH_TYPE_ID</code> - <code>login</code> is the
4877             * user's primary key
4878             * </li>
4879             * </ul>
4880             *
4881             * @param  companyId the primary key of the user's company
4882             * @param  login either the user's email address, screen name, or primary
4883             *         key depending on the value of <code>authType</code>
4884             * @param  password the user's password
4885             * @param  authType the type of authentication to perform
4886             * @param  headerMap the header map from the authentication request
4887             * @param  parameterMap the parameter map from the authentication request
4888             * @param  resultsMap the map of authentication results (may be nil). After
4889             *         a succesful authentication the user's primary key will be placed
4890             *         under the key <code>userId</code>.
4891             * @return the authentication status. This can be {@link
4892             *         com.liferay.portal.security.auth.Authenticator#FAILURE}
4893             *         indicating that the user's credentials are invalid, {@link
4894             *         com.liferay.portal.security.auth.Authenticator#SUCCESS}
4895             *         indicating a successful login, or {@link
4896             *         com.liferay.portal.security.auth.Authenticator#DNE} indicating
4897             *         that a user with that login does not exist.
4898             * @throws PortalException if <code>login</code> or <code>password</code>
4899             *         was <code>null</code>
4900             * @throws SystemException if a system exception occurred
4901             * @see    com.liferay.portal.security.auth.AuthPipeline
4902             */
4903            protected int authenticate(
4904                            long companyId, String login, String password, String authType,
4905                            Map<String, String[]> headerMap, Map<String, String[]> parameterMap,
4906                            Map<String, Object> resultsMap)
4907                    throws PortalException, SystemException {
4908    
4909                    if (PropsValues.AUTH_LOGIN_DISABLED) {
4910                            return Authenticator.FAILURE;
4911                    }
4912    
4913                    login = login.trim().toLowerCase();
4914    
4915                    long userId = GetterUtil.getLong(login);
4916    
4917                    // User input validation
4918    
4919                    if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
4920                            if (Validator.isNull(login)) {
4921                                    throw new UserEmailAddressException();
4922                            }
4923                    }
4924                    else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
4925                            if (Validator.isNull(login)) {
4926                                    throw new UserScreenNameException();
4927                            }
4928                    }
4929                    else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
4930                            if (Validator.isNull(login)) {
4931                                    throw new UserIdException();
4932                            }
4933                    }
4934    
4935                    if (Validator.isNull(password)) {
4936                            throw new UserPasswordException(
4937                                    UserPasswordException.PASSWORD_INVALID);
4938                    }
4939    
4940                    int authResult = Authenticator.FAILURE;
4941    
4942                    // Pre-authentication pipeline
4943    
4944                    if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
4945                            authResult = AuthPipeline.authenticateByEmailAddress(
4946                                    PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
4947                                    headerMap, parameterMap);
4948                    }
4949                    else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
4950                            authResult = AuthPipeline.authenticateByScreenName(
4951                                    PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
4952                                    headerMap, parameterMap);
4953                    }
4954                    else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
4955                            authResult = AuthPipeline.authenticateByUserId(
4956                                    PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
4957                                    headerMap, parameterMap);
4958                    }
4959    
4960                    // Get user
4961    
4962                    User user = null;
4963    
4964                    try {
4965                            if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
4966                                    user = userPersistence.findByC_EA(companyId, login);
4967                            }
4968                            else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
4969                                    user = userPersistence.findByC_SN(companyId, login);
4970                            }
4971                            else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
4972                                    user = userPersistence.findByC_U(
4973                                            companyId, GetterUtil.getLong(login));
4974                            }
4975                    }
4976                    catch (NoSuchUserException nsue) {
4977                            return Authenticator.DNE;
4978                    }
4979    
4980                    if (user.isDefaultUser()) {
4981                            if (_log.isInfoEnabled()) {
4982                                    _log.info("Authentication is disabled for the default user");
4983                            }
4984    
4985                            return Authenticator.DNE;
4986                    }
4987                    else if (!user.isActive()) {
4988                            if (_log.isInfoEnabled()) {
4989                                    _log.info(
4990                                            "Authentication is disabled for inactive user " +
4991                                                    user.getUserId());
4992                            }
4993    
4994                            return Authenticator.FAILURE;
4995                    }
4996    
4997                    if (!user.isPasswordEncrypted()) {
4998                            user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
4999                            user.setPasswordEncrypted(true);
5000    
5001                            userPersistence.update(user, false);
5002                    }
5003    
5004                    // Check password policy to see if the is account locked out or if the
5005                    // password is expired
5006    
5007                    checkLockout(user);
5008    
5009                    checkPasswordExpired(user);
5010    
5011                    // Authenticate against the User_ table
5012    
5013                    if (authResult == Authenticator.SUCCESS) {
5014                            if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5015                                    boolean authenticated = PwdAuthenticator.authenticate(
5016                                            login, password, user.getPassword());
5017    
5018                                    if (authenticated) {
5019                                            authResult = Authenticator.SUCCESS;
5020                                    }
5021                                    else {
5022                                            authResult = Authenticator.FAILURE;
5023                                    }
5024                            }
5025                    }
5026    
5027                    // Post-authentication pipeline
5028    
5029                    if (authResult == Authenticator.SUCCESS) {
5030                            if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5031                                    authResult = AuthPipeline.authenticateByEmailAddress(
5032                                            PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5033                                            headerMap, parameterMap);
5034                            }
5035                            else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5036                                    authResult = AuthPipeline.authenticateByScreenName(
5037                                            PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
5038                                            headerMap, parameterMap);
5039                            }
5040                            else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5041                                    authResult = AuthPipeline.authenticateByUserId(
5042                                            PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
5043                                            headerMap, parameterMap);
5044                            }
5045                    }
5046    
5047                    if (authResult == Authenticator.SUCCESS) {
5048                            if (resultsMap != null) {
5049                                    resultsMap.put("userId", user.getUserId());
5050                            }
5051    
5052                            // Update digest
5053    
5054                            boolean updateDigest = true;
5055    
5056                            if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
5057                                    if (Validator.isNotNull(user.getDigest())) {
5058                                            updateDigest = false;
5059                                    }
5060                            }
5061    
5062                            if (updateDigest) {
5063                                    String digest = user.getDigest(password);
5064    
5065                                    user.setDigest(digest);
5066    
5067                                    userPersistence.update(user, false);
5068                            }
5069                    }
5070    
5071                    // Execute code triggered by authentication failure
5072    
5073                    if (authResult == Authenticator.FAILURE) {
5074                            try {
5075                                    if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5076                                            AuthPipeline.onFailureByEmailAddress(
5077                                                    PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5078                                                    parameterMap);
5079                                    }
5080                                    else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
5081                                            AuthPipeline.onFailureByScreenName(
5082                                                    PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
5083                                                    parameterMap);
5084                                    }
5085                                    else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
5086                                            AuthPipeline.onFailureByUserId(
5087                                                    PropsKeys.AUTH_FAILURE, companyId, userId, headerMap,
5088                                                    parameterMap);
5089                                    }
5090    
5091                                    // Let LDAP handle max failure event
5092    
5093                                    if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
5094                                                    user.getCompanyId())) {
5095    
5096                                            PasswordPolicy passwordPolicy = user.getPasswordPolicy();
5097    
5098                                            int failedLoginAttempts = user.getFailedLoginAttempts();
5099                                            int maxFailures = passwordPolicy.getMaxFailure();
5100    
5101                                            if ((failedLoginAttempts >= maxFailures) &&
5102                                                    (maxFailures != 0)) {
5103    
5104                                                    if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
5105                                                            AuthPipeline.onMaxFailuresByEmailAddress(
5106                                                                    PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5107                                                                    headerMap, parameterMap);
5108                                                    }
5109                                                    else if (authType.equals(
5110                                                                            CompanyConstants.AUTH_TYPE_SN)) {
5111    
5112                                                            AuthPipeline.onMaxFailuresByScreenName(
5113                                                                    PropsKeys.AUTH_MAX_FAILURES, companyId, login,
5114                                                                    headerMap, parameterMap);
5115                                                    }
5116                                                    else if (authType.equals(
5117                                                                            CompanyConstants.AUTH_TYPE_ID)) {
5118    
5119                                                            AuthPipeline.onMaxFailuresByUserId(
5120                                                                    PropsKeys.AUTH_MAX_FAILURES, companyId, userId,
5121                                                                    headerMap, parameterMap);
5122                                                    }
5123                                            }
5124                                    }
5125                            }
5126                            catch (Exception e) {
5127                                    _log.error(e, e);
5128                            }
5129                    }
5130    
5131                    return authResult;
5132            }
5133    
5134            protected String getScreenName(String screenName) {
5135                    return StringUtil.lowerCase(StringUtil.trim(screenName));
5136            }
5137    
5138            protected long[] getUserIds(List<User> users) {
5139                    long[] userIds = new long[users.size()];
5140    
5141                    for (int i = 0; i < users.size(); i++) {
5142                            User user = users.get(i);
5143    
5144                            userIds[i] = user.getUserId();
5145                    }
5146    
5147                    return userIds;
5148            }
5149    
5150            protected void sendEmail(
5151                            User user, String password, ServiceContext serviceContext)
5152                    throws SystemException {
5153    
5154                    if (!PrefsPropsUtil.getBoolean(
5155                                    user.getCompanyId(),
5156                                    PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
5157    
5158                            return;
5159                    }
5160    
5161                    String fromName = PrefsPropsUtil.getString(
5162                            user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_NAME);
5163                    String fromAddress = PrefsPropsUtil.getString(
5164                            user.getCompanyId(), PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
5165    
5166                    String toName = user.getFullName();
5167                    String toAddress = user.getEmailAddress();
5168    
5169                    String subject = PrefsPropsUtil.getContent(
5170                            user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
5171    
5172                    String body = null;
5173    
5174                    if (Validator.isNotNull(password)) {
5175                            body = PrefsPropsUtil.getContent(
5176                                    user.getCompanyId(), PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
5177                    }
5178                    else {
5179                            body = PrefsPropsUtil.getContent(
5180                                    user.getCompanyId(),
5181                                    PropsKeys.ADMIN_EMAIL_USER_ADDED_NO_PASSWORD_BODY);
5182                    }
5183    
5184                    SubscriptionSender subscriptionSender = new SubscriptionSender();
5185    
5186                    subscriptionSender.setBody(body);
5187                    subscriptionSender.setCompanyId(user.getCompanyId());
5188                    subscriptionSender.setContextAttributes(
5189                            "[$USER_ID$]", user.getUserId(), "[$USER_PASSWORD$]", password,
5190                            "[$USER_SCREENNAME$]", user.getScreenName());
5191                    subscriptionSender.setFrom(fromAddress, fromName);
5192                    subscriptionSender.setHtmlFormat(true);
5193                    subscriptionSender.setMailId("user", user.getUserId());
5194                    subscriptionSender.setServiceContext(serviceContext);
5195                    subscriptionSender.setSubject(subject);
5196                    subscriptionSender.setUserId(user.getUserId());
5197    
5198                    subscriptionSender.addRuntimeSubscribers(toAddress, toName);
5199    
5200                    subscriptionSender.flushNotificationsAsync();
5201            }
5202    
5203            protected Hits search(
5204                            long companyId, String firstName, String middleName,
5205                            String lastName, String fullName, String screenName,
5206                            String emailAddress, String street, String city, String zip,
5207                            String region, String country, int status,
5208                            LinkedHashMap<String, Object> params, boolean andSearch, int start,
5209                            int end, Sort sort)
5210                    throws SystemException {
5211    
5212                    try {
5213                            Map<String, Serializable> attributes =
5214                                    new HashMap<String, Serializable>();
5215    
5216                            attributes.put("city", city);
5217                            attributes.put("country", country);
5218                            attributes.put("emailAddress", emailAddress);
5219                            attributes.put("firstName", firstName);
5220                            attributes.put("fullName", fullName);
5221                            attributes.put("lastName", lastName);
5222                            attributes.put("middleName", middleName);
5223                            attributes.put("params", params);
5224                            attributes.put("region", region);
5225                            attributes.put("screenName", screenName);
5226                            attributes.put("street", street);
5227                            attributes.put("status", status);
5228                            attributes.put("zip", zip);
5229    
5230                            SearchContext searchContext = new SearchContext();
5231    
5232                            searchContext.setAndSearch(andSearch);
5233                            searchContext.setAttributes(attributes);
5234                            searchContext.setCompanyId(companyId);
5235                            searchContext.setEnd(end);
5236    
5237                            String keywords = (String)params.remove("keywords");
5238    
5239                            if (Validator.isNotNull(keywords)) {
5240                                    searchContext.setKeywords(keywords);
5241                            }
5242    
5243                            searchContext.setSorts(new Sort[] {sort});
5244    
5245                            QueryConfig queryConfig = new QueryConfig();
5246    
5247                            queryConfig.setHighlightEnabled(false);
5248                            queryConfig.setScoreEnabled(false);
5249    
5250                            searchContext.setQueryConfig(queryConfig);
5251    
5252                            searchContext.setStart(start);
5253    
5254                            Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
5255    
5256                            return indexer.search(searchContext);
5257                    }
5258                    catch (Exception e) {
5259                            throw new SystemException(e);
5260                    }
5261            }
5262    
5263            protected void setEmailAddress(
5264                            User user, String password, String firstName, String middleName,
5265                            String lastName, String emailAddress)
5266                    throws PortalException, SystemException {
5267    
5268                    if (emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
5269                            return;
5270                    }
5271    
5272                    long userId = user.getUserId();
5273    
5274                    // test@test.com -> test@liferay.com
5275    
5276                    if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
5277                            Validator.isNotNull(password)) {
5278    
5279                            mailService.addUser(
5280                                    user.getCompanyId(), userId, password, firstName, middleName,
5281                                    lastName, emailAddress);
5282                    }
5283    
5284                    // test@liferay.com -> bob@liferay.com
5285    
5286                    else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
5287                            mailService.updateEmailAddress(
5288                                    user.getCompanyId(), userId, emailAddress);
5289                    }
5290    
5291                    // test@liferay.com -> test@test.com
5292    
5293                    else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
5294                            mailService.deleteEmailAddress(user.getCompanyId(), userId);
5295                    }
5296    
5297                    user.setEmailAddress(emailAddress);
5298                    user.setDigest(StringPool.BLANK);
5299            }
5300    
5301            protected void updateUserGroupRoles(
5302                            User user, long[] groupIds, long[] organizationIds,
5303                            List<UserGroupRole> userGroupRoles)
5304                    throws PortalException, SystemException {
5305    
5306                    if (userGroupRoles == null) {
5307                            return;
5308                    }
5309    
5310                    List<UserGroupRole> previousUserGroupRoles =
5311                            userGroupRolePersistence.findByUserId(user.getUserId());
5312    
5313                    for (UserGroupRole userGroupRole : previousUserGroupRoles) {
5314                            if (userGroupRoles.contains(userGroupRole)) {
5315                                    userGroupRoles.remove(userGroupRole);
5316                            }
5317                            else {
5318                                    userGroupRoleLocalService.deleteUserGroupRole(userGroupRole);
5319                            }
5320                    }
5321    
5322                    long[] validGroupIds = null;
5323    
5324                    if (groupIds != null) {
5325                            validGroupIds = ArrayUtil.clone(groupIds);
5326                    }
5327                    else {
5328                            validGroupIds = user.getGroupIds();
5329                    }
5330    
5331                    if (organizationIds == null) {
5332                            organizationIds = user.getOrganizationIds();
5333                    }
5334    
5335                    long[] organizationGroupIds = new long[organizationIds.length];
5336    
5337                    for (int i = 0; i < organizationIds.length; i++) {
5338                            long organizationId = organizationIds[i];
5339    
5340                            Organization organization =
5341                                    organizationPersistence.findByPrimaryKey(organizationId);
5342    
5343                            Group organizationGroup = organization.getGroup();
5344    
5345                            organizationGroupIds[i] = organizationGroup.getGroupId();
5346                    }
5347    
5348                    validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
5349    
5350                    Arrays.sort(validGroupIds);
5351    
5352                    for (UserGroupRole userGroupRole : userGroupRoles) {
5353                            if (Arrays.binarySearch(
5354                                            validGroupIds, userGroupRole.getGroupId()) >= 0) {
5355    
5356                                    userGroupRoleLocalService.addUserGroupRole(userGroupRole);
5357                            }
5358                    }
5359            }
5360    
5361            protected void validate(
5362                            long companyId, long userId, boolean autoPassword, String password1,
5363                            String password2, boolean autoScreenName, String screenName,
5364                            String emailAddress, String firstName, String middleName,
5365                            String lastName, long[] organizationIds)
5366                    throws PortalException, SystemException {
5367    
5368                    Company company = companyPersistence.findByPrimaryKey(companyId);
5369    
5370                    if (company.isSystem()) {
5371                            return;
5372                    }
5373    
5374                    if ((company.getMaxUsers() > 0) &&
5375                            (company.getMaxUsers() <=
5376                                    searchCount(
5377                                            companyId, null, WorkflowConstants.STATUS_APPROVED,
5378                                            null))) {
5379    
5380                            throw new CompanyMaxUsersException();
5381                    }
5382    
5383                    if (!autoScreenName) {
5384                            validateScreenName(companyId, userId, screenName);
5385                    }
5386    
5387                    if (!autoPassword) {
5388                            PasswordPolicy passwordPolicy =
5389                                    passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
5390    
5391                            PwdToolkitUtil.validate(
5392                                    companyId, 0, password1, password2, passwordPolicy);
5393                    }
5394    
5395                    validateEmailAddress(companyId, emailAddress);
5396    
5397                    if (Validator.isNotNull(emailAddress)) {
5398                            User user = userPersistence.fetchByC_EA(companyId, emailAddress);
5399    
5400                            if ((user != null) && (user.getUserId() != userId)) {
5401                                    throw new DuplicateUserEmailAddressException();
5402                            }
5403                    }
5404    
5405                    validateFullName(companyId, firstName, middleName, lastName);
5406            }
5407    
5408            protected void validate(
5409                            long userId, String screenName, String emailAddress,
5410                            String firstName, String middleName, String lastName, String smsSn)
5411                    throws PortalException, SystemException {
5412    
5413                    User user = userPersistence.findByPrimaryKey(userId);
5414    
5415                    if (!user.getScreenName().equalsIgnoreCase(screenName)) {
5416                            validateScreenName(user.getCompanyId(), userId, screenName);
5417                    }
5418    
5419                    validateEmailAddress(user.getCompanyId(), emailAddress);
5420    
5421                    if (!user.isDefaultUser()) {
5422                            if (Validator.isNotNull(emailAddress) &&
5423                                    !user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
5424    
5425                                    if (userPersistence.fetchByC_EA(
5426                                                    user.getCompanyId(), emailAddress) != null) {
5427    
5428                                            throw new DuplicateUserEmailAddressException();
5429                                    }
5430                            }
5431    
5432                            validateFullName(
5433                                    user.getCompanyId(), firstName, middleName, lastName);
5434                    }
5435    
5436                    if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
5437                            throw new UserSmsException();
5438                    }
5439            }
5440    
5441            protected void validateEmailAddress(long companyId, String emailAddress)
5442                    throws PortalException, SystemException {
5443    
5444                    if (Validator.isNull(emailAddress) &&
5445                            !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
5446    
5447                            return;
5448                    }
5449    
5450                    if (!Validator.isEmailAddress(emailAddress) ||
5451                            emailAddress.startsWith("root@") ||
5452                            emailAddress.startsWith("postmaster@")) {
5453    
5454                            throw new UserEmailAddressException();
5455                    }
5456    
5457                    String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
5458                            companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
5459                            StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
5460    
5461                    for (String reservedEmailAddress : reservedEmailAddresses) {
5462                            if (emailAddress.equalsIgnoreCase(reservedEmailAddress)) {
5463                                    throw new ReservedUserEmailAddressException();
5464                            }
5465                    }
5466            }
5467    
5468            protected void validateEmailAddress(
5469                            User user, String emailAddress1, String emailAddress2)
5470                    throws PortalException, SystemException {
5471    
5472                    if (!emailAddress1.equals(emailAddress2)) {
5473                            throw new UserEmailAddressException();
5474                    }
5475    
5476                    validateEmailAddress(user.getCompanyId(), emailAddress1);
5477                    validateEmailAddress(user.getCompanyId(), emailAddress2);
5478    
5479                    if (!emailAddress1.equalsIgnoreCase(user.getEmailAddress())) {
5480                            if (userPersistence.fetchByC_EA(
5481                                            user.getCompanyId(), emailAddress1) != null) {
5482    
5483                                    throw new DuplicateUserEmailAddressException();
5484                            }
5485                    }
5486            }
5487    
5488            protected void validateFullName(
5489                            long companyId, String firstName, String middleName,
5490                            String lastName)
5491                    throws PortalException, SystemException {
5492    
5493                    if (Validator.isNull(firstName)) {
5494                            throw new ContactFirstNameException();
5495                    }
5496                    else if (Validator.isNull(lastName) &&
5497                                     PrefsPropsUtil.getBoolean(
5498                                             companyId, PropsKeys.USERS_LAST_NAME_REQUIRED,
5499                                             PropsValues.USERS_LAST_NAME_REQUIRED)) {
5500    
5501                            throw new ContactLastNameException();
5502                    }
5503    
5504                    FullNameValidator fullNameValidator =
5505                            FullNameValidatorFactory.getInstance();
5506    
5507                    if (!fullNameValidator.validate(
5508                                    companyId, firstName, middleName, lastName)) {
5509    
5510                            throw new ContactFullNameException();
5511                    }
5512            }
5513    
5514            protected void validatePassword(
5515                            long companyId, long userId, String password1, String password2)
5516                    throws PortalException, SystemException {
5517    
5518                    if (Validator.isNull(password1) || Validator.isNull(password2)) {
5519                            throw new UserPasswordException(
5520                                    UserPasswordException.PASSWORD_INVALID);
5521                    }
5522    
5523                    if (!password1.equals(password2)) {
5524                            throw new UserPasswordException(
5525                                    UserPasswordException.PASSWORDS_DO_NOT_MATCH);
5526                    }
5527    
5528                    PasswordPolicy passwordPolicy =
5529                            passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
5530    
5531                    PwdToolkitUtil.validate(
5532                            companyId, userId, password1, password2, passwordPolicy);
5533            }
5534    
5535            protected void validateReminderQuery(String question, String answer)
5536                    throws PortalException {
5537    
5538                    if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
5539                            return;
5540                    }
5541    
5542                    if (Validator.isNull(question)) {
5543                            throw new UserReminderQueryException("Question cannot be null");
5544                    }
5545    
5546                    if (Validator.isNull(answer)) {
5547                            throw new UserReminderQueryException("Answer cannot be null");
5548                    }
5549            }
5550    
5551            protected void validateScreenName(
5552                            long companyId, long userId, String screenName)
5553                    throws PortalException, SystemException {
5554    
5555                    if (Validator.isNull(screenName)) {
5556                            throw new UserScreenNameException();
5557                    }
5558    
5559                    ScreenNameValidator screenNameValidator =
5560                            ScreenNameValidatorFactory.getInstance();
5561    
5562                    if (!screenNameValidator.validate(companyId, screenName)) {
5563                            throw new UserScreenNameException();
5564                    }
5565    
5566                    if (Validator.isNumber(screenName)) {
5567                            if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
5568                                    throw new UserScreenNameException();
5569                            }
5570    
5571                            if (!screenName.equals(String.valueOf(userId))) {
5572                                    Group group = groupPersistence.fetchByPrimaryKey(
5573                                            GetterUtil.getLong(screenName));
5574    
5575                                    if (group != null) {
5576                                            throw new UserScreenNameException();
5577                                    }
5578                            }
5579                    }
5580    
5581                    for (char c : screenName.toCharArray()) {
5582                            if ((!Validator.isChar(c)) && (!Validator.isDigit(c)) &&
5583                                    (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
5584                                    (c != CharPool.UNDERLINE)) {
5585    
5586                                    throw new UserScreenNameException();
5587                            }
5588                    }
5589    
5590                    String[] anonymousNames = PrincipalBean.ANONYMOUS_NAMES;
5591    
5592                    for (String anonymousName : anonymousNames) {
5593                            if (screenName.equalsIgnoreCase(anonymousName)) {
5594                                    throw new UserScreenNameException();
5595                            }
5596                    }
5597    
5598                    User user = userPersistence.fetchByC_SN(companyId, screenName);
5599    
5600                    if ((user != null) && (user.getUserId() != userId)) {
5601                            throw new DuplicateUserScreenNameException();
5602                    }
5603    
5604                    String friendlyURL = StringPool.SLASH + screenName;
5605    
5606                    Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
5607    
5608                    if ((group != null) && (group.getClassPK() != userId)) {
5609                            throw new GroupFriendlyURLException(
5610                                    GroupFriendlyURLException.DUPLICATE);
5611                    }
5612    
5613                    int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
5614    
5615                    if (exceptionType != -1) {
5616                            throw new UserScreenNameException(
5617                                    new GroupFriendlyURLException(exceptionType));
5618                    }
5619    
5620                    String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
5621                            companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
5622                            StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
5623    
5624                    for (String reservedScreenName : reservedScreenNames) {
5625                            if (screenName.equalsIgnoreCase(reservedScreenName)) {
5626                                    throw new ReservedUserScreenNameException();
5627                            }
5628                    }
5629            }
5630    
5631            private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
5632    
5633            private static Map<Long, User> _defaultUsers =
5634                    new ConcurrentHashMap<Long, User>();
5635    
5636    }