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