001    /**
002     * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.service.impl;
016    
017    import com.liferay.portal.CompanyMaxUsersException;
018    import com.liferay.portal.ContactBirthdayException;
019    import com.liferay.portal.ContactFirstNameException;
020    import com.liferay.portal.ContactFullNameException;
021    import com.liferay.portal.ContactLastNameException;
022    import com.liferay.portal.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.NoSuchUserException;
030    import com.liferay.portal.NoSuchUserGroupException;
031    import com.liferay.portal.PasswordExpiredException;
032    import com.liferay.portal.RequiredUserException;
033    import com.liferay.portal.ReservedUserEmailAddressException;
034    import com.liferay.portal.ReservedUserScreenNameException;
035    import com.liferay.portal.UserEmailAddressException;
036    import com.liferay.portal.UserIdException;
037    import com.liferay.portal.UserLockoutException;
038    import com.liferay.portal.UserPasswordException;
039    import com.liferay.portal.UserPortraitSizeException;
040    import com.liferay.portal.UserPortraitTypeException;
041    import com.liferay.portal.UserReminderQueryException;
042    import com.liferay.portal.UserScreenNameException;
043    import com.liferay.portal.UserSmsException;
044    import com.liferay.portal.kernel.annotation.Propagation;
045    import com.liferay.portal.kernel.annotation.Transactional;
046    import com.liferay.portal.kernel.exception.PortalException;
047    import com.liferay.portal.kernel.exception.SystemException;
048    import com.liferay.portal.kernel.image.ImageBag;
049    import com.liferay.portal.kernel.image.ImageProcessorUtil;
050    import com.liferay.portal.kernel.language.LanguageUtil;
051    import com.liferay.portal.kernel.log.Log;
052    import com.liferay.portal.kernel.log.LogFactoryUtil;
053    import com.liferay.portal.kernel.mail.MailMessage;
054    import com.liferay.portal.kernel.search.Hits;
055    import com.liferay.portal.kernel.search.Indexer;
056    import com.liferay.portal.kernel.search.IndexerRegistryUtil;
057    import com.liferay.portal.kernel.search.SearchContext;
058    import com.liferay.portal.kernel.search.Sort;
059    import com.liferay.portal.kernel.util.ArrayUtil;
060    import com.liferay.portal.kernel.util.CharPool;
061    import com.liferay.portal.kernel.util.GetterUtil;
062    import com.liferay.portal.kernel.util.HtmlUtil;
063    import com.liferay.portal.kernel.util.KeyValuePair;
064    import com.liferay.portal.kernel.util.OrderByComparator;
065    import com.liferay.portal.kernel.util.PropsKeys;
066    import com.liferay.portal.kernel.util.StringPool;
067    import com.liferay.portal.kernel.util.StringUtil;
068    import com.liferay.portal.kernel.util.Validator;
069    import com.liferay.portal.model.Company;
070    import com.liferay.portal.model.CompanyConstants;
071    import com.liferay.portal.model.Contact;
072    import com.liferay.portal.model.ContactConstants;
073    import com.liferay.portal.model.Group;
074    import com.liferay.portal.model.Organization;
075    import com.liferay.portal.model.PasswordPolicy;
076    import com.liferay.portal.model.ResourceConstants;
077    import com.liferay.portal.model.Role;
078    import com.liferay.portal.model.RoleConstants;
079    import com.liferay.portal.model.Ticket;
080    import com.liferay.portal.model.User;
081    import com.liferay.portal.model.UserGroup;
082    import com.liferay.portal.model.UserGroupRole;
083    import com.liferay.portal.model.impl.LayoutImpl;
084    import com.liferay.portal.security.auth.AuthPipeline;
085    import com.liferay.portal.security.auth.Authenticator;
086    import com.liferay.portal.security.auth.EmailAddressGenerator;
087    import com.liferay.portal.security.auth.EmailAddressGeneratorFactory;
088    import com.liferay.portal.security.auth.FullNameGenerator;
089    import com.liferay.portal.security.auth.FullNameGeneratorFactory;
090    import com.liferay.portal.security.auth.FullNameValidator;
091    import com.liferay.portal.security.auth.FullNameValidatorFactory;
092    import com.liferay.portal.security.auth.PrincipalException;
093    import com.liferay.portal.security.auth.ScreenNameGenerator;
094    import com.liferay.portal.security.auth.ScreenNameGeneratorFactory;
095    import com.liferay.portal.security.auth.ScreenNameValidator;
096    import com.liferay.portal.security.auth.ScreenNameValidatorFactory;
097    import com.liferay.portal.security.ldap.LDAPSettingsUtil;
098    import com.liferay.portal.security.permission.PermissionCacheUtil;
099    import com.liferay.portal.security.pwd.PwdAuthenticator;
100    import com.liferay.portal.security.pwd.PwdEncryptor;
101    import com.liferay.portal.security.pwd.PwdToolkitUtil;
102    import com.liferay.portal.service.ServiceContext;
103    import com.liferay.portal.service.base.PrincipalBean;
104    import com.liferay.portal.service.base.UserLocalServiceBaseImpl;
105    import com.liferay.portal.util.PortalUtil;
106    import com.liferay.portal.util.PrefsPropsUtil;
107    import com.liferay.portal.util.PropsValues;
108    import com.liferay.portlet.enterpriseadmin.util.EnterpriseAdminUtil;
109    import com.liferay.portlet.imagegallery.ImageSizeException;
110    import com.liferay.portlet.messageboards.model.MBMessage;
111    import com.liferay.util.Encryptor;
112    import com.liferay.util.EncryptorException;
113    
114    import java.awt.image.RenderedImage;
115    
116    import java.io.IOException;
117    import java.io.Serializable;
118    
119    import java.util.ArrayList;
120    import java.util.Arrays;
121    import java.util.Date;
122    import java.util.HashMap;
123    import java.util.HashSet;
124    import java.util.LinkedHashMap;
125    import java.util.List;
126    import java.util.Locale;
127    import java.util.Map;
128    import java.util.Set;
129    import java.util.concurrent.ConcurrentHashMap;
130    
131    import javax.mail.internet.InternetAddress;
132    
133    /**
134     * @author Brian Wing Shun Chan
135     * @author Scott Lee
136     * @author Raymond Augé
137     * @author Jorge Ferrer
138     * @author Julio Camarero
139     * @author Wesley Gong
140     * @author Zsigmond Rab
141     */
142    public class UserLocalServiceImpl extends UserLocalServiceBaseImpl {
143    
144            public void addDefaultGroups(long userId)
145                    throws PortalException, SystemException {
146    
147                    User user = userPersistence.findByPrimaryKey(userId);
148    
149                    Set<Long> groupIdsSet = new HashSet<Long>();
150    
151                    String[] defaultGroupNames = PrefsPropsUtil.getStringArray(
152                            user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_GROUP_NAMES,
153                            StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_GROUP_NAMES);
154    
155                    for (String defaultGroupName : defaultGroupNames) {
156                            try {
157                                    Group group = groupPersistence.findByC_N(
158                                            user.getCompanyId(), defaultGroupName);
159    
160                                    if (!userPersistence.containsGroup(
161                                                    userId, group.getGroupId())) {
162    
163                                            groupIdsSet.add(group.getGroupId());
164                                    }
165                            }
166                            catch (NoSuchGroupException nsge) {
167                            }
168                    }
169    
170                    long[] groupIds = ArrayUtil.toArray(
171                            groupIdsSet.toArray(new Long[groupIdsSet.size()]));
172    
173                    groupLocalService.addUserGroups(userId, groupIds);
174            }
175    
176            public void addDefaultRoles(long userId)
177                    throws PortalException, SystemException {
178    
179                    User user = userPersistence.findByPrimaryKey(userId);
180    
181                    Set<Long> roleIdSet = new HashSet<Long>();
182    
183                    String[] defaultRoleNames = PrefsPropsUtil.getStringArray(
184                            user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_ROLE_NAMES,
185                            StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_ROLE_NAMES);
186    
187                    for (String defaultRoleName : defaultRoleNames) {
188                            try {
189                                    Role role = rolePersistence.findByC_N(
190                                            user.getCompanyId(), defaultRoleName);
191    
192                                    if (!userPersistence.containsRole(
193                                                    userId, role.getRoleId())) {
194    
195                                            roleIdSet.add(role.getRoleId());
196                                    }
197                            }
198                            catch (NoSuchRoleException nsre) {
199                            }
200                    }
201    
202                    long[] roleIds = ArrayUtil.toArray(
203                            roleIdSet.toArray(new Long[roleIdSet.size()]));
204    
205                    roleIds = EnterpriseAdminUtil.addRequiredRoles(user, roleIds);
206    
207                    userPersistence.addRoles(userId, roleIds);
208            }
209    
210            public void addDefaultUserGroups(long userId)
211                    throws PortalException, SystemException {
212    
213                    User user = userPersistence.findByPrimaryKey(userId);
214    
215                    Set<Long> userGroupIdSet = new HashSet<Long>();
216    
217                    String[] defaultUserGroupNames = PrefsPropsUtil.getStringArray(
218                            user.getCompanyId(), PropsKeys.ADMIN_DEFAULT_USER_GROUP_NAMES,
219                            StringPool.NEW_LINE, PropsValues.ADMIN_DEFAULT_USER_GROUP_NAMES);
220    
221                    for (String defaultUserGroupName : defaultUserGroupNames) {
222                            try {
223                                    UserGroup userGroup = userGroupPersistence.findByC_N(
224                                            user.getCompanyId(), defaultUserGroupName);
225    
226                                    if (!userPersistence.containsUserGroup(
227                                                    userId, userGroup.getUserGroupId())) {
228    
229                                            userGroupIdSet.add(userGroup.getUserGroupId());
230                                    }
231                            }
232                            catch (NoSuchUserGroupException nsuge) {
233                            }
234                    }
235    
236                    long[] userGroupIds = ArrayUtil.toArray(
237                            userGroupIdSet.toArray(new Long[userGroupIdSet.size()]));
238    
239                    for (long userGroupId : userGroupIds) {
240                            userGroupLocalService.copyUserGroupLayouts(userGroupId, userId);
241                    }
242    
243                    userPersistence.addUserGroups(userId, userGroupIds);
244            }
245    
246            public void addGroupUsers(long groupId, long[] userIds)
247                    throws PortalException, SystemException {
248    
249                    groupPersistence.addUsers(groupId, userIds);
250    
251                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
252    
253                    indexer.reindex(userIds);
254    
255                    PermissionCacheUtil.clearCache();
256            }
257    
258            public void addOrganizationUsers(long organizationId, long[] userIds)
259                    throws PortalException, SystemException {
260    
261                    organizationPersistence.addUsers(organizationId, userIds);
262    
263                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
264    
265                    indexer.reindex(userIds);
266    
267                    PermissionCacheUtil.clearCache();
268            }
269    
270            public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
271                    throws SystemException {
272    
273                    passwordPolicyRelLocalService.addPasswordPolicyRels(
274                            passwordPolicyId, User.class.getName(), userIds);
275            }
276    
277            public void addRoleUsers(long roleId, long[] userIds)
278                    throws PortalException, SystemException {
279    
280                    rolePersistence.addUsers(roleId, userIds);
281    
282                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
283    
284                    indexer.reindex(userIds);
285    
286                    PermissionCacheUtil.clearCache();
287            }
288    
289            public void addTeamUsers(long teamId, long[] userIds)
290                    throws PortalException, SystemException {
291    
292                    teamPersistence.addUsers(teamId, userIds);
293    
294                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
295    
296                    indexer.reindex(userIds);
297    
298                    PermissionCacheUtil.clearCache();
299            }
300    
301            public User addUser(
302                            long creatorUserId, long companyId, boolean autoPassword,
303                            String password1, String password2, boolean autoScreenName,
304                            String screenName, String emailAddress, long facebookId,
305                            String openId, Locale locale, String firstName, String middleName,
306                            String lastName, int prefixId, int suffixId, boolean male,
307                            int birthdayMonth, int birthdayDay, int birthdayYear,
308                            String jobTitle, long[] groupIds, long[] organizationIds,
309                            long[] roleIds, long[] userGroupIds, boolean sendEmail,
310                            ServiceContext serviceContext)
311                    throws PortalException, SystemException {
312    
313                    // User
314    
315                    Company company = companyPersistence.findByPrimaryKey(companyId);
316                    screenName = getScreenName(screenName);
317                    emailAddress = emailAddress.trim().toLowerCase();
318                    openId = openId.trim();
319                    Date now = new Date();
320    
321                    if (PrefsPropsUtil.getBoolean(
322                                    companyId, PropsKeys.USERS_SCREEN_NAME_ALWAYS_AUTOGENERATE)) {
323    
324                            autoScreenName = true;
325                    }
326    
327                    long userId = counterLocalService.increment();
328    
329                    EmailAddressGenerator emailAddressGenerator =
330                            EmailAddressGeneratorFactory.getInstance();
331    
332                    if (emailAddressGenerator.isGenerated(emailAddress)) {
333                            emailAddress = StringPool.BLANK;
334                    }
335    
336                    if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
337                            Validator.isNull(emailAddress)) {
338    
339                            emailAddress = emailAddressGenerator.generate(companyId, userId);
340                    }
341    
342                    validate(
343                            companyId, userId, autoPassword, password1, password2,
344                            autoScreenName, screenName, emailAddress, firstName, middleName,
345                            lastName, organizationIds);
346    
347                    if (autoPassword) {
348                            PasswordPolicy passwordPolicy =
349                                    passwordPolicyLocalService.getPasswordPolicy(
350                                            companyId, organizationIds);
351    
352                            password1 = PwdToolkitUtil.generate(passwordPolicy);
353                    }
354                    else {
355                            if (Validator.isNull(password1) || Validator.isNull(password2)) {
356                                    throw new UserPasswordException(
357                                            UserPasswordException.PASSWORD_INVALID);
358                            }
359                    }
360    
361                    if (autoScreenName) {
362                            ScreenNameGenerator screenNameGenerator =
363                                    ScreenNameGeneratorFactory.getInstance();
364    
365                            try {
366                                    screenName = screenNameGenerator.generate(
367                                            companyId, userId, emailAddress);
368                            }
369                            catch (Exception e) {
370                                    throw new SystemException(e);
371                            }
372                    }
373    
374                    User defaultUser = getDefaultUser(companyId);
375    
376                    FullNameGenerator fullNameGenerator =
377                            FullNameGeneratorFactory.getInstance();
378    
379                    String fullName = fullNameGenerator.getFullName(
380                            firstName, middleName, lastName);
381    
382                    String greeting = LanguageUtil.format(
383                            locale, "welcome-x", " " + fullName, false);
384    
385                    User user = userPersistence.create(userId);
386    
387                    user.setCompanyId(companyId);
388                    user.setCreateDate(now);
389                    user.setModifiedDate(now);
390                    user.setDefaultUser(false);
391                    user.setContactId(counterLocalService.increment());
392                    user.setPassword(PwdEncryptor.encrypt(password1));
393                    user.setPasswordUnencrypted(password1);
394                    user.setPasswordEncrypted(true);
395                    user.setPasswordReset(false);
396                    user.setScreenName(screenName);
397                    user.setEmailAddress(emailAddress);
398                    user.setFacebookId(facebookId);
399                    user.setOpenId(openId);
400                    user.setLanguageId(locale.toString());
401                    user.setTimeZoneId(defaultUser.getTimeZoneId());
402                    user.setGreeting(greeting);
403                    user.setFirstName(firstName);
404                    user.setMiddleName(middleName);
405                    user.setLastName(lastName);
406                    user.setJobTitle(jobTitle);
407                    user.setActive(true);
408    
409                    userPersistence.update(user, false, serviceContext);
410    
411                    // Resources
412    
413                    String creatorUserName = StringPool.BLANK;
414    
415                    if (creatorUserId <= 0) {
416                            creatorUserId = user.getUserId();
417    
418                            // Don't grab the full name from the User object because it doesn't
419                            // have a corresponding Contact object yet
420    
421                            //creatorUserName = user.getFullName();
422                    }
423                    else {
424                            User creatorUser = userPersistence.findByPrimaryKey(creatorUserId);
425    
426                            creatorUserName = creatorUser.getFullName();
427                    }
428    
429                    resourceLocalService.addResources(
430                            companyId, 0, creatorUserId, User.class.getName(), user.getUserId(),
431                            false, false, false);
432    
433                    // Mail
434    
435                    if (user.hasCompanyMx()) {
436                            mailService.addUser(
437                                    companyId, userId, password1, firstName, middleName, lastName,
438                                    emailAddress);
439                    }
440    
441                    // Contact
442    
443                    Date birthday = PortalUtil.getDate(
444                            birthdayMonth, birthdayDay, birthdayYear,
445                            new ContactBirthdayException());
446    
447                    Contact contact = contactPersistence.create(user.getContactId());
448    
449                    contact.setCompanyId(user.getCompanyId());
450                    contact.setUserId(creatorUserId);
451                    contact.setUserName(creatorUserName);
452                    contact.setCreateDate(now);
453                    contact.setModifiedDate(now);
454                    contact.setAccountId(company.getAccountId());
455                    contact.setParentContactId(ContactConstants.DEFAULT_PARENT_CONTACT_ID);
456                    contact.setFirstName(firstName);
457                    contact.setMiddleName(middleName);
458                    contact.setLastName(lastName);
459                    contact.setPrefixId(prefixId);
460                    contact.setSuffixId(suffixId);
461                    contact.setMale(male);
462                    contact.setBirthday(birthday);
463                    contact.setJobTitle(jobTitle);
464    
465                    contactPersistence.update(contact, false, serviceContext);
466    
467                    // Group
468    
469                    groupLocalService.addGroup(
470                            user.getUserId(), User.class.getName(), user.getUserId(), null,
471                            null, 0, StringPool.SLASH + screenName, true, null);
472    
473                    // Groups
474    
475                    if (groupIds != null) {
476                            groupLocalService.addUserGroups(userId, groupIds);
477                    }
478    
479                    addDefaultGroups(userId);
480    
481                    // Organizations
482    
483                    updateOrganizations(userId, organizationIds);
484    
485                    // Roles
486    
487                    if (roleIds != null) {
488                            roleIds = EnterpriseAdminUtil.addRequiredRoles(user, roleIds);
489    
490                            userPersistence.setRoles(userId, roleIds);
491                    }
492    
493                    addDefaultRoles(userId);
494    
495                    // User groups
496    
497                    if (userGroupIds != null) {
498                            for (long userGroupId : userGroupIds) {
499                                    userGroupLocalService.copyUserGroupLayouts(
500                                            userGroupId, new long[] {userId});
501                            }
502    
503                            userPersistence.setUserGroups(userId, userGroupIds);
504                    }
505    
506                    addDefaultUserGroups(userId);
507    
508                    // Asset
509    
510                    if (serviceContext != null) {
511                            updateAsset(
512                                    creatorUserId, user, serviceContext.getAssetCategoryIds(),
513                                    serviceContext.getAssetTagNames());
514                    }
515    
516                    // Expando
517    
518                    user.setExpandoBridgeAttributes(serviceContext);
519    
520                    // Email
521    
522                    if (sendEmail) {
523                            try {
524                                    sendEmail(user, password1);
525                            }
526                            catch (IOException ioe) {
527                                    throw new SystemException(ioe);
528                            }
529                    }
530    
531                    // Indexer
532    
533                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
534    
535                    indexer.reindex(user);
536    
537                    return user;
538            }
539    
540            public void addUserGroupUsers(long userGroupId, long[] userIds)
541                    throws PortalException, SystemException {
542    
543                    userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
544    
545                    userGroupPersistence.addUsers(userGroupId, userIds);
546    
547                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
548    
549                    indexer.reindex(userIds);
550    
551                    PermissionCacheUtil.clearCache();
552            }
553    
554            @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
555            public int authenticateByEmailAddress(
556                            long companyId, String emailAddress, String password,
557                            Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
558                    throws PortalException, SystemException {
559    
560                    return authenticate(
561                            companyId, emailAddress, password, CompanyConstants.AUTH_TYPE_EA,
562                            headerMap, parameterMap);
563            }
564    
565            @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
566            public int authenticateByScreenName(
567                            long companyId, String screenName, String password,
568                            Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
569                    throws PortalException, SystemException {
570    
571                    return authenticate(
572                            companyId, screenName, password, CompanyConstants.AUTH_TYPE_SN,
573                            headerMap, parameterMap);
574            }
575    
576            @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
577            public int authenticateByUserId(
578                            long companyId, long userId, String password,
579                            Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
580                    throws PortalException, SystemException {
581    
582                    return authenticate(
583                            companyId, String.valueOf(userId), password,
584                            CompanyConstants.AUTH_TYPE_ID, headerMap, parameterMap);
585            }
586    
587            @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
588            public long authenticateForBasic(
589                            long companyId, String authType, String login, String password)
590                    throws PortalException, SystemException {
591    
592                    try {
593                            User user = null;
594    
595                            if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
596                                    user = getUserByEmailAddress(companyId, login);
597                            }
598                            else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
599                                    user = getUserByScreenName(companyId, login);
600                            }
601                            else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
602                                    user = getUserById(companyId, GetterUtil.getLong(login));
603                            }
604    
605                            if (!PropsValues.BASIC_AUTH_PASSWORD_REQUIRED) {
606                                    return user.getUserId();
607                            }
608    
609                            String userPassword = user.getPassword();
610    
611                            if (!user.isPasswordEncrypted()) {
612                                    userPassword = PwdEncryptor.encrypt(userPassword);
613                            }
614    
615                            String encPassword = PwdEncryptor.encrypt(password);
616    
617                            if (userPassword.equals(password) ||
618                                    userPassword.equals(encPassword)) {
619    
620                                    return user.getUserId();
621                            }
622                    }
623                    catch (NoSuchUserException nsue) {
624                    }
625    
626                    return 0;
627            }
628    
629            @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
630            public boolean authenticateForJAAS(long userId, String encPassword) {
631                    try {
632                            User user = userPersistence.findByPrimaryKey(userId);
633    
634                            if (user.isDefaultUser()) {
635                                    _log.error(
636                                            "The default user should never be allowed to authenticate");
637    
638                                    return false;
639                            }
640    
641                            String password = user.getPassword();
642    
643                            if (user.isPasswordEncrypted()) {
644                                    if (password.equals(encPassword)) {
645                                            return true;
646                                    }
647    
648                                    if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
649                                            encPassword = PwdEncryptor.encrypt(encPassword, password);
650    
651                                            if (password.equals(encPassword)) {
652                                                    return true;
653                                            }
654                                    }
655                            }
656                            else {
657                                    if (!PropsValues.PORTAL_JAAS_STRICT_PASSWORD) {
658                                            if (password.equals(encPassword)) {
659                                                    return true;
660                                            }
661                                    }
662    
663                                    password = PwdEncryptor.encrypt(password);
664    
665                                    if (password.equals(encPassword)) {
666                                            return true;
667                                    }
668                            }
669                    }
670                    catch (Exception e) {
671                            _log.error(e);
672                    }
673    
674                    return false;
675            }
676    
677            public void checkLockout(User user)
678                    throws PortalException, SystemException {
679    
680                    if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
681                            return;
682                    }
683    
684                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
685    
686                    if (passwordPolicy.isLockout()) {
687    
688                            // Reset failure count
689    
690                            Date now = new Date();
691                            int failedLoginAttempts = user.getFailedLoginAttempts();
692    
693                            if (failedLoginAttempts > 0) {
694                                    long failedLoginTime = user.getLastFailedLoginDate().getTime();
695                                    long elapsedTime = now.getTime() - failedLoginTime;
696                                    long requiredElapsedTime =
697                                            passwordPolicy.getResetFailureCount() * 1000;
698    
699                                    if ((requiredElapsedTime != 0) &&
700                                            (elapsedTime > requiredElapsedTime)) {
701    
702                                            user.setLastFailedLoginDate(null);
703                                            user.setFailedLoginAttempts(0);
704                                    }
705                            }
706    
707                            // Reset lockout
708    
709                            if (user.isLockout()) {
710                                    long lockoutTime = user.getLockoutDate().getTime();
711                                    long elapsedTime = now.getTime() - lockoutTime;
712                                    long requiredElapsedTime =
713                                            passwordPolicy.getLockoutDuration() * 1000;
714    
715                                    if ((requiredElapsedTime != 0) &&
716                                            (elapsedTime > requiredElapsedTime)) {
717    
718                                            user.setLockout(false);
719                                            user.setLockoutDate(null);
720                                    }
721                            }
722    
723                            if (user.isLockout()) {
724                                    throw new UserLockoutException();
725                            }
726                    }
727            }
728    
729            public void checkLoginFailure(User user) throws SystemException {
730                    Date now = new Date();
731    
732                    int failedLoginAttempts = user.getFailedLoginAttempts();
733    
734                    user.setLastFailedLoginDate(now);
735                    user.setFailedLoginAttempts(++failedLoginAttempts);
736    
737                    userPersistence.update(user, false);
738            }
739    
740            public void checkLoginFailureByEmailAddress(
741                            long companyId, String emailAddress)
742                    throws PortalException, SystemException {
743    
744                    User user = getUserByEmailAddress(companyId, emailAddress);
745    
746                    checkLoginFailure(user);
747            }
748    
749            public void checkLoginFailureById(long userId)
750                    throws PortalException, SystemException {
751    
752                    User user = userPersistence.findByPrimaryKey(userId);
753    
754                    checkLoginFailure(user);
755            }
756    
757            public void checkLoginFailureByScreenName(long companyId, String screenName)
758                    throws PortalException, SystemException {
759    
760                    User user = getUserByScreenName(companyId, screenName);
761    
762                    checkLoginFailure(user);
763            }
764    
765            public void checkPasswordExpired(User user)
766                    throws PortalException, SystemException {
767    
768                    if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
769                            return;
770                    }
771    
772                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
773    
774                    // Check if password has expired
775    
776                    if (isPasswordExpired(user)) {
777                            int graceLoginCount = user.getGraceLoginCount();
778    
779                            if (graceLoginCount < passwordPolicy.getGraceLimit()) {
780                                    user.setGraceLoginCount(++graceLoginCount);
781    
782                                    userPersistence.update(user, false);
783                            }
784                            else {
785                                    throw new PasswordExpiredException();
786                            }
787                    }
788    
789                    // Check if warning message should be sent
790    
791                    if (isPasswordExpiringSoon(user)) {
792                            user.setPasswordReset(true);
793    
794                            userPersistence.update(user, false);
795                    }
796    
797                    // Check if user should be forced to change password on first login
798    
799                    if (passwordPolicy.isChangeable() &&
800                            passwordPolicy.isChangeRequired()) {
801    
802                            if (user.getLastLoginDate() == null) {
803                                    boolean passwordReset = false;
804    
805                                    if (passwordPolicy.isChangeable() &&
806                                            passwordPolicy.isChangeRequired()) {
807    
808                                            passwordReset = true;
809                                    }
810    
811                                    user.setPasswordReset(passwordReset);
812    
813                                    userPersistence.update(user, false);
814                            }
815                    }
816            }
817    
818            public KeyValuePair decryptUserId(
819                            long companyId, String name, String password)
820                    throws PortalException, SystemException {
821    
822                    Company company = companyPersistence.findByPrimaryKey(companyId);
823    
824                    try {
825                            name = Encryptor.decrypt(company.getKeyObj(), name);
826                    }
827                    catch (EncryptorException ee) {
828                            throw new SystemException(ee);
829                    }
830    
831                    long userId = GetterUtil.getLong(name);
832    
833                    User user = userPersistence.findByPrimaryKey(userId);
834    
835                    try {
836                            password = Encryptor.decrypt(company.getKeyObj(), password);
837                    }
838                    catch (EncryptorException ee) {
839                            throw new SystemException(ee);
840                    }
841    
842                    String encPassword = PwdEncryptor.encrypt(password);
843    
844                    if (user.getPassword().equals(encPassword)) {
845                            if (isPasswordExpired(user)) {
846                                    user.setPasswordReset(true);
847    
848                                    userPersistence.update(user, false);
849                            }
850    
851                            return new KeyValuePair(name, password);
852                    }
853                    else {
854                            throw new PrincipalException();
855                    }
856            }
857    
858            public void deletePortrait(long userId)
859                    throws PortalException, SystemException {
860    
861                    User user = userPersistence.findByPrimaryKey(userId);
862    
863                    long portraitId = user.getPortraitId();
864    
865                    if (portraitId > 0) {
866                            user.setPortraitId(0);
867    
868                            userPersistence.update(user, false);
869    
870                            imageLocalService.deleteImage(portraitId);
871                    }
872            }
873    
874            public void deleteRoleUser(long roleId, long userId)
875                    throws PortalException, SystemException {
876    
877                    rolePersistence.removeUser(roleId, userId);
878    
879                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
880    
881                    indexer.reindex(userId);
882    
883                    PermissionCacheUtil.clearCache();
884            }
885    
886            public void deleteUser(long userId)
887                    throws PortalException, SystemException {
888    
889                    if (!PropsValues.USERS_DELETE) {
890                            throw new RequiredUserException();
891                    }
892    
893                    User user = userPersistence.findByPrimaryKey(userId);
894    
895                    // Indexer
896    
897                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
898    
899                    indexer.delete(user);
900    
901                    // Browser tracker
902    
903                    browserTrackerLocalService.deleteUserBrowserTracker(userId);
904    
905                    // Group
906    
907                    Group group = user.getGroup();
908    
909                    if (group != null) {
910                            groupLocalService.deleteGroup(group.getGroupId());
911                    }
912    
913                    // Portrait
914    
915                    imageLocalService.deleteImage(user.getPortraitId());
916    
917                    // Password policy relation
918    
919                    passwordPolicyRelLocalService.deletePasswordPolicyRel(
920                            User.class.getName(), userId);
921    
922                    // Old passwords
923    
924                    passwordTrackerLocalService.deletePasswordTrackers(userId);
925    
926                    // Subscriptions
927    
928                    subscriptionLocalService.deleteSubscriptions(userId);
929    
930                    // External user ids
931    
932                    userIdMapperLocalService.deleteUserIdMappers(userId);
933    
934                    // Announcements
935    
936                    announcementsDeliveryLocalService.deleteDeliveries(userId);
937    
938                    // Asset
939    
940                    assetEntryLocalService.deleteEntry(User.class.getName(), userId);
941    
942                    // Blogs
943    
944                    blogsStatsUserLocalService.deleteStatsUserByUserId(userId);
945    
946                    // Document library
947    
948                    dlFileRankLocalService.deleteFileRanks(userId);
949    
950                    // Expando
951    
952                    expandoValueLocalService.deleteValues(User.class.getName(), userId);
953    
954                    // Message boards
955    
956                    mbBanLocalService.deleteBansByBanUserId(userId);
957                    mbMessageFlagLocalService.deleteFlags(userId);
958                    mbStatsUserLocalService.deleteStatsUsersByUserId(userId);
959    
960                    // Shopping cart
961    
962                    shoppingCartLocalService.deleteUserCarts(userId);
963    
964                    // Social
965    
966                    socialActivityLocalService.deleteUserActivities(userId);
967                    socialRequestLocalService.deleteReceiverUserRequests(userId);
968                    socialRequestLocalService.deleteUserRequests(userId);
969    
970                    // Mail
971    
972                    mailService.deleteUser(user.getCompanyId(), userId);
973    
974                    // Contact
975    
976                    try {
977                            contactLocalService.deleteContact(user.getContactId());
978                    }
979                    catch (NoSuchContactException nsce) {
980                    }
981    
982                    // Resources
983    
984                    resourceLocalService.deleteResource(
985                            user.getCompanyId(), User.class.getName(),
986                            ResourceConstants.SCOPE_INDIVIDUAL, user.getUserId());
987    
988                    // Group roles
989    
990                    userGroupRoleLocalService.deleteUserGroupRolesByUserId(userId);
991    
992                    // User
993    
994                    userPersistence.remove(userId);
995    
996                    // Permission cache
997    
998                    PermissionCacheUtil.clearCache();
999            }
1000    
1001            public String encryptUserId(String name)
1002                    throws PortalException, SystemException {
1003    
1004                    long userId = GetterUtil.getLong(name);
1005    
1006                    User user = userPersistence.findByPrimaryKey(userId);
1007    
1008                    Company company = companyPersistence.findByPrimaryKey(
1009                            user.getCompanyId());
1010    
1011                    try {
1012                            return Encryptor.encrypt(company.getKeyObj(), name);
1013                    }
1014                    catch (EncryptorException ee) {
1015                            throw new SystemException(ee);
1016                    }
1017            }
1018    
1019            public List<User> getCompanyUsers(long companyId, int start, int end)
1020                    throws SystemException {
1021    
1022                    return userPersistence.findByCompanyId(companyId, start, end);
1023            }
1024    
1025            public int getCompanyUsersCount(long companyId) throws SystemException {
1026                    return userPersistence.countByCompanyId(companyId);
1027            }
1028    
1029            public User getDefaultUser(long companyId)
1030                    throws PortalException, SystemException {
1031    
1032                    User userModel = _defaultUsers.get(companyId);
1033    
1034                    if (userModel == null) {
1035                            userModel = userPersistence.findByC_DU(companyId, true);
1036    
1037                            _defaultUsers.put(companyId, userModel);
1038                    }
1039    
1040                    return userModel;
1041            }
1042    
1043            public long getDefaultUserId(long companyId)
1044                    throws PortalException, SystemException {
1045    
1046                    User user = getDefaultUser(companyId);
1047    
1048                    return user.getUserId();
1049            }
1050    
1051            public long[] getGroupUserIds(long groupId) throws SystemException {
1052                    return getUserIds(getGroupUsers(groupId));
1053            }
1054    
1055            public List<User> getGroupUsers(long groupId) throws SystemException {
1056                    return groupPersistence.getUsers(groupId);
1057            }
1058    
1059            public int getGroupUsersCount(long groupId) throws SystemException {
1060                    return groupPersistence.getUsersSize(groupId);
1061            }
1062    
1063            public int getGroupUsersCount(long groupId, boolean active)
1064                    throws PortalException, SystemException {
1065    
1066                    Group group = groupPersistence.findByPrimaryKey(groupId);
1067    
1068                    LinkedHashMap<String, Object> params =
1069                            new LinkedHashMap<String, Object>();
1070    
1071                    params.put("usersGroups", new Long(groupId));
1072    
1073                    return searchCount(group.getCompanyId(), null, active, params);
1074            }
1075    
1076            public List<User> getNoAnnouncementsDeliveries(String type)
1077                    throws SystemException {
1078    
1079                    return userFinder.findByNoAnnouncementsDeliveries(type);
1080            }
1081    
1082            public List<User> getNoContacts() throws SystemException {
1083                    return userFinder.findByNoContacts();
1084            }
1085    
1086            public List<User> getNoGroups() throws SystemException {
1087                    return userFinder.findByNoGroups();
1088            }
1089    
1090            public long[] getOrganizationUserIds(long organizationId)
1091                    throws SystemException {
1092    
1093                    return getUserIds(getOrganizationUsers(organizationId));
1094            }
1095    
1096            public List<User> getOrganizationUsers(long organizationId)
1097                    throws SystemException {
1098    
1099                    return organizationPersistence.getUsers(organizationId);
1100            }
1101    
1102            public int getOrganizationUsersCount(long organizationId)
1103                    throws SystemException {
1104    
1105                    return organizationPersistence.getUsersSize(organizationId);
1106            }
1107    
1108            public int getOrganizationUsersCount(long organizationId, boolean active)
1109                    throws PortalException, SystemException {
1110    
1111                    Organization organization = organizationPersistence.findByPrimaryKey(
1112                            organizationId);
1113    
1114                    LinkedHashMap<String, Object> params =
1115                            new LinkedHashMap<String, Object>();
1116    
1117                    params.put("usersOrgs", new Long(organizationId));
1118    
1119                    return searchCount(organization.getCompanyId(), null, active, params);
1120            }
1121    
1122            public long[] getRoleUserIds(long roleId) throws SystemException {
1123                    return getUserIds(getRoleUsers(roleId));
1124            }
1125    
1126            public List<User> getRoleUsers(long roleId) throws SystemException {
1127                    return rolePersistence.getUsers(roleId);
1128            }
1129    
1130            public List<User> getRoleUsers(long roleId, int start, int end)
1131                    throws SystemException {
1132    
1133                    return rolePersistence.getUsers(roleId, start, end);
1134            }
1135    
1136            public int getRoleUsersCount(long roleId) throws SystemException {
1137                    return rolePersistence.getUsersSize(roleId);
1138            }
1139    
1140            public int getRoleUsersCount(long roleId, boolean active)
1141                    throws PortalException, SystemException {
1142    
1143                    Role role = rolePersistence.findByPrimaryKey(
1144                            roleId);
1145    
1146                    LinkedHashMap<String, Object> params =
1147                            new LinkedHashMap<String, Object>();
1148    
1149                    params.put("usersRoles", new Long(roleId));
1150    
1151                    return searchCount(role.getCompanyId(), null, active, params);
1152            }
1153    
1154            public List<User> getSocialUsers(
1155                            long userId, int type, int start, int end, OrderByComparator obc)
1156                    throws PortalException, SystemException {
1157    
1158                    User user = userPersistence.findByPrimaryKey(userId);
1159    
1160                    LinkedHashMap<String, Object> params =
1161                            new LinkedHashMap<String, Object>();
1162    
1163                    params.put("socialRelationType", new Long[] {userId, new Long(type)});
1164    
1165                    return search(user.getCompanyId(), null, true, params, start, end, obc);
1166            }
1167    
1168            public List<User> getSocialUsers(
1169                            long userId, int start, int end, OrderByComparator obc)
1170                    throws PortalException, SystemException {
1171    
1172                    User user = userPersistence.findByPrimaryKey(userId);
1173    
1174                    LinkedHashMap<String, Object> params =
1175                            new LinkedHashMap<String, Object>();
1176    
1177                    params.put("socialRelation", new Long[] {userId});
1178    
1179                    return search(
1180                            user.getCompanyId(), null, true, params, start, end, obc);
1181            }
1182    
1183            public List<User> getSocialUsers(
1184                            long userId1, long userId2, int type, int start, int end,
1185                            OrderByComparator obc)
1186                    throws PortalException, SystemException {
1187    
1188                    User user1 = userPersistence.findByPrimaryKey(userId1);
1189    
1190                    LinkedHashMap<String, Object> params =
1191                            new LinkedHashMap<String, Object>();
1192    
1193                    params.put(
1194                            "socialMutualRelationType",
1195                            new Long[] {userId1, new Long(type), userId2, new Long(type)});
1196    
1197                    return search(
1198                            user1.getCompanyId(), null, true, params, start, end, obc);
1199            }
1200    
1201            public List<User> getSocialUsers(
1202                            long userId1, long userId2, int start, int end,
1203                            OrderByComparator obc)
1204                    throws PortalException, SystemException {
1205    
1206                    User user1 = userPersistence.findByPrimaryKey(userId1);
1207    
1208                    LinkedHashMap<String, Object> params =
1209                            new LinkedHashMap<String, Object>();
1210    
1211                    params.put("socialMutualRelation", new Long[] {userId1, userId2});
1212    
1213                    return search(
1214                            user1.getCompanyId(), null, true, params, start, end, obc);
1215            }
1216    
1217            public int getSocialUsersCount(long userId)
1218                    throws PortalException, SystemException {
1219    
1220                    User user = userPersistence.findByPrimaryKey(userId);
1221    
1222                    LinkedHashMap<String, Object> params =
1223                            new LinkedHashMap<String, Object>();
1224    
1225                    params.put("socialRelation", new Long[] {userId});
1226    
1227                    return searchCount(user.getCompanyId(), null, true, params);
1228            }
1229    
1230            public int getSocialUsersCount(long userId, int type)
1231                    throws PortalException, SystemException {
1232    
1233                    User user = userPersistence.findByPrimaryKey(userId);
1234    
1235                    LinkedHashMap<String, Object> params =
1236                            new LinkedHashMap<String, Object>();
1237    
1238                    params.put("socialRelationType", new Long[] {userId, new Long(type)});
1239    
1240                    return searchCount(user.getCompanyId(), null, true, params);
1241            }
1242    
1243            public int getSocialUsersCount(long userId1, long userId2)
1244                    throws PortalException, SystemException {
1245    
1246                    User user1 = userPersistence.findByPrimaryKey(userId1);
1247    
1248                    LinkedHashMap<String, Object> params =
1249                            new LinkedHashMap<String, Object>();
1250    
1251                    params.put("socialMutualRelation", new Long[] {userId1, userId2});
1252    
1253                    return searchCount(user1.getCompanyId(), null, true, params);
1254            }
1255    
1256            public int getSocialUsersCount(long userId1, long userId2, int type)
1257                    throws PortalException, SystemException {
1258    
1259                    User user1 = userPersistence.findByPrimaryKey(userId1);
1260    
1261                    LinkedHashMap<String, Object> params =
1262                            new LinkedHashMap<String, Object>();
1263    
1264                    params.put(
1265                            "socialMutualRelationType",
1266                            new Long[] {userId1, new Long(type), userId2, new Long(type)});
1267    
1268                    return searchCount(user1.getCompanyId(), null, true, params);
1269            }
1270    
1271            public User getUserByContactId(long contactId)
1272                    throws PortalException, SystemException {
1273    
1274                    return userPersistence.findByContactId(contactId);
1275            }
1276    
1277            public User getUserByEmailAddress(long companyId, String emailAddress)
1278                    throws PortalException, SystemException {
1279    
1280                    emailAddress = emailAddress.trim().toLowerCase();
1281    
1282                    return userPersistence.findByC_EA(companyId, emailAddress);
1283            }
1284    
1285            public User getUserByFacebookId(long companyId, long facebookId)
1286                    throws PortalException, SystemException {
1287    
1288                    return userPersistence.findByC_FID(companyId, facebookId);
1289            }
1290    
1291            public User getUserById(long userId)
1292                    throws PortalException, SystemException {
1293    
1294                    return userPersistence.findByPrimaryKey(userId);
1295            }
1296    
1297            public User getUserById(long companyId, long userId)
1298                    throws PortalException, SystemException {
1299    
1300                    return userPersistence.findByC_U(companyId, userId);
1301            }
1302    
1303            public User getUserByOpenId(long companyId, String openId)
1304                    throws PortalException, SystemException {
1305    
1306                    return userPersistence.findByC_O(companyId, openId);
1307            }
1308    
1309            public User getUserByPortraitId(long portraitId)
1310                    throws PortalException, SystemException {
1311    
1312                    return userPersistence.findByPortraitId(portraitId);
1313            }
1314    
1315            public User getUserByScreenName(long companyId, String screenName)
1316                    throws PortalException, SystemException {
1317    
1318                    screenName = getScreenName(screenName);
1319    
1320                    return userPersistence.findByC_SN(companyId, screenName);
1321            }
1322    
1323            public User getUserByUuid(String uuid)
1324                    throws PortalException, SystemException {
1325    
1326                    List<User> users = userPersistence.findByUuid(uuid);
1327    
1328                    if (users.isEmpty()) {
1329                            throw new NoSuchUserException();
1330                    }
1331                    else {
1332                            return users.get(0);
1333                    }
1334            }
1335    
1336            public List<User> getUserGroupUsers(long userGroupId)
1337                    throws SystemException {
1338    
1339                    return userGroupPersistence.getUsers(userGroupId);
1340            }
1341    
1342            public int getUserGroupUsersCount(long userGroupId) throws SystemException {
1343                    return userGroupPersistence.getUsersSize(userGroupId);
1344            }
1345    
1346            public int getUserGroupUsersCount(long userGroupId, boolean active)
1347                    throws PortalException, SystemException {
1348    
1349                    UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
1350                            userGroupId);
1351    
1352                    LinkedHashMap<String, Object> params =
1353                            new LinkedHashMap<String, Object>();
1354    
1355                    params.put("usersUserGroups", new Long(userGroupId));
1356    
1357                    return searchCount(userGroup.getCompanyId(), null, active, params);
1358            }
1359    
1360            public long getUserIdByEmailAddress(long companyId, String emailAddress)
1361                    throws PortalException, SystemException {
1362    
1363                    emailAddress = emailAddress.trim().toLowerCase();
1364    
1365                    User user = userPersistence.findByC_EA(companyId, emailAddress);
1366    
1367                    return user.getUserId();
1368            }
1369    
1370            public long getUserIdByScreenName(long companyId, String screenName)
1371                    throws PortalException, SystemException {
1372    
1373                    screenName = getScreenName(screenName);
1374    
1375                    User user = userPersistence.findByC_SN(companyId, screenName);
1376    
1377                    return user.getUserId();
1378            }
1379    
1380            public boolean hasGroupUser(long groupId, long userId)
1381                    throws SystemException {
1382    
1383                    return groupPersistence.containsUser(groupId, userId);
1384            }
1385    
1386            public boolean hasOrganizationUser(long organizationId, long userId)
1387                    throws SystemException {
1388    
1389                    return organizationPersistence.containsUser(organizationId, userId);
1390            }
1391    
1392            public boolean hasPasswordPolicyUser(long passwordPolicyId, long userId)
1393                    throws SystemException {
1394    
1395                    return passwordPolicyRelLocalService.hasPasswordPolicyRel(
1396                            passwordPolicyId, User.class.getName(), userId);
1397            }
1398    
1399            public boolean hasRoleUser(long roleId, long userId)
1400                    throws SystemException {
1401    
1402                    return rolePersistence.containsUser(roleId, userId);
1403            }
1404    
1405            /**
1406             * Returns <code>true</code> if the user has the role.
1407             *
1408             * @return <code>true</code> if the user has the role
1409             */
1410            public boolean hasRoleUser(
1411                            long companyId, String name, long userId, boolean inherited)
1412                    throws PortalException, SystemException {
1413    
1414                    return roleLocalService.hasUserRole(userId, companyId, name, inherited);
1415            }
1416    
1417            public boolean hasTeamUser(long teamId, long userId)
1418                    throws SystemException {
1419    
1420                    return teamPersistence.containsUser(teamId, userId);
1421            }
1422    
1423            public boolean hasUserGroupUser(long userGroupId, long userId)
1424                    throws SystemException {
1425    
1426                    return userGroupPersistence.containsUser(userGroupId, userId);
1427            }
1428    
1429            public boolean isPasswordExpired(User user)
1430                    throws PortalException, SystemException {
1431    
1432                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1433    
1434                    if (passwordPolicy.getExpireable()) {
1435                            Date now = new Date();
1436    
1437                            if (user.getPasswordModifiedDate() == null) {
1438                                    user.setPasswordModifiedDate(now);
1439    
1440                                    userLocalService.updateUser(user, false);
1441                            }
1442    
1443                            long passwordStartTime = user.getPasswordModifiedDate().getTime();
1444                            long elapsedTime = now.getTime() - passwordStartTime;
1445    
1446                            if (elapsedTime > (passwordPolicy.getMaxAge() * 1000)) {
1447                                    return true;
1448                            }
1449                            else {
1450                                    return false;
1451                            }
1452                    }
1453    
1454                    return false;
1455            }
1456    
1457            public boolean isPasswordExpiringSoon(User user)
1458                    throws PortalException, SystemException {
1459    
1460                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1461    
1462                    if (passwordPolicy.isExpireable()) {
1463                            Date now = new Date();
1464    
1465                            if (user.getPasswordModifiedDate() == null) {
1466                                    user.setPasswordModifiedDate(now);
1467    
1468                                    userLocalService.updateUser(user, false);
1469                            }
1470    
1471                            long timeModified = user.getPasswordModifiedDate().getTime();
1472                            long passwordExpiresOn =
1473                                    (passwordPolicy.getMaxAge() * 1000) + timeModified;
1474    
1475                            long timeStartWarning =
1476                                    passwordExpiresOn - (passwordPolicy.getWarningTime() * 1000);
1477    
1478                            if (now.getTime() > timeStartWarning) {
1479                                    return true;
1480                            }
1481                            else {
1482                                    return false;
1483                            }
1484                    }
1485    
1486                    return false;
1487            }
1488    
1489            public List<User> search(
1490                            long companyId, String keywords, Boolean active,
1491                            LinkedHashMap<String, Object> params, int start, int end,
1492                            OrderByComparator obc)
1493                    throws SystemException {
1494    
1495                    return userFinder.findByKeywords(
1496                            companyId, keywords, active, params, start, end, obc);
1497            }
1498    
1499            public Hits search(
1500                            long companyId, String keywords, Boolean active,
1501                            LinkedHashMap<String, Object> params, int start, int end, Sort sort)
1502                    throws SystemException {
1503    
1504                    String firstName = null;
1505                    String middleName = null;
1506                    String lastName = null;
1507                    String screenName = null;
1508                    String emailAddress = null;
1509                    boolean andOperator = false;
1510    
1511                    if (Validator.isNotNull(keywords)) {
1512                            firstName = keywords;
1513                            middleName = keywords;
1514                            lastName = keywords;
1515                            screenName = keywords;
1516                            emailAddress = keywords;
1517                    }
1518                    else {
1519                            andOperator = true;
1520                    }
1521    
1522                    return search(
1523                            companyId, firstName, middleName, lastName, screenName,
1524                            emailAddress, active, params, andOperator, start, end, sort);
1525            }
1526    
1527            public List<User> search(
1528                            long companyId, String firstName, String middleName,
1529                            String lastName, String screenName, String emailAddress,
1530                            Boolean active, LinkedHashMap<String, Object> params,
1531                            boolean andSearch, int start, int end, OrderByComparator obc)
1532                    throws SystemException {
1533    
1534                    return userFinder.findByC_FN_MN_LN_SN_EA_A(
1535                            companyId, firstName, middleName, lastName, screenName,
1536                            emailAddress, active, params, andSearch, start, end, obc);
1537            }
1538    
1539            public Hits search(
1540                            long companyId, String firstName, String middleName,
1541                            String lastName, String screenName, String emailAddress,
1542                            Boolean active, LinkedHashMap<String, Object> params,
1543                            boolean andSearch, int start, int end, Sort sort)
1544                    throws SystemException {
1545    
1546                    try {
1547                            Map<String, Serializable> attributes =
1548                                    new HashMap<String, Serializable>();
1549    
1550                            attributes.put("active", active);
1551                            attributes.put("emailAddress", emailAddress);
1552                            attributes.put("firstName", firstName);
1553                            attributes.put("lastName", lastName);
1554                            attributes.put("middleName", middleName);
1555                            attributes.put("params", params);
1556                            attributes.put("screenName", screenName);
1557    
1558                            SearchContext searchContext = new SearchContext();
1559    
1560                            searchContext.setAndSearch(andSearch);
1561                            searchContext.setAttributes(attributes);
1562                            searchContext.setCompanyId(companyId);
1563                            searchContext.setEnd(end);
1564                            searchContext.setSorts(new Sort[] {sort});
1565                            searchContext.setStart(start);
1566    
1567                            Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1568    
1569                            return indexer.search(searchContext);
1570                    }
1571                    catch (Exception e) {
1572                            throw new SystemException(e);
1573                    }
1574            }
1575    
1576            public int searchCount(
1577                            long companyId, String keywords, Boolean active,
1578                            LinkedHashMap<String, Object> params)
1579                    throws SystemException {
1580    
1581                    return userFinder.countByKeywords(companyId, keywords, active, params);
1582            }
1583    
1584            public int searchCount(
1585                            long companyId, String firstName, String middleName,
1586                            String lastName, String screenName, String emailAddress,
1587                            Boolean active, LinkedHashMap<String, Object> params,
1588                            boolean andSearch)
1589                    throws SystemException {
1590    
1591                    return userFinder.countByC_FN_MN_LN_SN_EA_A(
1592                            companyId, firstName, middleName, lastName, screenName,
1593                            emailAddress, active, params, andSearch);
1594            }
1595    
1596            public void sendPassword(
1597                            long companyId, String emailAddress, String remoteAddr,
1598                            String remoteHost, String userAgent, String fromName,
1599                            String fromAddress, String subject, String body,
1600                            ServiceContext serviceContext)
1601                    throws PortalException, SystemException {
1602    
1603                    try {
1604                            doSendPassword(
1605                                    companyId, emailAddress, remoteAddr, remoteHost, userAgent,
1606                                    fromName, fromAddress, subject, body, serviceContext);
1607                    }
1608                    catch (IOException ioe) {
1609                            throw new SystemException(ioe);
1610                    }
1611            }
1612    
1613            public void setRoleUsers(long roleId, long[] userIds)
1614                    throws PortalException, SystemException {
1615    
1616                    rolePersistence.setUsers(roleId, userIds);
1617    
1618                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1619    
1620                    indexer.reindex(userIds);
1621    
1622                    PermissionCacheUtil.clearCache();
1623            }
1624    
1625            public void setUserGroupUsers(long userGroupId, long[] userIds)
1626                    throws PortalException, SystemException {
1627    
1628                    userGroupLocalService.copyUserGroupLayouts(userGroupId, userIds);
1629    
1630                    userGroupPersistence.setUsers(userGroupId, userIds);
1631    
1632                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1633    
1634                    indexer.reindex(userIds);
1635    
1636                    PermissionCacheUtil.clearCache();
1637            }
1638    
1639            public void unsetGroupUsers(long groupId, long[] userIds)
1640                    throws PortalException, SystemException {
1641    
1642                    userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
1643    
1644                    groupPersistence.removeUsers(groupId, userIds);
1645    
1646                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1647    
1648                    indexer.reindex(userIds);
1649    
1650                    PermissionCacheUtil.clearCache();
1651            }
1652    
1653            public void unsetOrganizationUsers(long organizationId, long[] userIds)
1654                    throws PortalException, SystemException {
1655    
1656                    Organization organization = organizationPersistence.findByPrimaryKey(
1657                            organizationId);
1658    
1659                    Group group = organization.getGroup();
1660    
1661                    long groupId = group.getGroupId();
1662    
1663                    userGroupRoleLocalService.deleteUserGroupRoles(userIds, groupId);
1664    
1665                    organizationPersistence.removeUsers(organizationId, userIds);
1666    
1667                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1668    
1669                    indexer.reindex(userIds);
1670    
1671                    PermissionCacheUtil.clearCache();
1672            }
1673    
1674            public void unsetPasswordPolicyUsers(
1675                            long passwordPolicyId, long[] userIds)
1676                    throws SystemException {
1677    
1678                    passwordPolicyRelLocalService.deletePasswordPolicyRels(
1679                            passwordPolicyId, User.class.getName(), userIds);
1680            }
1681    
1682            public void unsetRoleUsers(long roleId, List<User> users)
1683                    throws PortalException, SystemException {
1684    
1685                    Role role = rolePersistence.findByPrimaryKey(roleId);
1686    
1687                    if (role.getName().equals(RoleConstants.USER)) {
1688                            return;
1689                    }
1690    
1691                    rolePersistence.removeUsers(roleId, users);
1692    
1693                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1694    
1695                    indexer.reindex(users);
1696    
1697                    PermissionCacheUtil.clearCache();
1698            }
1699    
1700            public void unsetRoleUsers(long roleId, long[] userIds)
1701                    throws PortalException, SystemException {
1702    
1703                    Role role = rolePersistence.findByPrimaryKey(roleId);
1704    
1705                    if (role.getName().equals(RoleConstants.USER)) {
1706                            return;
1707                    }
1708    
1709                    rolePersistence.removeUsers(roleId, userIds);
1710    
1711                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1712    
1713                    indexer.reindex(userIds);
1714    
1715                    PermissionCacheUtil.clearCache();
1716            }
1717    
1718            public void unsetTeamUsers(long teamId, long[] userIds)
1719                    throws PortalException, SystemException {
1720    
1721                    teamPersistence.removeUsers(teamId, userIds);
1722    
1723                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1724    
1725                    indexer.reindex(userIds);
1726    
1727                    PermissionCacheUtil.clearCache();
1728            }
1729    
1730            public void unsetUserGroupUsers(long userGroupId, long[] userIds)
1731                    throws PortalException, SystemException {
1732    
1733                    userGroupPersistence.removeUsers(userGroupId, userIds);
1734    
1735                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1736    
1737                    indexer.reindex(userIds);
1738    
1739                    PermissionCacheUtil.clearCache();
1740            }
1741    
1742            public User updateActive(long userId, boolean active)
1743                    throws PortalException, SystemException {
1744    
1745                    User user = userPersistence.findByPrimaryKey(userId);
1746    
1747                    user.setActive(active);
1748    
1749                    userPersistence.update(user, false);
1750    
1751                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1752    
1753                    indexer.reindex(user);
1754    
1755                    return user;
1756            }
1757    
1758            public User updateAgreedToTermsOfUse(
1759                            long userId, boolean agreedToTermsOfUse)
1760                    throws PortalException, SystemException {
1761    
1762                    User user = userPersistence.findByPrimaryKey(userId);
1763    
1764                    user.setAgreedToTermsOfUse(agreedToTermsOfUse);
1765    
1766                    userPersistence.update(user, false);
1767    
1768                    return user;
1769            }
1770    
1771            public void updateAsset(
1772                            long userId, User user, long[] assetCategoryIds,
1773                            String[] assetTagNames)
1774                    throws PortalException, SystemException {
1775    
1776                    User owner = userPersistence.findByPrimaryKey(userId);
1777    
1778                    Company company = companyPersistence.findByPrimaryKey(
1779                            owner.getCompanyId());
1780    
1781                    Group companyGroup = company.getGroup();
1782    
1783                    assetEntryLocalService.updateEntry(
1784                            userId, companyGroup.getGroupId(), User.class.getName(),
1785                            user.getUserId(), user.getUuid(), assetCategoryIds, assetTagNames,
1786                            false, null, null, null, null, null, user.getFullName(), null, null,
1787                            null, 0, 0, null, false);
1788            }
1789    
1790            public User updateCreateDate(long userId, Date createDate)
1791                    throws PortalException, SystemException {
1792    
1793                    User user = userPersistence.findByPrimaryKey(userId);
1794    
1795                    user.setCreateDate(createDate);
1796    
1797                    userPersistence.update(user, false);
1798    
1799                    return user;
1800            }
1801    
1802            public User updateEmailAddress(
1803                            long userId, String password, String emailAddress1,
1804                            String emailAddress2)
1805                    throws PortalException, SystemException {
1806    
1807                    emailAddress1 = emailAddress1.trim().toLowerCase();
1808                    emailAddress2 = emailAddress2.trim().toLowerCase();
1809    
1810                    if (!emailAddress1.equals(emailAddress2)) {
1811                            throw new UserEmailAddressException();
1812                    }
1813    
1814                    User user = userPersistence.findByPrimaryKey(userId);
1815    
1816                    validateEmailAddress(user.getCompanyId(), emailAddress1);
1817                    validateEmailAddress(user.getCompanyId(), emailAddress2);
1818    
1819                    if (!user.getEmailAddress().equalsIgnoreCase(emailAddress1)) {
1820                            if (userPersistence.fetchByC_EA(
1821                                            user.getCompanyId(), emailAddress1) != null) {
1822    
1823                                    throw new DuplicateUserEmailAddressException();
1824                            }
1825                    }
1826    
1827                    setEmailAddress(
1828                            user, password, user.getFirstName(), user.getMiddleName(),
1829                            user.getLastName(), emailAddress1);
1830    
1831                    userPersistence.update(user, false);
1832    
1833                    return user;
1834            }
1835    
1836            public void updateGroups(long userId, long[] newGroupIds)
1837                    throws PortalException, SystemException {
1838    
1839                    if (newGroupIds == null) {
1840                            return;
1841                    }
1842    
1843                    List<Group> oldGroups = userPersistence.getGroups(userId);
1844    
1845                    List<Long> oldGroupIds = new ArrayList<Long>(oldGroups.size());
1846    
1847                    for (Group oldGroup : oldGroups) {
1848                            long oldGroupId = oldGroup.getGroupId();
1849    
1850                            oldGroupIds.add(oldGroupId);
1851    
1852                            if (!ArrayUtil.contains(newGroupIds, oldGroupId)) {
1853                                    unsetGroupUsers(oldGroupId, new long[] {userId});
1854                            }
1855                    }
1856    
1857                    for (long newGroupId : newGroupIds) {
1858                            if (!oldGroupIds.contains(newGroupId)) {
1859                                    addGroupUsers(newGroupId, new long[] {userId});
1860                            }
1861                    }
1862    
1863                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
1864    
1865                    indexer.reindex(new long[] {userId});
1866    
1867                    PermissionCacheUtil.clearCache();
1868            }
1869    
1870            public User updateLastLogin(long userId, String loginIP)
1871                    throws PortalException, SystemException {
1872    
1873                    User user = userPersistence.findByPrimaryKey(userId);
1874    
1875                    Date lastLoginDate = user.getLoginDate();
1876    
1877                    if (lastLoginDate == null) {
1878                            lastLoginDate = new Date();
1879                    }
1880    
1881                    user.setLoginDate(new Date());
1882                    user.setLoginIP(loginIP);
1883                    user.setLastLoginDate(lastLoginDate);
1884                    user.setLastLoginIP(user.getLoginIP());
1885                    user.setLastFailedLoginDate(null);
1886                    user.setFailedLoginAttempts(0);
1887    
1888                    userPersistence.update(user, false);
1889    
1890                    return user;
1891            }
1892    
1893            public User updateLockout(User user, boolean lockout)
1894                    throws PortalException, SystemException {
1895    
1896                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
1897    
1898                    if ((passwordPolicy == null) || !passwordPolicy.isLockout()) {
1899                            return user;
1900                    }
1901    
1902                    Date lockoutDate = null;
1903    
1904                    if (lockout) {
1905                            lockoutDate = new Date();
1906                    }
1907    
1908                    user.setLockout(lockout);
1909                    user.setLockoutDate(lockoutDate);
1910    
1911                    if (!lockout) {
1912                            user.setLastFailedLoginDate(lockoutDate);
1913                            user.setFailedLoginAttempts(0);
1914                    }
1915    
1916                    userPersistence.update(user, false);
1917    
1918                    return user;
1919            }
1920    
1921            public User updateLockoutByEmailAddress(
1922                            long companyId, String emailAddress, boolean lockout)
1923                    throws PortalException, SystemException {
1924    
1925                    User user = getUserByEmailAddress(companyId, emailAddress);
1926    
1927                    return updateLockout(user, lockout);
1928            }
1929    
1930            public User updateLockoutById(long userId, boolean lockout)
1931                    throws PortalException, SystemException {
1932    
1933                    User user = userPersistence.findByPrimaryKey(userId);
1934    
1935                    return updateLockout(user, lockout);
1936            }
1937    
1938            public User updateLockoutByScreenName(
1939                            long companyId, String screenName, boolean lockout)
1940                    throws PortalException, SystemException {
1941    
1942                    User user = getUserByScreenName(companyId, screenName);
1943    
1944                    return updateLockout(user, lockout);
1945            }
1946    
1947            public User updateModifiedDate(long userId, Date modifiedDate)
1948                    throws PortalException, SystemException {
1949    
1950                    User user = userPersistence.findByPrimaryKey(userId);
1951    
1952                    user.setModifiedDate(modifiedDate);
1953    
1954                    userPersistence.update(user, false);
1955    
1956                    return user;
1957            }
1958    
1959            public void updateOpenId(long userId, String openId)
1960                    throws PortalException, SystemException {
1961    
1962                    openId = openId.trim();
1963    
1964                    User user = userPersistence.findByPrimaryKey(userId);
1965    
1966                    user.setOpenId(openId);
1967    
1968                    userPersistence.update(user, false);
1969            }
1970    
1971            public void updateOrganizations(long userId, long[] newOrganizationIds)
1972                    throws PortalException, SystemException {
1973    
1974                    if (newOrganizationIds == null) {
1975                            return;
1976                    }
1977    
1978                    List<Organization> oldOrganizations = userPersistence.getOrganizations(
1979                            userId);
1980    
1981                    List<Long> oldOrganizationIds = new ArrayList<Long>(
1982                            oldOrganizations.size());
1983    
1984                    for (Organization oldOrganization : oldOrganizations) {
1985                            long oldOrganizationId = oldOrganization.getOrganizationId();
1986    
1987                            oldOrganizationIds.add(oldOrganizationId);
1988    
1989                            if (!ArrayUtil.contains(newOrganizationIds, oldOrganizationId)) {
1990                                    unsetOrganizationUsers(oldOrganizationId, new long[] {userId});
1991                            }
1992                    }
1993    
1994                    for (long newOrganizationId : newOrganizationIds) {
1995                            if (!oldOrganizationIds.contains(newOrganizationId)) {
1996                                    addOrganizationUsers(newOrganizationId, new long[] {userId});
1997                            }
1998                    }
1999    
2000                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
2001    
2002                    indexer.reindex(new long[] {userId});
2003    
2004                    PermissionCacheUtil.clearCache();
2005            }
2006    
2007            public User updatePassword(
2008                            long userId, String password1, String password2,
2009                            boolean passwordReset)
2010                    throws PortalException, SystemException {
2011    
2012                    return updatePassword(
2013                            userId, password1, password2, passwordReset, false);
2014            }
2015    
2016            public User updatePassword(
2017                            long userId, String password1, String password2,
2018                            boolean passwordReset, boolean silentUpdate)
2019                    throws PortalException, SystemException {
2020    
2021                    User user = userPersistence.findByPrimaryKey(userId);
2022    
2023                    // Use silentUpdate so that imported user passwords are not exported,
2024                    // tracked, or validated
2025    
2026                    if (!silentUpdate) {
2027                            validatePassword(user.getCompanyId(), userId, password1, password2);
2028                    }
2029    
2030                    String oldEncPwd = user.getPassword();
2031    
2032                    if (!user.isPasswordEncrypted()) {
2033                            oldEncPwd = PwdEncryptor.encrypt(user.getPassword());
2034                    }
2035    
2036                    String newEncPwd = PwdEncryptor.encrypt(password1);
2037    
2038                    if (user.hasCompanyMx()) {
2039                            mailService.updatePassword(user.getCompanyId(), userId, password1);
2040                    }
2041    
2042                    user.setPassword(newEncPwd);
2043                    user.setPasswordUnencrypted(password1);
2044                    user.setPasswordEncrypted(true);
2045                    user.setPasswordReset(passwordReset);
2046                    user.setPasswordModifiedDate(new Date());
2047                    user.setGraceLoginCount(0);
2048    
2049                    if (!silentUpdate) {
2050                            user.setPasswordModified(true);
2051                    }
2052    
2053                    try {
2054                            userPersistence.update(user, false);
2055                    }
2056                    catch (ModelListenerException mle) {
2057                            String msg = GetterUtil.getString(mle.getCause().getMessage());
2058    
2059                            if (LDAPSettingsUtil.isPasswordPolicyEnabled(user.getCompanyId())) {
2060                                    String passwordHistory = PrefsPropsUtil.getString(
2061                                            user.getCompanyId(), PropsKeys.LDAP_ERROR_PASSWORD_HISTORY);
2062    
2063                                    if (msg.indexOf(passwordHistory) != -1) {
2064                                            throw new UserPasswordException(
2065                                                    UserPasswordException.PASSWORD_ALREADY_USED);
2066                                    }
2067                            }
2068    
2069                            throw new UserPasswordException(
2070                                    UserPasswordException.PASSWORD_INVALID);
2071                    }
2072    
2073                    if (!silentUpdate) {
2074                            user.setPasswordModified(false);
2075    
2076                            passwordTrackerLocalService.trackPassword(userId, oldEncPwd);
2077                    }
2078    
2079                    return user;
2080            }
2081    
2082            public User updatePasswordManually(
2083                            long userId, String password, boolean passwordEncrypted,
2084                            boolean passwordReset, Date passwordModifiedDate)
2085                    throws PortalException, SystemException {
2086    
2087                    // This method should only be used to manually massage data
2088    
2089                    User user = userPersistence.findByPrimaryKey(userId);
2090    
2091                    user.setPassword(password);
2092                    user.setPasswordEncrypted(passwordEncrypted);
2093                    user.setPasswordReset(passwordReset);
2094                    user.setPasswordModifiedDate(passwordModifiedDate);
2095    
2096                    userPersistence.update(user, false);
2097    
2098                    return user;
2099            }
2100    
2101            public void updatePasswordReset(long userId, boolean passwordReset)
2102                    throws PortalException, SystemException {
2103    
2104                    User user = userPersistence.findByPrimaryKey(userId);
2105    
2106                    user.setPasswordReset(passwordReset);
2107    
2108                    userPersistence.update(user, false);
2109            }
2110    
2111            public void updatePortrait(long userId, byte[] bytes)
2112                    throws PortalException, SystemException {
2113    
2114                    User user = userPersistence.findByPrimaryKey(userId);
2115    
2116                    long imageMaxSize = PrefsPropsUtil.getLong(
2117                            PropsKeys.USERS_IMAGE_MAX_SIZE);
2118    
2119                    if ((imageMaxSize > 0) &&
2120                            ((bytes == null) || (bytes.length > imageMaxSize))) {
2121    
2122                            throw new UserPortraitSizeException();
2123                    }
2124    
2125                    long portraitId = user.getPortraitId();
2126    
2127                    if (portraitId <= 0) {
2128                            portraitId = counterLocalService.increment();
2129    
2130                            user.setPortraitId(portraitId);
2131    
2132                            userPersistence.update(user, false);
2133                    }
2134    
2135                    try {
2136                            ImageBag imageBag = ImageProcessorUtil.read(bytes);
2137    
2138                            RenderedImage renderedImage = imageBag.getRenderedImage();
2139    
2140                            if (renderedImage == null) {
2141                                    throw new UserPortraitTypeException();
2142                            }
2143    
2144                            renderedImage = ImageProcessorUtil.scale(
2145                                    renderedImage, PropsValues.USERS_IMAGE_MAX_HEIGHT,
2146                                    PropsValues.USERS_IMAGE_MAX_WIDTH);
2147    
2148                            String contentType = imageBag.getType();
2149    
2150                            imageLocalService.updateImage(
2151                                    portraitId,
2152                                    ImageProcessorUtil.getBytes(renderedImage, contentType));
2153                    }
2154                    catch (IOException ioe) {
2155                            throw new ImageSizeException(ioe);
2156                    }
2157            }
2158    
2159            public void updateReminderQuery(long userId, String question, String answer)
2160                    throws PortalException, SystemException {
2161    
2162                    validateReminderQuery(question, answer) ;
2163    
2164                    User user = userPersistence.findByPrimaryKey(userId);
2165    
2166                    user.setReminderQueryQuestion(question);
2167                    user.setReminderQueryAnswer(answer);
2168    
2169                    userPersistence.update(user, false);
2170            }
2171    
2172            public void updateScreenName(long userId, String screenName)
2173                    throws PortalException, SystemException {
2174    
2175                    // User
2176    
2177                    User user = userPersistence.findByPrimaryKey(userId);
2178    
2179                    screenName = getScreenName(screenName);
2180    
2181                    validateScreenName(user.getCompanyId(), userId, screenName);
2182    
2183                    user.setScreenName(screenName);
2184    
2185                    userPersistence.update(user, false);
2186    
2187                    // Group
2188    
2189                    Group group = groupLocalService.getUserGroup(
2190                            user.getCompanyId(), userId);
2191    
2192                    group.setFriendlyURL(StringPool.SLASH + screenName);
2193    
2194                    groupPersistence.update(group, false);
2195            }
2196    
2197            public User updateUser(
2198                            long userId, String oldPassword, String newPassword1,
2199                            String newPassword2, boolean passwordReset,
2200                            String reminderQueryQuestion, String reminderQueryAnswer,
2201                            String screenName, String emailAddress, long facebookId,
2202                            String openId, String languageId, String timeZoneId,
2203                            String greeting, String comments, String firstName,
2204                            String middleName, String lastName, int prefixId, int suffixId,
2205                            boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
2206                            String smsSn, String aimSn, String facebookSn, String icqSn,
2207                            String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
2208                            String twitterSn, String ymSn, String jobTitle, long[] groupIds,
2209                            long[] organizationIds, long[] roleIds,
2210                            List<UserGroupRole> userGroupRoles, long[] userGroupIds,
2211                            ServiceContext serviceContext)
2212                    throws PortalException, SystemException {
2213    
2214                    // User
2215    
2216                    User user = userPersistence.findByPrimaryKey(userId);
2217                    Company company = companyPersistence.findByPrimaryKey(
2218                            user.getCompanyId());
2219                    String password = oldPassword;
2220                    screenName = getScreenName(screenName);
2221                    emailAddress = emailAddress.trim().toLowerCase();
2222                    openId = openId.trim();
2223                    String oldFullName = user.getFullName();
2224                    aimSn = aimSn.trim().toLowerCase();
2225                    facebookSn = facebookSn.trim().toLowerCase();
2226                    icqSn = icqSn.trim().toLowerCase();
2227                    jabberSn = jabberSn.trim().toLowerCase();
2228                    msnSn = msnSn.trim().toLowerCase();
2229                    mySpaceSn = mySpaceSn.trim().toLowerCase();
2230                    skypeSn = skypeSn.trim().toLowerCase();
2231                    twitterSn = twitterSn.trim().toLowerCase();
2232                    ymSn = ymSn.trim().toLowerCase();
2233                    Date now = new Date();
2234    
2235                    EmailAddressGenerator emailAddressGenerator =
2236                            EmailAddressGeneratorFactory.getInstance();
2237    
2238                    if (emailAddressGenerator.isGenerated(emailAddress)) {
2239                            emailAddress = StringPool.BLANK;
2240                    }
2241    
2242                    if (!PropsValues.USERS_EMAIL_ADDRESS_REQUIRED &&
2243                            Validator.isNull(emailAddress)) {
2244    
2245                            emailAddress = emailAddressGenerator.generate(
2246                                    user.getCompanyId(), userId);
2247                    }
2248    
2249                    validate(
2250                            userId, screenName, emailAddress, firstName, middleName, lastName,
2251                            smsSn);
2252    
2253                    if (Validator.isNotNull(newPassword1) ||
2254                            Validator.isNotNull(newPassword2)) {
2255    
2256                            user = updatePassword(
2257                                    userId, newPassword1, newPassword2, passwordReset);
2258    
2259                            password = newPassword1;
2260                    }
2261    
2262                    user.setModifiedDate(now);
2263    
2264                    if (user.getContactId() <= 0) {
2265                            user.setContactId(counterLocalService.increment());
2266                    }
2267    
2268                    user.setPasswordReset(passwordReset);
2269    
2270                    if (Validator.isNotNull(reminderQueryQuestion) &&
2271                            Validator.isNotNull(reminderQueryAnswer)) {
2272    
2273                            user.setReminderQueryQuestion(reminderQueryQuestion);
2274                            user.setReminderQueryAnswer(reminderQueryAnswer);
2275                    }
2276    
2277                    user.setScreenName(screenName);
2278    
2279                    setEmailAddress(
2280                            user, password, firstName, middleName, lastName, emailAddress);
2281    
2282                    user.setOpenId(openId);
2283                    user.setLanguageId(languageId);
2284                    user.setTimeZoneId(timeZoneId);
2285                    user.setGreeting(greeting);
2286                    user.setComments(comments);
2287                    user.setFirstName(firstName);
2288                    user.setMiddleName(middleName);
2289                    user.setLastName(lastName);
2290                    user.setJobTitle(jobTitle);
2291    
2292                    userPersistence.update(user, false, serviceContext);
2293    
2294                    // Contact
2295    
2296                    Date birthday = PortalUtil.getDate(
2297                            birthdayMonth, birthdayDay, birthdayYear,
2298                            new ContactBirthdayException());
2299    
2300                    long contactId = user.getContactId();
2301    
2302                    Contact contact = contactPersistence.fetchByPrimaryKey(contactId);
2303    
2304                    if (contact == null) {
2305                            contact = contactPersistence.create(contactId);
2306    
2307                            contact.setCompanyId(user.getCompanyId());
2308                            contact.setUserName(StringPool.BLANK);
2309                            contact.setCreateDate(now);
2310                            contact.setAccountId(company.getAccountId());
2311                            contact.setParentContactId(
2312                                    ContactConstants.DEFAULT_PARENT_CONTACT_ID);
2313                    }
2314    
2315                    contact.setModifiedDate(now);
2316                    contact.setFirstName(firstName);
2317                    contact.setMiddleName(middleName);
2318                    contact.setLastName(lastName);
2319                    contact.setPrefixId(prefixId);
2320                    contact.setSuffixId(suffixId);
2321                    contact.setMale(male);
2322                    contact.setBirthday(birthday);
2323                    contact.setSmsSn(smsSn);
2324                    contact.setAimSn(aimSn);
2325                    contact.setFacebookSn(facebookSn);
2326                    contact.setIcqSn(icqSn);
2327                    contact.setJabberSn(jabberSn);
2328                    contact.setMsnSn(msnSn);
2329                    contact.setMySpaceSn(mySpaceSn);
2330                    contact.setSkypeSn(skypeSn);
2331                    contact.setTwitterSn(twitterSn);
2332                    contact.setYmSn(ymSn);
2333                    contact.setJobTitle(jobTitle);
2334    
2335                    contactPersistence.update(contact, false, serviceContext);
2336    
2337                    // Group
2338    
2339                    Group group = groupLocalService.getUserGroup(
2340                            user.getCompanyId(), userId);
2341    
2342                    group.setFriendlyURL(StringPool.SLASH + screenName);
2343    
2344                    groupPersistence.update(group, false);
2345    
2346                    // Groups
2347    
2348                    updateGroups(userId, groupIds);
2349    
2350                    // Organizations
2351    
2352                    updateOrganizations(userId, organizationIds);
2353    
2354                    // Roles
2355    
2356                    if (roleIds != null) {
2357                            roleIds = EnterpriseAdminUtil.addRequiredRoles(user, roleIds);
2358    
2359                            userPersistence.setRoles(userId, roleIds);
2360                    }
2361    
2362                    // User group roles
2363    
2364                    updateUserGroupRoles(user, groupIds, organizationIds, userGroupRoles);
2365    
2366                    // User groups
2367    
2368                    if (userGroupIds != null) {
2369                            userGroupLocalService.copyUserGroupLayouts(userGroupIds, userId);
2370    
2371                            userPersistence.setUserGroups(userId, userGroupIds);
2372                    }
2373    
2374                    // Announcements
2375    
2376                    announcementsDeliveryLocalService.getUserDeliveries(user.getUserId());
2377    
2378                    // Asset
2379    
2380                    if (serviceContext != null) {
2381                            updateAsset(
2382                                    userId, user, serviceContext.getAssetCategoryIds(),
2383                                    serviceContext.getAssetTagNames());
2384                    }
2385    
2386                    // Expando
2387    
2388                    user.setExpandoBridgeAttributes(serviceContext);
2389    
2390                    // Message boards
2391    
2392                    if (GetterUtil.getBoolean(
2393                                    PropsKeys.USERS_UPDATE_USER_NAME + MBMessage.class.getName()) &&
2394                            !oldFullName.equals(user.getFullName())) {
2395    
2396                            mbMessageLocalService.updateUserName(userId, user.getFullName());
2397                    }
2398    
2399                    // Indexer
2400    
2401                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
2402    
2403                    indexer.reindex(user);
2404    
2405                    // Permission cache
2406    
2407                    PermissionCacheUtil.clearCache();
2408    
2409                    return user;
2410            }
2411    
2412            protected int authenticate(
2413                            long companyId, String login, String password, String authType,
2414                            Map<String, String[]> headerMap, Map<String, String[]> parameterMap)
2415                    throws PortalException, SystemException {
2416    
2417                    login = login.trim().toLowerCase();
2418    
2419                    long userId = GetterUtil.getLong(login);
2420    
2421                    // User input validation
2422    
2423                    if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2424                            if (!Validator.isEmailAddress(login)) {
2425                                    throw new UserEmailAddressException();
2426                            }
2427                    }
2428                    else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2429                            if (Validator.isNull(login)) {
2430                                    throw new UserScreenNameException();
2431                            }
2432                    }
2433                    else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2434                            if (Validator.isNull(login)) {
2435                                    throw new UserIdException();
2436                            }
2437                    }
2438    
2439                    if (Validator.isNull(password)) {
2440                            throw new UserPasswordException(
2441                                    UserPasswordException.PASSWORD_INVALID);
2442                    }
2443    
2444                    int authResult = Authenticator.FAILURE;
2445    
2446                    // Pre-authentication pipeline
2447    
2448                    if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2449                            authResult = AuthPipeline.authenticateByEmailAddress(
2450                                    PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
2451                                    headerMap, parameterMap);
2452                    }
2453                    else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2454                            authResult = AuthPipeline.authenticateByScreenName(
2455                                    PropsKeys.AUTH_PIPELINE_PRE, companyId, login, password,
2456                                    headerMap, parameterMap);
2457                    }
2458                    else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2459                            authResult = AuthPipeline.authenticateByUserId(
2460                                    PropsKeys.AUTH_PIPELINE_PRE, companyId, userId, password,
2461                                    headerMap, parameterMap);
2462                    }
2463    
2464                    // Get user
2465    
2466                    User user = null;
2467    
2468                    try {
2469                            if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2470                                    user = userPersistence.findByC_EA(companyId, login);
2471                            }
2472                            else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2473                                    user = userPersistence.findByC_SN(companyId, login);
2474                            }
2475                            else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2476                                    user = userPersistence.findByC_U(
2477                                            companyId, GetterUtil.getLong(login));
2478                            }
2479                    }
2480                    catch (NoSuchUserException nsue) {
2481                            return Authenticator.DNE;
2482                    }
2483    
2484                    if (user.isDefaultUser()) {
2485                            _log.error(
2486                                    "The default user should never be allowed to authenticate");
2487    
2488                            return Authenticator.DNE;
2489                    }
2490    
2491                    if (!user.isPasswordEncrypted()) {
2492                            user.setPassword(PwdEncryptor.encrypt(user.getPassword()));
2493                            user.setPasswordEncrypted(true);
2494    
2495                            userPersistence.update(user, false);
2496                    }
2497    
2498                    // Check password policy to see if the is account locked out or if the
2499                    // password is expired
2500    
2501                    checkLockout(user);
2502    
2503                    checkPasswordExpired(user);
2504    
2505                    // Authenticate against the User_ table
2506    
2507                    if (authResult == Authenticator.SUCCESS) {
2508                            if (PropsValues.AUTH_PIPELINE_ENABLE_LIFERAY_CHECK) {
2509                                    boolean authenticated = PwdAuthenticator.authenticate(
2510                                            login, password, user.getPassword());
2511    
2512                                    if (authenticated) {
2513                                            authResult = Authenticator.SUCCESS;
2514                                    }
2515                                    else {
2516                                            authResult = Authenticator.FAILURE;
2517                                    }
2518                            }
2519                    }
2520    
2521                    // Post-authentication pipeline
2522    
2523                    if (authResult == Authenticator.SUCCESS) {
2524                            if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2525                                    authResult = AuthPipeline.authenticateByEmailAddress(
2526                                            PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
2527                                            headerMap, parameterMap);
2528                            }
2529                            else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2530                                    authResult = AuthPipeline.authenticateByScreenName(
2531                                            PropsKeys.AUTH_PIPELINE_POST, companyId, login, password,
2532                                            headerMap, parameterMap);
2533                            }
2534                            else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2535                                    authResult = AuthPipeline.authenticateByUserId(
2536                                            PropsKeys.AUTH_PIPELINE_POST, companyId, userId, password,
2537                                            headerMap, parameterMap);
2538                            }
2539                    }
2540    
2541                    // Execute code triggered by authentication failure
2542    
2543                    if (authResult == Authenticator.FAILURE) {
2544                            try {
2545                                    if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2546                                            AuthPipeline.onFailureByEmailAddress(
2547                                                    PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
2548                                                    parameterMap);
2549                                    }
2550                                    else if (authType.equals(CompanyConstants.AUTH_TYPE_SN)) {
2551                                            AuthPipeline.onFailureByScreenName(
2552                                                    PropsKeys.AUTH_FAILURE, companyId, login, headerMap,
2553                                                    parameterMap);
2554                                    }
2555                                    else if (authType.equals(CompanyConstants.AUTH_TYPE_ID)) {
2556                                            AuthPipeline.onFailureByUserId(
2557                                                    PropsKeys.AUTH_FAILURE, companyId, userId, headerMap,
2558                                                    parameterMap);
2559                                    }
2560    
2561                                    // Let LDAP handle max failure event
2562    
2563                                    if (!LDAPSettingsUtil.isPasswordPolicyEnabled(
2564                                                    user.getCompanyId())) {
2565    
2566                                            PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2567    
2568                                            int failedLoginAttempts = user.getFailedLoginAttempts();
2569                                            int maxFailures = passwordPolicy.getMaxFailure();
2570    
2571                                            if ((failedLoginAttempts >= maxFailures) &&
2572                                                    (maxFailures != 0)) {
2573    
2574                                                    if (authType.equals(CompanyConstants.AUTH_TYPE_EA)) {
2575                                                            AuthPipeline.onMaxFailuresByEmailAddress(
2576                                                                    PropsKeys.AUTH_MAX_FAILURES, companyId, login,
2577                                                                    headerMap, parameterMap);
2578                                                    }
2579                                                    else if (authType.equals(
2580                                                                            CompanyConstants.AUTH_TYPE_SN)) {
2581    
2582                                                            AuthPipeline.onMaxFailuresByScreenName(
2583                                                                    PropsKeys.AUTH_MAX_FAILURES, companyId, login,
2584                                                                    headerMap, parameterMap);
2585                                                    }
2586                                                    else if (authType.equals(
2587                                                                            CompanyConstants.AUTH_TYPE_ID)) {
2588    
2589                                                            AuthPipeline.onMaxFailuresByUserId(
2590                                                                    PropsKeys.AUTH_MAX_FAILURES, companyId, userId,
2591                                                                    headerMap, parameterMap);
2592                                                    }
2593                                            }
2594                                    }
2595                            }
2596                            catch (Exception e) {
2597                                    _log.error(e, e);
2598                            }
2599                    }
2600    
2601                    return authResult;
2602            }
2603    
2604            protected void doSendPassword(
2605                            long companyId, String emailAddress, String remoteAddr,
2606                            String remoteHost, String userAgent, String fromName,
2607                            String fromAddress, String subject, String body,
2608                            ServiceContext serviceContext)
2609                    throws IOException, PortalException, SystemException {
2610    
2611                    Company company = companyPersistence.findByPrimaryKey(companyId);
2612    
2613                    if (!company.isSendPassword() && !company.isSendPasswordResetLink()) {
2614                            return;
2615                    }
2616    
2617                    emailAddress = emailAddress.trim().toLowerCase();
2618    
2619                    if (!Validator.isEmailAddress(emailAddress)) {
2620                            throw new UserEmailAddressException();
2621                    }
2622    
2623                    User user = userPersistence.findByC_EA(companyId, emailAddress);
2624    
2625                    PasswordPolicy passwordPolicy = user.getPasswordPolicy();
2626    
2627                    String newPassword = StringPool.BLANK;
2628                    String passwordResetURL = StringPool.BLANK;
2629    
2630                    if (company.isSendPasswordResetLink()) {
2631                            Date expirationDate = new Date(
2632                                    System.currentTimeMillis() +
2633                                            (passwordPolicy.getResetTicketMaxAge() * 1000));
2634    
2635                            Ticket ticket = ticketLocalService.addTicket(
2636                                    companyId, User.class.getName(), user.getUserId(),
2637                                    expirationDate, serviceContext);
2638    
2639                            passwordResetURL =
2640                                    serviceContext.getPortalURL() + serviceContext.getPathMain() +
2641                                            "/portal/update_password?p_l_id="+
2642                                                    serviceContext.getPlid() + "&ticket=" + ticket.getKey();
2643                    }
2644                    else {
2645                            if (!PwdEncryptor.PASSWORDS_ENCRYPTION_ALGORITHM.equals(
2646                                            PwdEncryptor.TYPE_NONE)) {
2647    
2648                                    newPassword = PwdToolkitUtil.generate(passwordPolicy);
2649    
2650                                    boolean passwordReset = false;
2651    
2652                                    if (passwordPolicy.getChangeable() &&
2653                                            passwordPolicy.getChangeRequired()) {
2654    
2655                                            passwordReset = true;
2656                                    }
2657    
2658                                    user.setPassword(PwdEncryptor.encrypt(newPassword));
2659                                    user.setPasswordUnencrypted(newPassword);
2660                                    user.setPasswordEncrypted(true);
2661                                    user.setPasswordReset(passwordReset);
2662                                    user.setPasswordModified(true);
2663                                    user.setPasswordModifiedDate(new Date());
2664    
2665                                    userPersistence.update(user, false);
2666    
2667                                    user.setPasswordModified(false);
2668                            }
2669                            else {
2670                                    newPassword = user.getPassword();
2671                            }
2672                    }
2673    
2674                    if (Validator.isNull(fromName)) {
2675                            fromName = PrefsPropsUtil.getString(
2676                                    companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
2677                    }
2678    
2679                    if (Validator.isNull(fromAddress)) {
2680                            fromAddress = PrefsPropsUtil.getString(
2681                                    companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
2682                    }
2683    
2684                    String toName = user.getFullName();
2685                    String toAddress = user.getEmailAddress();
2686    
2687                    if (Validator.isNull(subject)) {
2688                            if (company.isSendPasswordResetLink()) {
2689                                    subject = PrefsPropsUtil.getContent(
2690                                            companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_SUBJECT);
2691                            }
2692                            else {
2693                                    subject = PrefsPropsUtil.getContent(
2694                                            companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_SUBJECT);
2695                            }
2696                    }
2697    
2698                    if (Validator.isNull(body)) {
2699                            if (company.isSendPasswordResetLink()) {
2700                                    body = PrefsPropsUtil.getContent(
2701                                            companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_RESET_BODY);
2702                            }
2703                            else {
2704                                    body = PrefsPropsUtil.getContent(
2705                                            companyId, PropsKeys.ADMIN_EMAIL_PASSWORD_SENT_BODY);
2706                            }
2707                    }
2708    
2709                    subject = StringUtil.replace(
2710                            subject,
2711                            new String[] {
2712                                    "[$FROM_ADDRESS$]",
2713                                    "[$FROM_NAME$]",
2714                                    "[$PASSWORD_RESET_URL$]",
2715                                    "[$PORTAL_URL$]",
2716                                    "[$REMOTE_ADDRESS$]",
2717                                    "[$REMOTE_HOST$]",
2718                                    "[$TO_ADDRESS$]",
2719                                    "[$TO_NAME$]",
2720                                    "[$USER_AGENT$]",
2721                                    "[$USER_ID$]",
2722                                    "[$USER_PASSWORD$]",
2723                                    "[$USER_SCREENNAME$]"
2724                            },
2725                            new String[] {
2726                                    fromAddress,
2727                                    fromName,
2728                                    passwordResetURL,
2729                                    company.getVirtualHost(),
2730                                    remoteAddr,
2731                                    remoteHost,
2732                                    toAddress,
2733                                    toName,
2734                                    HtmlUtil.escape(userAgent),
2735                                    String.valueOf(user.getUserId()),
2736                                    newPassword,
2737                                    user.getScreenName()
2738                            });
2739    
2740                    body = StringUtil.replace(
2741                            body,
2742                            new String[] {
2743                                    "[$FROM_ADDRESS$]",
2744                                    "[$FROM_NAME$]",
2745                                    "[$PASSWORD_RESET_URL$]",
2746                                    "[$PORTAL_URL$]",
2747                                    "[$REMOTE_ADDRESS$]",
2748                                    "[$REMOTE_HOST$]",
2749                                    "[$TO_ADDRESS$]",
2750                                    "[$TO_NAME$]",
2751                                    "[$USER_AGENT$]",
2752                                    "[$USER_ID$]",
2753                                    "[$USER_PASSWORD$]",
2754                                    "[$USER_SCREENNAME$]"
2755                            },
2756                            new String[] {
2757                                    fromAddress,
2758                                    fromName,
2759                                    passwordResetURL,
2760                                    company.getVirtualHost(),
2761                                    remoteAddr,
2762                                    remoteHost,
2763                                    toAddress,
2764                                    toName,
2765                                    HtmlUtil.escape(userAgent),
2766                                    String.valueOf(user.getUserId()),
2767                                    newPassword,
2768                                    user.getScreenName()
2769                            });
2770    
2771                    InternetAddress from = new InternetAddress(fromAddress, fromName);
2772    
2773                    InternetAddress to = new InternetAddress(toAddress, toName);
2774    
2775                    MailMessage message = new MailMessage(from, to, subject, body, true);
2776    
2777                    mailService.sendEmail(message);
2778            }
2779    
2780            protected String getScreenName(String screenName) {
2781                    return StringUtil.lowerCase(StringUtil.trim(screenName));
2782            }
2783    
2784            protected long[] getUserIds(List<User> users) {
2785                    long[] userIds = new long[users.size()];
2786    
2787                    for (int i = 0; i < users.size(); i++) {
2788                            User user = users.get(i);
2789    
2790                            userIds[i] = user.getUserId();
2791                    }
2792    
2793                    return userIds;
2794            }
2795    
2796            protected void sendEmail(User user, String password)
2797                    throws IOException, PortalException, SystemException {
2798    
2799                    if (!PrefsPropsUtil.getBoolean(
2800                                    user.getCompanyId(),
2801                                    PropsKeys.ADMIN_EMAIL_USER_ADDED_ENABLED)) {
2802    
2803                            return;
2804                    }
2805    
2806                    long companyId = user.getCompanyId();
2807    
2808                    Company company = companyPersistence.findByPrimaryKey(companyId);
2809    
2810                    String fromName = PrefsPropsUtil.getString(
2811                            companyId, PropsKeys.ADMIN_EMAIL_FROM_NAME);
2812                    String fromAddress = PrefsPropsUtil.getString(
2813                            companyId, PropsKeys.ADMIN_EMAIL_FROM_ADDRESS);
2814    
2815                    String toName = user.getFullName();
2816                    String toAddress = user.getEmailAddress();
2817    
2818                    String subject = PrefsPropsUtil.getContent(
2819                            companyId, PropsKeys.ADMIN_EMAIL_USER_ADDED_SUBJECT);
2820                    String body = PrefsPropsUtil.getContent(
2821                            companyId, PropsKeys.ADMIN_EMAIL_USER_ADDED_BODY);
2822    
2823                    subject = StringUtil.replace(
2824                            subject,
2825                            new String[] {
2826                                    "[$FROM_ADDRESS$]",
2827                                    "[$FROM_NAME$]",
2828                                    "[$PORTAL_URL$]",
2829                                    "[$TO_ADDRESS$]",
2830                                    "[$TO_NAME$]",
2831                                    "[$USER_ID$]",
2832                                    "[$USER_PASSWORD$]",
2833                                    "[$USER_SCREENNAME$]"
2834                            },
2835                            new String[] {
2836                                    fromAddress,
2837                                    fromName,
2838                                    company.getVirtualHost(),
2839                                    toAddress,
2840                                    toName,
2841                                    String.valueOf(user.getUserId()),
2842                                    password,
2843                                    user.getScreenName()
2844                            });
2845    
2846                    body = StringUtil.replace(
2847                            body,
2848                            new String[] {
2849                                    "[$FROM_ADDRESS$]",
2850                                    "[$FROM_NAME$]",
2851                                    "[$PORTAL_URL$]",
2852                                    "[$TO_ADDRESS$]",
2853                                    "[$TO_NAME$]",
2854                                    "[$USER_ID$]",
2855                                    "[$USER_PASSWORD$]",
2856                                    "[$USER_SCREENNAME$]"
2857                            },
2858                            new String[] {
2859                                    fromAddress,
2860                                    fromName,
2861                                    company.getVirtualHost(),
2862                                    toAddress,
2863                                    toName,
2864                                    String.valueOf(user.getUserId()),
2865                                    password,
2866                                    user.getScreenName()
2867                            });
2868    
2869                    InternetAddress from = new InternetAddress(fromAddress, fromName);
2870    
2871                    InternetAddress to = new InternetAddress(toAddress, toName);
2872    
2873                    MailMessage message = new MailMessage(from, to, subject, body, true);
2874    
2875                    mailService.sendEmail(message);
2876            }
2877    
2878            protected void setEmailAddress(
2879                            User user, String password, String firstName, String middleName,
2880                            String lastName, String emailAddress)
2881                    throws PortalException, SystemException {
2882    
2883                    if (emailAddress.equalsIgnoreCase(user.getEmailAddress())) {
2884                            return;
2885                    }
2886    
2887                    long userId = user.getUserId();
2888    
2889                    // test@test.com -> test@liferay.com
2890    
2891                    if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress) &&
2892                            Validator.isNotNull(password)) {
2893                            mailService.addUser(
2894                                    user.getCompanyId(), userId, password, firstName, middleName,
2895                                    lastName, emailAddress);
2896                    }
2897    
2898                    // test@liferay.com -> bob@liferay.com
2899    
2900                    else if (user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
2901                            mailService.updateEmailAddress(
2902                                    user.getCompanyId(), userId, emailAddress);
2903                    }
2904    
2905                    // test@liferay.com -> test@test.com
2906    
2907                    else if (user.hasCompanyMx() && !user.hasCompanyMx(emailAddress)) {
2908                            mailService.deleteEmailAddress(user.getCompanyId(), userId);
2909                    }
2910    
2911                    user.setEmailAddress(emailAddress);
2912            }
2913    
2914            protected void updateUserGroupRoles(
2915                            User user, long[] groupIds, long[] organizationIds,
2916                            List<UserGroupRole> userGroupRoles)
2917                    throws PortalException, SystemException {
2918    
2919                    if (userGroupRoles == null) {
2920                            return;
2921                    }
2922    
2923                    List<UserGroupRole> previousUserGroupRoles =
2924                            userGroupRolePersistence.findByUserId(user.getUserId());
2925    
2926                    for (UserGroupRole userGroupRole : previousUserGroupRoles) {
2927                            if (userGroupRoles.contains(userGroupRole)) {
2928                                    userGroupRoles.remove(userGroupRole);
2929                            }
2930                            else {
2931                                    userGroupRoleLocalService.deleteUserGroupRole(
2932                                            userGroupRole);
2933                            }
2934                    }
2935    
2936                    long[] validGroupIds = null;
2937    
2938                    if (groupIds != null) {
2939                            validGroupIds = ArrayUtil.clone(groupIds);
2940                    }
2941                    else {
2942                            validGroupIds = user.getGroupIds();
2943                    }
2944    
2945                    if (organizationIds == null) {
2946                            organizationIds = user.getOrganizationIds();
2947                    }
2948    
2949                    long[] organizationGroupIds = new long[organizationIds.length];
2950    
2951                    for (int i = 0; i < organizationIds.length; i++) {
2952                            long organizationId = organizationIds[i];
2953    
2954                            Organization organization =
2955                                    organizationPersistence.findByPrimaryKey(
2956                                            organizationId);
2957    
2958                            Group organizationGroup = organization.getGroup();
2959    
2960                            organizationGroupIds[i] = organizationGroup.getGroupId();
2961                    }
2962    
2963                    validGroupIds = ArrayUtil.append(validGroupIds, organizationGroupIds);
2964    
2965                    Arrays.sort(validGroupIds);
2966    
2967                    for (UserGroupRole userGroupRole : userGroupRoles) {
2968                            if (Arrays.binarySearch(
2969                                            validGroupIds, userGroupRole.getGroupId()) >= 0) {
2970    
2971                                    userGroupRoleLocalService.addUserGroupRole(userGroupRole);
2972                            }
2973                    }
2974            }
2975    
2976            protected void validate(
2977                            long companyId, long userId, boolean autoPassword, String password1,
2978                            String password2, boolean autoScreenName, String screenName,
2979                            String emailAddress, String firstName, String middleName,
2980                            String lastName, long[] organizationIds)
2981                    throws PortalException, SystemException {
2982    
2983                    Company company = companyPersistence.findByPrimaryKey(companyId);
2984    
2985                    if (company.isSystem()) {
2986                            return;
2987                    }
2988    
2989                    if ((company.getMaxUsers() > 0) &&
2990                            (company.getMaxUsers() <=
2991                                    searchCount(companyId, null, true, null))) {
2992    
2993                            throw new CompanyMaxUsersException();
2994                    }
2995    
2996                    if (!autoScreenName) {
2997                            validateScreenName(companyId, userId, screenName);
2998                    }
2999    
3000                    if (!autoPassword) {
3001                            PasswordPolicy passwordPolicy =
3002                                    passwordPolicyLocalService.getDefaultPasswordPolicy(companyId);
3003    
3004                            PwdToolkitUtil.validate(
3005                                    companyId, 0, password1, password2, passwordPolicy);
3006                    }
3007    
3008                    validateEmailAddress(companyId, emailAddress);
3009    
3010                    if (Validator.isNotNull(emailAddress)) {
3011                            User user = userPersistence.fetchByC_EA(companyId, emailAddress);
3012    
3013                            if (user != null) {
3014                                    throw new DuplicateUserEmailAddressException();
3015                            }
3016                    }
3017    
3018                    validateFullName(companyId, firstName, middleName, lastName);
3019            }
3020    
3021            protected void validate(
3022                            long userId, String screenName, String emailAddress,
3023                            String firstName, String middleName, String lastName, String smsSn)
3024                    throws PortalException, SystemException {
3025    
3026                    User user = userPersistence.findByPrimaryKey(userId);
3027    
3028                    if (!user.getScreenName().equalsIgnoreCase(screenName)) {
3029                            validateScreenName(user.getCompanyId(), userId, screenName);
3030                    }
3031    
3032                    validateEmailAddress(user.getCompanyId(), emailAddress);
3033    
3034                    if (!user.isDefaultUser()) {
3035                            if (Validator.isNotNull(emailAddress) &&
3036                                    !user.getEmailAddress().equalsIgnoreCase(emailAddress)) {
3037    
3038                                    if (userPersistence.fetchByC_EA(
3039                                                    user.getCompanyId(), emailAddress) != null) {
3040    
3041                                            throw new DuplicateUserEmailAddressException();
3042                                    }
3043                            }
3044    
3045                            validateFullName(
3046                                    user.getCompanyId(), firstName, middleName, lastName);
3047                    }
3048    
3049                    if (Validator.isNotNull(smsSn) && !Validator.isEmailAddress(smsSn)) {
3050                            throw new UserSmsException();
3051                    }
3052            }
3053    
3054            protected void validateEmailAddress(long companyId, String emailAddress)
3055                    throws PortalException, SystemException {
3056    
3057                    if (Validator.isNull(emailAddress) &&
3058                            !PropsValues.USERS_EMAIL_ADDRESS_REQUIRED) {
3059    
3060                            return;
3061                    }
3062    
3063                    if (!Validator.isEmailAddress(emailAddress) ||
3064                            emailAddress.startsWith("root@") ||
3065                            emailAddress.startsWith("postmaster@")) {
3066    
3067                            throw new UserEmailAddressException();
3068                    }
3069    
3070                    String[] reservedEmailAddresses = PrefsPropsUtil.getStringArray(
3071                            companyId, PropsKeys.ADMIN_RESERVED_EMAIL_ADDRESSES,
3072                            StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_EMAIL_ADDRESSES);
3073    
3074                    for (int i = 0; i < reservedEmailAddresses.length; i++) {
3075                            if (emailAddress.equalsIgnoreCase(reservedEmailAddresses[i])) {
3076                                    throw new ReservedUserEmailAddressException();
3077                            }
3078                    }
3079            }
3080    
3081            protected void validateFullName(
3082                            long companyId, String firstName, String middleName,
3083                            String lastName)
3084                    throws PortalException {
3085    
3086                    if (Validator.isNull(firstName)) {
3087                            throw new ContactFirstNameException();
3088                    }
3089                    else if (Validator.isNull(lastName)) {
3090                            throw new ContactLastNameException();
3091                    }
3092    
3093                    FullNameValidator fullNameValidator =
3094                            FullNameValidatorFactory.getInstance();
3095    
3096                    if (!fullNameValidator.validate(
3097                                    companyId, firstName, middleName, lastName)) {
3098    
3099                            throw new ContactFullNameException();
3100                    }
3101            }
3102    
3103            protected void validatePassword(
3104                            long companyId, long userId, String password1, String password2)
3105                    throws PortalException, SystemException {
3106    
3107                    if (Validator.isNull(password1) || Validator.isNull(password2)) {
3108                            throw new UserPasswordException(
3109                                    UserPasswordException.PASSWORD_INVALID);
3110                    }
3111    
3112                    if (!password1.equals(password2)) {
3113                            throw new UserPasswordException(
3114                                    UserPasswordException.PASSWORDS_DO_NOT_MATCH);
3115                    }
3116    
3117                    PasswordPolicy passwordPolicy =
3118                            passwordPolicyLocalService.getPasswordPolicyByUserId(userId);
3119    
3120                    PwdToolkitUtil.validate(
3121                            companyId, userId, password1, password2, passwordPolicy);
3122            }
3123    
3124            protected void validateReminderQuery(String question, String answer)
3125                    throws PortalException {
3126    
3127                    if (!PropsValues.USERS_REMINDER_QUERIES_ENABLED) {
3128                            return;
3129                    }
3130    
3131                    if (Validator.isNull(question)) {
3132                            throw new UserReminderQueryException("Question cannot be null");
3133                    }
3134    
3135                    if (Validator.isNull(answer)) {
3136                            throw new UserReminderQueryException("Answer cannot be null");
3137                    }
3138            }
3139    
3140            protected void validateScreenName(
3141                            long companyId, long userId, String screenName)
3142                    throws PortalException, SystemException {
3143    
3144                    if (Validator.isNull(screenName)) {
3145                            throw new UserScreenNameException();
3146                    }
3147    
3148                    ScreenNameValidator screenNameValidator =
3149                            ScreenNameValidatorFactory.getInstance();
3150    
3151                    if (!screenNameValidator.validate(companyId, screenName)) {
3152                            throw new UserScreenNameException();
3153                    }
3154    
3155                    if (Validator.isNumber(screenName) &&
3156                            !screenName.equals(String.valueOf(userId))) {
3157    
3158                            if (!PropsValues.USERS_SCREEN_NAME_ALLOW_NUMERIC) {
3159                                    throw new UserScreenNameException();
3160                            }
3161    
3162                            Group group = groupPersistence.fetchByPrimaryKey(
3163                                    GetterUtil.getLong(screenName));
3164    
3165                            if (group != null) {
3166                                    throw new UserScreenNameException();
3167                            }
3168                    }
3169    
3170                    for (char c : screenName.toCharArray()) {
3171                            if ((!Validator.isChar(c)) && (!Validator.isDigit(c)) &&
3172                                    (c != CharPool.DASH) && (c != CharPool.PERIOD) &&
3173                                    (c != CharPool.UNDERLINE)) {
3174    
3175                                    throw new UserScreenNameException();
3176                            }
3177                    }
3178    
3179                    String[] anonymousNames = PrincipalBean.ANONYMOUS_NAMES;
3180    
3181                    for (int i = 0; i < anonymousNames.length; i++) {
3182                            if (screenName.equalsIgnoreCase(anonymousNames[i])) {
3183                                    throw new UserScreenNameException();
3184                            }
3185                    }
3186    
3187                    User user = userPersistence.fetchByC_SN(companyId, screenName);
3188    
3189                    if (user != null) {
3190                            throw new DuplicateUserScreenNameException();
3191                    }
3192    
3193                    String friendlyURL = StringPool.SLASH + screenName;
3194    
3195                    Group group = groupPersistence.fetchByC_F(companyId, friendlyURL);
3196    
3197                    if (group != null) {
3198                            throw new DuplicateUserScreenNameException();
3199                    }
3200    
3201                    int exceptionType = LayoutImpl.validateFriendlyURL(friendlyURL);
3202    
3203                    if (exceptionType != -1) {
3204                            throw new UserScreenNameException(
3205                                    new GroupFriendlyURLException(exceptionType));
3206                    }
3207    
3208                    String[] reservedScreenNames = PrefsPropsUtil.getStringArray(
3209                            companyId, PropsKeys.ADMIN_RESERVED_SCREEN_NAMES,
3210                            StringPool.NEW_LINE, PropsValues.ADMIN_RESERVED_SCREEN_NAMES);
3211    
3212                    for (int i = 0; i < reservedScreenNames.length; i++) {
3213                            if (screenName.equalsIgnoreCase(reservedScreenNames[i])) {
3214                                    throw new ReservedUserScreenNameException();
3215                            }
3216                    }
3217            }
3218    
3219            private static Log _log = LogFactoryUtil.getLog(UserLocalServiceImpl.class);
3220    
3221            private static Map<Long, User> _defaultUsers =
3222                    new ConcurrentHashMap<Long, User>();
3223    
3224    }