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