001    /**
002     * Copyright (c) 2000-present 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.RequiredUserException;
018    import com.liferay.portal.UserEmailAddressException;
019    import com.liferay.portal.UserFieldException;
020    import com.liferay.portal.kernel.exception.PortalException;
021    import com.liferay.portal.kernel.log.Log;
022    import com.liferay.portal.kernel.log.LogFactoryUtil;
023    import com.liferay.portal.kernel.search.Indexer;
024    import com.liferay.portal.kernel.search.IndexerRegistryUtil;
025    import com.liferay.portal.kernel.util.ArrayUtil;
026    import com.liferay.portal.kernel.util.CalendarFactoryUtil;
027    import com.liferay.portal.kernel.util.ListUtil;
028    import com.liferay.portal.kernel.util.ParamUtil;
029    import com.liferay.portal.kernel.util.SetUtil;
030    import com.liferay.portal.kernel.util.StringUtil;
031    import com.liferay.portal.kernel.workflow.WorkflowConstants;
032    import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
033    import com.liferay.portal.model.Address;
034    import com.liferay.portal.model.Company;
035    import com.liferay.portal.model.CompanyConstants;
036    import com.liferay.portal.model.Contact;
037    import com.liferay.portal.model.EmailAddress;
038    import com.liferay.portal.model.Group;
039    import com.liferay.portal.model.GroupConstants;
040    import com.liferay.portal.model.Organization;
041    import com.liferay.portal.model.Phone;
042    import com.liferay.portal.model.Role;
043    import com.liferay.portal.model.RoleConstants;
044    import com.liferay.portal.model.User;
045    import com.liferay.portal.model.UserGroup;
046    import com.liferay.portal.model.UserGroupRole;
047    import com.liferay.portal.model.Website;
048    import com.liferay.portal.security.auth.PrincipalException;
049    import com.liferay.portal.security.membershippolicy.OrganizationMembershipPolicyUtil;
050    import com.liferay.portal.security.membershippolicy.RoleMembershipPolicyUtil;
051    import com.liferay.portal.security.membershippolicy.SiteMembershipPolicyUtil;
052    import com.liferay.portal.security.membershippolicy.UserGroupMembershipPolicyUtil;
053    import com.liferay.portal.security.permission.ActionKeys;
054    import com.liferay.portal.security.permission.PermissionChecker;
055    import com.liferay.portal.service.ServiceContext;
056    import com.liferay.portal.service.base.UserServiceBaseImpl;
057    import com.liferay.portal.service.permission.GroupPermissionUtil;
058    import com.liferay.portal.service.permission.OrganizationPermissionUtil;
059    import com.liferay.portal.service.permission.PasswordPolicyPermissionUtil;
060    import com.liferay.portal.service.permission.PortalPermissionUtil;
061    import com.liferay.portal.service.permission.RolePermissionUtil;
062    import com.liferay.portal.service.permission.TeamPermissionUtil;
063    import com.liferay.portal.service.permission.UserGroupPermissionUtil;
064    import com.liferay.portal.service.permission.UserGroupRolePermissionUtil;
065    import com.liferay.portal.service.permission.UserPermissionUtil;
066    import com.liferay.portal.util.PropsValues;
067    import com.liferay.portlet.announcements.model.AnnouncementsDelivery;
068    import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
069    
070    import java.util.ArrayList;
071    import java.util.Calendar;
072    import java.util.List;
073    import java.util.Locale;
074    import java.util.Set;
075    
076    /**
077     * Provides the remote service for accessing, adding, authenticating, deleting,
078     * and updating users. Its methods include permission checks.
079     *
080     * @author Brian Wing Shun Chan
081     * @author Brian Myunghun Kim
082     * @author Scott Lee
083     * @author Jorge Ferrer
084     * @author Julio Camarero
085     */
086    public class UserServiceImpl extends UserServiceBaseImpl {
087    
088            /**
089             * Adds the users to the group.
090             *
091             * @param  groupId the primary key of the group
092             * @param  userIds the primary keys of the users
093             * @param  serviceContext the service context to be applied (optionally
094             *         <code>null</code>)
095             * @throws PortalException if a group or user with the primary key could not
096             *         be found, if the user did not have permission to assign group
097             *         members, or if the operation was not allowed by the membership
098             *         policy
099             */
100            @Override
101            public void addGroupUsers(
102                            long groupId, long[] userIds, ServiceContext serviceContext)
103                    throws PortalException {
104    
105                    if (userIds.length == 0) {
106                            return;
107                    }
108    
109                    if (!GroupPermissionUtil.contains(
110                                    getPermissionChecker(), groupId, ActionKeys.ASSIGN_MEMBERS)) {
111    
112                            // Allow any user to join open sites
113    
114                            boolean hasPermission = false;
115    
116                            if (userIds.length == 1) {
117                                    User user = getUser();
118    
119                                    if (user.getUserId() == userIds[0]) {
120                                            Group group = groupPersistence.findByPrimaryKey(groupId);
121    
122                                            if (user.getCompanyId() == group.getCompanyId()) {
123                                                    int type = group.getType();
124    
125                                                    if (type == GroupConstants.TYPE_SITE_OPEN) {
126                                                            hasPermission = true;
127                                                    }
128                                            }
129                                    }
130                            }
131    
132                            if (!hasPermission) {
133                                    throw new PrincipalException();
134                            }
135                    }
136    
137                    SiteMembershipPolicyUtil.checkMembership(
138                            userIds, new long[] {groupId}, null);
139    
140                    userLocalService.addGroupUsers(groupId, userIds);
141    
142                    SiteMembershipPolicyUtil.propagateMembership(
143                            userIds, new long[] {groupId}, null);
144            }
145    
146            /**
147             * Adds the users to the organization.
148             *
149             * @param  organizationId the primary key of the organization
150             * @param  userIds the primary keys of the users
151             * @throws PortalException if an organization or user with the primary key
152             *         could not be found, if the user did not have permission to assign
153             *         organization members, if current user did not have an
154             *         organization in common with a given user, or if the operation was
155             *         not allowed by the membership policy
156             */
157            @Override
158            public void addOrganizationUsers(long organizationId, long[] userIds)
159                    throws PortalException {
160    
161                    if (userIds.length == 0) {
162                            return;
163                    }
164    
165                    OrganizationPermissionUtil.check(
166                            getPermissionChecker(), organizationId, ActionKeys.ASSIGN_MEMBERS);
167    
168                    validateOrganizationUsers(userIds);
169    
170                    OrganizationMembershipPolicyUtil.checkMembership(
171                            userIds, new long[] {organizationId}, null);
172    
173                    userLocalService.addOrganizationUsers(organizationId, userIds);
174    
175                    OrganizationMembershipPolicyUtil.propagateMembership(
176                            userIds, new long[] {organizationId}, null);
177            }
178    
179            /**
180             * Assigns the password policy to the users, removing any other currently
181             * assigned password policies.
182             *
183             * @param  passwordPolicyId the primary key of the password policy
184             * @param  userIds the primary keys of the users
185             * @throws PortalException if the user did not have permission to assign
186             *         policy members
187             */
188            @Override
189            public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
190                    throws PortalException {
191    
192                    if (userIds.length == 0) {
193                            return;
194                    }
195    
196                    PasswordPolicyPermissionUtil.check(
197                            getPermissionChecker(), passwordPolicyId,
198                            ActionKeys.ASSIGN_MEMBERS);
199    
200                    userLocalService.addPasswordPolicyUsers(passwordPolicyId, userIds);
201            }
202    
203            /**
204             * Adds the users to the role.
205             *
206             * @param  roleId the primary key of the role
207             * @param  userIds the primary keys of the users
208             * @throws PortalException if a role or user with the primary key could not
209             *         be found, if the user did not have permission to assign role
210             *         members, or if the operation was not allowed by the membership
211             *         policy
212             */
213            @Override
214            public void addRoleUsers(long roleId, long[] userIds)
215                    throws PortalException {
216    
217                    if (userIds.length == 0) {
218                            return;
219                    }
220    
221                    RolePermissionUtil.check(
222                            getPermissionChecker(), roleId, ActionKeys.ASSIGN_MEMBERS);
223    
224                    RoleMembershipPolicyUtil.checkRoles(userIds, new long[] {roleId}, null);
225    
226                    userLocalService.addRoleUsers(roleId, userIds);
227    
228                    RoleMembershipPolicyUtil.propagateRoles(
229                            userIds, new long[] {roleId}, null);
230            }
231    
232            /**
233             * Adds the users to the team.
234             *
235             * @param  teamId the primary key of the team
236             * @param  userIds the primary keys of the users
237             * @throws PortalException if a team or user with the primary key could not
238             *         be found or if the user did not have permission to assign team
239             *         members
240             */
241            @Override
242            public void addTeamUsers(long teamId, long[] userIds)
243                    throws PortalException {
244    
245                    if (userIds.length == 0) {
246                            return;
247                    }
248    
249                    TeamPermissionUtil.check(
250                            getPermissionChecker(), teamId, ActionKeys.ASSIGN_MEMBERS);
251    
252                    userLocalService.addTeamUsers(teamId, userIds);
253            }
254    
255            /**
256             * Adds a user.
257             *
258             * <p>
259             * This method handles the creation and bookkeeping of the user including
260             * its resources, metadata, and internal data structures. It is not
261             * necessary to make subsequent calls to any methods to setup default
262             * groups, resources, etc.
263             * </p>
264             *
265             * @param  companyId the primary key of the user's company
266             * @param  autoPassword whether a password should be automatically generated
267             *         for the user
268             * @param  password1 the user's password
269             * @param  password2 the user's password confirmation
270             * @param  autoScreenName whether a screen name should be automatically
271             *         generated for the user
272             * @param  screenName the user's screen name
273             * @param  emailAddress the user's email address
274             * @param  facebookId the user's facebook ID
275             * @param  openId the user's OpenID
276             * @param  locale the user's locale
277             * @param  firstName the user's first name
278             * @param  middleName the user's middle name
279             * @param  lastName the user's last name
280             * @param  prefixId the user's name prefix ID
281             * @param  suffixId the user's name suffix ID
282             * @param  male whether the user is male
283             * @param  birthdayMonth the user's birthday month (0-based, meaning 0 for
284             *         January)
285             * @param  birthdayDay the user's birthday day
286             * @param  birthdayYear the user's birthday year
287             * @param  jobTitle the user's job title
288             * @param  groupIds the primary keys of the user's groups
289             * @param  organizationIds the primary keys of the user's organizations
290             * @param  roleIds the primary keys of the roles this user possesses
291             * @param  userGroupIds the primary keys of the user's user groups
292             * @param  sendEmail whether to send the user an email notification about
293             *         their new account
294             * @param  serviceContext the service context to be applied (optionally
295             *         <code>null</code>). Can set the UUID (with the <code>uuid</code>
296             *         attribute), asset category IDs, asset tag names, and expando
297             *         bridge attributes for the user.
298             * @return the new user
299             * @throws PortalException if the user's information was invalid, if the
300             *         operation was not allowed by the membership policy, if the
301             *         creator did not have permission to add users, or if the email
302             *         address was reserved
303             */
304            @Override
305            public User addUser(
306                            long companyId, boolean autoPassword, String password1,
307                            String password2, boolean autoScreenName, String screenName,
308                            String emailAddress, long facebookId, String openId, Locale locale,
309                            String firstName, String middleName, String lastName, long prefixId,
310                            long suffixId, boolean male, int birthdayMonth, int birthdayDay,
311                            int birthdayYear, String jobTitle, long[] groupIds,
312                            long[] organizationIds, long[] roleIds, long[] userGroupIds,
313                            boolean sendEmail, ServiceContext serviceContext)
314                    throws PortalException {
315    
316                    boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
317    
318                    try {
319                            WorkflowThreadLocal.setEnabled(false);
320    
321                            return addUserWithWorkflow(
322                                    companyId, autoPassword, password1, password2, autoScreenName,
323                                    screenName, emailAddress, facebookId, openId, locale, firstName,
324                                    middleName, lastName, prefixId, suffixId, male, birthdayMonth,
325                                    birthdayDay, birthdayYear, jobTitle, groupIds, organizationIds,
326                                    roleIds, userGroupIds, sendEmail, serviceContext);
327                    }
328                    finally {
329                            WorkflowThreadLocal.setEnabled(workflowEnabled);
330                    }
331            }
332    
333            /**
334             * Adds a user with additional parameters.
335             *
336             * <p>
337             * This method handles the creation and bookkeeping of the user including
338             * its resources, metadata, and internal data structures. It is not
339             * necessary to make subsequent calls to any methods to setup default
340             * groups, resources, etc.
341             * </p>
342             *
343             * @param  companyId the primary key of the user's company
344             * @param  autoPassword whether a password should be automatically generated
345             *         for the user
346             * @param  password1 the user's password
347             * @param  password2 the user's password confirmation
348             * @param  autoScreenName whether a screen name should be automatically
349             *         generated for the user
350             * @param  screenName the user's screen name
351             * @param  emailAddress the user's email address
352             * @param  facebookId the user's facebook ID
353             * @param  openId the user's OpenID
354             * @param  locale the user's locale
355             * @param  firstName the user's first name
356             * @param  middleName the user's middle name
357             * @param  lastName the user's last name
358             * @param  prefixId the user's name prefix ID
359             * @param  suffixId the user's name suffix ID
360             * @param  male whether the user is male
361             * @param  birthdayMonth the user's birthday month (0-based, meaning 0 for
362             *         January)
363             * @param  birthdayDay the user's birthday day
364             * @param  birthdayYear the user's birthday year
365             * @param  jobTitle the user's job title
366             * @param  groupIds the primary keys of the user's groups
367             * @param  organizationIds the primary keys of the user's organizations
368             * @param  roleIds the primary keys of the roles this user possesses
369             * @param  userGroupIds the primary keys of the user's user groups
370             * @param  addresses the user's addresses
371             * @param  emailAddresses the user's email addresses
372             * @param  phones the user's phone numbers
373             * @param  websites the user's websites
374             * @param  announcementsDelivers the announcements deliveries
375             * @param  sendEmail whether to send the user an email notification about
376             *         their new account
377             * @param  serviceContext the service context to be applied (optionally
378             *         <code>null</code>). Can set the UUID (with the <code>uuid</code>
379             *         attribute), asset category IDs, asset tag names, and expando
380             *         bridge attributes for the user.
381             * @return the new user
382             * @throws PortalException if the user's information was invalid, if the
383             *         creator did not have permission to add users, if the email
384             *         address was reserved, if the operation was not allowed by the
385             *         membership policy, or if some other portal exception occurred
386             */
387            @Override
388            public User addUser(
389                            long companyId, boolean autoPassword, String password1,
390                            String password2, boolean autoScreenName, String screenName,
391                            String emailAddress, long facebookId, String openId, Locale locale,
392                            String firstName, String middleName, String lastName, long prefixId,
393                            long suffixId, boolean male, int birthdayMonth, int birthdayDay,
394                            int birthdayYear, String jobTitle, long[] groupIds,
395                            long[] organizationIds, long[] roleIds, long[] userGroupIds,
396                            List<Address> addresses, List<EmailAddress> emailAddresses,
397                            List<Phone> phones, List<Website> websites,
398                            List<AnnouncementsDelivery> announcementsDelivers,
399                            boolean sendEmail, ServiceContext serviceContext)
400                    throws PortalException {
401    
402                    boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
403    
404                    try {
405                            WorkflowThreadLocal.setEnabled(false);
406    
407                            return addUserWithWorkflow(
408                                    companyId, autoPassword, password1, password2, autoScreenName,
409                                    screenName, emailAddress, facebookId, openId, locale, firstName,
410                                    middleName, lastName, prefixId, suffixId, male, birthdayMonth,
411                                    birthdayDay, birthdayYear, jobTitle, groupIds, organizationIds,
412                                    roleIds, userGroupIds, addresses, emailAddresses, phones,
413                                    websites, announcementsDelivers, sendEmail, serviceContext);
414                    }
415                    finally {
416                            WorkflowThreadLocal.setEnabled(workflowEnabled);
417                    }
418            }
419    
420            /**
421             * Adds the users to the user group.
422             *
423             * @param  userGroupId the primary key of the user group
424             * @param  userIds the primary keys of the users
425             * @throws PortalException if a user group or user with the primary could
426             *         could not be found, if the current user did not have permission
427             *         to assign group members, or if the operation was not allowed by
428             *         the membership policy
429             */
430            @Override
431            public void addUserGroupUsers(long userGroupId, long[] userIds)
432                    throws PortalException {
433    
434                    if (userIds.length == 0) {
435                            return;
436                    }
437    
438                    UserGroupPermissionUtil.check(
439                            getPermissionChecker(), userGroupId, ActionKeys.ASSIGN_MEMBERS);
440    
441                    UserGroupMembershipPolicyUtil.checkMembership(
442                            userIds, new long[] {userGroupId}, null);
443    
444                    userLocalService.addUserGroupUsers(userGroupId, userIds);
445    
446                    UserGroupMembershipPolicyUtil.propagateMembership(
447                            userIds, new long[] {userGroupId}, null);
448            }
449    
450            /**
451             * Adds a user with workflow.
452             *
453             * <p>
454             * This method handles the creation and bookkeeping of the user including
455             * its resources, metadata, and internal data structures. It is not
456             * necessary to make subsequent calls to any methods to setup default
457             * groups, resources, etc.
458             * </p>
459             *
460             * @param  companyId the primary key of the user's company
461             * @param  autoPassword whether a password should be automatically generated
462             *         for the user
463             * @param  password1 the user's password
464             * @param  password2 the user's password confirmation
465             * @param  autoScreenName whether a screen name should be automatically
466             *         generated for the user
467             * @param  screenName the user's screen name
468             * @param  emailAddress the user's email address
469             * @param  facebookId the user's facebook ID
470             * @param  openId the user's OpenID
471             * @param  locale the user's locale
472             * @param  firstName the user's first name
473             * @param  middleName the user's middle name
474             * @param  lastName the user's last name
475             * @param  prefixId the user's name prefix ID
476             * @param  suffixId the user's name suffix ID
477             * @param  male whether the user is male
478             * @param  birthdayMonth the user's birthday month (0-based, meaning 0 for
479             *         January)
480             * @param  birthdayDay the user's birthday day
481             * @param  birthdayYear the user's birthday year
482             * @param  jobTitle the user's job title
483             * @param  groupIds the primary keys of the user's groups
484             * @param  organizationIds the primary keys of the user's organizations
485             * @param  roleIds the primary keys of the roles this user possesses
486             * @param  userGroupIds the primary keys of the user's user groups
487             * @param  sendEmail whether to send the user an email notification about
488             *         their new account
489             * @param  serviceContext the service context to be applied (optionally
490             *         <code>null</code>). Can set the UUID (with the <code>uuid</code>
491             *         attribute), asset category IDs, asset tag names, and expando
492             *         bridge attributes for the user.
493             * @return the new user
494             * @throws PortalException if the user's information was invalid, if the
495             *         operation was not allowed by the membership policy, if the
496             *         creator did not have permission to add users, or if the email
497             *         address was reserved
498             */
499            @Override
500            public User addUserWithWorkflow(
501                            long companyId, boolean autoPassword, String password1,
502                            String password2, boolean autoScreenName, String screenName,
503                            String emailAddress, long facebookId, String openId, Locale locale,
504                            String firstName, String middleName, String lastName, long prefixId,
505                            long suffixId, boolean male, int birthdayMonth, int birthdayDay,
506                            int birthdayYear, String jobTitle, long[] groupIds,
507                            long[] organizationIds, long[] roleIds, long[] userGroupIds,
508                            boolean sendEmail, ServiceContext serviceContext)
509                    throws PortalException {
510    
511                    long creatorUserId = 0;
512    
513                    try {
514                            creatorUserId = getGuestOrUserId();
515                    }
516                    catch (PrincipalException pe) {
517                            if (_log.isWarnEnabled()) {
518                                    _log.warn("Unable to get guest or current user ID", pe);
519                            }
520                    }
521    
522                    checkAddUserPermission(
523                            creatorUserId, companyId, emailAddress, groupIds, organizationIds,
524                            roleIds, userGroupIds, serviceContext);
525    
526                    User user = userLocalService.addUserWithWorkflow(
527                            creatorUserId, companyId, autoPassword, password1, password2,
528                            autoScreenName, screenName, emailAddress, facebookId, openId,
529                            locale, firstName, middleName, lastName, prefixId, suffixId, male,
530                            birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
531                            organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
532    
533                    checkMembership(
534                            new long[] {user.getUserId()}, groupIds, organizationIds, roleIds,
535                            userGroupIds);
536    
537                    propagateMembership(
538                            new long[] {user.getUserId()}, groupIds, organizationIds, roleIds,
539                            userGroupIds);
540    
541                    return user;
542            }
543    
544            /**
545             * Adds a user with workflow and additional parameters.
546             *
547             * <p>
548             * This method handles the creation and bookkeeping of the user including
549             * its resources, metadata, and internal data structures. It is not
550             * necessary to make subsequent calls to any methods to setup default
551             * groups, resources, etc.
552             * </p>
553             *
554             * @param  companyId the primary key of the user's company
555             * @param  autoPassword whether a password should be automatically generated
556             *         for the user
557             * @param  password1 the user's password
558             * @param  password2 the user's password confirmation
559             * @param  autoScreenName whether a screen name should be automatically
560             *         generated for the user
561             * @param  screenName the user's screen name
562             * @param  emailAddress the user's email address
563             * @param  facebookId the user's facebook ID
564             * @param  openId the user's OpenID
565             * @param  locale the user's locale
566             * @param  firstName the user's first name
567             * @param  middleName the user's middle name
568             * @param  lastName the user's last name
569             * @param  prefixId the user's name prefix ID
570             * @param  suffixId the user's name suffix ID
571             * @param  male whether the user is male
572             * @param  birthdayMonth the user's birthday month (0-based, meaning 0 for
573             *         January)
574             * @param  birthdayDay the user's birthday day
575             * @param  birthdayYear the user's birthday year
576             * @param  jobTitle the user's job title
577             * @param  groupIds the primary keys of the user's groups
578             * @param  organizationIds the primary keys of the user's organizations
579             * @param  roleIds the primary keys of the roles this user possesses
580             * @param  userGroupIds the primary keys of the user's user groups
581             * @param  addresses the user's addresses
582             * @param  emailAddresses the user's email addresses
583             * @param  phones the user's phone numbers
584             * @param  websites the user's websites
585             * @param  announcementsDelivers the announcements deliveries
586             * @param  sendEmail whether to send the user an email notification about
587             *         their new account
588             * @param  serviceContext the service context to be applied (optionally
589             *         <code>null</code>). Can set the UUID (with the <code>uuid</code>
590             *         attribute), asset category IDs, asset tag names, and expando
591             *         bridge attributes for the user.
592             * @return the new user
593             * @throws PortalException if the user's information was invalid, if the
594             *         operation was not allowed by the membership policy, if the
595             *         creator did not have permission to add users, if the email
596             *         address was reserved, or if some other portal exception occurred
597             */
598            @Override
599            public User addUserWithWorkflow(
600                            long companyId, boolean autoPassword, String password1,
601                            String password2, boolean autoScreenName, String screenName,
602                            String emailAddress, long facebookId, String openId, Locale locale,
603                            String firstName, String middleName, String lastName, long prefixId,
604                            long suffixId, boolean male, int birthdayMonth, int birthdayDay,
605                            int birthdayYear, String jobTitle, long[] groupIds,
606                            long[] organizationIds, long[] roleIds, long[] userGroupIds,
607                            List<Address> addresses, List<EmailAddress> emailAddresses,
608                            List<Phone> phones, List<Website> websites,
609                            List<AnnouncementsDelivery> announcementsDelivers,
610                            boolean sendEmail, ServiceContext serviceContext)
611                    throws PortalException {
612    
613                    boolean indexingEnabled = true;
614    
615                    if (serviceContext != null) {
616                            indexingEnabled = serviceContext.isIndexingEnabled();
617    
618                            serviceContext.setIndexingEnabled(false);
619                    }
620    
621                    try {
622                            User user = addUserWithWorkflow(
623                                    companyId, autoPassword, password1, password2, autoScreenName,
624                                    screenName, emailAddress, facebookId, openId, locale, firstName,
625                                    middleName, lastName, prefixId, suffixId, male, birthdayMonth,
626                                    birthdayDay, birthdayYear, jobTitle, groupIds, organizationIds,
627                                    roleIds, userGroupIds, sendEmail, serviceContext);
628    
629                            UsersAdminUtil.updateAddresses(
630                                    Contact.class.getName(), user.getContactId(), addresses);
631    
632                            UsersAdminUtil.updateEmailAddresses(
633                                    Contact.class.getName(), user.getContactId(), emailAddresses);
634    
635                            UsersAdminUtil.updatePhones(
636                                    Contact.class.getName(), user.getContactId(), phones);
637    
638                            UsersAdminUtil.updateWebsites(
639                                    Contact.class.getName(), user.getContactId(), websites);
640    
641                            updateAnnouncementsDeliveries(
642                                    user.getUserId(), announcementsDelivers);
643    
644                            if (indexingEnabled) {
645                                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
646                                            User.class);
647    
648                                    indexer.reindex(user);
649                            }
650    
651                            return user;
652                    }
653                    finally {
654                            if (serviceContext != null) {
655                                    serviceContext.setIndexingEnabled(indexingEnabled);
656                            }
657                    }
658            }
659    
660            /**
661             * Deletes the user's portrait image.
662             *
663             * @param  userId the primary key of the user
664             * @throws PortalException if a user with the primary key could not be
665             *         found, if the user's portrait could not be found, or if the
666             *         current user did not have permission to update the user
667             */
668            @Override
669            public void deletePortrait(long userId) throws PortalException {
670                    UserPermissionUtil.check(
671                            getPermissionChecker(), userId, ActionKeys.UPDATE);
672    
673                    userLocalService.deletePortrait(userId);
674            }
675    
676            /**
677             * Removes the user from the role.
678             *
679             * @param  roleId the primary key of the role
680             * @param  userId the primary key of the user
681             * @throws PortalException if a role or user with the primary key could not
682             *         be found, or if the current user did not have permission to
683             *         assign role members
684             */
685            @Override
686            public void deleteRoleUser(long roleId, long userId)
687                    throws PortalException {
688    
689                    RolePermissionUtil.check(
690                            getPermissionChecker(), roleId, ActionKeys.ASSIGN_MEMBERS);
691    
692                    userLocalService.deleteRoleUser(roleId, userId);
693            }
694    
695            /**
696             * Deletes the user.
697             *
698             * @param  userId the primary key of the user
699             * @throws PortalException if a user with the primary key could not be found
700             *         or if the current user did not have permission to delete the user
701             */
702            @Override
703            public void deleteUser(long userId) throws PortalException {
704                    if (getUserId() == userId) {
705                            throw new RequiredUserException();
706                    }
707    
708                    UserPermissionUtil.check(
709                            getPermissionChecker(), userId, ActionKeys.DELETE);
710    
711                    userLocalService.deleteUser(userId);
712            }
713    
714            @Override
715            public List<User> getCompanyUsers(long companyId, int start, int end)
716                    throws PortalException {
717    
718                    PermissionChecker permissionChecker = getPermissionChecker();
719    
720                    if (!permissionChecker.isCompanyAdmin(companyId)) {
721                            throw new PrincipalException();
722                    }
723    
724                    return userPersistence.findByCompanyId(companyId, start, end);
725            }
726    
727            @Override
728            public int getCompanyUsersCount(long companyId) throws PortalException {
729                    PermissionChecker permissionChecker = getPermissionChecker();
730    
731                    if (!permissionChecker.isCompanyAdmin(companyId)) {
732                            throw new PrincipalException();
733                    }
734    
735                    return userPersistence.countByCompanyId(companyId);
736            }
737    
738            @Override
739            public User getCurrentUser() throws PortalException {
740                    return getUser();
741            }
742    
743            /**
744             * Returns the primary keys of all the users belonging to the group.
745             *
746             * @param  groupId the primary key of the group
747             * @return the primary keys of the users belonging to the group
748             * @throws PortalException if the current user did not have permission to
749             *         view group assignments
750             */
751            @Override
752            public long[] getGroupUserIds(long groupId) throws PortalException {
753                    GroupPermissionUtil.check(
754                            getPermissionChecker(), groupId, ActionKeys.VIEW_MEMBERS);
755    
756                    return userLocalService.getGroupUserIds(groupId);
757            }
758    
759            /**
760             * Returns all the users belonging to the group.
761             *
762             * @param  groupId the primary key of the group
763             * @return the users belonging to the group
764             * @throws PortalException if the current user did not have permission to
765             *         view group assignments
766             */
767            @Override
768            public List<User> getGroupUsers(long groupId) throws PortalException {
769                    GroupPermissionUtil.check(
770                            getPermissionChecker(), groupId, ActionKeys.VIEW_MEMBERS);
771    
772                    return userLocalService.getGroupUsers(groupId);
773            }
774    
775            /**
776             * Returns the primary keys of all the users belonging to the organization.
777             *
778             * @param  organizationId the primary key of the organization
779             * @return the primary keys of the users belonging to the organization
780             * @throws PortalException if the current user did not have permission to
781             *         view organization assignments
782             */
783            @Override
784            public long[] getOrganizationUserIds(long organizationId)
785                    throws PortalException {
786    
787                    OrganizationPermissionUtil.check(
788                            getPermissionChecker(), organizationId, ActionKeys.VIEW_MEMBERS);
789    
790                    return userLocalService.getOrganizationUserIds(organizationId);
791            }
792    
793            /**
794             * Returns all the users belonging to the organization.
795             *
796             * @param  organizationId the primary key of the organization
797             * @return users belonging to the organization
798             * @throws PortalException if the current user did not have permission to
799             *         view organization assignments
800             */
801            @Override
802            public List<User> getOrganizationUsers(long organizationId)
803                    throws PortalException {
804    
805                    OrganizationPermissionUtil.check(
806                            getPermissionChecker(), organizationId, ActionKeys.VIEW_MEMBERS);
807    
808                    return userLocalService.getOrganizationUsers(organizationId);
809            }
810    
811            /**
812             * Returns the primary keys of all the users belonging to the role.
813             *
814             * @param  roleId the primary key of the role
815             * @return the primary keys of the users belonging to the role
816             * @throws PortalException if the current user did not have permission to
817             *         view role members
818             */
819            @Override
820            public long[] getRoleUserIds(long roleId) throws PortalException {
821                    RolePermissionUtil.check(
822                            getPermissionChecker(), roleId, ActionKeys.VIEW);
823    
824                    return userLocalService.getRoleUserIds(roleId);
825            }
826    
827            /**
828             * Returns the user with the email address.
829             *
830             * @param  companyId the primary key of the user's company
831             * @param  emailAddress the user's email address
832             * @return the user with the email address
833             * @throws PortalException if a user with the email address could not be
834             *         found or if the current user did not have permission to view the
835             *         user
836             */
837            @Override
838            public User getUserByEmailAddress(long companyId, String emailAddress)
839                    throws PortalException {
840    
841                    User user = userLocalService.getUserByEmailAddress(
842                            companyId, emailAddress);
843    
844                    UserPermissionUtil.check(
845                            getPermissionChecker(), user.getUserId(), ActionKeys.VIEW);
846    
847                    return user;
848            }
849    
850            /**
851             * Returns the user with the primary key.
852             *
853             * @param  userId the primary key of the user
854             * @return the user with the primary key
855             * @throws PortalException if a user with the primary key could not be found
856             *         or if the current user did not have permission to view the user
857             */
858            @Override
859            public User getUserById(long userId) throws PortalException {
860                    User user = userPersistence.findByPrimaryKey(userId);
861    
862                    UserPermissionUtil.check(
863                            getPermissionChecker(), user.getUserId(), ActionKeys.VIEW);
864    
865                    return user;
866            }
867    
868            /**
869             * Returns the user with the screen name.
870             *
871             * @param  companyId the primary key of the user's company
872             * @param  screenName the user's screen name
873             * @return the user with the screen name
874             * @throws PortalException if a user with the screen name could not be found
875             *         or if the current user did not have permission to view the user
876             */
877            @Override
878            public User getUserByScreenName(long companyId, String screenName)
879                    throws PortalException {
880    
881                    User user = userLocalService.getUserByScreenName(companyId, screenName);
882    
883                    UserPermissionUtil.check(
884                            getPermissionChecker(), user.getUserId(), ActionKeys.VIEW);
885    
886                    return user;
887            }
888    
889            @Override
890            public List<User> getUserGroupUsers(long userGroupId)
891                    throws PortalException {
892    
893                    UserGroupPermissionUtil.check(
894                            getPermissionChecker(), userGroupId, ActionKeys.VIEW_MEMBERS);
895    
896                    return userGroupPersistence.getUsers(userGroupId);
897            }
898    
899            /**
900             * Returns the primary key of the user with the email address.
901             *
902             * @param  companyId the primary key of the user's company
903             * @param  emailAddress the user's email address
904             * @return the primary key of the user with the email address
905             * @throws PortalException if a user with the email address could not be
906             *         found
907             */
908            @Override
909            public long getUserIdByEmailAddress(long companyId, String emailAddress)
910                    throws PortalException {
911    
912                    User user = getUserByEmailAddress(companyId, emailAddress);
913    
914                    UserPermissionUtil.check(
915                            getPermissionChecker(), user.getUserId(), ActionKeys.VIEW);
916    
917                    return user.getUserId();
918            }
919    
920            /**
921             * Returns the primary key of the user with the screen name.
922             *
923             * @param  companyId the primary key of the user's company
924             * @param  screenName the user's screen name
925             * @return the primary key of the user with the screen name
926             * @throws PortalException if a user with the screen name could not be found
927             */
928            @Override
929            public long getUserIdByScreenName(long companyId, String screenName)
930                    throws PortalException {
931    
932                    User user = getUserByScreenName(companyId, screenName);
933    
934                    UserPermissionUtil.check(
935                            getPermissionChecker(), user.getUserId(), ActionKeys.VIEW);
936    
937                    return user.getUserId();
938            }
939    
940            /**
941             * Returns <code>true</code> if the user is a member of the group.
942             *
943             * @param  groupId the primary key of the group
944             * @param  userId the primary key of the user
945             * @return <code>true</code> if the user is a member of the group;
946             *         <code>false</code> otherwise
947             * @throws PortalException if the current user did not have permission to
948             *         view the user or group members
949             */
950            @Override
951            public boolean hasGroupUser(long groupId, long userId)
952                    throws PortalException {
953    
954                    if (!UserPermissionUtil.contains(
955                                    getPermissionChecker(), userId, ActionKeys.VIEW)) {
956    
957                            GroupPermissionUtil.check(
958                                    getPermissionChecker(), groupId, ActionKeys.VIEW_MEMBERS);
959                    }
960    
961                    return userLocalService.hasGroupUser(groupId, userId);
962            }
963    
964            /**
965             * Returns <code>true</code> if the user is a member of the role.
966             *
967             * @param  roleId the primary key of the role
968             * @param  userId the primary key of the user
969             * @return <code>true</code> if the user is a member of the role;
970             *         <code>false</code> otherwise
971             * @throws PortalException if the current user did not have permission to
972             *         view the user or role members
973             */
974            @Override
975            public boolean hasRoleUser(long roleId, long userId)
976                    throws PortalException {
977    
978                    if (!UserPermissionUtil.contains(
979                                    getPermissionChecker(), userId, ActionKeys.VIEW)) {
980    
981                            RolePermissionUtil.check(
982                                    getPermissionChecker(), roleId, ActionKeys.VIEW_MEMBERS);
983                    }
984    
985                    return userLocalService.hasRoleUser(roleId, userId);
986            }
987    
988            /**
989             * Returns <code>true</code> if the user has the role with the name,
990             * optionally through inheritance.
991             *
992             * @param  companyId the primary key of the role's company
993             * @param  name the name of the role (must be a regular role, not an
994             *         organization, site or provider role)
995             * @param  userId the primary key of the user
996             * @param  inherited whether to include roles inherited from organizations,
997             *         sites, etc.
998             * @return <code>true</code> if the user has the role; <code>false</code>
999             *         otherwise
1000             * @throws PortalException if a role with the name could not be found
1001             */
1002            @Override
1003            public boolean hasRoleUser(
1004                            long companyId, String name, long userId, boolean inherited)
1005                    throws PortalException {
1006    
1007                    if (!UserPermissionUtil.contains(
1008                                    getPermissionChecker(), userId, ActionKeys.VIEW)) {
1009    
1010                            Role role = roleLocalService.getRole(companyId, name);
1011    
1012                            RolePermissionUtil.check(
1013                                    getPermissionChecker(), role.getRoleId(),
1014                                    ActionKeys.VIEW_MEMBERS);
1015                    }
1016    
1017                    return userLocalService.hasRoleUser(companyId, name, userId, inherited);
1018            }
1019    
1020            /**
1021             * Sends a password notification email to the user matching the email
1022             * address. The portal's settings determine whether a password is sent
1023             * explicitly or whether a link for resetting the user's password is sent.
1024             * The method sends the email asynchronously and returns before the email is
1025             * sent.
1026             *
1027             * <p>
1028             * The content of the notification email is specified with the
1029             * <code>admin.email.password</code> portal property keys. They can be
1030             * overridden via a <code>portal-ext.properties</code> file or modified
1031             * through the Portal Settings UI.
1032             * </p>
1033             *
1034             * @param  companyId the primary key of the user's company
1035             * @param  emailAddress the user's email address
1036             * @return <code>true</code> if the notification email includes a new
1037             *         password; <code>false</code> if the notification email only
1038             *         contains a reset link
1039             * @throws PortalException if a user with the email address could not be
1040             *         found
1041             */
1042            @Override
1043            public boolean sendPasswordByEmailAddress(
1044                            long companyId, String emailAddress)
1045                    throws PortalException {
1046    
1047                    return userLocalService.sendPasswordByEmailAddress(
1048                            companyId, emailAddress);
1049            }
1050    
1051            /**
1052             * Sends a password notification email to the user matching the screen name.
1053             * The portal's settings determine whether a password is sent explicitly or
1054             * whether a link for resetting the user's password is sent. The method
1055             * sends the email asynchronously and returns before the email is sent.
1056             *
1057             * <p>
1058             * The content of the notification email is specified with the
1059             * <code>admin.email.password</code> portal property keys. They can be
1060             * overridden via a <code>portal-ext.properties</code> file or modified
1061             * through the Portal Settings UI.
1062             * </p>
1063             *
1064             * @param  companyId the primary key of the user's company
1065             * @param  screenName the user's screen name
1066             * @return <code>true</code> if the notification email includes a new
1067             *         password; <code>false</code> if the notification email only
1068             *         contains a reset link
1069             * @throws PortalException if a user with the screen name could not be found
1070             */
1071            @Override
1072            public boolean sendPasswordByScreenName(long companyId, String screenName)
1073                    throws PortalException {
1074    
1075                    return userLocalService.sendPasswordByScreenName(companyId, screenName);
1076            }
1077    
1078            /**
1079             * Sends a password notification email to the user matching the ID. The
1080             * portal's settings determine whether a password is sent explicitly or
1081             * whether a link for resetting the user's password is sent. The method
1082             * sends the email asynchronously and returns before the email is sent.
1083             *
1084             * <p>
1085             * The content of the notification email is specified with the
1086             * <code>admin.email.password</code> portal property keys. They can be
1087             * overridden via a <code>portal-ext.properties</code> file or modified
1088             * through the Portal Settings UI.
1089             * </p>
1090             *
1091             * @param  userId the user's primary key
1092             * @return <code>true</code> if the notification email includes a new
1093             *         password; <code>false</code> if the notification email only
1094             *         contains a reset link
1095             * @throws PortalException if a user with the user ID could not be found
1096             */
1097            @Override
1098            public boolean sendPasswordByUserId(long userId) throws PortalException {
1099                    return userLocalService.sendPasswordByUserId(userId);
1100            }
1101    
1102            /**
1103             * Sets the users in the role, removing and adding users to the role as
1104             * necessary.
1105             *
1106             * @param  roleId the primary key of the role
1107             * @param  userIds the primary keys of the users
1108             * @throws PortalException if the current user did not have permission to
1109             *         assign role members or if the operation was not allowed by the
1110             *         membership policy
1111             */
1112            @Override
1113            public void setRoleUsers(long roleId, long[] userIds)
1114                    throws PortalException {
1115    
1116                    RolePermissionUtil.check(
1117                            getPermissionChecker(), roleId, ActionKeys.ASSIGN_MEMBERS);
1118    
1119                    Set<Long> unsetUserIds = SetUtil.fromArray(
1120                            rolePersistence.getUserPrimaryKeys(roleId));
1121    
1122                    unsetUserIds.removeAll(SetUtil.fromArray(userIds));
1123    
1124                    if (!unsetUserIds.isEmpty()) {
1125                            RoleMembershipPolicyUtil.checkRoles(
1126                                    ArrayUtil.toLongArray(unsetUserIds), null, new long[] {roleId});
1127                    }
1128    
1129                    if (userIds.length > 0) {
1130                            RoleMembershipPolicyUtil.checkRoles(
1131                                    userIds, new long[] {roleId}, null);
1132                    }
1133    
1134                    userLocalService.setRoleUsers(roleId, userIds);
1135    
1136                    if (!unsetUserIds.isEmpty()) {
1137                            RoleMembershipPolicyUtil.propagateRoles(
1138                                    ArrayUtil.toLongArray(unsetUserIds), null, new long[] {roleId});
1139                    }
1140    
1141                    if (userIds.length > 0) {
1142                            RoleMembershipPolicyUtil.propagateRoles(
1143                                    userIds, new long[] {roleId}, null);
1144                    }
1145            }
1146    
1147            /**
1148             * Sets the users in the user group, removing and adding users to the user
1149             * group as necessary.
1150             *
1151             * @param  userGroupId the primary key of the user group
1152             * @param  userIds the primary keys of the users
1153             * @throws PortalException if the current user did not have permission to
1154             *         assign group members
1155             */
1156            @Override
1157            public void setUserGroupUsers(long userGroupId, long[] userIds)
1158                    throws PortalException {
1159    
1160                    UserGroupPermissionUtil.check(
1161                            getPermissionChecker(), userGroupId, ActionKeys.ASSIGN_MEMBERS);
1162    
1163                    Set<Long> unsetUserIds = SetUtil.fromArray(
1164                            userGroupPersistence.getUserPrimaryKeys(userGroupId));
1165    
1166                    unsetUserIds.removeAll(SetUtil.fromArray(userIds));
1167    
1168                    if (!unsetUserIds.isEmpty()) {
1169                            UserGroupMembershipPolicyUtil.checkMembership(
1170                                    ArrayUtil.toLongArray(unsetUserIds), null,
1171                                    new long[] {userGroupId});
1172                    }
1173    
1174                    if (userIds.length > 0) {
1175                            UserGroupMembershipPolicyUtil.checkMembership(
1176                                    userIds, new long[] {userGroupId}, null);
1177                    }
1178    
1179                    userLocalService.setUserGroupUsers(userGroupId, userIds);
1180    
1181                    if (!unsetUserIds.isEmpty()) {
1182                            UserGroupMembershipPolicyUtil.propagateMembership(
1183                                    ArrayUtil.toLongArray(unsetUserIds), null,
1184                                    new long[] {userGroupId});
1185                    }
1186    
1187                    if (userIds.length > 0) {
1188                            UserGroupMembershipPolicyUtil.propagateMembership(
1189                                    userIds, new long[] {userGroupId}, null);
1190                    }
1191            }
1192    
1193            /**
1194             * Removes the users from the teams of a group.
1195             *
1196             * @param  groupId the primary key of the group
1197             * @param  userIds the primary keys of the users
1198             * @throws PortalException if the current user did not have permission to
1199             *         modify user group assignments
1200             */
1201            @Override
1202            public void unsetGroupTeamsUsers(long groupId, long[] userIds)
1203                    throws PortalException {
1204    
1205                    if (userIds.length == 0) {
1206                            return;
1207                    }
1208    
1209                    UserGroupPermissionUtil.check(
1210                            getPermissionChecker(), groupId, ActionKeys.ASSIGN_MEMBERS);
1211    
1212                    userLocalService.unsetGroupTeamsUsers(groupId, userIds);
1213            }
1214    
1215            /**
1216             * Removes the users from the group.
1217             *
1218             * @param  groupId the primary key of the group
1219             * @param  userIds the primary keys of the users
1220             * @param  serviceContext the service context to be applied (optionally
1221             *         <code>null</code>)
1222             * @throws PortalException if the current user did not have permission to
1223             *         modify group assignments or if the operation was not allowed by
1224             *         the membership policy
1225             */
1226            @Override
1227            public void unsetGroupUsers(
1228                            long groupId, long[] userIds, ServiceContext serviceContext)
1229                    throws PortalException {
1230    
1231                    userIds = UsersAdminUtil.filterUnsetGroupUserIds(
1232                            getPermissionChecker(), groupId, userIds);
1233    
1234                    if (userIds.length == 0) {
1235                            return;
1236                    }
1237    
1238                    if (!GroupPermissionUtil.contains(
1239                                    getPermissionChecker(), groupId, ActionKeys.ASSIGN_MEMBERS)) {
1240    
1241                            // Allow any user to leave open and restricted sites
1242    
1243                            boolean hasPermission = false;
1244    
1245                            if (userIds.length == 1) {
1246                                    User user = getUser();
1247    
1248                                    if (user.getUserId() == userIds[0]) {
1249                                            Group group = groupPersistence.findByPrimaryKey(groupId);
1250    
1251                                            if (user.getCompanyId() == group.getCompanyId()) {
1252                                                    int type = group.getType();
1253    
1254                                                    if ((type == GroupConstants.TYPE_SITE_OPEN) ||
1255                                                            (type == GroupConstants.TYPE_SITE_RESTRICTED)) {
1256    
1257                                                            hasPermission = true;
1258                                                    }
1259                                            }
1260                                    }
1261                            }
1262    
1263                            if (!hasPermission) {
1264                                    throw new PrincipalException();
1265                            }
1266                    }
1267    
1268                    SiteMembershipPolicyUtil.checkMembership(
1269                            userIds, null, new long[] {groupId});
1270    
1271                    userLocalService.unsetGroupUsers(groupId, userIds, serviceContext);
1272    
1273                    SiteMembershipPolicyUtil.propagateMembership(
1274                            userIds, null, new long[] {groupId});
1275            }
1276    
1277            /**
1278             * Removes the users from the organization.
1279             *
1280             * @param  organizationId the primary key of the organization
1281             * @param  userIds the primary keys of the users
1282             * @throws PortalException if the current user did not have permission to
1283             *         modify organization assignments or if the operation was not
1284             *         allowed by the membership policy
1285             */
1286            @Override
1287            public void unsetOrganizationUsers(long organizationId, long[] userIds)
1288                    throws PortalException {
1289    
1290                    userIds = UsersAdminUtil.filterUnsetOrganizationUserIds(
1291                            getPermissionChecker(), organizationId, userIds);
1292    
1293                    if (userIds.length == 0) {
1294                            return;
1295                    }
1296    
1297                    OrganizationPermissionUtil.check(
1298                            getPermissionChecker(), organizationId, ActionKeys.ASSIGN_MEMBERS);
1299    
1300                    OrganizationMembershipPolicyUtil.checkMembership(
1301                            userIds, null, new long[] {organizationId});
1302    
1303                    userLocalService.unsetOrganizationUsers(organizationId, userIds);
1304    
1305                    OrganizationMembershipPolicyUtil.propagateMembership(
1306                            userIds, null, new long[] {organizationId});
1307            }
1308    
1309            /**
1310             * Removes the users from the password policy.
1311             *
1312             * @param  passwordPolicyId the primary key of the password policy
1313             * @param  userIds the primary keys of the users
1314             * @throws PortalException if the current user did not have permission to
1315             *         modify policy assignments
1316             */
1317            @Override
1318            public void unsetPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
1319                    throws PortalException {
1320    
1321                    if (userIds.length == 0) {
1322                            return;
1323                    }
1324    
1325                    PasswordPolicyPermissionUtil.check(
1326                            getPermissionChecker(), passwordPolicyId,
1327                            ActionKeys.ASSIGN_MEMBERS);
1328    
1329                    userLocalService.unsetPasswordPolicyUsers(passwordPolicyId, userIds);
1330            }
1331    
1332            /**
1333             * Removes the users from the role.
1334             *
1335             * @param  roleId the primary key of the role
1336             * @param  userIds the primary keys of the users
1337             * @throws PortalException if the current user did not have permission to
1338             *         modify role assignments or if the operation was not allowed by
1339             *         the membership policy
1340             */
1341            @Override
1342            public void unsetRoleUsers(long roleId, long[] userIds)
1343                    throws PortalException {
1344    
1345                    if (userIds.length == 0) {
1346                            return;
1347                    }
1348    
1349                    RolePermissionUtil.check(
1350                            getPermissionChecker(), roleId, ActionKeys.ASSIGN_MEMBERS);
1351    
1352                    RoleMembershipPolicyUtil.checkRoles(userIds, null, new long[] {roleId});
1353    
1354                    userLocalService.unsetRoleUsers(roleId, userIds);
1355    
1356                    RoleMembershipPolicyUtil.propagateRoles(
1357                            userIds, null, new long[] {roleId});
1358            }
1359    
1360            /**
1361             * Removes the users from the team.
1362             *
1363             * @param  teamId the primary key of the team
1364             * @param  userIds the primary keys of the users
1365             * @throws PortalException if the current user did not have permission to
1366             *         modify team assignments
1367             */
1368            @Override
1369            public void unsetTeamUsers(long teamId, long[] userIds)
1370                    throws PortalException {
1371    
1372                    if (userIds.length == 0) {
1373                            return;
1374                    }
1375    
1376                    TeamPermissionUtil.check(
1377                            getPermissionChecker(), teamId, ActionKeys.ASSIGN_MEMBERS);
1378    
1379                    userLocalService.unsetTeamUsers(teamId, userIds);
1380            }
1381    
1382            /**
1383             * Removes the users from the user group.
1384             *
1385             * @param  userGroupId the primary key of the user group
1386             * @param  userIds the primary keys of the users
1387             * @throws PortalException if the current user did not have permission to
1388             *         modify user group assignments or if the operation was not allowed
1389             *         by the membership policy
1390             */
1391            @Override
1392            public void unsetUserGroupUsers(long userGroupId, long[] userIds)
1393                    throws PortalException {
1394    
1395                    if (userIds.length == 0) {
1396                            return;
1397                    }
1398    
1399                    UserGroupPermissionUtil.check(
1400                            getPermissionChecker(), userGroupId, ActionKeys.ASSIGN_MEMBERS);
1401    
1402                    UserGroupMembershipPolicyUtil.checkMembership(
1403                            userIds, null, new long[] {userGroupId});
1404    
1405                    userLocalService.unsetUserGroupUsers(userGroupId, userIds);
1406    
1407                    UserGroupMembershipPolicyUtil.propagateMembership(
1408                            userIds, null, new long[] {userGroupId});
1409            }
1410    
1411            /**
1412             * Updates the user's response to the terms of use agreement.
1413             *
1414             * @param  userId the primary key of the user
1415             * @param  agreedToTermsOfUse whether the user has agree to the terms of use
1416             * @return the user
1417             * @throws PortalException if the current user did not have permission to
1418             *         update the user's agreement to terms-of-use
1419             */
1420            @Override
1421            public User updateAgreedToTermsOfUse(
1422                            long userId, boolean agreedToTermsOfUse)
1423                    throws PortalException {
1424    
1425                    UserPermissionUtil.check(
1426                            getPermissionChecker(), userId, ActionKeys.UPDATE);
1427    
1428                    return userLocalService.updateAgreedToTermsOfUse(
1429                            userId, agreedToTermsOfUse);
1430            }
1431    
1432            /**
1433             * Updates the user's email address.
1434             *
1435             * @param  userId the primary key of the user
1436             * @param  password the user's password
1437             * @param  emailAddress1 the user's new email address
1438             * @param  emailAddress2 the user's new email address confirmation
1439             * @param  serviceContext the service context to be applied. Must set the
1440             *         portal URL, main path, primary key of the layout, remote address,
1441             *         remote host, and agent for the user.
1442             * @return the user
1443             * @throws PortalException if a user with the primary key could not be found
1444             *         or if the current user did not have permission to update the user
1445             */
1446            @Override
1447            public User updateEmailAddress(
1448                            long userId, String password, String emailAddress1,
1449                            String emailAddress2, ServiceContext serviceContext)
1450                    throws PortalException {
1451    
1452                    UserPermissionUtil.check(
1453                            getPermissionChecker(), userId, ActionKeys.UPDATE);
1454    
1455                    User user = userPersistence.findByPrimaryKey(userId);
1456    
1457                    validateEmailAddress(user, emailAddress2);
1458    
1459                    return userLocalService.updateEmailAddress(
1460                            userId, password, emailAddress1, emailAddress2, serviceContext);
1461            }
1462    
1463            /**
1464             * Updates a user account that was automatically created when a guest user
1465             * participated in an action (e.g. posting a comment) and only provided his
1466             * name and email address.
1467             *
1468             * @param  companyId the primary key of the user's company
1469             * @param  autoPassword whether a password should be automatically generated
1470             *         for the user
1471             * @param  password1 the user's password
1472             * @param  password2 the user's password confirmation
1473             * @param  autoScreenName whether a screen name should be automatically
1474             *         generated for the user
1475             * @param  screenName the user's screen name
1476             * @param  emailAddress the user's email address
1477             * @param  facebookId the user's facebook ID
1478             * @param  openId the user's OpenID
1479             * @param  locale the user's locale
1480             * @param  firstName the user's first name
1481             * @param  middleName the user's middle name
1482             * @param  lastName the user's last name
1483             * @param  prefixId the user's name prefix ID
1484             * @param  suffixId the user's name suffix ID
1485             * @param  male whether the user is male
1486             * @param  birthdayMonth the user's birthday month (0-based, meaning 0 for
1487             *         January)
1488             * @param  birthdayDay the user's birthday day
1489             * @param  birthdayYear the user's birthday year
1490             * @param  jobTitle the user's job title
1491             * @param  updateUserInformation whether to update the user's information
1492             * @param  sendEmail whether to send the user an email notification about
1493             *         their new account
1494             * @param  serviceContext the service context to be applied (optionally
1495             *         <code>null</code>). Can set the expando bridge attributes for the
1496             *         user.
1497             * @return the user
1498             * @throws PortalException if the user's information was invalid or if the
1499             *         email address was reserved
1500             */
1501            @Override
1502            public User updateIncompleteUser(
1503                            long companyId, boolean autoPassword, String password1,
1504                            String password2, boolean autoScreenName, String screenName,
1505                            String emailAddress, long facebookId, String openId, Locale locale,
1506                            String firstName, String middleName, String lastName, long prefixId,
1507                            long suffixId, boolean male, int birthdayMonth, int birthdayDay,
1508                            int birthdayYear, String jobTitle, boolean updateUserInformation,
1509                            boolean sendEmail, ServiceContext serviceContext)
1510                    throws PortalException {
1511    
1512                    long creatorUserId = 0;
1513    
1514                    try {
1515                            creatorUserId = getGuestOrUserId();
1516                    }
1517                    catch (PrincipalException pe) {
1518                            if (_log.isWarnEnabled()) {
1519                                    _log.warn("Unable to get guest or current user ID", pe);
1520                            }
1521                    }
1522    
1523                    checkAddUserPermission(
1524                            creatorUserId, companyId, emailAddress, null, null, null, null,
1525                            serviceContext);
1526    
1527                    return userLocalService.updateIncompleteUser(
1528                            creatorUserId, companyId, autoPassword, password1, password2,
1529                            autoScreenName, screenName, emailAddress, facebookId, openId,
1530                            locale, firstName, middleName, lastName, prefixId, suffixId, male,
1531                            birthdayMonth, birthdayDay, birthdayYear, jobTitle,
1532                            updateUserInformation, sendEmail, serviceContext);
1533            }
1534    
1535            /**
1536             * Updates whether the user is locked out from logging in.
1537             *
1538             * @param  userId the primary key of the user
1539             * @param  lockout whether the user is locked out
1540             * @return the user
1541             * @throws PortalException if the user did not have permission to lock out
1542             *         the user
1543             */
1544            @Override
1545            public User updateLockoutById(long userId, boolean lockout)
1546                    throws PortalException {
1547    
1548                    UserPermissionUtil.check(
1549                            getPermissionChecker(), userId, ActionKeys.DELETE);
1550    
1551                    return userLocalService.updateLockoutById(userId, lockout);
1552            }
1553    
1554            /**
1555             * Updates the user's OpenID.
1556             *
1557             * @param  userId the primary key of the user
1558             * @param  openId the new OpenID
1559             * @return the user
1560             * @throws PortalException if a user with the primary key could not be found
1561             *         or if the current user did not have permission to update the user
1562             */
1563            @Override
1564            public User updateOpenId(long userId, String openId)
1565                    throws PortalException {
1566    
1567                    UserPermissionUtil.check(
1568                            getPermissionChecker(), userId, ActionKeys.UPDATE);
1569    
1570                    return userLocalService.updateOpenId(userId, openId);
1571            }
1572    
1573            /**
1574             * Sets the organizations that the user is in, removing and adding
1575             * organizations as necessary.
1576             *
1577             * @param  userId the primary key of the user
1578             * @param  organizationIds the primary keys of the organizations
1579             * @param  serviceContext the service context to be applied. Must set
1580             *         whether user indexing is enabled.
1581             * @throws PortalException if a user with the primary key could not be found
1582             *         or if the current user did not have permission to update the user
1583             */
1584            @Override
1585            public void updateOrganizations(
1586                            long userId, long[] organizationIds, ServiceContext serviceContext)
1587                    throws PortalException {
1588    
1589                    UserPermissionUtil.check(
1590                            getPermissionChecker(), userId, ActionKeys.UPDATE);
1591    
1592                    checkOrganizations(userId, organizationIds);
1593    
1594                    userLocalService.updateOrganizations(
1595                            userId, organizationIds, serviceContext);
1596            }
1597    
1598            /**
1599             * Updates the user's password without tracking or validation of the change.
1600             *
1601             * @param  userId the primary key of the user
1602             * @param  password1 the user's new password
1603             * @param  password2 the user's new password confirmation
1604             * @param  passwordReset whether the user should be asked to reset their
1605             *         password the next time they log in
1606             * @return the user
1607             * @throws PortalException if a user with the primary key could not be found
1608             *         or if the current user did not have permission to update the user
1609             */
1610            @Override
1611            public User updatePassword(
1612                            long userId, String password1, String password2,
1613                            boolean passwordReset)
1614                    throws PortalException {
1615    
1616                    UserPermissionUtil.check(
1617                            getPermissionChecker(), userId, ActionKeys.UPDATE);
1618    
1619                    return userLocalService.updatePassword(
1620                            userId, password1, password2, passwordReset);
1621            }
1622    
1623            /**
1624             * Updates the user's portrait image.
1625             *
1626             * @param  userId the primary key of the user
1627             * @param  bytes the new portrait image data
1628             * @return the user
1629             * @throws PortalException if a user with the primary key could not be
1630             *         found, if the new portrait was invalid, or if the current user
1631             *         did not have permission to update the user
1632             */
1633            @Override
1634            public User updatePortrait(long userId, byte[] bytes)
1635                    throws PortalException {
1636    
1637                    UserPermissionUtil.check(
1638                            getPermissionChecker(), userId, ActionKeys.UPDATE);
1639    
1640                    return userLocalService.updatePortrait(userId, bytes);
1641            }
1642    
1643            /**
1644             * Updates the user's password reset question and answer.
1645             *
1646             * @param  userId the primary key of the user
1647             * @param  question the user's new password reset question
1648             * @param  answer the user's new password reset answer
1649             * @return the user
1650             * @throws PortalException if a user with the primary key could not be
1651             *         found, if the new question or answer were invalid, or if the
1652             *         current user did not have permission to update the user
1653             */
1654            @Override
1655            public User updateReminderQuery(long userId, String question, String answer)
1656                    throws PortalException {
1657    
1658                    UserPermissionUtil.check(
1659                            getPermissionChecker(), userId, ActionKeys.UPDATE);
1660    
1661                    return userLocalService.updateReminderQuery(userId, question, answer);
1662            }
1663    
1664            /**
1665             * Updates the user's screen name.
1666             *
1667             * @param  userId the primary key of the user
1668             * @param  screenName the user's new screen name
1669             * @return the user
1670             * @throws PortalException if a user with the primary key could not be
1671             *         found, if the new screen name was invalid, or if the current user
1672             *         did not have permission to update the user
1673             */
1674            @Override
1675            public User updateScreenName(long userId, String screenName)
1676                    throws PortalException {
1677    
1678                    UserPermissionUtil.check(
1679                            getPermissionChecker(), userId, ActionKeys.UPDATE);
1680    
1681                    return userLocalService.updateScreenName(userId, screenName);
1682            }
1683    
1684            /**
1685             * Updates the user's workflow status.
1686             *
1687             * @param      userId the primary key of the user
1688             * @param      status the user's new workflow status
1689             * @return     the user
1690             * @throws     PortalException if a user with the primary key could not be
1691             *             found, if the current user was updating her own status to
1692             *             anything but {@link
1693             *             com.liferay.portal.kernel.workflow.WorkflowConstants#STATUS_APPROVED},
1694             *             or if the current user did not have permission to update the
1695             *             user's workflow status.
1696             * @deprecated As of 7.0.0, replaced by {@link #updateStatus(long, int,
1697             *             ServiceContext)}
1698             */
1699            @Deprecated
1700            @Override
1701            public User updateStatus(long userId, int status) throws PortalException {
1702                    return updateStatus(userId, status, new ServiceContext());
1703            }
1704    
1705            /**
1706             * Updates the user's workflow status.
1707             *
1708             * @param  userId the primary key of the user
1709             * @param  status the user's new workflow status
1710             * @param  serviceContext the service context to be applied. You can specify
1711             *         an unencrypted custom password (used by an LDAP listener) for the
1712             *         user via attribute <code>passwordUnencrypted</code>.
1713             * @return the user
1714             * @throws PortalException if a user with the primary key could not be
1715             *         found, if the current user was updating her own status to
1716             *         anything but {@link
1717             *         com.liferay.portal.kernel.workflow.WorkflowConstants#STATUS_APPROVED},
1718             *         or if the current user did not have permission to update the
1719             *         user's workflow status.
1720             */
1721            @Override
1722            public User updateStatus(
1723                            long userId, int status, ServiceContext serviceContext)
1724                    throws PortalException {
1725    
1726                    if ((getUserId() == userId) &&
1727                            (status != WorkflowConstants.STATUS_APPROVED)) {
1728    
1729                            throw new RequiredUserException();
1730                    }
1731    
1732                    UserPermissionUtil.check(
1733                            getPermissionChecker(), userId, ActionKeys.DELETE);
1734    
1735                    return userLocalService.updateStatus(userId, status, serviceContext);
1736            }
1737    
1738            /**
1739             * Updates the user with additional parameters.
1740             *
1741             * @param  userId the primary key of the user
1742             * @param  oldPassword the user's old password
1743             * @param  newPassword1 the user's new password (optionally
1744             *         <code>null</code>)
1745             * @param  newPassword2 the user's new password confirmation (optionally
1746             *         <code>null</code>)
1747             * @param  passwordReset whether the user should be asked to reset their
1748             *         password the next time they login
1749             * @param  reminderQueryQuestion the user's new password reset question
1750             * @param  reminderQueryAnswer the user's new password reset answer
1751             * @param  screenName the user's new screen name
1752             * @param  emailAddress the user's new email address
1753             * @param  facebookId the user's new Facebook ID
1754             * @param  openId the user's new OpenID
1755             * @param  portrait whether to update the user's portrait image
1756             * @param  portraitBytes the new portrait image data
1757             * @param  languageId the user's new language ID
1758             * @param  timeZoneId the user's new time zone ID
1759             * @param  greeting the user's new greeting
1760             * @param  comments the user's new comments
1761             * @param  firstName the user's new first name
1762             * @param  middleName the user's new middle name
1763             * @param  lastName the user's new last name
1764             * @param  prefixId the user's new name prefix ID
1765             * @param  suffixId the user's new name suffix ID
1766             * @param  male whether user is male
1767             * @param  birthdayMonth the user's new birthday month (0-based, meaning 0
1768             *         for January)
1769             * @param  birthdayDay the user's new birthday day
1770             * @param  birthdayYear the user's birthday year
1771             * @param  smsSn the user's new SMS screen name
1772             * @param  aimSn the user's new AIM screen name
1773             * @param  facebookSn the user's new Facebook screen name
1774             * @param  icqSn the user's new ICQ screen name
1775             * @param  jabberSn the user's new Jabber screen name
1776             * @param  msnSn the user's new MSN screen name
1777             * @param  mySpaceSn the user's new MySpace screen name
1778             * @param  skypeSn the user's new Skype screen name
1779             * @param  twitterSn the user's new Twitter screen name
1780             * @param  ymSn the user's new Yahoo! Messenger screen name
1781             * @param  jobTitle the user's new job title
1782             * @param  groupIds the primary keys of the user's groups
1783             * @param  organizationIds the primary keys of the user's organizations
1784             * @param  roleIds the primary keys of the user's roles
1785             * @param  userGroupRoles the user user's group roles
1786             * @param  userGroupIds the primary keys of the user's user groups
1787             * @param  addresses the user's addresses
1788             * @param  emailAddresses the user's email addresses
1789             * @param  phones the user's phone numbers
1790             * @param  websites the user's websites
1791             * @param  announcementsDelivers the announcements deliveries
1792             * @param  serviceContext the service context to be applied (optionally
1793             *         <code>null</code>). Can set the UUID (with the <code>uuid</code>
1794             *         attribute), asset category IDs, asset tag names, and expando
1795             *         bridge attributes for the user.
1796             * @return the user
1797             * @throws PortalException if a user with the primary key could not be
1798             *         found, if the new information was invalid, if the current user
1799             *         did not have permission to update the user, or if the operation
1800             *         was not allowed by the membership policy
1801             */
1802            @Override
1803            public User updateUser(
1804                            long userId, String oldPassword, String newPassword1,
1805                            String newPassword2, boolean passwordReset,
1806                            String reminderQueryQuestion, String reminderQueryAnswer,
1807                            String screenName, String emailAddress, long facebookId,
1808                            String openId, boolean portrait, byte[] portraitBytes,
1809                            String languageId, String timeZoneId, String greeting,
1810                            String comments, String firstName, String middleName,
1811                            String lastName, long prefixId, long suffixId, boolean male,
1812                            int birthdayMonth, int birthdayDay, int birthdayYear, String smsSn,
1813                            String aimSn, String facebookSn, String icqSn, String jabberSn,
1814                            String msnSn, String mySpaceSn, String skypeSn, String twitterSn,
1815                            String ymSn, String jobTitle, long[] groupIds,
1816                            long[] organizationIds, long[] roleIds,
1817                            List<UserGroupRole> userGroupRoles, long[] userGroupIds,
1818                            List<Address> addresses, List<EmailAddress> emailAddresses,
1819                            List<Phone> phones, List<Website> websites,
1820                            List<AnnouncementsDelivery> announcementsDelivers,
1821                            ServiceContext serviceContext)
1822                    throws PortalException {
1823    
1824                    UserPermissionUtil.check(
1825                            getPermissionChecker(), userId, organizationIds, ActionKeys.UPDATE);
1826    
1827                    User user = userPersistence.findByPrimaryKey(userId);
1828    
1829                    if (addresses != null) {
1830                            UsersAdminUtil.updateAddresses(
1831                                    Contact.class.getName(), user.getContactId(), addresses);
1832                    }
1833    
1834                    if (emailAddresses != null) {
1835                            UsersAdminUtil.updateEmailAddresses(
1836                                    Contact.class.getName(), user.getContactId(), emailAddresses);
1837                    }
1838    
1839                    if (phones != null) {
1840                            UsersAdminUtil.updatePhones(
1841                                    Contact.class.getName(), user.getContactId(), phones);
1842                    }
1843    
1844                    if (websites != null) {
1845                            UsersAdminUtil.updateWebsites(
1846                                    Contact.class.getName(), user.getContactId(), websites);
1847                    }
1848    
1849                    if (announcementsDelivers != null) {
1850                            updateAnnouncementsDeliveries(
1851                                    user.getUserId(), announcementsDelivers);
1852                    }
1853    
1854                    long curUserId = getUserId();
1855    
1856                    if (curUserId == userId) {
1857                            emailAddress = StringUtil.toLowerCase(emailAddress.trim());
1858    
1859                            if (!StringUtil.equalsIgnoreCase(
1860                                            emailAddress, user.getEmailAddress())) {
1861    
1862                                    validateEmailAddress(user, emailAddress);
1863                            }
1864                    }
1865    
1866                    validateUpdatePermission(
1867                            user, screenName, emailAddress, firstName, middleName, lastName,
1868                            prefixId, suffixId, birthdayMonth, birthdayDay, birthdayYear, male,
1869                            jobTitle);
1870    
1871                    // Group membership policy
1872    
1873                    long[] oldGroupIds = user.getGroupIds();
1874    
1875                    List<Long> addGroupIds = new ArrayList<>();
1876                    List<Long> removeGroupIds = ListUtil.toList(oldGroupIds);
1877    
1878                    if (groupIds != null) {
1879                            groupIds = checkGroups(userId, groupIds);
1880    
1881                            for (long groupId : groupIds) {
1882                                    if (ArrayUtil.contains(oldGroupIds, groupId)) {
1883                                            removeGroupIds.remove(groupId);
1884                                    }
1885                                    else {
1886                                            addGroupIds.add(groupId);
1887                                    }
1888                            }
1889    
1890                            if (!addGroupIds.isEmpty() || !removeGroupIds.isEmpty()) {
1891                                    SiteMembershipPolicyUtil.checkMembership(
1892                                            new long[] {userId}, ArrayUtil.toLongArray(addGroupIds),
1893                                            ArrayUtil.toLongArray(removeGroupIds));
1894                            }
1895                    }
1896    
1897                    // Organization membership policy
1898    
1899                    long[] oldOrganizationIds = user.getOrganizationIds();
1900    
1901                    List<Long> addOrganizationIds = new ArrayList<>();
1902                    List<Long> removeOrganizationIds = ListUtil.toList(oldOrganizationIds);
1903    
1904                    if (organizationIds != null) {
1905                            organizationIds = checkOrganizations(userId, organizationIds);
1906    
1907                            for (long organizationId : organizationIds) {
1908                                    if (ArrayUtil.contains(oldOrganizationIds, organizationId)) {
1909                                            removeOrganizationIds.remove(organizationId);
1910                                    }
1911                                    else {
1912                                            addOrganizationIds.add(organizationId);
1913                                    }
1914                            }
1915    
1916                            if (!addOrganizationIds.isEmpty() ||
1917                                    !removeOrganizationIds.isEmpty()) {
1918    
1919                                    OrganizationMembershipPolicyUtil.checkMembership(
1920                                            new long[] {userId},
1921                                            ArrayUtil.toLongArray(addOrganizationIds),
1922                                            ArrayUtil.toLongArray(removeOrganizationIds));
1923                            }
1924                    }
1925    
1926                    // Role membership policy
1927    
1928                    long[] oldRoleIds = user.getRoleIds();
1929    
1930                    List<Long> addRoleIds = new ArrayList<>();
1931                    List<Long> removeRoleIds = ListUtil.toList(oldRoleIds);
1932    
1933                    if (roleIds != null) {
1934                            roleIds = checkRoles(userId, roleIds);
1935    
1936                            for (long roleId : roleIds) {
1937                                    if (ArrayUtil.contains(oldRoleIds, roleId)) {
1938                                            removeRoleIds.remove(roleId);
1939                                    }
1940                                    else {
1941                                            addRoleIds.add(roleId);
1942                                    }
1943                            }
1944    
1945                            if (!addRoleIds.isEmpty() || !removeRoleIds.isEmpty()) {
1946                                    RoleMembershipPolicyUtil.checkRoles(
1947                                            new long[] {userId}, ArrayUtil.toLongArray(addRoleIds),
1948                                            ArrayUtil.toLongArray(removeRoleIds));
1949                            }
1950                    }
1951    
1952                    List<UserGroupRole> oldOrganizationUserGroupRoles = new ArrayList<>();
1953                    List<UserGroupRole> oldSiteUserGroupRoles = new ArrayList<>();
1954    
1955                    List<UserGroupRole> oldUserGroupRoles =
1956                            userGroupRolePersistence.findByUserId(userId);
1957    
1958                    for (UserGroupRole oldUserGroupRole : oldUserGroupRoles) {
1959                            Role role = oldUserGroupRole.getRole();
1960    
1961                            if (role.getType() == RoleConstants.TYPE_ORGANIZATION) {
1962                                    oldOrganizationUserGroupRoles.add(oldUserGroupRole);
1963                            }
1964                            else if (role.getType() == RoleConstants.TYPE_SITE) {
1965                                    oldSiteUserGroupRoles.add(oldUserGroupRole);
1966                            }
1967                    }
1968    
1969                    List<UserGroupRole> addOrganizationUserGroupRoles = new ArrayList<>();
1970                    List<UserGroupRole> removeOrganizationUserGroupRoles = ListUtil.copy(
1971                            oldOrganizationUserGroupRoles);
1972                    List<UserGroupRole> addSiteUserGroupRoles = new ArrayList<>();
1973                    List<UserGroupRole> removeSiteUserGroupRoles = ListUtil.copy(
1974                            oldSiteUserGroupRoles);
1975    
1976                    if (userGroupRoles != null) {
1977                            userGroupRoles = checkUserGroupRoles(userId, userGroupRoles);
1978    
1979                            for (UserGroupRole userGroupRole : userGroupRoles) {
1980                                    Role role = userGroupRole.getRole();
1981    
1982                                    if (role.getType() == RoleConstants.TYPE_ORGANIZATION) {
1983                                            if (oldOrganizationUserGroupRoles.contains(userGroupRole)) {
1984                                                    removeOrganizationUserGroupRoles.remove(userGroupRole);
1985                                            }
1986                                            else {
1987                                                    addOrganizationUserGroupRoles.add(userGroupRole);
1988                                            }
1989                                    }
1990                                    else if (role.getType() == RoleConstants.TYPE_SITE) {
1991                                            if (oldSiteUserGroupRoles.contains(userGroupRole)) {
1992                                                    removeSiteUserGroupRoles.remove(userGroupRole);
1993                                            }
1994                                            else {
1995                                                    addSiteUserGroupRoles.add(userGroupRole);
1996                                            }
1997                                    }
1998                            }
1999    
2000                            if (!addOrganizationUserGroupRoles.isEmpty() ||
2001                                    !removeOrganizationUserGroupRoles.isEmpty()) {
2002    
2003                                    OrganizationMembershipPolicyUtil.checkRoles(
2004                                            addOrganizationUserGroupRoles,
2005                                            removeOrganizationUserGroupRoles);
2006                            }
2007    
2008                            if (!addSiteUserGroupRoles.isEmpty() ||
2009                                    !removeSiteUserGroupRoles.isEmpty()) {
2010    
2011                                    SiteMembershipPolicyUtil.checkRoles(
2012                                            addSiteUserGroupRoles, removeSiteUserGroupRoles);
2013                            }
2014                    }
2015    
2016                    // User group membership policy
2017    
2018                    long[] oldUserGroupIds = user.getUserGroupIds();
2019    
2020                    List<Long> addUserGroupIds = new ArrayList<>();
2021                    List<Long> removeUserGroupIds = ListUtil.toList(oldUserGroupIds);
2022    
2023                    if (userGroupIds != null) {
2024                            userGroupIds = checkUserGroupIds(userId, userGroupIds);
2025    
2026                            for (long userGroupId : userGroupIds) {
2027                                    if (ArrayUtil.contains(oldUserGroupIds, userGroupId)) {
2028                                            removeUserGroupIds.remove(userGroupId);
2029                                    }
2030                                    else {
2031                                            addUserGroupIds.add(userGroupId);
2032                                    }
2033                            }
2034    
2035                            if (!addUserGroupIds.isEmpty() || !removeUserGroupIds.isEmpty()) {
2036                                    UserGroupMembershipPolicyUtil.checkMembership(
2037                                            new long[] {userId}, ArrayUtil.toLongArray(addUserGroupIds),
2038                                            ArrayUtil.toLongArray(removeUserGroupIds));
2039                            }
2040                    }
2041    
2042                    user = userLocalService.updateUser(
2043                            userId, oldPassword, newPassword1, newPassword2, passwordReset,
2044                            reminderQueryQuestion, reminderQueryAnswer, screenName,
2045                            emailAddress, facebookId, openId, portrait, portraitBytes,
2046                            languageId, timeZoneId, greeting, comments, firstName, middleName,
2047                            lastName, prefixId, suffixId, male, birthdayMonth, birthdayDay,
2048                            birthdayYear, smsSn, aimSn, facebookSn, icqSn, jabberSn, msnSn,
2049                            mySpaceSn, skypeSn, twitterSn, ymSn, jobTitle, groupIds,
2050                            organizationIds, roleIds, userGroupRoles, userGroupIds,
2051                            serviceContext);
2052    
2053                    if (!addGroupIds.isEmpty() || !removeGroupIds.isEmpty()) {
2054                            SiteMembershipPolicyUtil.propagateMembership(
2055                                    new long[] {user.getUserId()},
2056                                    ArrayUtil.toLongArray(addGroupIds),
2057                                    ArrayUtil.toLongArray(removeGroupIds));
2058                    }
2059    
2060                    if (!addOrganizationIds.isEmpty() || !removeOrganizationIds.isEmpty()) {
2061                            OrganizationMembershipPolicyUtil.propagateMembership(
2062                                    new long[] {user.getUserId()},
2063                                    ArrayUtil.toLongArray(addOrganizationIds),
2064                                    ArrayUtil.toLongArray(removeOrganizationIds));
2065                    }
2066    
2067                    if (!addRoleIds.isEmpty() || !removeRoleIds.isEmpty()) {
2068                            RoleMembershipPolicyUtil.propagateRoles(
2069                                    new long[] {user.getUserId()},
2070                                    ArrayUtil.toLongArray(addRoleIds),
2071                                    ArrayUtil.toLongArray(removeRoleIds));
2072                    }
2073    
2074                    if (!addSiteUserGroupRoles.isEmpty() ||
2075                            !removeSiteUserGroupRoles.isEmpty()) {
2076    
2077                            SiteMembershipPolicyUtil.propagateRoles(
2078                                    addSiteUserGroupRoles, removeSiteUserGroupRoles);
2079                    }
2080    
2081                    if (!addOrganizationUserGroupRoles.isEmpty() ||
2082                            !removeOrganizationUserGroupRoles.isEmpty()) {
2083    
2084                            OrganizationMembershipPolicyUtil.propagateRoles(
2085                                    addOrganizationUserGroupRoles,
2086                                    removeOrganizationUserGroupRoles);
2087                    }
2088    
2089                    if (!addUserGroupIds.isEmpty() || !removeGroupIds.isEmpty()) {
2090                            UserGroupMembershipPolicyUtil.propagateMembership(
2091                                    new long[] {user.getUserId()},
2092                                    ArrayUtil.toLongArray(addUserGroupIds),
2093                                    ArrayUtil.toLongArray(removeUserGroupIds));
2094                    }
2095    
2096                    return user;
2097            }
2098    
2099            /**
2100             * Updates the user with additional parameters.
2101             *
2102             * @param      userId the primary key of the user
2103             * @param      oldPassword the user's old password
2104             * @param      newPassword1 the user's new password (optionally
2105             *             <code>null</code>)
2106             * @param      newPassword2 the user's new password confirmation (optionally
2107             *             <code>null</code>)
2108             * @param      passwordReset whether the user should be asked to reset their
2109             *             password the next time they login
2110             * @param      reminderQueryQuestion the user's new password reset question
2111             * @param      reminderQueryAnswer the user's new password reset answer
2112             * @param      screenName the user's new screen name
2113             * @param      emailAddress the user's new email address
2114             * @param      facebookId the user's new Facebook ID
2115             * @param      openId the user's new OpenID
2116             * @param      languageId the user's new language ID
2117             * @param      timeZoneId the user's new time zone ID
2118             * @param      greeting the user's new greeting
2119             * @param      comments the user's new comments
2120             * @param      firstName the user's new first name
2121             * @param      middleName the user's new middle name
2122             * @param      lastName the user's new last name
2123             * @param      prefixId the user's new name prefix ID
2124             * @param      suffixId the user's new name suffix ID
2125             * @param      male whether user is male
2126             * @param      birthdayMonth the user's new birthday month (0-based, meaning
2127             *             0 for January)
2128             * @param      birthdayDay the user's new birthday day
2129             * @param      birthdayYear the user's birthday year
2130             * @param      smsSn the user's new SMS screen name
2131             * @param      aimSn the user's new AIM screen name
2132             * @param      facebookSn the user's new Facebook screen name
2133             * @param      icqSn the user's new ICQ screen name
2134             * @param      jabberSn the user's new Jabber screen name
2135             * @param      msnSn the user's new MSN screen name
2136             * @param      mySpaceSn the user's new MySpace screen name
2137             * @param      skypeSn the user's new Skype screen name
2138             * @param      twitterSn the user's new Twitter screen name
2139             * @param      ymSn the user's new Yahoo! Messenger screen name
2140             * @param      jobTitle the user's new job title
2141             * @param      groupIds the primary keys of the user's groups
2142             * @param      organizationIds the primary keys of the user's organizations
2143             * @param      roleIds the primary keys of the user's roles
2144             * @param      userGroupRoles the user user's group roles
2145             * @param      userGroupIds the primary keys of the user's user groups
2146             * @param      addresses the user's addresses
2147             * @param      emailAddresses the user's email addresses
2148             * @param      phones the user's phone numbers
2149             * @param      websites the user's websites
2150             * @param      announcementsDelivers the announcements deliveries
2151             * @param      serviceContext the service context to be applied (optionally
2152             *             <code>null</code>). Can set the UUID (with the
2153             *             <code>uuid</code> attribute), asset category IDs, asset tag
2154             *             names, and expando bridge attributes for the user.
2155             * @return     the user
2156             * @throws     PortalException if a user with the primary key could not be
2157             *             found, if the new information was invalid, if the current
2158             *             user did not have permission to update the user, or if the
2159             *             operation was not allowed by the membership policy
2160             * @deprecated As of 7.0.0, replaced by {@link #updateUser(long, String,
2161             *             String, String, boolean, String, String, String, String,
2162             *             long, String, boolean, byte[], String, String, String,
2163             *             String, String, String, String, int, int, boolean, int, int,
2164             *             int, String, String, String, String, String, String, String,
2165             *             String, String, String, String, long[], long[], long[],
2166             *             java.util.List, long[], java.util.List, java.util.List,
2167             *             java.util.List, java.util.List, java.util.List,
2168             *             com.liferay.portal.service.ServiceContext)}
2169             */
2170            @Deprecated
2171            @Override
2172            public User updateUser(
2173                            long userId, String oldPassword, String newPassword1,
2174                            String newPassword2, boolean passwordReset,
2175                            String reminderQueryQuestion, String reminderQueryAnswer,
2176                            String screenName, String emailAddress, long facebookId,
2177                            String openId, String languageId, String timeZoneId,
2178                            String greeting, String comments, String firstName,
2179                            String middleName, String lastName, long prefixId, long suffixId,
2180                            boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
2181                            String smsSn, String aimSn, String facebookSn, String icqSn,
2182                            String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
2183                            String twitterSn, String ymSn, String jobTitle, long[] groupIds,
2184                            long[] organizationIds, long[] roleIds,
2185                            List<UserGroupRole> userGroupRoles, long[] userGroupIds,
2186                            List<Address> addresses, List<EmailAddress> emailAddresses,
2187                            List<Phone> phones, List<Website> websites,
2188                            List<AnnouncementsDelivery> announcementsDelivers,
2189                            ServiceContext serviceContext)
2190                    throws PortalException {
2191    
2192                    return updateUser(
2193                            userId, oldPassword, newPassword1, newPassword2, passwordReset,
2194                            reminderQueryQuestion, reminderQueryAnswer, screenName,
2195                            emailAddress, facebookId, openId, true, null, languageId,
2196                            timeZoneId, greeting, comments, firstName, middleName, lastName,
2197                            prefixId, suffixId, male, birthdayMonth, birthdayDay, birthdayYear,
2198                            smsSn, aimSn, facebookSn, icqSn, jabberSn, msnSn, mySpaceSn,
2199                            skypeSn, twitterSn, ymSn, jobTitle, groupIds, organizationIds,
2200                            roleIds, userGroupRoles, userGroupIds, addresses, emailAddresses,
2201                            phones, websites, announcementsDelivers, serviceContext);
2202            }
2203    
2204            /**
2205             * Updates the user.
2206             *
2207             * @param  userId the primary key of the user
2208             * @param  oldPassword the user's old password
2209             * @param  newPassword1 the user's new password (optionally
2210             *         <code>null</code>)
2211             * @param  newPassword2 the user's new password confirmation (optionally
2212             *         <code>null</code>)
2213             * @param  passwordReset whether the user should be asked to reset their
2214             *         password the next time they login
2215             * @param  reminderQueryQuestion the user's new password reset question
2216             * @param  reminderQueryAnswer the user's new password reset answer
2217             * @param  screenName the user's new screen name
2218             * @param  emailAddress the user's new email address
2219             * @param  facebookId the user's new Facebook ID
2220             * @param  openId the user's new OpenID
2221             * @param  languageId the user's new language ID
2222             * @param  timeZoneId the user's new time zone ID
2223             * @param  greeting the user's new greeting
2224             * @param  comments the user's new comments
2225             * @param  firstName the user's new first name
2226             * @param  middleName the user's new middle name
2227             * @param  lastName the user's new last name
2228             * @param  prefixId the user's new name prefix ID
2229             * @param  suffixId the user's new name suffix ID
2230             * @param  male whether user is male
2231             * @param  birthdayMonth the user's new birthday month (0-based, meaning 0
2232             *         for January)
2233             * @param  birthdayDay the user's new birthday day
2234             * @param  birthdayYear the user's birthday year
2235             * @param  smsSn the user's new SMS screen name
2236             * @param  aimSn the user's new AIM screen name
2237             * @param  facebookSn the user's new Facebook screen name
2238             * @param  icqSn the user's new ICQ screen name
2239             * @param  jabberSn the user's new Jabber screen name
2240             * @param  msnSn the user's new MSN screen name
2241             * @param  mySpaceSn the user's new MySpace screen name
2242             * @param  skypeSn the user's new Skype screen name
2243             * @param  twitterSn the user's new Twitter screen name
2244             * @param  ymSn the user's new Yahoo! Messenger screen name
2245             * @param  jobTitle the user's new job title
2246             * @param  groupIds the primary keys of the user's groups
2247             * @param  organizationIds the primary keys of the user's organizations
2248             * @param  roleIds the primary keys of the user's roles
2249             * @param  userGroupRoles the user user's group roles
2250             * @param  userGroupIds the primary keys of the user's user groups
2251             * @param  serviceContext the service context to be applied (optionally
2252             *         <code>null</code>). Can set the UUID (with the <code>uuid</code>
2253             *         attribute), asset category IDs, asset tag names, and expando
2254             *         bridge attributes for the user.
2255             * @return the user
2256             * @throws PortalException if a user with the primary key could not be
2257             *         found, if the new information was invalid, if the current user
2258             *         did not have permission to update the user, or if the operation
2259             *         was not allowed by the membership policy
2260             */
2261            @Override
2262            public User updateUser(
2263                            long userId, String oldPassword, String newPassword1,
2264                            String newPassword2, boolean passwordReset,
2265                            String reminderQueryQuestion, String reminderQueryAnswer,
2266                            String screenName, String emailAddress, long facebookId,
2267                            String openId, String languageId, String timeZoneId,
2268                            String greeting, String comments, String firstName,
2269                            String middleName, String lastName, long prefixId, long suffixId,
2270                            boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
2271                            String smsSn, String aimSn, String facebookSn, String icqSn,
2272                            String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
2273                            String twitterSn, String ymSn, String jobTitle, long[] groupIds,
2274                            long[] organizationIds, long[] roleIds,
2275                            List<UserGroupRole> userGroupRoles, long[] userGroupIds,
2276                            ServiceContext serviceContext)
2277                    throws PortalException {
2278    
2279                    return updateUser(
2280                            userId, oldPassword, newPassword1, newPassword2, passwordReset,
2281                            reminderQueryQuestion, reminderQueryAnswer, screenName,
2282                            emailAddress, facebookId, openId, true, null, languageId,
2283                            timeZoneId, greeting, comments, firstName, middleName, lastName,
2284                            prefixId, suffixId, male, birthdayMonth, birthdayDay, birthdayYear,
2285                            smsSn, aimSn, facebookSn, icqSn, jabberSn, msnSn, mySpaceSn,
2286                            skypeSn, twitterSn, ymSn, jobTitle, groupIds, organizationIds,
2287                            roleIds, userGroupRoles, userGroupIds, null, null, null, null, null,
2288                            serviceContext);
2289            }
2290    
2291            protected void checkAddUserPermission(
2292                            long creatorUserId, long companyId, String emailAddress,
2293                            long[] groupIds, long[] organizationIds, long[] roleIds,
2294                            long[] userGroupIds, ServiceContext serviceContext)
2295                    throws PortalException {
2296    
2297                    Company company = companyPersistence.findByPrimaryKey(companyId);
2298    
2299                    if (groupIds != null) {
2300                            checkGroups(0, groupIds);
2301                    }
2302    
2303                    if (organizationIds != null) {
2304                            checkOrganizations(0, organizationIds);
2305                    }
2306    
2307                    if (roleIds != null) {
2308                            checkRoles(0, roleIds);
2309                    }
2310    
2311                    if (userGroupIds != null) {
2312                            checkUserGroupIds(0, userGroupIds);
2313                    }
2314    
2315                    boolean anonymousUser = ParamUtil.getBoolean(
2316                            serviceContext, "anonymousUser");
2317    
2318                    long defaultUserId = userLocalService.getDefaultUserId(companyId);
2319    
2320                    if (((creatorUserId != 0) && (creatorUserId != defaultUserId)) ||
2321                            (!company.isStrangers() && !anonymousUser)) {
2322    
2323                            if (!PortalPermissionUtil.contains(
2324                                            getPermissionChecker(), ActionKeys.ADD_USER) &&
2325                                    !OrganizationPermissionUtil.contains(
2326                                            getPermissionChecker(), organizationIds,
2327                                            ActionKeys.ASSIGN_MEMBERS)) {
2328    
2329                                    throw new PrincipalException();
2330                            }
2331                    }
2332    
2333                    if ((creatorUserId == 0) || (creatorUserId == defaultUserId)) {
2334                            if (!company.isStrangersWithMx() &&
2335                                    company.hasCompanyMx(emailAddress)) {
2336    
2337                                    throw new UserEmailAddressException.MustNotUseCompanyMx(
2338                                            emailAddress);
2339                            }
2340                    }
2341            }
2342    
2343            protected long[] checkGroups(long userId, long[] groupIds)
2344                    throws PortalException {
2345    
2346                    long[] oldGroupIds = null;
2347    
2348                    PermissionChecker permissionChecker = getPermissionChecker();
2349    
2350                    User user = null;
2351    
2352                    if (userId != CompanyConstants.SYSTEM) {
2353    
2354                            // Add back any mandatory groups or groups that the administrator
2355                            // does not have the rights to remove and check that he has the
2356                            // permission to add a new group
2357    
2358                            user = userPersistence.findByPrimaryKey(userId);
2359    
2360                            List<Group> oldGroups = groupLocalService.getUserGroups(userId);
2361    
2362                            oldGroupIds = new long[oldGroups.size()];
2363    
2364                            for (int i = 0; i < oldGroups.size(); i++) {
2365                                    Group group = oldGroups.get(i);
2366    
2367                                    if (!ArrayUtil.contains(groupIds, group.getGroupId()) &&
2368                                            (!GroupPermissionUtil.contains(
2369                                                    permissionChecker, group, ActionKeys.ASSIGN_MEMBERS) ||
2370                                             SiteMembershipPolicyUtil.isMembershipProtected(
2371                                                     permissionChecker, user.getUserId(),
2372                                                     group.getGroupId()) ||
2373                                             SiteMembershipPolicyUtil.isMembershipRequired(
2374                                                     userId, group.getGroupId()))) {
2375    
2376                                            groupIds = ArrayUtil.append(groupIds, group.getGroupId());
2377                                    }
2378    
2379                                    oldGroupIds[i] = group.getGroupId();
2380                            }
2381                    }
2382    
2383                    // Check that the administrator has the permission to add a new group
2384                    // and that the group membership is allowed
2385    
2386                    for (long groupId : groupIds) {
2387                            if ((oldGroupIds != null) &&
2388                                    ArrayUtil.contains(oldGroupIds, groupId)) {
2389    
2390                                    continue;
2391                            }
2392    
2393                            Group group = groupPersistence.findByPrimaryKey(groupId);
2394    
2395                            GroupPermissionUtil.check(
2396                                    permissionChecker, group, ActionKeys.ASSIGN_MEMBERS);
2397                    }
2398    
2399                    return groupIds;
2400            }
2401    
2402            protected void checkMembership(
2403                            long[] userIds, long[] groupIds, long[] organizationIds,
2404                            long[] roleIds, long[] userGroupIds)
2405                    throws PortalException {
2406    
2407                    if (groupIds != null) {
2408                            SiteMembershipPolicyUtil.checkMembership(userIds, groupIds, null);
2409                    }
2410    
2411                    if (organizationIds != null) {
2412                            OrganizationMembershipPolicyUtil.checkMembership(
2413                                    userIds, organizationIds, null);
2414                    }
2415    
2416                    if (roleIds != null) {
2417                            RoleMembershipPolicyUtil.checkRoles(userIds, roleIds, null);
2418                    }
2419    
2420                    if (userGroupIds != null) {
2421                            UserGroupMembershipPolicyUtil.checkMembership(
2422                                    userIds, userGroupIds, null);
2423                    }
2424            }
2425    
2426            protected long[] checkOrganizations(long userId, long[] organizationIds)
2427                    throws PortalException {
2428    
2429                    long[] oldOrganizationIds = null;
2430    
2431                    PermissionChecker permissionChecker = getPermissionChecker();
2432    
2433                    if (userId != CompanyConstants.SYSTEM) {
2434    
2435                            // Add back any mandatory organizations or organizations that the
2436                            // administrator does not have the rights to remove and check that
2437                            // he has the permission to add a new organization
2438    
2439                            List<Organization> oldOrganizations =
2440                                    organizationLocalService.getUserOrganizations(userId);
2441    
2442                            oldOrganizationIds = new long[oldOrganizations.size()];
2443    
2444                            for (int i = 0; i < oldOrganizations.size(); i++) {
2445                                    Organization organization = oldOrganizations.get(i);
2446    
2447                                    if (!ArrayUtil.contains(
2448                                                    organizationIds, organization.getOrganizationId()) &&
2449                                            (!OrganizationPermissionUtil.contains(
2450                                                    permissionChecker, organization,
2451                                                    ActionKeys.ASSIGN_MEMBERS) ||
2452                                             OrganizationMembershipPolicyUtil.isMembershipProtected(
2453                                                     permissionChecker, userId,
2454                                                     organization.getOrganizationId()) ||
2455                                             OrganizationMembershipPolicyUtil.isMembershipRequired(
2456                                                     userId, organization.getOrganizationId()))) {
2457    
2458                                            organizationIds = ArrayUtil.append(
2459                                                    organizationIds, organization.getOrganizationId());
2460                                    }
2461    
2462                                    oldOrganizationIds[i] = organization.getOrganizationId();
2463                            }
2464                    }
2465    
2466                    // Check that the administrator has the permission to add a new
2467                    // organization and that the organization membership is allowed
2468    
2469                    for (long organizationId : organizationIds) {
2470                            if ((oldOrganizationIds != null) &&
2471                                    ArrayUtil.contains(oldOrganizationIds, organizationId)) {
2472    
2473                                    continue;
2474                            }
2475    
2476                            Organization organization =
2477                                    organizationPersistence.findByPrimaryKey(organizationId);
2478    
2479                            OrganizationPermissionUtil.check(
2480                                    permissionChecker, organization, ActionKeys.ASSIGN_MEMBERS);
2481                    }
2482    
2483                    return organizationIds;
2484            }
2485    
2486            protected long[] checkRoles(long userId, long[] roleIds)
2487                    throws PortalException {
2488    
2489                    long[] oldRoleIds = null;
2490    
2491                    PermissionChecker permissionChecker = getPermissionChecker();
2492    
2493                    if (userId != CompanyConstants.SYSTEM) {
2494    
2495                            // Add back any mandatory roles or roles that the administrator does
2496                            // not have the rights to remove and check that he has the
2497                            // permission to add a new role
2498    
2499                            List<Role> oldRoles = roleLocalService.getUserRoles(userId);
2500    
2501                            oldRoleIds = new long[oldRoles.size()];
2502    
2503                            for (int i = 0; i < oldRoles.size(); i++) {
2504                                    Role role = oldRoles.get(i);
2505    
2506                                    if (!ArrayUtil.contains(roleIds, role.getRoleId()) &&
2507                                            (!RolePermissionUtil.contains(
2508                                                    permissionChecker, role.getRoleId(),
2509                                                    ActionKeys.ASSIGN_MEMBERS) ||
2510                                             RoleMembershipPolicyUtil.isRoleRequired(
2511                                                     userId, role.getRoleId()))) {
2512    
2513                                            roleIds = ArrayUtil.append(roleIds, role.getRoleId());
2514                                    }
2515    
2516                                    oldRoleIds[i] = role.getRoleId();
2517                            }
2518                    }
2519    
2520                    // Check that the administrator has the permission to add a new role and
2521                    // that the role membership is allowed
2522    
2523                    for (long roleId : roleIds) {
2524                            if ((oldRoleIds != null) &&
2525                                    ArrayUtil.contains(oldRoleIds, roleId)) {
2526    
2527                                    continue;
2528                            }
2529    
2530                            RolePermissionUtil.check(
2531                                    permissionChecker, roleId, ActionKeys.ASSIGN_MEMBERS);
2532                    }
2533    
2534                    if (userId != CompanyConstants.SYSTEM) {
2535                            return UsersAdminUtil.addRequiredRoles(userId, roleIds);
2536                    }
2537    
2538                    return roleIds;
2539            }
2540    
2541            protected long[] checkUserGroupIds(long userId, long[] userGroupIds)
2542                    throws PortalException {
2543    
2544                    long[] oldUserGroupIds = null;
2545    
2546                    PermissionChecker permissionChecker = getPermissionChecker();
2547    
2548                    if (userId != CompanyConstants.SYSTEM) {
2549    
2550                            // Add back any user groups that the administrator does not have the
2551                            // rights to remove or that have a mandatory membership
2552    
2553                            List<UserGroup> oldUserGroups =
2554                                    userGroupLocalService.getUserUserGroups(userId);
2555    
2556                            oldUserGroupIds = new long[oldUserGroups.size()];
2557    
2558                            for (int i = 0; i < oldUserGroups.size(); i++) {
2559                                    UserGroup userGroup = oldUserGroups.get(i);
2560    
2561                                    if (!ArrayUtil.contains(
2562                                                    userGroupIds, userGroup.getUserGroupId()) &&
2563                                            (!UserGroupPermissionUtil.contains(
2564                                                    permissionChecker, userGroup.getUserGroupId(),
2565                                                    ActionKeys.ASSIGN_MEMBERS) ||
2566                                             UserGroupMembershipPolicyUtil.isMembershipRequired(
2567                                                     userId, userGroup.getUserGroupId()))) {
2568    
2569                                            userGroupIds = ArrayUtil.append(
2570                                                    userGroupIds, userGroup.getUserGroupId());
2571                                    }
2572    
2573                                    oldUserGroupIds[i] = userGroup.getUserGroupId();
2574                            }
2575                    }
2576    
2577                    // Check that the administrator has the permission to add a new user
2578                    // group and that the user group membership is allowed
2579    
2580                    for (long userGroupId : userGroupIds) {
2581                            if ((oldUserGroupIds == null) ||
2582                                    !ArrayUtil.contains(oldUserGroupIds, userGroupId)) {
2583    
2584                                    UserGroupPermissionUtil.check(
2585                                            permissionChecker, userGroupId, ActionKeys.ASSIGN_MEMBERS);
2586                            }
2587                    }
2588    
2589                    return userGroupIds;
2590            }
2591    
2592            protected List<UserGroupRole> checkUserGroupRoles(
2593                            long userId, List<UserGroupRole> userGroupRoles)
2594                    throws PortalException {
2595    
2596                    List<UserGroupRole> oldUserGroupRoles = null;
2597    
2598                    PermissionChecker permissionChecker = getPermissionChecker();
2599    
2600                    if (userId != CompanyConstants.SYSTEM) {
2601    
2602                            // Add back any user group roles that the administrator does not
2603                            // have the rights to remove or that have a mandatory membership
2604    
2605                            oldUserGroupRoles = userGroupRoleLocalService.getUserGroupRoles(
2606                                    userId);
2607    
2608                            for (UserGroupRole oldUserGroupRole : oldUserGroupRoles) {
2609                                    Role role = oldUserGroupRole.getRole();
2610                                    Group group = oldUserGroupRole.getGroup();
2611    
2612                                    if (userGroupRoles.contains(oldUserGroupRole)) {
2613                                            continue;
2614                                    }
2615    
2616                                    if (role.getType() == RoleConstants.TYPE_ORGANIZATION) {
2617                                            Organization organization =
2618                                                    organizationPersistence.findByPrimaryKey(
2619                                                            group.getOrganizationId());
2620    
2621                                            if (!UserGroupRolePermissionUtil.contains(
2622                                                            permissionChecker, group, role) ||
2623                                                    OrganizationMembershipPolicyUtil.isRoleProtected(
2624                                                            getPermissionChecker(), userId,
2625                                                            organization.getOrganizationId(),
2626                                                            role.getRoleId()) ||
2627                                                    OrganizationMembershipPolicyUtil.isRoleRequired(
2628                                                            userId, organization.getOrganizationId(),
2629                                                            role.getRoleId())) {
2630    
2631                                                    userGroupRoles.add(oldUserGroupRole);
2632                                            }
2633                                    }
2634                                    else if (role.getType() == RoleConstants.TYPE_SITE) {
2635                                            if (!userGroupRoles.contains(oldUserGroupRole) &&
2636                                                    (!UserGroupRolePermissionUtil.contains(
2637                                                            permissionChecker, group, role) ||
2638                                                     SiteMembershipPolicyUtil.isRoleProtected(
2639                                                             getPermissionChecker(), userId, group.getGroupId(),
2640                                                             role.getRoleId()) ||
2641                                                     SiteMembershipPolicyUtil.isRoleRequired(
2642                                                             userId, group.getGroupId(), role.getRoleId()))) {
2643    
2644                                                    userGroupRoles.add(oldUserGroupRole);
2645                                            }
2646                                    }
2647                            }
2648                    }
2649    
2650                    // Check that the administrator has the permission to add a new user
2651                    // group role and that the user group role membership is allowed
2652    
2653                    for (UserGroupRole userGroupRole : userGroupRoles) {
2654                            if ((oldUserGroupRoles == null) ||
2655                                    !oldUserGroupRoles.contains(userGroupRole)) {
2656    
2657                                    UserGroupRolePermissionUtil.check(
2658                                            permissionChecker, userGroupRole.getGroupId(),
2659                                            userGroupRole.getRoleId());
2660                            }
2661                    }
2662    
2663                    return userGroupRoles;
2664            }
2665    
2666            protected void propagateMembership(
2667                            long[] userIds, long[] groupIds, long[] organizationIds,
2668                            long[] roleIds, long[] userGroupIds)
2669                    throws PortalException {
2670    
2671                    if (groupIds != null) {
2672                            SiteMembershipPolicyUtil.propagateMembership(
2673                                    userIds, groupIds, null);
2674                    }
2675    
2676                    if (organizationIds != null) {
2677                            OrganizationMembershipPolicyUtil.propagateMembership(
2678                                    userIds, organizationIds, null);
2679                    }
2680    
2681                    if (roleIds != null) {
2682                            RoleMembershipPolicyUtil.propagateRoles(userIds, roleIds, null);
2683                    }
2684    
2685                    if (userGroupIds != null) {
2686                            UserGroupMembershipPolicyUtil.propagateMembership(
2687                                    userIds, userGroupIds, null);
2688                    }
2689            }
2690    
2691            protected void updateAnnouncementsDeliveries(
2692                            long userId, List<AnnouncementsDelivery> announcementsDeliveries)
2693                    throws PortalException {
2694    
2695                    for (AnnouncementsDelivery announcementsDelivery :
2696                                    announcementsDeliveries) {
2697    
2698                            announcementsDeliveryService.updateDelivery(
2699                                    userId, announcementsDelivery.getType(),
2700                                    announcementsDelivery.getEmail(),
2701                                    announcementsDelivery.getSms(),
2702                                    announcementsDelivery.getWebsite());
2703                    }
2704            }
2705    
2706            protected void validateEmailAddress(User user, String emailAddress)
2707                    throws PortalException {
2708    
2709                    if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
2710                            Company company = companyPersistence.findByPrimaryKey(
2711                                    user.getCompanyId());
2712    
2713                            if (!company.isStrangersWithMx()) {
2714                                    throw new UserEmailAddressException.MustNotUseCompanyMx(
2715                                            emailAddress);
2716                            }
2717                    }
2718            }
2719    
2720            protected void validateOrganizationUsers(long[] userIds)
2721                    throws PortalException {
2722    
2723                    PermissionChecker permissionChecker = getPermissionChecker();
2724    
2725                    if (!PropsValues.ORGANIZATIONS_ASSIGNMENT_STRICT ||
2726                            permissionChecker.isCompanyAdmin()) {
2727    
2728                            return;
2729                    }
2730    
2731                    for (long userId : userIds) {
2732                            boolean allowed = false;
2733    
2734                            List<Organization> organizations =
2735                                    organizationLocalService.getUserOrganizations(userId);
2736    
2737                            for (Organization organization : organizations) {
2738                                    if (OrganizationPermissionUtil.contains(
2739                                                    permissionChecker, organization,
2740                                                    ActionKeys.MANAGE_USERS)) {
2741    
2742                                            allowed = true;
2743    
2744                                            break;
2745                                    }
2746                            }
2747    
2748                            if (!allowed) {
2749                                    throw new PrincipalException();
2750                            }
2751                    }
2752            }
2753    
2754            protected void validateUpdatePermission(
2755                            User user, String screenName, String emailAddress, String firstName,
2756                            String middleName, String lastName, long prefixId, long suffixId,
2757                            int birthdayMonth, int birthdayDay, int birthdayYear, boolean male,
2758                            String jobTitle)
2759                    throws PortalException {
2760    
2761                    List<String> fields = new ArrayList<>();
2762    
2763                    Contact contact = user.getContact();
2764    
2765                    Calendar birthday = CalendarFactoryUtil.getCalendar();
2766    
2767                    birthday.setTime(contact.getBirthday());
2768    
2769                    if ((birthdayMonth != birthday.get(Calendar.MONTH)) ||
2770                            (birthdayDay != birthday.get(Calendar.DAY_OF_MONTH)) ||
2771                            (birthdayYear != birthday.get(Calendar.YEAR))) {
2772    
2773                            fields.add("birthday");
2774                    }
2775    
2776                    if (!StringUtil.equalsIgnoreCase(
2777                                    emailAddress, user.getEmailAddress())) {
2778    
2779                            fields.add("emailAddress");
2780                    }
2781    
2782                    if (!StringUtil.equalsIgnoreCase(firstName, user.getFirstName())) {
2783                            fields.add("firstName");
2784                    }
2785    
2786                    if (male != contact.getMale()) {
2787                            fields.add("gender");
2788                    }
2789    
2790                    if (!StringUtil.equalsIgnoreCase(jobTitle, user.getJobTitle())) {
2791                            fields.add("jobTitle");
2792                    }
2793    
2794                    if (!StringUtil.equalsIgnoreCase(lastName, user.getLastName())) {
2795                            fields.add("lastName");
2796                    }
2797    
2798                    if (!StringUtil.equalsIgnoreCase(middleName, user.getMiddleName())) {
2799                            fields.add("middleName");
2800                    }
2801    
2802                    if (prefixId != contact.getPrefixId()) {
2803                            fields.add("prefix");
2804                    }
2805    
2806                    if (!StringUtil.equalsIgnoreCase(screenName, user.getScreenName())) {
2807                            fields.add("screenName");
2808                    }
2809    
2810                    if (suffixId != contact.getSuffixId()) {
2811                            fields.add("suffix");
2812                    }
2813    
2814                    UserFieldException ufe = new UserFieldException();
2815    
2816                    for (String field : fields) {
2817                            if (!UsersAdminUtil.hasUpdateFieldPermission(
2818                                            getPermissionChecker(), getUser(), user, field)) {
2819    
2820                                    ufe.addField(field);
2821                            }
2822                    }
2823    
2824                    if (ufe.hasFields()) {
2825                            throw ufe;
2826                    }
2827            }
2828    
2829            private static final Log _log = LogFactoryUtil.getLog(
2830                    UserServiceImpl.class);
2831    
2832    }