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