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