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