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