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