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