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