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