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