001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.service.impl;
016    
017    import com.liferay.portal.RequiredUserException;
018    import com.liferay.portal.ReservedUserEmailAddressException;
019    import com.liferay.portal.UserFieldException;
020    import com.liferay.portal.kernel.exception.PortalException;
021    import com.liferay.portal.kernel.exception.SystemException;
022    import com.liferay.portal.kernel.search.Indexer;
023    import com.liferay.portal.kernel.search.IndexerRegistryUtil;
024    import com.liferay.portal.kernel.util.ArrayUtil;
025    import com.liferay.portal.kernel.util.CalendarFactoryUtil;
026    import com.liferay.portal.kernel.util.ListUtil;
027    import com.liferay.portal.kernel.util.ParamUtil;
028    import com.liferay.portal.kernel.util.StringUtil;
029    import com.liferay.portal.kernel.workflow.WorkflowConstants;
030    import com.liferay.portal.kernel.workflow.WorkflowThreadLocal;
031    import com.liferay.portal.model.Address;
032    import com.liferay.portal.model.Company;
033    import com.liferay.portal.model.CompanyConstants;
034    import com.liferay.portal.model.Contact;
035    import com.liferay.portal.model.EmailAddress;
036    import com.liferay.portal.model.Group;
037    import com.liferay.portal.model.GroupConstants;
038    import com.liferay.portal.model.Organization;
039    import com.liferay.portal.model.Phone;
040    import com.liferay.portal.model.Role;
041    import com.liferay.portal.model.RoleConstants;
042    import com.liferay.portal.model.User;
043    import com.liferay.portal.model.UserGroup;
044    import com.liferay.portal.model.UserGroupRole;
045    import com.liferay.portal.model.Website;
046    import com.liferay.portal.security.auth.PrincipalException;
047    import com.liferay.portal.security.membershippolicy.OrganizationMembershipPolicyUtil;
048    import com.liferay.portal.security.membershippolicy.RoleMembershipPolicyUtil;
049    import com.liferay.portal.security.membershippolicy.SiteMembershipPolicyUtil;
050    import com.liferay.portal.security.membershippolicy.UserGroupMembershipPolicyUtil;
051    import com.liferay.portal.security.permission.ActionKeys;
052    import com.liferay.portal.security.permission.PermissionChecker;
053    import com.liferay.portal.service.ServiceContext;
054    import com.liferay.portal.service.base.UserServiceBaseImpl;
055    import com.liferay.portal.service.permission.GroupPermissionUtil;
056    import com.liferay.portal.service.permission.OrganizationPermissionUtil;
057    import com.liferay.portal.service.permission.PasswordPolicyPermissionUtil;
058    import com.liferay.portal.service.permission.PortalPermissionUtil;
059    import com.liferay.portal.service.permission.RolePermissionUtil;
060    import com.liferay.portal.service.permission.TeamPermissionUtil;
061    import com.liferay.portal.service.permission.UserGroupPermissionUtil;
062    import com.liferay.portal.service.permission.UserGroupRolePermissionUtil;
063    import com.liferay.portal.service.permission.UserPermissionUtil;
064    import com.liferay.portal.util.PropsValues;
065    import com.liferay.portlet.announcements.model.AnnouncementsDelivery;
066    import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
067    
068    import java.util.ArrayList;
069    import java.util.Calendar;
070    import java.util.List;
071    import java.util.Locale;
072    
073    /**
074     * Provides the remote service for accessing, adding, authenticating, deleting,
075     * and updating users. Its methods include permission checks.
076     *
077     * @author Brian Wing Shun Chan
078     * @author Brian Myunghun Kim
079     * @author Scott Lee
080     * @author Jorge Ferrer
081     * @author Julio Camarero
082     */
083    public class UserServiceImpl extends UserServiceBaseImpl {
084    
085            /**
086             * Adds the users to the group.
087             *
088             * @param  groupId the primary key of the group
089             * @param  userIds the primary keys of the users
090             * @param  serviceContext the service context to be applied (optionally
091             *         <code>null</code>)
092             * @throws PortalException if a group or user with the primary key could not
093             *         be found, if the user did not have permission to assign group
094             *         members, or if the operation was not allowed by the membership
095             *         policy
096             * @throws SystemException if a system exception occurred
097             */
098            @Override
099            public void addGroupUsers(
100                            long groupId, long[] userIds, ServiceContext serviceContext)
101                    throws PortalException, SystemException {
102    
103                    if (userIds.length == 0) {
104                            return;
105                    }
106    
107                    try {
108                            GroupPermissionUtil.check(
109                                    getPermissionChecker(), groupId, ActionKeys.ASSIGN_MEMBERS);
110                    }
111                    catch (PrincipalException pe) {
112    
113                            // Allow any user to join open sites
114    
115                            boolean hasPermission = false;
116    
117                            if (userIds.length == 1) {
118                                    User user = getUser();
119    
120                                    if (user.getUserId() == userIds[0]) {
121                                            Group group = groupPersistence.findByPrimaryKey(groupId);
122    
123                                            if (user.getCompanyId() == group.getCompanyId()) {
124                                                    int type = group.getType();
125    
126                                                    if (type == GroupConstants.TYPE_SITE_OPEN) {
127                                                            hasPermission = true;
128                                                    }
129                                            }
130                                    }
131                            }
132    
133                            if (!hasPermission) {
134                                    throw new PrincipalException();
135                            }
136                    }
137    
138                    SiteMembershipPolicyUtil.checkMembership(
139                            userIds, new long[] {groupId}, null);
140    
141                    userLocalService.addGroupUsers(groupId, userIds);
142    
143                    SiteMembershipPolicyUtil.propagateMembership(
144                            userIds, new long[] {groupId}, null);
145            }
146    
147            /**
148             * Adds the users to the organization.
149             *
150             * @param  organizationId the primary key of the organization
151             * @param  userIds the primary keys of the users
152             * @throws PortalException if an organization or user with the primary key
153             *         could not be found, if the user did not have permission to assign
154             *         organization members, if current user did not have an
155             *         organization in common with a given user, or if the operation was
156             *         not allowed by the membership policy
157             * @throws SystemException if a system exception occurred
158             */
159            @Override
160            public void addOrganizationUsers(long organizationId, long[] userIds)
161                    throws PortalException, SystemException {
162    
163                    if (userIds.length == 0) {
164                            return;
165                    }
166    
167                    OrganizationPermissionUtil.check(
168                            getPermissionChecker(), organizationId, ActionKeys.ASSIGN_MEMBERS);
169    
170                    validateOrganizationUsers(userIds);
171    
172                    OrganizationMembershipPolicyUtil.checkMembership(
173                            userIds, new long[] {organizationId}, null);
174    
175                    userLocalService.addOrganizationUsers(organizationId, userIds);
176    
177                    OrganizationMembershipPolicyUtil.propagateMembership(
178                            userIds, new long[] {organizationId}, null);
179            }
180    
181            /**
182             * Assigns the password policy to the users, removing any other currently
183             * assigned password policies.
184             *
185             * @param  passwordPolicyId the primary key of the password policy
186             * @param  userIds the primary keys of the users
187             * @throws PortalException if the user did not have permission to assign
188             *         policy members
189             * @throws SystemException if a system exception occurred
190             */
191            @Override
192            public void addPasswordPolicyUsers(long passwordPolicyId, long[] userIds)
193                    throws PortalException, SystemException {
194    
195                    if (userIds.length == 0) {
196                            return;
197                    }
198    
199                    PasswordPolicyPermissionUtil.check(
200                            getPermissionChecker(), passwordPolicyId,
201                            ActionKeys.ASSIGN_MEMBERS);
202    
203                    userLocalService.addPasswordPolicyUsers(passwordPolicyId, userIds);
204            }
205    
206            /**
207             * Adds the users to the role.
208             *
209             * @param  roleId the primary key of the role
210             * @param  userIds the primary keys of the users
211             * @throws PortalException if a role or user with the primary key could not
212             *         be found, if the user did not have permission to assign role
213             *         members, or if the operation was not allowed by the membership
214             *         policy
215             * @throws SystemException if a system exception occurred
216             */
217            @Override
218            public void addRoleUsers(long roleId, long[] userIds)
219                    throws PortalException, SystemException {
220    
221                    if (userIds.length == 0) {
222                            return;
223                    }
224    
225                    RolePermissionUtil.check(
226                            getPermissionChecker(), roleId, ActionKeys.ASSIGN_MEMBERS);
227    
228                    RoleMembershipPolicyUtil.checkRoles(userIds, new long[] {roleId}, null);
229    
230                    userLocalService.addRoleUsers(roleId, userIds);
231    
232                    RoleMembershipPolicyUtil.propagateRoles(
233                            userIds, new long[] {roleId}, null);
234            }
235    
236            /**
237             * Adds the users to the team.
238             *
239             * @param  teamId the primary key of the team
240             * @param  userIds the primary keys of the users
241             * @throws PortalException if a team or user with the primary key could not
242             *         be found or if the user did not have permission to assign team
243             *         members
244             * @throws SystemException if a system exception occurred
245             */
246            @Override
247            public void addTeamUsers(long teamId, long[] userIds)
248                    throws PortalException, SystemException {
249    
250                    if (userIds.length == 0) {
251                            return;
252                    }
253    
254                    TeamPermissionUtil.check(
255                            getPermissionChecker(), teamId, ActionKeys.ASSIGN_MEMBERS);
256    
257                    userLocalService.addTeamUsers(teamId, userIds);
258            }
259    
260            /**
261             * Adds a user.
262             *
263             * <p>
264             * This method handles the creation and bookkeeping of the user including
265             * its resources, metadata, and internal data structures. It is not
266             * necessary to make subsequent calls to any methods to setup default
267             * groups, resources, etc.
268             * </p>
269             *
270             * @param  companyId the primary key of the user's company
271             * @param  autoPassword whether a password should be automatically generated
272             *         for the user
273             * @param  password1 the user's password
274             * @param  password2 the user's password confirmation
275             * @param  autoScreenName whether a screen name should be automatically
276             *         generated for the user
277             * @param  screenName the user's screen name
278             * @param  emailAddress the user's email address
279             * @param  facebookId the user's facebook ID
280             * @param  openId the user's OpenID
281             * @param  locale the user's locale
282             * @param  firstName the user's first name
283             * @param  middleName the user's middle name
284             * @param  lastName the user's last name
285             * @param  prefixId the user's name prefix ID
286             * @param  suffixId the user's name suffix ID
287             * @param  male whether the user is male
288             * @param  birthdayMonth the user's birthday month (0-based, meaning 0 for
289             *         January)
290             * @param  birthdayDay the user's birthday day
291             * @param  birthdayYear the user's birthday year
292             * @param  jobTitle the user's job title
293             * @param  groupIds the primary keys of the user's groups
294             * @param  organizationIds the primary keys of the user's organizations
295             * @param  roleIds the primary keys of the roles this user possesses
296             * @param  userGroupIds the primary keys of the user's user groups
297             * @param  sendEmail whether to send the user an email notification about
298             *         their new account
299             * @param  serviceContext the service context to be applied (optionally
300             *         <code>null</code>). Can set the UUID (with the <code>uuid</code>
301             *         attribute), asset category IDs, asset tag names, and expando
302             *         bridge attributes for the user.
303             * @return the new user
304             * @throws PortalException if the user's information was invalid, if the
305             *         operation was not allowed by the membership policy, if the
306             *         creator did not have permission to add users, or if the email
307             *         address was reserved
308             * @throws SystemException if a system exception occurred
309             */
310            @Override
311            public User addUser(
312                            long companyId, boolean autoPassword, String password1,
313                            String password2, boolean autoScreenName, String screenName,
314                            String emailAddress, long facebookId, String openId, Locale locale,
315                            String firstName, String middleName, String lastName, int prefixId,
316                            int suffixId, boolean male, int birthdayMonth, int birthdayDay,
317                            int birthdayYear, String jobTitle, long[] groupIds,
318                            long[] organizationIds, long[] roleIds, long[] userGroupIds,
319                            boolean sendEmail, ServiceContext serviceContext)
320                    throws PortalException, SystemException {
321    
322                    boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
323    
324                    try {
325                            WorkflowThreadLocal.setEnabled(false);
326    
327                            return addUserWithWorkflow(
328                                    companyId, autoPassword, password1, password2, autoScreenName,
329                                    screenName, emailAddress, facebookId, openId, locale, firstName,
330                                    middleName, lastName, prefixId, suffixId, male, birthdayMonth,
331                                    birthdayDay, birthdayYear, jobTitle, groupIds, organizationIds,
332                                    roleIds, userGroupIds, sendEmail, serviceContext);
333                    }
334                    finally {
335                            WorkflowThreadLocal.setEnabled(workflowEnabled);
336                    }
337            }
338    
339            /**
340             * Adds a user with additional parameters.
341             *
342             * <p>
343             * This method handles the creation and bookkeeping of the user including
344             * its resources, metadata, and internal data structures. It is not
345             * necessary to make subsequent calls to any methods to setup default
346             * groups, resources, etc.
347             * </p>
348             *
349             * @param  companyId the primary key of the user's company
350             * @param  autoPassword whether a password should be automatically generated
351             *         for the user
352             * @param  password1 the user's password
353             * @param  password2 the user's password confirmation
354             * @param  autoScreenName whether a screen name should be automatically
355             *         generated for the user
356             * @param  screenName the user's screen name
357             * @param  emailAddress the user's email address
358             * @param  facebookId the user's facebook ID
359             * @param  openId the user's OpenID
360             * @param  locale the user's locale
361             * @param  firstName the user's first name
362             * @param  middleName the user's middle name
363             * @param  lastName the user's last name
364             * @param  prefixId the user's name prefix ID
365             * @param  suffixId the user's name suffix ID
366             * @param  male whether the user is male
367             * @param  birthdayMonth the user's birthday month (0-based, meaning 0 for
368             *         January)
369             * @param  birthdayDay the user's birthday day
370             * @param  birthdayYear the user's birthday year
371             * @param  jobTitle the user's job title
372             * @param  groupIds the primary keys of the user's groups
373             * @param  organizationIds the primary keys of the user's organizations
374             * @param  roleIds the primary keys of the roles this user possesses
375             * @param  userGroupIds the primary keys of the user's user groups
376             * @param  addresses the user's addresses
377             * @param  emailAddresses the user's email addresses
378             * @param  phones the user's phone numbers
379             * @param  websites the user's websites
380             * @param  announcementsDelivers the announcements deliveries
381             * @param  sendEmail whether to send the user an email notification about
382             *         their new account
383             * @param  serviceContext the service context to be applied (optionally
384             *         <code>null</code>). Can set the UUID (with the <code>uuid</code>
385             *         attribute), asset category IDs, asset tag names, and expando
386             *         bridge attributes for the user.
387             * @return the new user
388             * @throws PortalException if the user's information was invalid, if the
389             *         creator did not have permission to add users, if the email
390             *         address was reserved, if the operation was not allowed by the
391             *         membership policy, or if some other portal exception occurred
392             * @throws SystemException if a system exception occurred
393             */
394            @Override
395            public User addUser(
396                            long companyId, boolean autoPassword, String password1,
397                            String password2, boolean autoScreenName, String screenName,
398                            String emailAddress, long facebookId, String openId, Locale locale,
399                            String firstName, String middleName, String lastName, int prefixId,
400                            int suffixId, boolean male, int birthdayMonth, int birthdayDay,
401                            int birthdayYear, String jobTitle, long[] groupIds,
402                            long[] organizationIds, long[] roleIds, long[] userGroupIds,
403                            List<Address> addresses, List<EmailAddress> emailAddresses,
404                            List<Phone> phones, List<Website> websites,
405                            List<AnnouncementsDelivery> announcementsDelivers,
406                            boolean sendEmail, ServiceContext serviceContext)
407                    throws PortalException, SystemException {
408    
409                    boolean workflowEnabled = WorkflowThreadLocal.isEnabled();
410    
411                    try {
412                            WorkflowThreadLocal.setEnabled(false);
413    
414                            return addUserWithWorkflow(
415                                    companyId, autoPassword, password1, password2, autoScreenName,
416                                    screenName, emailAddress, facebookId, openId, locale, firstName,
417                                    middleName, lastName, prefixId, suffixId, male, birthdayMonth,
418                                    birthdayDay, birthdayYear, jobTitle, groupIds, organizationIds,
419                                    roleIds, userGroupIds, addresses, emailAddresses, phones,
420                                    websites, announcementsDelivers, sendEmail, serviceContext);
421                    }
422                    finally {
423                            WorkflowThreadLocal.setEnabled(workflowEnabled);
424                    }
425            }
426    
427            /**
428             * Adds the users to the user group.
429             *
430             * @param  userGroupId the primary key of the user group
431             * @param  userIds the primary keys of the users
432             * @throws PortalException if a user group or user with the primary could
433             *         could not be found, if the current user did not have permission
434             *         to assign group members, or if the operation was not allowed by
435             *         the membership policy
436             * @throws SystemException if a system exception occurred
437             */
438            @Override
439            public void addUserGroupUsers(long userGroupId, long[] userIds)
440                    throws PortalException, SystemException {
441    
442                    if (userIds.length == 0) {
443                            return;
444                    }
445    
446                    UserGroupPermissionUtil.check(
447                            getPermissionChecker(), userGroupId, ActionKeys.ASSIGN_MEMBERS);
448    
449                    UserGroupMembershipPolicyUtil.checkMembership(
450                            userIds, new long[] {userGroupId}, null);
451    
452                    userLocalService.addUserGroupUsers(userGroupId, userIds);
453    
454                    UserGroupMembershipPolicyUtil.propagateMembership(
455                            userIds, new long[] {userGroupId}, null);
456            }
457    
458            /**
459             * Adds a user with workflow.
460             *
461             * <p>
462             * This method handles the creation and bookkeeping of the user including
463             * its resources, metadata, and internal data structures. It is not
464             * necessary to make subsequent calls to any methods to setup default
465             * groups, resources, etc.
466             * </p>
467             *
468             * @param  companyId the primary key of the user's company
469             * @param  autoPassword whether a password should be automatically generated
470             *         for the user
471             * @param  password1 the user's password
472             * @param  password2 the user's password confirmation
473             * @param  autoScreenName whether a screen name should be automatically
474             *         generated for the user
475             * @param  screenName the user's screen name
476             * @param  emailAddress the user's email address
477             * @param  facebookId the user's facebook ID
478             * @param  openId the user's OpenID
479             * @param  locale the user's locale
480             * @param  firstName the user's first name
481             * @param  middleName the user's middle name
482             * @param  lastName the user's last name
483             * @param  prefixId the user's name prefix ID
484             * @param  suffixId the user's name suffix ID
485             * @param  male whether the user is male
486             * @param  birthdayMonth the user's birthday month (0-based, meaning 0 for
487             *         January)
488             * @param  birthdayDay the user's birthday day
489             * @param  birthdayYear the user's birthday year
490             * @param  jobTitle the user's job title
491             * @param  groupIds the primary keys of the user's groups
492             * @param  organizationIds the primary keys of the user's organizations
493             * @param  roleIds the primary keys of the roles this user possesses
494             * @param  userGroupIds the primary keys of the user's user groups
495             * @param  sendEmail whether to send the user an email notification about
496             *         their new account
497             * @param  serviceContext the service context to be applied (optionally
498             *         <code>null</code>). Can set the UUID (with the <code>uuid</code>
499             *         attribute), asset category IDs, asset tag names, and expando
500             *         bridge attributes for the user.
501             * @return the new user
502             * @throws PortalException if the user's information was invalid, if the
503             *         operation was not allowed by the membership policy, if the
504             *         creator did not have permission to add users, or if the email
505             *         address was reserved
506             * @throws SystemException if a system exception occurred
507             */
508            @Override
509            public User addUserWithWorkflow(
510                            long companyId, boolean autoPassword, String password1,
511                            String password2, boolean autoScreenName, String screenName,
512                            String emailAddress, long facebookId, String openId, Locale locale,
513                            String firstName, String middleName, String lastName, int prefixId,
514                            int suffixId, boolean male, int birthdayMonth, int birthdayDay,
515                            int birthdayYear, String jobTitle, long[] groupIds,
516                            long[] organizationIds, long[] roleIds, long[] userGroupIds,
517                            boolean sendEmail, ServiceContext serviceContext)
518                    throws PortalException, SystemException {
519    
520                    long creatorUserId = 0;
521    
522                    try {
523                            creatorUserId = getGuestOrUserId();
524                    }
525                    catch (PrincipalException pe) {
526                    }
527    
528                    checkAddUserPermission(
529                            creatorUserId, companyId, emailAddress, groupIds, organizationIds,
530                            roleIds, userGroupIds, serviceContext);
531    
532                    User user = userLocalService.addUserWithWorkflow(
533                            creatorUserId, companyId, autoPassword, password1, password2,
534                            autoScreenName, screenName, emailAddress, facebookId, openId,
535                            locale, firstName, middleName, lastName, prefixId, suffixId, male,
536                            birthdayMonth, birthdayDay, birthdayYear, jobTitle, groupIds,
537                            organizationIds, roleIds, userGroupIds, sendEmail, serviceContext);
538    
539                    checkMembership(
540                            new long[] {user.getUserId()}, groupIds, organizationIds, roleIds,
541                            userGroupIds);
542    
543                    propagateMembership(
544                            new long[]{user.getUserId()}, groupIds, organizationIds, roleIds,
545                            userGroupIds);
546    
547                    return user;
548            }
549    
550            /**
551             * Adds a user with workflow and additional parameters.
552             *
553             * <p>
554             * This method handles the creation and bookkeeping of the user including
555             * its resources, metadata, and internal data structures. It is not
556             * necessary to make subsequent calls to any methods to setup default
557             * groups, resources, etc.
558             * </p>
559             *
560             * @param  companyId the primary key of the user's company
561             * @param  autoPassword whether a password should be automatically generated
562             *         for the user
563             * @param  password1 the user's password
564             * @param  password2 the user's password confirmation
565             * @param  autoScreenName whether a screen name should be automatically
566             *         generated for the user
567             * @param  screenName the user's screen name
568             * @param  emailAddress the user's email address
569             * @param  facebookId the user's facebook ID
570             * @param  openId the user's OpenID
571             * @param  locale the user's locale
572             * @param  firstName the user's first name
573             * @param  middleName the user's middle name
574             * @param  lastName the user's last name
575             * @param  prefixId the user's name prefix ID
576             * @param  suffixId the user's name suffix ID
577             * @param  male whether the user is male
578             * @param  birthdayMonth the user's birthday month (0-based, meaning 0 for
579             *         January)
580             * @param  birthdayDay the user's birthday day
581             * @param  birthdayYear the user's birthday year
582             * @param  jobTitle the user's job title
583             * @param  groupIds the primary keys of the user's groups
584             * @param  organizationIds the primary keys of the user's organizations
585             * @param  roleIds the primary keys of the roles this user possesses
586             * @param  userGroupIds the primary keys of the user's user groups
587             * @param  addresses the user's addresses
588             * @param  emailAddresses the user's email addresses
589             * @param  phones the user's phone numbers
590             * @param  websites the user's websites
591             * @param  announcementsDelivers the announcements deliveries
592             * @param  sendEmail whether to send the user an email notification about
593             *         their new account
594             * @param  serviceContext the service context to be applied (optionally
595             *         <code>null</code>). Can set the UUID (with the <code>uuid</code>
596             *         attribute), asset category IDs, asset tag names, and expando
597             *         bridge attributes for the user.
598             * @return the new user
599             * @throws PortalException if the user's information was invalid, if the
600             *         operation was not allowed by the membership policy, if the
601             *         creator did not have permission to add users, if the email
602             *         address was reserved, or if some other portal exception occurred
603             * @throws SystemException if a system exception occurred
604             */
605            @Override
606            public User addUserWithWorkflow(
607                            long companyId, boolean autoPassword, String password1,
608                            String password2, boolean autoScreenName, String screenName,
609                            String emailAddress, long facebookId, String openId, Locale locale,
610                            String firstName, String middleName, String lastName, int prefixId,
611                            int suffixId, boolean male, int birthdayMonth, int birthdayDay,
612                            int birthdayYear, String jobTitle, long[] groupIds,
613                            long[] organizationIds, long[] roleIds, long[] userGroupIds,
614                            List<Address> addresses, List<EmailAddress> emailAddresses,
615                            List<Phone> phones, List<Website> websites,
616                            List<AnnouncementsDelivery> announcementsDelivers,
617                            boolean sendEmail, ServiceContext serviceContext)
618                    throws PortalException, SystemException {
619    
620                    boolean indexingEnabled = 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 = StringUtil.toLowerCase(emailAddress.trim());
1816    
1817                            if (!StringUtil.equalsIgnoreCase(
1818                                            emailAddress, user.getEmailAddress())) {
1819    
1820                                    validateEmailAddress(user, emailAddress);
1821                            }
1822                    }
1823    
1824                    // Group membership policy
1825    
1826                    long[] oldGroupIds = user.getGroupIds();
1827    
1828                    List<Long> addGroupIds = new ArrayList<Long>();
1829                    List<Long> removeGroupIds = ListUtil.toList(oldGroupIds);
1830    
1831                    if (groupIds != null) {
1832                            groupIds = checkGroups(userId, groupIds);
1833    
1834                            for (long groupId : groupIds) {
1835                                    if (ArrayUtil.contains(oldGroupIds, groupId)) {
1836                                            removeGroupIds.remove(groupId);
1837                                    }
1838                                    else {
1839                                            addGroupIds.add(groupId);
1840                                    }
1841                            }
1842    
1843                            if (!addGroupIds.isEmpty() || !removeGroupIds.isEmpty()) {
1844                                    SiteMembershipPolicyUtil.checkMembership(
1845                                            new long[] {userId}, ArrayUtil.toLongArray(addGroupIds),
1846                                            ArrayUtil.toLongArray(removeGroupIds));
1847                            }
1848                    }
1849    
1850                    // Organization membership policy
1851    
1852                    long[] oldOrganizationIds = user.getOrganizationIds();
1853    
1854                    List<Long> addOrganizationIds = new ArrayList<Long>();
1855                    List<Long> removeOrganizationIds = ListUtil.toList(oldOrganizationIds);
1856    
1857                    if (organizationIds != null) {
1858                            organizationIds = checkOrganizations(userId, organizationIds);
1859    
1860                            for (long organizationId : organizationIds) {
1861                                    if (ArrayUtil.contains(oldOrganizationIds, organizationId)) {
1862                                            removeOrganizationIds.remove(organizationId);
1863                                    }
1864                                    else {
1865                                            addOrganizationIds.add(organizationId);
1866                                    }
1867                            }
1868    
1869                            if (!addOrganizationIds.isEmpty() ||
1870                                    !removeOrganizationIds.isEmpty()) {
1871    
1872                                    OrganizationMembershipPolicyUtil.checkMembership(
1873                                            new long[] {userId},
1874                                            ArrayUtil.toLongArray(addOrganizationIds),
1875                                            ArrayUtil.toLongArray(removeOrganizationIds));
1876                            }
1877                    }
1878    
1879                    // Role membership policy
1880    
1881                    long[] oldRoleIds = user.getRoleIds();
1882    
1883                    List<Long> addRoleIds = new ArrayList<Long>();
1884                    List<Long> removeRoleIds = ListUtil.toList(oldRoleIds);
1885    
1886                    if (roleIds != null) {
1887                            roleIds = checkRoles(userId, roleIds);
1888    
1889                            for (long roleId : roleIds) {
1890                                    if (ArrayUtil.contains(oldRoleIds, roleId)) {
1891                                            removeRoleIds.remove(roleId);
1892                                    }
1893                                    else {
1894                                            addRoleIds.add(roleId);
1895                                    }
1896                            }
1897    
1898                            if (!addRoleIds.isEmpty() || !removeRoleIds.isEmpty()) {
1899                                    RoleMembershipPolicyUtil.checkRoles(
1900                                            new long[] {userId}, ArrayUtil.toLongArray(addRoleIds),
1901                                            ArrayUtil.toLongArray(removeRoleIds));
1902                            }
1903                    }
1904    
1905                    List<UserGroupRole> oldOrganizationUserGroupRoles =
1906                            new ArrayList<UserGroupRole>();
1907                    List<UserGroupRole> oldSiteUserGroupRoles =
1908                            new ArrayList<UserGroupRole>();
1909    
1910                    List<UserGroupRole> oldUserGroupRoles =
1911                            userGroupRolePersistence.findByUserId(userId);
1912    
1913                    for (UserGroupRole oldUserGroupRole : oldUserGroupRoles) {
1914                            Role role = oldUserGroupRole.getRole();
1915    
1916                            if (role.getType() == RoleConstants.TYPE_ORGANIZATION) {
1917                                    oldOrganizationUserGroupRoles.add(oldUserGroupRole);
1918                            }
1919                            else if (role.getType() == RoleConstants.TYPE_SITE) {
1920                                    oldSiteUserGroupRoles.add(oldUserGroupRole);
1921                            }
1922                    }
1923    
1924                    List<UserGroupRole> addOrganizationUserGroupRoles =
1925                            new ArrayList<UserGroupRole>();
1926                    List<UserGroupRole> removeOrganizationUserGroupRoles = ListUtil.copy(
1927                            oldOrganizationUserGroupRoles);
1928                    List<UserGroupRole> addSiteUserGroupRoles =
1929                            new ArrayList<UserGroupRole>();
1930                    List<UserGroupRole> removeSiteUserGroupRoles = ListUtil.copy(
1931                            oldSiteUserGroupRoles);
1932    
1933                    if (userGroupRoles != null) {
1934                            userGroupRoles = checkUserGroupRoles(userId, userGroupRoles);
1935    
1936                            for (UserGroupRole userGroupRole : userGroupRoles) {
1937                                    Role role = userGroupRole.getRole();
1938    
1939                                    if (role.getType() == RoleConstants.TYPE_ORGANIZATION) {
1940                                            if (oldOrganizationUserGroupRoles.contains(userGroupRole)) {
1941                                                    removeOrganizationUserGroupRoles.remove(userGroupRole);
1942                                            }
1943                                            else {
1944                                                    addOrganizationUserGroupRoles.add(userGroupRole);
1945                                            }
1946                                    }
1947                                    else if (role.getType() == RoleConstants.TYPE_SITE) {
1948                                            if (oldSiteUserGroupRoles.contains(userGroupRole)) {
1949                                                    removeSiteUserGroupRoles.remove(userGroupRole);
1950                                            }
1951                                            else {
1952                                                    addSiteUserGroupRoles.add(userGroupRole);
1953                                            }
1954                                    }
1955                            }
1956    
1957                            if (!addOrganizationUserGroupRoles.isEmpty() ||
1958                                    !removeOrganizationUserGroupRoles.isEmpty()) {
1959    
1960                                    OrganizationMembershipPolicyUtil.checkRoles(
1961                                            addOrganizationUserGroupRoles,
1962                                            removeOrganizationUserGroupRoles);
1963                            }
1964    
1965                            if (!addSiteUserGroupRoles.isEmpty() ||
1966                                    !removeSiteUserGroupRoles.isEmpty()) {
1967    
1968                                    SiteMembershipPolicyUtil.checkRoles(
1969                                            addSiteUserGroupRoles, removeSiteUserGroupRoles);
1970                            }
1971                    }
1972    
1973                    // User group membership policy
1974    
1975                    long[] oldUserGroupIds = user.getUserGroupIds();
1976    
1977                    List<Long> addUserGroupIds = new ArrayList<Long>();
1978                    List<Long> removeUserGroupIds = ListUtil.toList(oldUserGroupIds);
1979    
1980                    if (userGroupIds != null) {
1981                            userGroupIds = checkUserGroupIds(userId, userGroupIds);
1982    
1983                            for (long userGroupId : userGroupIds) {
1984                                    if (ArrayUtil.contains(oldUserGroupIds, userGroupId)) {
1985                                            removeUserGroupIds.remove(userGroupId);
1986                                    }
1987                                    else {
1988                                            addUserGroupIds.add(userGroupId);
1989                                    }
1990                            }
1991    
1992                            if (!addUserGroupIds.isEmpty() || !removeUserGroupIds.isEmpty()) {
1993                                    UserGroupMembershipPolicyUtil.checkMembership(
1994                                            new long[] {userId}, ArrayUtil.toLongArray(addUserGroupIds),
1995                                            ArrayUtil.toLongArray(removeUserGroupIds));
1996                            }
1997                    }
1998    
1999                    user = userLocalService.updateUser(
2000                            userId, oldPassword, newPassword1, newPassword2, passwordReset,
2001                            reminderQueryQuestion, reminderQueryAnswer, screenName,
2002                            emailAddress, facebookId, openId, languageId, timeZoneId, greeting,
2003                            comments, firstName, middleName, lastName, prefixId, suffixId, male,
2004                            birthdayMonth, birthdayDay, birthdayYear, smsSn, aimSn, facebookSn,
2005                            icqSn, jabberSn, msnSn, mySpaceSn, skypeSn, twitterSn, ymSn,
2006                            jobTitle, groupIds, organizationIds, roleIds, userGroupRoles,
2007                            userGroupIds, serviceContext);
2008    
2009                    if (!addGroupIds.isEmpty() || !removeGroupIds.isEmpty()) {
2010                            SiteMembershipPolicyUtil.propagateMembership(
2011                                    new long[] {user.getUserId()},
2012                                    ArrayUtil.toLongArray(addGroupIds),
2013                                    ArrayUtil.toLongArray(removeGroupIds));
2014                    }
2015    
2016                    if (!addOrganizationIds.isEmpty() || !removeOrganizationIds.isEmpty()) {
2017                            OrganizationMembershipPolicyUtil.propagateMembership(
2018                                    new long[] {user.getUserId()},
2019                                    ArrayUtil.toLongArray(addOrganizationIds),
2020                                    ArrayUtil.toLongArray(removeOrganizationIds));
2021                    }
2022    
2023                    if (!addRoleIds.isEmpty() || !removeRoleIds.isEmpty()) {
2024                            RoleMembershipPolicyUtil.propagateRoles(
2025                                    new long[] {user.getUserId()},
2026                                    ArrayUtil.toLongArray(addRoleIds),
2027                                    ArrayUtil.toLongArray(removeRoleIds));
2028                    }
2029    
2030                    if (!addSiteUserGroupRoles.isEmpty() ||
2031                            !removeSiteUserGroupRoles.isEmpty()) {
2032    
2033                            SiteMembershipPolicyUtil.propagateRoles(
2034                                    addSiteUserGroupRoles, removeSiteUserGroupRoles);
2035                    }
2036    
2037                    if (!addOrganizationUserGroupRoles.isEmpty() ||
2038                            !removeOrganizationUserGroupRoles.isEmpty()) {
2039    
2040                            OrganizationMembershipPolicyUtil.propagateRoles(
2041                                    addOrganizationUserGroupRoles,
2042                                    removeOrganizationUserGroupRoles);
2043                    }
2044    
2045                    if (!addUserGroupIds.isEmpty() || !removeGroupIds.isEmpty()) {
2046                            UserGroupMembershipPolicyUtil.propagateMembership(
2047                                    new long[] {user.getUserId()},
2048                                    ArrayUtil.toLongArray(addUserGroupIds),
2049                                    ArrayUtil.toLongArray(removeUserGroupIds));
2050                    }
2051    
2052                    return user;
2053            }
2054    
2055            /**
2056             * Updates the user.
2057             *
2058             * @param  userId the primary key of the user
2059             * @param  oldPassword the user's old password
2060             * @param  newPassword1 the user's new password (optionally
2061             *         <code>null</code>)
2062             * @param  newPassword2 the user's new password confirmation (optionally
2063             *         <code>null</code>)
2064             * @param  passwordReset whether the user should be asked to reset their
2065             *         password the next time they login
2066             * @param  reminderQueryQuestion the user's new password reset question
2067             * @param  reminderQueryAnswer the user's new password reset answer
2068             * @param  screenName the user's new screen name
2069             * @param  emailAddress the user's new email address
2070             * @param  facebookId the user's new Facebook ID
2071             * @param  openId the user's new OpenID
2072             * @param  languageId the user's new language ID
2073             * @param  timeZoneId the user's new time zone ID
2074             * @param  greeting the user's new greeting
2075             * @param  comments the user's new comments
2076             * @param  firstName the user's new first name
2077             * @param  middleName the user's new middle name
2078             * @param  lastName the user's new last name
2079             * @param  prefixId the user's new name prefix ID
2080             * @param  suffixId the user's new name suffix ID
2081             * @param  male whether user is male
2082             * @param  birthdayMonth the user's new birthday month (0-based, meaning 0
2083             *         for January)
2084             * @param  birthdayDay the user's new birthday day
2085             * @param  birthdayYear the user's birthday year
2086             * @param  smsSn the user's new SMS screen name
2087             * @param  aimSn the user's new AIM screen name
2088             * @param  facebookSn the user's new Facebook screen name
2089             * @param  icqSn the user's new ICQ screen name
2090             * @param  jabberSn the user's new Jabber screen name
2091             * @param  msnSn the user's new MSN screen name
2092             * @param  mySpaceSn the user's new MySpace screen name
2093             * @param  skypeSn the user's new Skype screen name
2094             * @param  twitterSn the user's new Twitter screen name
2095             * @param  ymSn the user's new Yahoo! Messenger screen name
2096             * @param  jobTitle the user's new job title
2097             * @param  groupIds the primary keys of the user's groups
2098             * @param  organizationIds the primary keys of the user's organizations
2099             * @param  roleIds the primary keys of the user's roles
2100             * @param  userGroupRoles the user user's group roles
2101             * @param  userGroupIds the primary keys of the user's user groups
2102             * @param  serviceContext the service context to be applied (optionally
2103             *         <code>null</code>). Can set the UUID (with the <code>uuid</code>
2104             *         attribute), asset category IDs, asset tag names, and expando
2105             *         bridge attributes for the user.
2106             * @return the user
2107             * @throws PortalException if a user with the primary key could not be
2108             *         found, if the new information was invalid, if the current user
2109             *         did not have permission to update the user, or if the operation
2110             *         was not allowed by the membership policy
2111             * @throws SystemException if a system exception occurred
2112             */
2113            @Override
2114            public User updateUser(
2115                            long userId, String oldPassword, String newPassword1,
2116                            String newPassword2, boolean passwordReset,
2117                            String reminderQueryQuestion, String reminderQueryAnswer,
2118                            String screenName, String emailAddress, long facebookId,
2119                            String openId, String languageId, String timeZoneId,
2120                            String greeting, String comments, String firstName,
2121                            String middleName, String lastName, int prefixId, int suffixId,
2122                            boolean male, int birthdayMonth, int birthdayDay, int birthdayYear,
2123                            String smsSn, String aimSn, String facebookSn, String icqSn,
2124                            String jabberSn, String msnSn, String mySpaceSn, String skypeSn,
2125                            String twitterSn, String ymSn, String jobTitle, long[] groupIds,
2126                            long[] organizationIds, long[] roleIds,
2127                            List<UserGroupRole> userGroupRoles, long[] userGroupIds,
2128                            ServiceContext serviceContext)
2129                    throws PortalException, SystemException {
2130    
2131                    return updateUser(
2132                            userId, oldPassword, newPassword1, newPassword2, passwordReset,
2133                            reminderQueryQuestion, reminderQueryAnswer, screenName,
2134                            emailAddress, facebookId, openId, languageId, timeZoneId, greeting,
2135                            comments, firstName, middleName, lastName, prefixId, suffixId, male,
2136                            birthdayMonth, birthdayDay, birthdayYear, smsSn, aimSn, facebookSn,
2137                            icqSn, jabberSn, msnSn, mySpaceSn, skypeSn, twitterSn, ymSn,
2138                            jobTitle, groupIds, organizationIds, roleIds, userGroupRoles,
2139                            userGroupIds, null, null, null, null, null, serviceContext);
2140            }
2141    
2142            protected void checkAddUserPermission(
2143                            long creatorUserId, long companyId, String emailAddress,
2144                            long[] groupIds, long[] organizationIds, long[] roleIds,
2145                            long[] userGroupIds, ServiceContext serviceContext)
2146                    throws PortalException, SystemException {
2147    
2148                    Company company = companyPersistence.findByPrimaryKey(companyId);
2149    
2150                    if (groupIds != null) {
2151                            checkGroups(0, groupIds);
2152                    }
2153    
2154                    if (organizationIds != null) {
2155                            checkOrganizations(0, organizationIds);
2156                    }
2157    
2158                    if (roleIds != null) {
2159                            checkRoles(0, roleIds);
2160                    }
2161    
2162                    if (userGroupIds != null) {
2163                            checkUserGroupIds(0, userGroupIds);
2164                    }
2165    
2166                    boolean anonymousUser = ParamUtil.getBoolean(
2167                            serviceContext, "anonymousUser");
2168    
2169                    long defaultUserId = userLocalService.getDefaultUserId(companyId);
2170    
2171                    if (((creatorUserId != 0) && (creatorUserId != defaultUserId)) ||
2172                            (!company.isStrangers() && !anonymousUser)) {
2173    
2174                            if (!PortalPermissionUtil.contains(
2175                                            getPermissionChecker(), ActionKeys.ADD_USER) &&
2176                                    !OrganizationPermissionUtil.contains(
2177                                            getPermissionChecker(), organizationIds,
2178                                            ActionKeys.ASSIGN_MEMBERS)) {
2179    
2180                                    throw new PrincipalException();
2181                            }
2182                    }
2183    
2184                    if ((creatorUserId == 0) || (creatorUserId == defaultUserId)) {
2185                            if (!company.isStrangersWithMx() &&
2186                                    company.hasCompanyMx(emailAddress)) {
2187    
2188                                    throw new ReservedUserEmailAddressException();
2189                            }
2190                    }
2191            }
2192    
2193            protected long[] checkGroups(long userId, long[] groupIds)
2194                    throws PortalException, SystemException {
2195    
2196                    long[] oldGroupIds = null;
2197    
2198                    PermissionChecker permissionChecker = getPermissionChecker();
2199    
2200                    User user = null;
2201    
2202                    if (userId != CompanyConstants.SYSTEM) {
2203    
2204                            // Add back any mandatory groups or groups that the administrator
2205                            // does not have the rights to remove and check that he has the
2206                            // permission to add a new group
2207    
2208                            user = userPersistence.findByPrimaryKey(userId);
2209    
2210                            List<Group> oldGroups = groupLocalService.getUserGroups(userId);
2211    
2212                            oldGroupIds = new long[oldGroups.size()];
2213    
2214                            for (int i = 0; i < oldGroups.size(); i++) {
2215                                    Group group = oldGroups.get(i);
2216    
2217                                    if (!ArrayUtil.contains(groupIds, group.getGroupId()) &&
2218                                            (!GroupPermissionUtil.contains(
2219                                                    permissionChecker, group.getGroupId(),
2220                                                    ActionKeys.ASSIGN_MEMBERS) ||
2221                                             SiteMembershipPolicyUtil.isMembershipProtected(
2222                                                     permissionChecker, user.getUserId(),
2223                                                     group.getGroupId()) ||
2224                                             SiteMembershipPolicyUtil.isMembershipRequired(
2225                                                     userId, group.getGroupId()))) {
2226    
2227                                            groupIds = ArrayUtil.append(groupIds, group.getGroupId());
2228                                    }
2229    
2230                                    oldGroupIds[i] = group.getGroupId();
2231                            }
2232                    }
2233    
2234                    // Check that the administrator has the permission to add a new group
2235                    // and that the group membership is allowed
2236    
2237                    for (long groupId : groupIds) {
2238                            if ((oldGroupIds != null) &&
2239                                    ArrayUtil.contains(oldGroupIds, groupId)) {
2240    
2241                                    continue;
2242                            }
2243    
2244                            Group group = groupPersistence.findByPrimaryKey(groupId);
2245    
2246                            GroupPermissionUtil.check(
2247                                    permissionChecker, group, ActionKeys.ASSIGN_MEMBERS);
2248                    }
2249    
2250                    return groupIds;
2251            }
2252    
2253            protected void checkMembership(
2254                            long[] userIds, long[] groupIds, long[] organizationIds,
2255                            long[] roleIds, long[] userGroupIds)
2256                    throws PortalException, SystemException {
2257    
2258                    if (groupIds != null) {
2259                            SiteMembershipPolicyUtil.checkMembership(userIds, groupIds, null);
2260                    }
2261    
2262                    if (organizationIds != null) {
2263                            OrganizationMembershipPolicyUtil.checkMembership(
2264                                    userIds, organizationIds, null);
2265                    }
2266    
2267                    if (roleIds != null) {
2268                            RoleMembershipPolicyUtil.checkRoles(userIds, roleIds, null);
2269                    }
2270    
2271                    if (userGroupIds != null) {
2272                            UserGroupMembershipPolicyUtil.checkMembership(
2273                                    userIds, userGroupIds, null);
2274                    }
2275            }
2276    
2277            protected long[] checkOrganizations(long userId, long[] organizationIds)
2278                    throws PortalException, SystemException {
2279    
2280                    long[] oldOrganizationIds = null;
2281    
2282                    PermissionChecker permissionChecker = getPermissionChecker();
2283    
2284                    if (userId != CompanyConstants.SYSTEM) {
2285    
2286                            // Add back any mandatory organizations or organizations that the
2287                            // administrator does not have the rights to remove and check that
2288                            // he has the permission to add a new organization
2289    
2290                            List<Organization> oldOrganizations =
2291                                    organizationLocalService.getUserOrganizations(userId);
2292    
2293                            oldOrganizationIds = new long[oldOrganizations.size()];
2294    
2295                            for (int i = 0; i < oldOrganizations.size(); i++) {
2296                                    Organization organization = oldOrganizations.get(i);
2297    
2298                                    if (!ArrayUtil.contains(
2299                                                    organizationIds, organization.getOrganizationId()) &&
2300                                            (!OrganizationPermissionUtil.contains(
2301                                                    permissionChecker, organization.getOrganizationId(),
2302                                                    ActionKeys.ASSIGN_MEMBERS) ||
2303                                             OrganizationMembershipPolicyUtil.isMembershipProtected(
2304                                                    permissionChecker, userId,
2305                                                    organization.getOrganizationId()) ||
2306                                             OrganizationMembershipPolicyUtil.isMembershipRequired(
2307                                                    userId, organization.getOrganizationId()))) {
2308    
2309                                            organizationIds = ArrayUtil.append(
2310                                                    organizationIds, organization.getOrganizationId());
2311                                    }
2312    
2313                                    oldOrganizationIds[i] = organization.getOrganizationId();
2314                            }
2315                    }
2316    
2317                    // Check that the administrator has the permission to add a new
2318                    // organization and that the organization membership is allowed
2319    
2320                    for (long organizationId : organizationIds) {
2321                            if ((oldOrganizationIds != null) &&
2322                                    ArrayUtil.contains(oldOrganizationIds, organizationId)) {
2323    
2324                                    continue;
2325                            }
2326    
2327                            Organization organization =
2328                                    organizationPersistence.findByPrimaryKey(organizationId);
2329    
2330                            OrganizationPermissionUtil.check(
2331                                    permissionChecker, organization, ActionKeys.ASSIGN_MEMBERS);
2332                    }
2333    
2334                    return organizationIds;
2335            }
2336    
2337            protected long[] checkRoles(long userId, long[] roleIds)
2338                    throws PortalException, SystemException {
2339    
2340                    long[] oldRoleIds = null;
2341    
2342                    PermissionChecker permissionChecker = getPermissionChecker();
2343    
2344                    if (userId != CompanyConstants.SYSTEM) {
2345    
2346                            // Add back any mandatory roles or roles that the administrator does
2347                            // not have the rights to remove and check that he has the
2348                            // permission to add a new role
2349    
2350                            List<Role> oldRoles = roleLocalService.getUserRoles(userId);
2351    
2352                            oldRoleIds = new long[oldRoles.size()];
2353    
2354                            for (int i = 0; i < oldRoles.size(); i++) {
2355                                    Role role = oldRoles.get(i);
2356    
2357                                    if (!ArrayUtil.contains(roleIds, role.getRoleId()) &&
2358                                            (!RolePermissionUtil.contains(
2359                                                    permissionChecker, role.getRoleId(),
2360                                                    ActionKeys.ASSIGN_MEMBERS) ||
2361                                             RoleMembershipPolicyUtil.isRoleRequired(
2362                                                    userId, role.getRoleId()))) {
2363    
2364                                            roleIds = ArrayUtil.append(roleIds, role.getRoleId());
2365                                    }
2366    
2367                                    oldRoleIds[i] = role.getRoleId();
2368                            }
2369                    }
2370    
2371                    // Check that the administrator has the permission to add a new role and
2372                    // that the role membership is allowed
2373    
2374                    for (long roleId : roleIds) {
2375                            if ((oldRoleIds != null) &&
2376                                    ArrayUtil.contains(oldRoleIds, roleId)) {
2377    
2378                                    continue;
2379                            }
2380    
2381                            RolePermissionUtil.check(
2382                                    permissionChecker, roleId, ActionKeys.ASSIGN_MEMBERS);
2383                    }
2384    
2385                    if (userId != CompanyConstants.SYSTEM) {
2386                            return UsersAdminUtil.addRequiredRoles(userId, roleIds);
2387                    }
2388    
2389                    return roleIds;
2390            }
2391    
2392            protected long[] checkUserGroupIds(long userId, long[] userGroupIds)
2393                    throws PortalException, SystemException {
2394    
2395                    long[] oldUserGroupIds = null;
2396    
2397                    PermissionChecker permissionChecker = getPermissionChecker();
2398    
2399                    if (userId != CompanyConstants.SYSTEM) {
2400    
2401                            // Add back any user groups that the administrator does not have the
2402                            // rights to remove or that have a mandatory membership
2403    
2404                            List<UserGroup> oldUserGroups =
2405                                    userGroupLocalService.getUserUserGroups(userId);
2406    
2407                            oldUserGroupIds = new long[oldUserGroups.size()];
2408    
2409                            for (int i = 0; i < oldUserGroups.size(); i++) {
2410                                    UserGroup userGroup = oldUserGroups.get(i);
2411    
2412                                    if (!ArrayUtil.contains(
2413                                                    userGroupIds, userGroup.getUserGroupId()) &&
2414                                            (!UserGroupPermissionUtil.contains(
2415                                                    permissionChecker, userGroup.getUserGroupId(),
2416                                                    ActionKeys.ASSIGN_MEMBERS) ||
2417                                             UserGroupMembershipPolicyUtil.isMembershipRequired(
2418                                                    userId, userGroup.getUserGroupId()))) {
2419    
2420                                            userGroupIds = ArrayUtil.append(
2421                                                    userGroupIds, userGroup.getUserGroupId());
2422                                    }
2423    
2424                                    oldUserGroupIds[i] = userGroup.getUserGroupId();
2425                            }
2426                    }
2427    
2428                    // Check that the administrator has the permission to add a new user
2429                    // group and that the user group membership is allowed
2430    
2431                    for (long userGroupId : userGroupIds) {
2432                            if ((oldUserGroupIds == null) ||
2433                                    !ArrayUtil.contains(oldUserGroupIds, userGroupId)) {
2434    
2435                                    UserGroupPermissionUtil.check(
2436                                            permissionChecker, userGroupId, ActionKeys.ASSIGN_MEMBERS);
2437                            }
2438                    }
2439    
2440                    return userGroupIds;
2441            }
2442    
2443            protected List<UserGroupRole> checkUserGroupRoles(
2444                            long userId, List<UserGroupRole> userGroupRoles)
2445                    throws PortalException, SystemException {
2446    
2447                    List<UserGroupRole> oldUserGroupRoles = null;
2448    
2449                    PermissionChecker permissionChecker = getPermissionChecker();
2450    
2451                    if (userId != CompanyConstants.SYSTEM) {
2452    
2453                            // Add back any user group roles that the administrator does not
2454                            // have the rights to remove or that have a mandatory membership
2455    
2456                            oldUserGroupRoles = userGroupRoleLocalService.getUserGroupRoles(
2457                                    userId);
2458    
2459                            for (UserGroupRole oldUserGroupRole : oldUserGroupRoles) {
2460                                    Role role = oldUserGroupRole.getRole();
2461                                    Group group = oldUserGroupRole.getGroup();
2462    
2463                                    if (userGroupRoles.contains(oldUserGroupRole)) {
2464                                            continue;
2465                                    }
2466    
2467                                    if (role.getType() == RoleConstants.TYPE_ORGANIZATION) {
2468                                            Organization organization =
2469                                                    organizationPersistence.findByPrimaryKey(
2470                                                            group.getOrganizationId());
2471    
2472                                            if (!UserGroupRolePermissionUtil.contains(
2473                                                            permissionChecker, oldUserGroupRole.getGroupId(),
2474                                                            oldUserGroupRole.getRoleId()) ||
2475                                                    OrganizationMembershipPolicyUtil.isRoleProtected(
2476                                                            getPermissionChecker(), userId,
2477                                                            organization.getOrganizationId(),
2478                                                            role.getRoleId()) ||
2479                                                    OrganizationMembershipPolicyUtil.isRoleRequired(
2480                                                            userId, organization.getOrganizationId(),
2481                                                            role.getRoleId())) {
2482    
2483                                                    userGroupRoles.add(oldUserGroupRole);
2484                                            }
2485                                    }
2486                                    else if (role.getType() == RoleConstants.TYPE_SITE) {
2487                                            if (!userGroupRoles.contains(oldUserGroupRole) &&
2488                                                    (!UserGroupRolePermissionUtil.contains(
2489                                                            permissionChecker, oldUserGroupRole.getGroupId(),
2490                                                            oldUserGroupRole.getRoleId()) ||
2491                                                     SiteMembershipPolicyUtil.isRoleProtected(
2492                                                             getPermissionChecker(), userId, group.getGroupId(),
2493                                                             role.getRoleId()) ||
2494                                                     SiteMembershipPolicyUtil.isRoleRequired(
2495                                                             userId, group.getGroupId(), role.getRoleId()))) {
2496    
2497                                                    userGroupRoles.add(oldUserGroupRole);
2498                                            }
2499                                    }
2500                            }
2501                    }
2502    
2503                    // Check that the administrator has the permission to add a new user
2504                    // group role and that the user group role membership is allowed
2505    
2506                    for (UserGroupRole userGroupRole : userGroupRoles) {
2507                            if ((oldUserGroupRoles == null) ||
2508                                    !oldUserGroupRoles.contains(userGroupRole)) {
2509    
2510                                    UserGroupRolePermissionUtil.check(
2511                                            permissionChecker, userGroupRole.getGroupId(),
2512                                            userGroupRole.getRoleId());
2513                            }
2514                    }
2515    
2516                    return userGroupRoles;
2517            }
2518    
2519            protected void propagateMembership(
2520                            long[] userIds, long[] groupIds, long[] organizationIds,
2521                            long[] roleIds, long[] userGroupIds)
2522                    throws PortalException, SystemException {
2523    
2524                    if (groupIds != null) {
2525                            SiteMembershipPolicyUtil.propagateMembership(
2526                                    userIds, groupIds, null);
2527                    }
2528    
2529                    if (organizationIds != null) {
2530                            OrganizationMembershipPolicyUtil.propagateMembership(
2531                                    userIds, organizationIds, null);
2532                    }
2533    
2534                    if (roleIds != null) {
2535                            RoleMembershipPolicyUtil.propagateRoles(userIds, roleIds, null);
2536                    }
2537    
2538                    if (userGroupIds != null) {
2539                            UserGroupMembershipPolicyUtil.propagateMembership(
2540                                    userIds, userGroupIds, null);
2541                    }
2542            }
2543    
2544            protected void updateAnnouncementsDeliveries(
2545                            long userId, List<AnnouncementsDelivery> announcementsDeliveries)
2546                    throws PortalException, SystemException {
2547    
2548                    for (AnnouncementsDelivery announcementsDelivery :
2549                                    announcementsDeliveries) {
2550    
2551                            announcementsDeliveryService.updateDelivery(
2552                                    userId, announcementsDelivery.getType(),
2553                                    announcementsDelivery.getEmail(),
2554                                    announcementsDelivery.getSms(),
2555                                    announcementsDelivery.getWebsite());
2556                    }
2557            }
2558    
2559            protected void validateEmailAddress(User user, String emailAddress)
2560                    throws PortalException, SystemException {
2561    
2562                    if (!user.hasCompanyMx() && user.hasCompanyMx(emailAddress)) {
2563                            Company company = companyPersistence.findByPrimaryKey(
2564                                    user.getCompanyId());
2565    
2566                            if (!company.isStrangersWithMx()) {
2567                                    throw new ReservedUserEmailAddressException();
2568                            }
2569                    }
2570            }
2571    
2572            protected void validateOrganizationUsers(long[] userIds)
2573                    throws PortalException, SystemException {
2574    
2575                    PermissionChecker permissionChecker = getPermissionChecker();
2576    
2577                    if (!PropsValues.ORGANIZATIONS_ASSIGNMENT_STRICT ||
2578                            permissionChecker.isCompanyAdmin()) {
2579    
2580                            return;
2581                    }
2582    
2583                    for (long userId : userIds) {
2584                            boolean allowed = false;
2585    
2586                            List<Organization> organizations =
2587                                    organizationLocalService.getUserOrganizations(userId);
2588    
2589                            for (Organization organization : organizations) {
2590                                    if (OrganizationPermissionUtil.contains(
2591                                                    permissionChecker, organization,
2592                                                    ActionKeys.MANAGE_USERS)) {
2593    
2594                                            allowed = true;
2595    
2596                                            break;
2597                                    }
2598                            }
2599    
2600                            if (!allowed) {
2601                                    throw new PrincipalException();
2602                            }
2603                    }
2604            }
2605    
2606            protected void validateUpdatePermission(
2607                            User user, String screenName, String emailAddress, String firstName,
2608                            String middleName, String lastName, int prefixId, int suffixId,
2609                            int birthdayMonth, int birthdayDay, int birthdayYear, boolean male,
2610                            String jobTitle)
2611                    throws PortalException, SystemException {
2612    
2613                    List<String> fields = new ArrayList<String>();
2614    
2615                    Contact contact = user.getContact();
2616    
2617                    Calendar birthday = CalendarFactoryUtil.getCalendar();
2618    
2619                    birthday.setTime(contact.getBirthday());
2620    
2621                    if ((birthdayMonth != birthday.get(Calendar.MONTH)) ||
2622                            (birthdayDay != birthday.get(Calendar.DAY_OF_MONTH)) ||
2623                            (birthdayYear != birthday.get(Calendar.YEAR))) {
2624    
2625                            fields.add("birthday");
2626                    }
2627    
2628                    if (!StringUtil.equalsIgnoreCase(
2629                                    emailAddress, user.getEmailAddress())) {
2630    
2631                            fields.add("emailAddress");
2632                    }
2633    
2634                    if (!StringUtil.equalsIgnoreCase(firstName, user.getFirstName())) {
2635                            fields.add("firstName");
2636                    }
2637    
2638                    if (male != contact.getMale()) {
2639                            fields.add("gender");
2640                    }
2641    
2642                    if (!StringUtil.equalsIgnoreCase(jobTitle, user.getJobTitle())) {
2643                            fields.add("jobTitle");
2644                    }
2645    
2646                    if (!StringUtil.equalsIgnoreCase(lastName, user.getLastName())) {
2647                            fields.add("lastName");
2648                    }
2649    
2650                    if (!StringUtil.equalsIgnoreCase(middleName, user.getMiddleName())) {
2651                            fields.add("middleName");
2652                    }
2653    
2654                    if (prefixId != contact.getPrefixId()) {
2655                            fields.add("prefix");
2656                    }
2657    
2658                    if (!StringUtil.equalsIgnoreCase(screenName, user.getScreenName())) {
2659                            fields.add("screenName");
2660                    }
2661    
2662                    if (suffixId != contact.getSuffixId()) {
2663                            fields.add("suffix");
2664                    }
2665    
2666                    UserFieldException ufe = new UserFieldException();
2667    
2668                    for (String field : fields) {
2669                            if (!UsersAdminUtil.hasUpdateFieldPermission(user, field)) {
2670                                    ufe.addField(field);
2671                            }
2672                    }
2673    
2674                    if (ufe.hasFields()) {
2675                            throw ufe;
2676                    }
2677            }
2678    
2679    }