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.admin.kernel.util.PortalMyAccountApplicationType;
018    import com.liferay.exportimport.kernel.lar.ExportImportThreadLocal;
019    import com.liferay.portal.kernel.cache.thread.local.Lifecycle;
020    import com.liferay.portal.kernel.cache.thread.local.ThreadLocalCachable;
021    import com.liferay.portal.kernel.cache.thread.local.ThreadLocalCache;
022    import com.liferay.portal.kernel.cache.thread.local.ThreadLocalCacheManager;
023    import com.liferay.portal.kernel.exception.DuplicateRoleException;
024    import com.liferay.portal.kernel.exception.NoSuchRoleException;
025    import com.liferay.portal.kernel.exception.PortalException;
026    import com.liferay.portal.kernel.exception.RequiredRoleException;
027    import com.liferay.portal.kernel.exception.RoleNameException;
028    import com.liferay.portal.kernel.model.Company;
029    import com.liferay.portal.kernel.model.Group;
030    import com.liferay.portal.kernel.model.Layout;
031    import com.liferay.portal.kernel.model.ResourceAction;
032    import com.liferay.portal.kernel.model.ResourceBlockPermission;
033    import com.liferay.portal.kernel.model.ResourceConstants;
034    import com.liferay.portal.kernel.model.ResourcePermission;
035    import com.liferay.portal.kernel.model.ResourceTypePermission;
036    import com.liferay.portal.kernel.model.Role;
037    import com.liferay.portal.kernel.model.RoleConstants;
038    import com.liferay.portal.kernel.model.SystemEventConstants;
039    import com.liferay.portal.kernel.model.Team;
040    import com.liferay.portal.kernel.model.User;
041    import com.liferay.portal.kernel.portlet.PortletProvider;
042    import com.liferay.portal.kernel.portlet.PortletProviderUtil;
043    import com.liferay.portal.kernel.search.Indexer;
044    import com.liferay.portal.kernel.search.IndexerRegistryUtil;
045    import com.liferay.portal.kernel.search.SearchException;
046    import com.liferay.portal.kernel.security.auth.CompanyThreadLocal;
047    import com.liferay.portal.kernel.security.permission.ActionKeys;
048    import com.liferay.portal.kernel.security.permission.PermissionThreadLocal;
049    import com.liferay.portal.kernel.service.ServiceContext;
050    import com.liferay.portal.kernel.spring.aop.Skip;
051    import com.liferay.portal.kernel.systemevent.SystemEvent;
052    import com.liferay.portal.kernel.transaction.Propagation;
053    import com.liferay.portal.kernel.transaction.Transactional;
054    import com.liferay.portal.kernel.util.ArrayUtil;
055    import com.liferay.portal.kernel.util.CharPool;
056    import com.liferay.portal.kernel.util.GetterUtil;
057    import com.liferay.portal.kernel.util.ListUtil;
058    import com.liferay.portal.kernel.util.LocaleUtil;
059    import com.liferay.portal.kernel.util.OrderByComparator;
060    import com.liferay.portal.kernel.util.PortalUtil;
061    import com.liferay.portal.kernel.util.PortletKeys;
062    import com.liferay.portal.kernel.util.SetUtil;
063    import com.liferay.portal.kernel.util.StringUtil;
064    import com.liferay.portal.kernel.util.Validator;
065    import com.liferay.portal.security.permission.PermissionCacheUtil;
066    import com.liferay.portal.service.base.RoleLocalServiceBaseImpl;
067    import com.liferay.portal.util.PropsUtil;
068    import com.liferay.portal.util.PropsValues;
069    import com.liferay.users.admin.kernel.util.UsersAdminUtil;
070    
071    import java.util.ArrayList;
072    import java.util.Arrays;
073    import java.util.Collection;
074    import java.util.Collections;
075    import java.util.HashMap;
076    import java.util.LinkedHashMap;
077    import java.util.List;
078    import java.util.Locale;
079    import java.util.Map;
080    import java.util.Set;
081    
082    /**
083     * Provides the local service for accessing, adding, checking, deleting, and
084     * updating roles.
085     *
086     * @author Brian Wing Shun Chan
087     * @author Marcellus Tavares
088     */
089    public class RoleLocalServiceImpl extends RoleLocalServiceBaseImpl {
090    
091            /**
092             * Adds a role with additional parameters. The user is reindexed after role
093             * is added.
094             *
095             * @param  userId the primary key of the user
096             * @param  className the name of the class for which the role is created
097             *         (optionally <code>null</code>)
098             * @param  classPK the primary key of the class for which the role is
099             *         created (optionally <code>0</code>)
100             * @param  name the role's name
101             * @param  titleMap the role's localized titles (optionally
102             *         <code>null</code>)
103             * @param  descriptionMap the role's localized descriptions (optionally
104             *         <code>null</code>)
105             * @param  type the role's type (optionally <code>0</code>)
106             * @param  subtype the role's subtype (optionally <code>null</code>)
107             * @param  serviceContext the service context to be applied (optionally
108             *         <code>null</code>). Can set expando bridge attributes for the
109             *         role.
110             * @return the role
111             */
112            @Override
113            public Role addRole(
114                            long userId, String className, long classPK, String name,
115                            Map<Locale, String> titleMap, Map<Locale, String> descriptionMap,
116                            int type, String subtype, ServiceContext serviceContext)
117                    throws PortalException {
118    
119                    // Role
120    
121                    User user = userPersistence.findByPrimaryKey(userId);
122                    className = GetterUtil.getString(className);
123                    long classNameId = classNameLocalService.getClassNameId(className);
124    
125                    long roleId = counterLocalService.increment();
126    
127                    if ((classNameId <= 0) || className.equals(Role.class.getName())) {
128                            classNameId = classNameLocalService.getClassNameId(Role.class);
129                            classPK = roleId;
130                    }
131    
132                    validate(0, user.getCompanyId(), classNameId, name);
133    
134                    Role role = rolePersistence.create(roleId);
135    
136                    if (serviceContext != null) {
137                            role.setUuid(serviceContext.getUuid());
138                    }
139    
140                    role.setCompanyId(user.getCompanyId());
141                    role.setUserId(user.getUserId());
142                    role.setUserName(user.getFullName());
143                    role.setClassNameId(classNameId);
144                    role.setClassPK(classPK);
145                    role.setName(name);
146                    role.setTitleMap(titleMap);
147                    role.setDescriptionMap(descriptionMap);
148                    role.setType(type);
149                    role.setSubtype(subtype);
150                    role.setExpandoBridgeAttributes(serviceContext);
151    
152                    rolePersistence.update(role);
153    
154                    // Resources
155    
156                    long ownerId = userId;
157    
158                    if (user.isDefaultUser()) {
159                            ownerId = 0;
160                    }
161    
162                    resourceLocalService.addResources(
163                            user.getCompanyId(), 0, ownerId, Role.class.getName(),
164                            role.getRoleId(), false, false, false);
165    
166                    if (!user.isDefaultUser()) {
167                            resourceLocalService.addResources(
168                                    user.getCompanyId(), 0, userId, Role.class.getName(),
169                                    role.getRoleId(), false, false, false);
170    
171                            if (!ExportImportThreadLocal.isImportInProcess()) {
172                                    reindex(userId);
173                            }
174                    }
175    
176                    return role;
177            }
178    
179            /**
180             * Adds the role to the user. The user is reindexed after the role is added.
181             *
182             * @param userId the primary key of the user
183             * @param roleId the primary key of the role
184             * @see   com.liferay.portal.kernel.service.persistence.UserPersistence#addRole(
185             *        long, long)
186             */
187            @Override
188            public void addUserRole(long userId, long roleId) throws PortalException {
189                    userPersistence.addRole(userId, roleId);
190    
191                    reindex(userId);
192    
193                    PermissionCacheUtil.clearCache(userId);
194            }
195    
196            /**
197             * Adds the role to the user. The user is reindexed after the role is added.
198             *
199             * @param userId the primary key of the user
200             * @param role the role
201             * @see   com.liferay.portal.kernel.service.persistence.UserPersistence#addRole(
202             *        long, Role)
203             */
204            @Override
205            public void addUserRole(long userId, Role role) throws PortalException {
206                    userPersistence.addRole(userId, role);
207    
208                    reindex(userId);
209    
210                    PermissionCacheUtil.clearCache(userId);
211            }
212    
213            /**
214             * Adds the roles to the user. The user is reindexed after the roles are
215             * added.
216             *
217             * @param userId the primary key of the user
218             * @param roles the roles
219             * @see   com.liferay.portal.kernel.service.persistence.UserPersistence#addRoles(
220             *        long, List)
221             */
222            @Override
223            public void addUserRoles(long userId, List<Role> roles)
224                    throws PortalException {
225    
226                    userPersistence.addRoles(userId, roles);
227    
228                    reindex(userId);
229    
230                    PermissionCacheUtil.clearCache(userId);
231            }
232    
233            /**
234             * Adds the roles to the user. The user is reindexed after the roles are
235             * added.
236             *
237             * @param userId the primary key of the user
238             * @param roleIds the primary keys of the roles
239             * @see   com.liferay.portal.kernel.service.persistence.UserPersistence#addRoles(
240             *        long, long[])
241             */
242            @Override
243            public void addUserRoles(long userId, long[] roleIds)
244                    throws PortalException {
245    
246                    userPersistence.addRoles(userId, roleIds);
247    
248                    reindex(userId);
249    
250                    PermissionCacheUtil.clearCache(userId);
251            }
252    
253            /**
254             * Checks to ensure that the system roles map has appropriate default roles
255             * in each company.
256             */
257            @Override
258            public void checkSystemRoles() throws PortalException {
259                    List<Company> companies = companyLocalService.getCompanies();
260    
261                    for (Company company : companies) {
262                            checkSystemRoles(company.getCompanyId());
263                    }
264            }
265    
266            /**
267             * Checks to ensure that the system roles map has appropriate default roles
268             * in the company.
269             *
270             * @param companyId the primary key of the company
271             */
272            @Override
273            @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
274            public void checkSystemRoles(long companyId) throws PortalException {
275                    String companyIdHexString = StringUtil.toHexString(companyId);
276    
277                    List<Role> roles = null;
278    
279                    try {
280                            roles = roleFinder.findBySystem(companyId);
281                    }
282                    catch (Exception e) {
283    
284                            // LPS-34324
285    
286                            runSQL("alter table Role_ add uuid_ VARCHAR(75) null");
287                            runSQL("alter table Role_ add userId LONG");
288                            runSQL("alter table Role_ add userName VARCHAR(75) null");
289                            runSQL("alter table Role_ add createDate DATE null");
290                            runSQL("alter table Role_ add modifiedDate DATE null");
291    
292                            roles = roleFinder.findBySystem(companyId);
293                    }
294    
295                    for (Role role : roles) {
296                            _systemRolesMap.put(
297                                    companyIdHexString.concat(role.getName()), role);
298                    }
299    
300                    // Regular roles
301    
302                    String[] systemRoles = PortalUtil.getSystemRoles();
303    
304                    for (String name : systemRoles) {
305                            String key =
306                                    "system.role." +
307                                            StringUtil.replace(name, CharPool.SPACE, CharPool.PERIOD) +
308                                                    ".description";
309    
310                            Map<Locale, String> descriptionMap = new HashMap<>();
311    
312                            descriptionMap.put(LocaleUtil.getDefault(), PropsUtil.get(key));
313    
314                            int type = RoleConstants.TYPE_REGULAR;
315    
316                            checkSystemRole(companyId, name, descriptionMap, type);
317                    }
318    
319                    // Organization roles
320    
321                    String[] systemOrganizationRoles =
322                            PortalUtil.getSystemOrganizationRoles();
323    
324                    for (String name : systemOrganizationRoles) {
325                            String key =
326                                    "system.organization.role." +
327                                            StringUtil.replace(name, CharPool.SPACE, CharPool.PERIOD) +
328                                                    ".description";
329    
330                            Map<Locale, String> descriptionMap = new HashMap<>();
331    
332                            descriptionMap.put(LocaleUtil.getDefault(), PropsUtil.get(key));
333    
334                            int type = RoleConstants.TYPE_ORGANIZATION;
335    
336                            checkSystemRole(companyId, name, descriptionMap, type);
337                    }
338    
339                    // Site roles
340    
341                    String[] systemSiteRoles = PortalUtil.getSystemSiteRoles();
342    
343                    for (String name : systemSiteRoles) {
344                            String key =
345                                    "system.site.role." +
346                                            StringUtil.replace(name, CharPool.SPACE, CharPool.PERIOD) +
347                                                    ".description";
348    
349                            Map<Locale, String> descriptionMap = new HashMap<>();
350    
351                            descriptionMap.put(LocaleUtil.getDefault(), PropsUtil.get(key));
352    
353                            int type = RoleConstants.TYPE_SITE;
354    
355                            checkSystemRole(companyId, name, descriptionMap, type);
356                    }
357    
358                    String[] allSystemRoles = ArrayUtil.append(
359                            systemRoles, systemOrganizationRoles, systemSiteRoles);
360    
361                    for (String roleName : allSystemRoles) {
362                            Role role = getRole(companyId, roleName);
363    
364                            resourceLocalService.addResources(
365                                    companyId, 0, 0, Role.class.getName(), role.getRoleId(), false,
366                                    false, false);
367                    }
368    
369                    // All users should be able to view all system roles
370    
371                    Role userRole = getRole(companyId, RoleConstants.USER);
372    
373                    for (String roleName : allSystemRoles) {
374                            Role role = getRole(companyId, roleName);
375    
376                            resourcePermissionLocalService.setResourcePermissions(
377                                    companyId, Role.class.getName(),
378                                    ResourceConstants.SCOPE_INDIVIDUAL,
379                                    String.valueOf(role.getRoleId()), userRole.getRoleId(),
380                                    new String[] {ActionKeys.VIEW});
381                    }
382            }
383    
384            /**
385             * Removes every role from the user. The user is reindexed after the roles
386             * are removed.
387             *
388             * @param userId the primary key of the user
389             * @see   com.liferay.portal.kernel.service.persistence.UserPersistence#clearRoles(
390             *        long)
391             */
392            @Override
393            public void clearUserRoles(long userId) throws PortalException {
394                    userPersistence.clearRoles(userId);
395    
396                    reindex(userId);
397    
398                    PermissionCacheUtil.clearCache(userId);
399            }
400    
401            /**
402             * Deletes the role with the primary key and its associated permissions.
403             *
404             * @param  roleId the primary key of the role
405             * @return the deleted role
406             */
407            @Override
408            public Role deleteRole(long roleId) throws PortalException {
409                    Role role = rolePersistence.findByPrimaryKey(roleId);
410    
411                    return roleLocalService.deleteRole(role);
412            }
413    
414            /**
415             * Deletes the role and its associated permissions.
416             *
417             * @param  role the role
418             * @return the deleted role
419             */
420            @Override
421            @SystemEvent(
422                    action = SystemEventConstants.ACTION_SKIP,
423                    type = SystemEventConstants.TYPE_DELETE
424            )
425            public Role deleteRole(Role role) throws PortalException {
426                    if (role.isSystem() && !CompanyThreadLocal.isDeleteInProcess()) {
427                            throw new RequiredRoleException();
428                    }
429    
430                    // Resources
431    
432                    List<ResourceBlockPermission> resourceBlockPermissions =
433                            resourceBlockPermissionPersistence.findByRoleId(role.getRoleId());
434    
435                    for (ResourceBlockPermission resourceBlockPermission :
436                                    resourceBlockPermissions) {
437    
438                            resourceBlockPermissionLocalService.deleteResourceBlockPermission(
439                                    resourceBlockPermission);
440                    }
441    
442                    List<ResourcePermission> resourcePermissions =
443                            resourcePermissionPersistence.findByRoleId(role.getRoleId());
444    
445                    for (ResourcePermission resourcePermission : resourcePermissions) {
446                            resourcePermissionLocalService.deleteResourcePermission(
447                                    resourcePermission);
448                    }
449    
450                    List<ResourceTypePermission> resourceTypePermissions =
451                            resourceTypePermissionPersistence.findByRoleId(role.getRoleId());
452    
453                    for (ResourceTypePermission resourceTypePermission :
454                                    resourceTypePermissions) {
455    
456                            resourceTypePermissionLocalService.deleteResourceTypePermission(
457                                    resourceTypePermission);
458                    }
459    
460                    String className = role.getClassName();
461                    long classNameId = role.getClassNameId();
462    
463                    if ((classNameId <= 0) || className.equals(Role.class.getName())) {
464                            resourceLocalService.deleteResource(
465                                    role.getCompanyId(), Role.class.getName(),
466                                    ResourceConstants.SCOPE_INDIVIDUAL, role.getRoleId());
467                    }
468    
469                    if ((role.getType() == RoleConstants.TYPE_ORGANIZATION) ||
470                            (role.getType() == RoleConstants.TYPE_SITE)) {
471    
472                            userGroupRoleLocalService.deleteUserGroupRolesByRoleId(
473                                    role.getRoleId());
474    
475                            userGroupGroupRoleLocalService.deleteUserGroupGroupRolesByRoleId(
476                                    role.getRoleId());
477                    }
478    
479                    // Role
480    
481                    rolePersistence.remove(role);
482    
483                    // Expando
484    
485                    expandoRowLocalService.deleteRows(role.getRoleId());
486    
487                    // Permission cache
488    
489                    PermissionCacheUtil.clearCache();
490    
491                    return role;
492            }
493    
494            /**
495             * Removes the role from the user. The user is reindexed after the role is
496             * removed.
497             *
498             * @param userId the primary key of the user
499             * @param roleId the primary key of the role
500             * @see   com.liferay.portal.kernel.service.persistence.UserPersistence#removeRole(
501             *        long, long)
502             */
503            @Override
504            public void deleteUserRole(long userId, long roleId)
505                    throws PortalException {
506    
507                    userPersistence.removeRole(userId, roleId);
508    
509                    reindex(userId);
510    
511                    PermissionCacheUtil.clearCache(userId);
512            }
513    
514            /**
515             * Removes the role from the user. The user is reindexed after the role is
516             * removed.
517             *
518             * @param userId the primary key of the user
519             * @param role the role
520             * @see   com.liferay.portal.kernel.service.persistence.UserPersistence#removeRole(
521             *        long, Role)
522             */
523            @Override
524            public void deleteUserRole(long userId, Role role) throws PortalException {
525                    userPersistence.removeRole(userId, role);
526    
527                    reindex(userId);
528    
529                    PermissionCacheUtil.clearCache(userId);
530            }
531    
532            /**
533             * Removes the roles from the user. The user is reindexed after the roles
534             * are removed.
535             *
536             * @param userId the primary key of the user
537             * @param roles the roles
538             * @see   com.liferay.portal.kernel.service.persistence.UserPersistence#removeRoles(
539             *        long, List)
540             */
541            @Override
542            public void deleteUserRoles(long userId, List<Role> roles)
543                    throws PortalException {
544    
545                    userPersistence.removeRoles(userId, roles);
546    
547                    reindex(userId);
548    
549                    PermissionCacheUtil.clearCache(userId);
550            }
551    
552            /**
553             * Removes the roles from the user. The user is reindexed after the roles
554             * are removed.
555             *
556             * @param userId the primary key of the user
557             * @param roleIds the primary keys of the roles
558             * @see   com.liferay.portal.kernel.service.persistence.UserPersistence#removeRoles(
559             *        long, long[])
560             */
561            @Override
562            public void deleteUserRoles(long userId, long[] roleIds)
563                    throws PortalException {
564    
565                    userPersistence.removeRoles(userId, roleIds);
566    
567                    reindex(userId);
568    
569                    PermissionCacheUtil.clearCache(userId);
570            }
571    
572            /**
573             * Returns the role with the name in the company.
574             *
575             * <p>
576             * The method searches the system roles map first for default roles. If a
577             * role with the name is not found, then the method will query the database.
578             * </p>
579             *
580             * @param  companyId the primary key of the company
581             * @param  name the role's name
582             * @return Returns the role with the name or <code>null</code> if a role
583             *         with the name could not be found in the company
584             */
585            @Override
586            @Skip
587            public Role fetchRole(long companyId, String name) {
588                    String companyIdHexString = StringUtil.toHexString(companyId);
589    
590                    Role role = _systemRolesMap.get(companyIdHexString.concat(name));
591    
592                    if (role != null) {
593                            return role;
594                    }
595    
596                    return roleLocalService.loadFetchRole(companyId, name);
597            }
598    
599            /**
600             * Returns the default role for the group with the primary key.
601             *
602             * <p>
603             * If the group is a site, then the default role is {@link
604             * RoleConstants#SITE_MEMBER}. If the group is an organization, then the
605             * default role is {@link RoleConstants#ORGANIZATION_USER}. If the group is
606             * a user or user group, then the default role is {@link
607             * RoleConstants#POWER_USER}. For all other group types, the default role is
608             * {@link RoleConstants#USER}.
609             * </p>
610             *
611             * @param  groupId the primary key of the group
612             * @return the default role for the group with the primary key
613             */
614            @Override
615            public Role getDefaultGroupRole(long groupId) throws PortalException {
616                    Group group = groupPersistence.findByPrimaryKey(groupId);
617    
618                    if (group.isLayout()) {
619                            Layout layout = layoutLocalService.getLayout(group.getClassPK());
620    
621                            group = layout.getGroup();
622                    }
623    
624                    if (group.isStagingGroup()) {
625                            group = group.getLiveGroup();
626                    }
627    
628                    Role role = null;
629    
630                    if (group.isCompany()) {
631                            role = getRole(group.getCompanyId(), RoleConstants.USER);
632                    }
633                    else if (group.isLayoutPrototype() || group.isLayoutSetPrototype() ||
634                                     group.isRegularSite() || group.isSite()) {
635    
636                            role = getRole(group.getCompanyId(), RoleConstants.SITE_MEMBER);
637                    }
638                    else if (group.isOrganization()) {
639                            role = getRole(
640                                    group.getCompanyId(), RoleConstants.ORGANIZATION_USER);
641                    }
642                    else {
643                            role = getRole(group.getCompanyId(), RoleConstants.USER);
644                    }
645    
646                    return role;
647            }
648    
649            @Override
650            public List<Role> getGroupRelatedRoles(long groupId)
651                    throws PortalException {
652    
653                    List<Role> roles = new ArrayList<>();
654    
655                    Group group = groupLocalService.getGroup(groupId);
656    
657                    if (group.isStagingGroup()) {
658                            group = group.getLiveGroup();
659                    }
660    
661                    int[] types = RoleConstants.TYPES_REGULAR;
662    
663                    if (group.isOrganization()) {
664                            if (group.isSite()) {
665                                    types = RoleConstants.TYPES_ORGANIZATION_AND_REGULAR_AND_SITE;
666                            }
667                            else {
668                                    types = RoleConstants.TYPES_ORGANIZATION_AND_REGULAR;
669                            }
670                    }
671                    else if (group.isLayout() || group.isLayoutSetPrototype() ||
672                                     group.isSite() || group.isUser()) {
673    
674                            types = RoleConstants.TYPES_REGULAR_AND_SITE;
675                    }
676    
677                    roles.addAll(getRoles(group.getCompanyId(), types));
678    
679                    roles.addAll(getTeamRoles(groupId));
680    
681                    return roles;
682            }
683    
684            @Override
685            public List<Role> getResourceBlockRoles(
686                    long resourceBlockId, String className, String actionId) {
687    
688                    return roleFinder.findByR_N_A(resourceBlockId, className, actionId);
689            }
690    
691            /**
692             * Returns a map of role names to associated action IDs for the named
693             * resource in the company within the permission scope.
694             *
695             * @param  companyId the primary key of the company
696             * @param  name the resource name
697             * @param  scope the permission scope
698             * @param  primKey the primary key of the resource's class
699             * @return the role names and action IDs
700             * @see    com.liferay.portal.kernel.service.persistence.RoleFinder#findByC_N_S_P(
701             *         long, String, int, String)
702             */
703            @Override
704            public Map<String, List<String>> getResourceRoles(
705                    long companyId, String name, int scope, String primKey) {
706    
707                    return roleFinder.findByC_N_S_P(companyId, name, scope, primKey);
708            }
709    
710            /**
711             * Returns all the roles associated with the action ID in the company within
712             * the permission scope.
713             *
714             * @param  companyId the primary key of the company
715             * @param  name the resource name
716             * @param  scope the permission scope
717             * @param  primKey the primary key of the resource's class
718             * @param  actionId the name of the resource action
719             * @return the roles
720             * @see    com.liferay.portal.kernel.service.persistence.RoleFinder#findByC_N_S_P_A(
721             *         long, String, int, String, String)
722             */
723            @Override
724            public List<Role> getResourceRoles(
725                    long companyId, String name, int scope, String primKey,
726                    String actionId) {
727    
728                    return roleFinder.findByC_N_S_P_A(
729                            companyId, name, scope, primKey, actionId);
730            }
731    
732            /**
733             * Returns the role with the name in the company.
734             *
735             * <p>
736             * The method searches the system roles map first for default roles. If a
737             * role with the name is not found, then the method will query the database.
738             * </p>
739             *
740             * @param  companyId the primary key of the company
741             * @param  name the role's name
742             * @return the role with the name
743             */
744            @Override
745            @Skip
746            public Role getRole(long companyId, String name) throws PortalException {
747                    String companyIdHexString = StringUtil.toHexString(companyId);
748    
749                    Role role = _systemRolesMap.get(companyIdHexString.concat(name));
750    
751                    if (role != null) {
752                            return role;
753                    }
754    
755                    return roleLocalService.loadGetRole(companyId, name);
756            }
757    
758            /**
759             * Returns all the roles of the type and subtype.
760             *
761             * @param  type the role's type (optionally <code>0</code>)
762             * @param  subtype the role's subtype (optionally <code>null</code>)
763             * @return the roles of the type and subtype
764             */
765            @Override
766            public List<Role> getRoles(int type, String subtype) {
767                    return rolePersistence.findByT_S(type, subtype);
768            }
769    
770            /**
771             * Returns all the roles in the company.
772             *
773             * @param  companyId the primary key of the company
774             * @return the roles in the company
775             */
776            @Override
777            public List<Role> getRoles(long companyId) {
778                    return rolePersistence.findByCompanyId(companyId);
779            }
780    
781            /**
782             * Returns all the roles with the types.
783             *
784             * @param  companyId the primary key of the company
785             * @param  types the role types (optionally <code>null</code>)
786             * @return the roles with the types
787             */
788            @Override
789            public List<Role> getRoles(long companyId, int[] types) {
790                    return rolePersistence.findByC_T(companyId, types);
791            }
792    
793            /**
794             * Returns all the roles with the primary keys.
795             *
796             * @param  roleIds the primary keys of the roles
797             * @return the roles with the primary keys
798             */
799            @Override
800            public List<Role> getRoles(long[] roleIds) throws PortalException {
801                    List<Role> roles = new ArrayList<>(roleIds.length);
802    
803                    for (long roleId : roleIds) {
804                            Role role = getRole(roleId);
805    
806                            roles.add(role);
807                    }
808    
809                    return roles;
810            }
811    
812            /**
813             * Returns all the roles of the subtype.
814             *
815             * @param  subtype the role's subtype (optionally <code>null</code>)
816             * @return the roles of the subtype
817             */
818            @Override
819            public List<Role> getSubtypeRoles(String subtype) {
820                    return rolePersistence.findBySubtype(subtype);
821            }
822    
823            /**
824             * Returns the number of roles of the subtype.
825             *
826             * @param  subtype the role's subtype (optionally <code>null</code>)
827             * @return the number of roles of the subtype
828             */
829            @Override
830            public int getSubtypeRolesCount(String subtype) {
831                    return rolePersistence.countBySubtype(subtype);
832            }
833    
834            /**
835             * Returns the team role in the company.
836             *
837             * @param  companyId the primary key of the company
838             * @param  teamId the primary key of the team
839             * @return the team role in the company
840             */
841            @Override
842            public Role getTeamRole(long companyId, long teamId)
843                    throws PortalException {
844    
845                    long classNameId = classNameLocalService.getClassNameId(Team.class);
846    
847                    return rolePersistence.findByC_C_C(companyId, classNameId, teamId);
848            }
849    
850            /**
851             * Returns the team role map for the group.
852             *
853             * @param  groupId the primary key of the group
854             * @return the team role map for the group
855             */
856            @Override
857            public Map<Team, Role> getTeamRoleMap(long groupId) throws PortalException {
858                    return getTeamRoleMap(groupId, null);
859            }
860    
861            /**
862             * Returns the team roles in the group.
863             *
864             * @param  groupId the primary key of the group
865             * @return the team roles in the group
866             */
867            @Override
868            public List<Role> getTeamRoles(long groupId) throws PortalException {
869                    return getTeamRoles(groupId, null);
870            }
871    
872            /**
873             * Returns the team roles in the group, excluding the specified role IDs.
874             *
875             * @param  groupId the primary key of the group
876             * @param  excludedRoleIds the primary keys of the roles to exclude
877             *         (optionally <code>null</code>)
878             * @return the team roles in the group, excluding the specified role IDs
879             */
880            @Override
881            public List<Role> getTeamRoles(long groupId, long[] excludedRoleIds)
882                    throws PortalException {
883    
884                    Map<Team, Role> teamRoleMap = getTeamRoleMap(groupId, excludedRoleIds);
885    
886                    Collection<Role> roles = teamRoleMap.values();
887    
888                    return ListUtil.fromCollection(roles);
889            }
890    
891            /**
892             * Returns all the roles of the type.
893             *
894             * @param  type the role's type (optionally <code>0</code>)
895             * @return the range of the roles of the type
896             */
897            @Override
898            public List<Role> getTypeRoles(int type) {
899                    return rolePersistence.findByType(type);
900            }
901    
902            /**
903             * Returns a range of all the roles of the type.
904             *
905             * @param  type the role's type (optionally <code>0</code>)
906             * @param  start the lower bound of the range of roles to return
907             * @param  end the upper bound of the range of roles to return (not
908             *         inclusive)
909             * @return the range of the roles of the type
910             */
911            @Override
912            public List<Role> getTypeRoles(int type, int start, int end) {
913                    return rolePersistence.findByType(type, start, end);
914            }
915    
916            /**
917             * Returns the number of roles of the type.
918             *
919             * @param  type the role's type (optionally <code>0</code>)
920             * @return the number of roles of the type
921             */
922            @Override
923            public int getTypeRolesCount(int type) {
924                    return rolePersistence.countByType(type);
925            }
926    
927            /**
928             * Returns all the user's roles within the user group.
929             *
930             * @param  userId the primary key of the user
931             * @param  groupId the primary key of the group
932             * @return the user's roles within the user group
933             * @see    com.liferay.portal.kernel.service.persistence.RoleFinder#findByUserGroupGroupRole(
934             *         long, long)
935             */
936            @Override
937            public List<Role> getUserGroupGroupRoles(long userId, long groupId) {
938                    return roleFinder.findByUserGroupGroupRole(userId, groupId);
939            }
940    
941            @Override
942            public List<Role> getUserGroupGroupRoles(
943                    long userId, long groupId, int start, int end) {
944    
945                    return roleFinder.findByUserGroupGroupRole(userId, groupId, start, end);
946            }
947    
948            @Override
949            public int getUserGroupGroupRolesCount(long userId, long groupId) {
950                    return roleFinder.countByUserGroupGroupRole(userId, groupId);
951            }
952    
953            /**
954             * Returns all the user's roles within the user group.
955             *
956             * @param  userId the primary key of the user
957             * @param  groupId the primary key of the group
958             * @return the user's roles within the user group
959             * @see    com.liferay.portal.kernel.service.persistence.RoleFinder#findByUserGroupRole(
960             *         long, long)
961             */
962            @Override
963            public List<Role> getUserGroupRoles(long userId, long groupId) {
964                    return roleFinder.findByUserGroupRole(userId, groupId);
965            }
966    
967            /**
968             * Returns the union of all the user's roles within the groups.
969             *
970             * @param  userId the primary key of the user
971             * @param  groups the groups (optionally <code>null</code>)
972             * @return the union of all the user's roles within the groups
973             * @see    com.liferay.portal.kernel.service.persistence.RoleFinder#findByU_G(
974             *         long, List)
975             */
976            @Override
977            public List<Role> getUserRelatedRoles(long userId, List<Group> groups) {
978                    if ((groups == null) || groups.isEmpty()) {
979                            return Collections.emptyList();
980                    }
981    
982                    return roleFinder.findByU_G(userId, groups);
983            }
984    
985            /**
986             * Returns all the user's roles within the group.
987             *
988             * @param  userId the primary key of the user
989             * @param  groupId the primary key of the group
990             * @return the user's roles within the group
991             * @see    com.liferay.portal.kernel.service.persistence.RoleFinder#findByU_G(
992             *         long, long)
993             */
994            @Override
995            public List<Role> getUserRelatedRoles(long userId, long groupId) {
996                    return roleFinder.findByU_G(userId, groupId);
997            }
998    
999            /**
1000             * Returns the union of all the user's roles within the groups.
1001             *
1002             * @param  userId the primary key of the user
1003             * @param  groupIds the primary keys of the groups
1004             * @return the union of all the user's roles within the groups
1005             * @see    com.liferay.portal.kernel.service.persistence.RoleFinder#findByU_G(
1006             *         long, long[])
1007             */
1008            @Override
1009            public List<Role> getUserRelatedRoles(long userId, long[] groupIds) {
1010                    return roleFinder.findByU_G(userId, groupIds);
1011            }
1012    
1013            /**
1014             * Returns <code>true</code> if the user is associated with the named
1015             * regular role.
1016             *
1017             * @param  userId the primary key of the user
1018             * @param  companyId the primary key of the company
1019             * @param  name the name of the role
1020             * @param  inherited whether to include the user's inherited roles in the
1021             *         search
1022             * @return <code>true</code> if the user is associated with the regular
1023             *         role; <code>false</code> otherwise
1024             */
1025            @Override
1026            @ThreadLocalCachable
1027            public boolean hasUserRole(
1028                            long userId, long companyId, String name, boolean inherited)
1029                    throws PortalException {
1030    
1031                    Role role = rolePersistence.fetchByC_N(companyId, name);
1032    
1033                    if (role == null) {
1034                            return false;
1035                    }
1036    
1037                    if (role.getType() != RoleConstants.TYPE_REGULAR) {
1038                            throw new IllegalArgumentException(name + " is not a regular role");
1039                    }
1040    
1041                    long defaultUserId = userLocalService.getDefaultUserId(companyId);
1042    
1043                    if (userId == defaultUserId) {
1044                            if (name.equals(RoleConstants.GUEST)) {
1045                                    return true;
1046                            }
1047                            else {
1048                                    return false;
1049                            }
1050                    }
1051    
1052                    if (inherited) {
1053                            if (userPersistence.containsRole(userId, role.getRoleId())) {
1054                                    return true;
1055                            }
1056    
1057                            ThreadLocalCache<Boolean> threadLocalCache =
1058                                    ThreadLocalCacheManager.getThreadLocalCache(
1059                                            Lifecycle.REQUEST, RoleLocalServiceImpl.class.getName());
1060    
1061                            String key = String.valueOf(role.getRoleId()).concat(
1062                                    String.valueOf(userId));
1063    
1064                            Boolean value = threadLocalCache.get(key);
1065    
1066                            if (value != null) {
1067                                    return value;
1068                            }
1069    
1070                            value = PermissionCacheUtil.getUserRole(userId, role);
1071    
1072                            if (value == null) {
1073                                    int count = roleFinder.countByR_U(role.getRoleId(), userId);
1074    
1075                                    if (count > 0) {
1076                                            value = true;
1077                                    }
1078                                    else {
1079                                            value = false;
1080                                    }
1081    
1082                                    PermissionCacheUtil.putUserRole(userId, role, value);
1083                            }
1084    
1085                            threadLocalCache.put(key, value);
1086    
1087                            return value;
1088                    }
1089                    else {
1090                            return userPersistence.containsRole(userId, role.getRoleId());
1091                    }
1092            }
1093    
1094            /**
1095             * Returns <code>true</code> if the user has any one of the named regular
1096             * roles.
1097             *
1098             * @param  userId the primary key of the user
1099             * @param  companyId the primary key of the company
1100             * @param  names the names of the roles
1101             * @param  inherited whether to include the user's inherited roles in the
1102             *         search
1103             * @return <code>true</code> if the user has any one of the regular roles;
1104             *         <code>false</code> otherwise
1105             */
1106            @Override
1107            public boolean hasUserRoles(
1108                            long userId, long companyId, String[] names, boolean inherited)
1109                    throws PortalException {
1110    
1111                    for (String name : names) {
1112                            if (hasUserRole(userId, companyId, name, inherited)) {
1113                                    return true;
1114                            }
1115                    }
1116    
1117                    return false;
1118            }
1119    
1120            /**
1121             * Returns a role with the name in the company.
1122             *
1123             * @param  companyId the primary key of the company
1124             * @param  name the role's name (optionally <code>null</code>)
1125             * @return the role with the name, or <code>null</code> if a role with the
1126             *         name could not be found in the company
1127             */
1128            @Override
1129            public Role loadFetchRole(long companyId, String name) {
1130                    return rolePersistence.fetchByC_N(companyId, name);
1131            }
1132    
1133            /**
1134             * Returns a role with the name in the company.
1135             *
1136             * @param  companyId the primary key of the company
1137             * @param  name the role's name
1138             * @return the role with the name in the company
1139             */
1140            @Override
1141            public Role loadGetRole(long companyId, String name)
1142                    throws PortalException {
1143    
1144                    return rolePersistence.findByC_N(companyId, name);
1145            }
1146    
1147            /**
1148             * Returns an ordered range of all the roles that match the keywords and
1149             * types.
1150             *
1151             * <p>
1152             * Useful when paginating results. Returns a maximum of <code>end -
1153             * start</code> instances. <code>start</code> and <code>end</code> are not
1154             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1155             * refers to the first result in the set. Setting both <code>start</code>
1156             * and <code>end</code> to {@link
1157             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1158             * result set.
1159             * </p>
1160             *
1161             * @param  companyId the primary key of the company
1162             * @param  keywords the keywords (space separated), which may occur in the
1163             *         role's name or description (optionally <code>null</code>)
1164             * @param  types the role types (optionally <code>null</code>)
1165             * @param  start the lower bound of the range of roles to return
1166             * @param  end the upper bound of the range of roles to return (not
1167             *         inclusive)
1168             * @param  obc the comparator to order the roles (optionally
1169             *         <code>null</code>)
1170             * @return the ordered range of the matching roles, ordered by
1171             *         <code>obc</code>
1172             * @see    com.liferay.portal.kernel.service.persistence.RoleFinder
1173             */
1174            @Override
1175            public List<Role> search(
1176                    long companyId, String keywords, Integer[] types, int start, int end,
1177                    OrderByComparator<Role> obc) {
1178    
1179                    return search(
1180                            companyId, keywords, types, new LinkedHashMap<String, Object>(),
1181                            start, end, obc);
1182            }
1183    
1184            /**
1185             * Returns an ordered range of all the roles that match the keywords, types,
1186             * and params.
1187             *
1188             * <p>
1189             * Useful when paginating results. Returns a maximum of <code>end -
1190             * start</code> instances. <code>start</code> and <code>end</code> are not
1191             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1192             * refers to the first result in the set. Setting both <code>start</code>
1193             * and <code>end</code> to {@link
1194             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1195             * result set.
1196             * </p>
1197             *
1198             * @param  companyId the primary key of the company
1199             * @param  keywords the keywords (space separated), which may occur in the
1200             *         role's name or description (optionally <code>null</code>)
1201             * @param  types the role types (optionally <code>null</code>)
1202             * @param  params the finder parameters. Can specify values for the
1203             *         "usersRoles" key. For more information, see {@link
1204             *         com.liferay.portal.kernel.service.persistence.RoleFinder}
1205             * @param  start the lower bound of the range of roles to return
1206             * @param  end the upper bound of the range of roles to return (not
1207             *         inclusive)
1208             * @param  obc the comparator to order the roles (optionally
1209             *         <code>null</code>)
1210             * @return the ordered range of the matching roles, ordered by
1211             *         <code>obc</code>
1212             * @see    com.liferay.portal.kernel.service.persistence.RoleFinder
1213             */
1214            @Override
1215            public List<Role> search(
1216                    long companyId, String keywords, Integer[] types,
1217                    LinkedHashMap<String, Object> params, int start, int end,
1218                    OrderByComparator<Role> obc) {
1219    
1220                    return roleFinder.findByKeywords(
1221                            companyId, keywords, types, params, start, end, obc);
1222            }
1223    
1224            /**
1225             * Returns an ordered range of all the roles that match the name,
1226             * description, and types.
1227             *
1228             * <p>
1229             * Useful when paginating results. Returns a maximum of <code>end -
1230             * start</code> instances. <code>start</code> and <code>end</code> are not
1231             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1232             * refers to the first result in the set. Setting both <code>start</code>
1233             * and <code>end</code> to {@link
1234             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1235             * result set.
1236             * </p>
1237             *
1238             * @param  companyId the primary key of the company
1239             * @param  name the role's name (optionally <code>null</code>)
1240             * @param  description the role's description (optionally <code>null</code>)
1241             * @param  types the role types (optionally <code>null</code>)
1242             * @param  start the lower bound of the range of the roles to return
1243             * @param  end the upper bound of the range of the roles to return (not
1244             *         inclusive)
1245             * @param  obc the comparator to order the roles (optionally
1246             *         <code>null</code>)
1247             * @return the ordered range of the matching roles, ordered by
1248             *         <code>obc</code>
1249             * @see    com.liferay.portal.kernel.service.persistence.RoleFinder
1250             */
1251            @Override
1252            public List<Role> search(
1253                    long companyId, String name, String description, Integer[] types,
1254                    int start, int end, OrderByComparator<Role> obc) {
1255    
1256                    return search(
1257                            companyId, name, description, types,
1258                            new LinkedHashMap<String, Object>(), start, end, obc);
1259            }
1260    
1261            /**
1262             * Returns an ordered range of all the roles that match the name,
1263             * description, types, and params.
1264             *
1265             * <p>
1266             * Useful when paginating results. Returns a maximum of <code>end -
1267             * start</code> instances. <code>start</code> and <code>end</code> are not
1268             * primary keys, they are indexes in the result set. Thus, <code>0</code>
1269             * refers to the first result in the set. Setting both <code>start</code>
1270             * and <code>end</code> to {@link
1271             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
1272             * result set.
1273             * </p>
1274             *
1275             * @param  companyId the primary key of the company
1276             * @param  name the role's name (optionally <code>null</code>)
1277             * @param  description the role's description (optionally <code>null</code>)
1278             * @param  types the role types (optionally <code>null</code>)
1279             * @param  params the finder's parameters. Can specify values for the
1280             *         "usersRoles" key. For more information, see {@link
1281             *         com.liferay.portal.kernel.service.persistence.RoleFinder}
1282             * @param  start the lower bound of the range of the roles to return
1283             * @param  end the upper bound of the range of the roles to return (not
1284             *         inclusive)
1285             * @param  obc the comparator to order the roles (optionally
1286             *         <code>null</code>)
1287             * @return the ordered range of the matching roles, ordered by
1288             *         <code>obc</code>
1289             * @see    com.liferay.portal.kernel.service.persistence.RoleFinder
1290             */
1291            @Override
1292            public List<Role> search(
1293                    long companyId, String name, String description, Integer[] types,
1294                    LinkedHashMap<String, Object> params, int start, int end,
1295                    OrderByComparator<Role> obc) {
1296    
1297                    return roleFinder.findByC_N_D_T(
1298                            companyId, name, description, types, params, true, start, end, obc);
1299            }
1300    
1301            /**
1302             * Returns the number of roles that match the keywords and types.
1303             *
1304             * @param  companyId the primary key of the company
1305             * @param  keywords the keywords (space separated), which may occur in the
1306             *         role's name or description (optionally <code>null</code>)
1307             * @param  types the role types (optionally <code>null</code>)
1308             * @return the number of matching roles
1309             */
1310            @Override
1311            public int searchCount(long companyId, String keywords, Integer[] types) {
1312                    return searchCount(
1313                            companyId, keywords, types, new LinkedHashMap<String, Object>());
1314            }
1315    
1316            /**
1317             * Returns the number of roles that match the keywords, types and params.
1318             *
1319             * @param  companyId the primary key of the company
1320             * @param  keywords the keywords (space separated), which may occur in the
1321             *         role's name or description (optionally <code>null</code>)
1322             * @param  types the role types (optionally <code>null</code>)
1323             * @param  params the finder parameters. For more information, see {@link
1324             *         com.liferay.portal.kernel.service.persistence.RoleFinder}
1325             * @return the number of matching roles
1326             */
1327            @Override
1328            public int searchCount(
1329                    long companyId, String keywords, Integer[] types,
1330                    LinkedHashMap<String, Object> params) {
1331    
1332                    return roleFinder.countByKeywords(companyId, keywords, types, params);
1333            }
1334    
1335            /**
1336             * Returns the number of roles that match the name, description, and types.
1337             *
1338             * @param  companyId the primary key of the company
1339             * @param  name the role's name (optionally <code>null</code>)
1340             * @param  description the role's description (optionally <code>null</code>)
1341             * @param  types the role types (optionally <code>null</code>)
1342             * @return the number of matching roles
1343             */
1344            @Override
1345            public int searchCount(
1346                    long companyId, String name, String description, Integer[] types) {
1347    
1348                    return searchCount(
1349                            companyId, name, description, types,
1350                            new LinkedHashMap<String, Object>());
1351            }
1352    
1353            /**
1354             * Returns the number of roles that match the name, description, types, and
1355             * params.
1356             *
1357             * @param  companyId the primary key of the company
1358             * @param  name the role's name (optionally <code>null</code>)
1359             * @param  description the role's description (optionally <code>null</code>)
1360             * @param  types the role types (optionally <code>null</code>)
1361             * @param  params the finder parameters. Can specify values for the
1362             *         "usersRoles" key. For more information, see {@link
1363             *         com.liferay.portal.kernel.service.persistence.RoleFinder}
1364             * @return the number of matching roles
1365             */
1366            @Override
1367            public int searchCount(
1368                    long companyId, String name, String description, Integer[] types,
1369                    LinkedHashMap<String, Object> params) {
1370    
1371                    return roleFinder.countByC_N_D_T(
1372                            companyId, name, description, types, params, true);
1373            }
1374    
1375            /**
1376             * Sets the roles associated with the user, replacing the user's existing
1377             * roles. The user is reindexed after the roles are set.
1378             *
1379             * @param userId the primary key of the user
1380             * @param roleIds the primary keys of the roles
1381             */
1382            @Override
1383            public void setUserRoles(long userId, long[] roleIds)
1384                    throws PortalException {
1385    
1386                    roleIds = UsersAdminUtil.addRequiredRoles(userId, roleIds);
1387    
1388                    userPersistence.setRoles(userId, roleIds);
1389    
1390                    reindex(userId);
1391    
1392                    PermissionCacheUtil.clearCache(userId);
1393            }
1394    
1395            /**
1396             * Removes the matching roles associated with the user. The user is
1397             * reindexed after the roles are removed.
1398             *
1399             * @param userId the primary key of the user
1400             * @param roleIds the primary keys of the roles
1401             */
1402            @Override
1403            public void unsetUserRoles(long userId, long[] roleIds)
1404                    throws PortalException {
1405    
1406                    roleIds = UsersAdminUtil.removeRequiredRoles(userId, roleIds);
1407    
1408                    userPersistence.removeRoles(userId, roleIds);
1409    
1410                    reindex(userId);
1411    
1412                    PermissionCacheUtil.clearCache(userId);
1413            }
1414    
1415            /**
1416             * Updates the role with the primary key.
1417             *
1418             * @param  roleId the primary key of the role
1419             * @param  name the role's new name
1420             * @param  titleMap the new localized titles (optionally <code>null</code>)
1421             *         to replace those existing for the role
1422             * @param  descriptionMap the new localized descriptions (optionally
1423             *         <code>null</code>) to replace those existing for the role
1424             * @param  subtype the role's new subtype (optionally <code>null</code>)
1425             * @param  serviceContext the service context to be applied (optionally
1426             *         <code>null</code>). Can set expando bridge attributes for the
1427             *         role.
1428             * @return the role with the primary key
1429             */
1430            @Override
1431            public Role updateRole(
1432                            long roleId, String name, Map<Locale, String> titleMap,
1433                            Map<Locale, String> descriptionMap, String subtype,
1434                            ServiceContext serviceContext)
1435                    throws PortalException {
1436    
1437                    Role role = rolePersistence.findByPrimaryKey(roleId);
1438    
1439                    validate(roleId, role.getCompanyId(), role.getClassNameId(), name);
1440    
1441                    if (role.isSystem()) {
1442                            name = role.getName();
1443                            subtype = null;
1444                    }
1445    
1446                    role.setName(name);
1447                    role.setTitleMap(titleMap);
1448                    role.setDescriptionMap(descriptionMap);
1449                    role.setSubtype(subtype);
1450                    role.setExpandoBridgeAttributes(serviceContext);
1451    
1452                    rolePersistence.update(role);
1453    
1454                    return role;
1455            }
1456    
1457            protected void checkSystemRole(
1458                            long companyId, String name, Map<Locale, String> descriptionMap,
1459                            int type)
1460                    throws PortalException {
1461    
1462                    String companyIdHexString = StringUtil.toHexString(companyId);
1463    
1464                    String key = companyIdHexString.concat(name);
1465    
1466                    Role role = _systemRolesMap.get(key);
1467    
1468                    try {
1469                            if (role == null) {
1470                                    role = rolePersistence.findByC_N(companyId, name);
1471                            }
1472    
1473                            if (!descriptionMap.equals(role.getDescriptionMap())) {
1474                                    role.setDescriptionMap(descriptionMap);
1475    
1476                                    roleLocalService.updateRole(role);
1477                            }
1478                    }
1479                    catch (NoSuchRoleException nsre) {
1480                            User user = userLocalService.getDefaultUser(companyId);
1481    
1482                            PermissionThreadLocal.setAddResource(false);
1483    
1484                            try {
1485                                    role = roleLocalService.addRole(
1486                                            user.getUserId(), null, 0, name, null, descriptionMap, type,
1487                                            null, null);
1488                            }
1489                            finally {
1490                                    PermissionThreadLocal.setAddResource(true);
1491                            }
1492    
1493                            if (name.equals(RoleConstants.USER)) {
1494                                    initPersonalControlPanelPortletsPermissions(role);
1495                            }
1496                    }
1497    
1498                    _systemRolesMap.put(key, role);
1499            }
1500    
1501            protected String[] getDefaultControlPanelPortlets() {
1502                    String myAccountPortletId = PortletProviderUtil.getPortletId(
1503                            PortalMyAccountApplicationType.MyAccount.CLASS_NAME,
1504                            PortletProvider.Action.VIEW);
1505    
1506                    return new String[] {
1507                            myAccountPortletId, PortletKeys.MY_PAGES,
1508                            PortletKeys.MY_WORKFLOW_INSTANCE, PortletKeys.MY_WORKFLOW_TASK
1509                    };
1510            }
1511    
1512            protected Map<Team, Role> getTeamRoleMap(
1513                            long groupId, long[] excludedRoleIds)
1514                    throws PortalException {
1515    
1516                    Group group = groupPersistence.findByPrimaryKey(groupId);
1517    
1518                    if (group.isLayout()) {
1519                            group = group.getParentGroup();
1520                    }
1521    
1522                    List<Team> teams = teamPersistence.findByGroupId(group.getGroupId());
1523    
1524                    if (teams.isEmpty()) {
1525                            return Collections.emptyMap();
1526                    }
1527    
1528                    Set<Long> roleIds = SetUtil.fromArray(excludedRoleIds);
1529    
1530                    Map<Team, Role> teamRoleMap = new LinkedHashMap<>();
1531    
1532                    for (Team team : teams) {
1533                            Role role = getTeamRole(team.getCompanyId(), team.getTeamId());
1534    
1535                            if (roleIds.contains(role.getRoleId())) {
1536                                    continue;
1537                            }
1538    
1539                            teamRoleMap.put(team, role);
1540                    }
1541    
1542                    return teamRoleMap;
1543            }
1544    
1545            protected void initPersonalControlPanelPortletsPermissions(Role role)
1546                    throws PortalException {
1547    
1548                    for (String portletId : getDefaultControlPanelPortlets()) {
1549                            int count = resourcePermissionPersistence.countByC_N_S_P_R(
1550                                    role.getCompanyId(), portletId, ResourceConstants.SCOPE_COMPANY,
1551                                    String.valueOf(role.getCompanyId()), role.getRoleId());
1552    
1553                            if (count > 0) {
1554                                    continue;
1555                            }
1556    
1557                            ResourceAction resourceAction =
1558                                    resourceActionLocalService.fetchResourceAction(
1559                                            portletId, ActionKeys.ACCESS_IN_CONTROL_PANEL);
1560    
1561                            if (resourceAction == null) {
1562                                    continue;
1563                            }
1564    
1565                            setRolePermissions(
1566                                    role, portletId,
1567                                    new String[] {ActionKeys.ACCESS_IN_CONTROL_PANEL});
1568                    }
1569            }
1570    
1571            protected void reindex(long userId) throws SearchException {
1572                    Indexer<User> indexer = IndexerRegistryUtil.nullSafeGetIndexer(
1573                            User.class);
1574    
1575                    User user = userLocalService.fetchUser(userId);
1576    
1577                    indexer.reindex(user);
1578            }
1579    
1580            protected void setRolePermissions(
1581                            Role role, String name, String[] actionIds)
1582                    throws PortalException {
1583    
1584                    if (resourceBlockLocalService.isSupported(name)) {
1585                            resourceBlockLocalService.setCompanyScopePermissions(
1586                                    role.getCompanyId(), name, role.getRoleId(),
1587                                    Arrays.asList(actionIds));
1588                    }
1589                    else {
1590                            resourcePermissionLocalService.setResourcePermissions(
1591                                    role.getCompanyId(), name, ResourceConstants.SCOPE_COMPANY,
1592                                    String.valueOf(role.getCompanyId()), role.getRoleId(),
1593                                    actionIds);
1594                    }
1595            }
1596    
1597            protected void validate(
1598                            long roleId, long companyId, long classNameId, String name)
1599                    throws PortalException {
1600    
1601                    if (classNameId == classNameLocalService.getClassNameId(Role.class)) {
1602                            if (Validator.isNull(name) ||
1603                                    (name.indexOf(CharPool.COMMA) != -1) ||
1604                                    (name.indexOf(CharPool.STAR) != -1)) {
1605    
1606                                    throw new RoleNameException();
1607                            }
1608    
1609                            if (Validator.isNumber(name) &&
1610                                    !PropsValues.ROLES_NAME_ALLOW_NUMERIC) {
1611    
1612                                    throw new RoleNameException();
1613                            }
1614                    }
1615    
1616                    try {
1617                            Role role = roleFinder.findByC_N(companyId, name);
1618    
1619                            if (role.getRoleId() != roleId) {
1620                                    throw new DuplicateRoleException("{roleId=" + roleId + "}");
1621                            }
1622                    }
1623                    catch (NoSuchRoleException nsre) {
1624                    }
1625    
1626                    if (name.equals(RoleConstants.PLACEHOLDER_DEFAULT_GROUP_ROLE)) {
1627                            throw new RoleNameException(
1628                                    RoleConstants.PLACEHOLDER_DEFAULT_GROUP_ROLE +
1629                                            " is a temporary placeholder that must not be persisted");
1630                    }
1631            }
1632    
1633            private final Map<String, Role> _systemRolesMap = new HashMap<>();
1634    
1635    }