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