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