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