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