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