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