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