001    /**
002     * Copyright (c) 2000-2011 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.service.impl;
016    
017    import com.liferay.portal.DuplicateRoleException;
018    import com.liferay.portal.NoSuchRoleException;
019    import com.liferay.portal.RequiredRoleException;
020    import com.liferay.portal.RoleNameException;
021    import com.liferay.portal.kernel.annotation.Propagation;
022    import com.liferay.portal.kernel.annotation.Transactional;
023    import com.liferay.portal.kernel.cache.ThreadLocalCachable;
024    import com.liferay.portal.kernel.exception.PortalException;
025    import com.liferay.portal.kernel.exception.SystemException;
026    import com.liferay.portal.kernel.search.Indexer;
027    import com.liferay.portal.kernel.search.IndexerRegistryUtil;
028    import com.liferay.portal.kernel.util.GetterUtil;
029    import com.liferay.portal.kernel.util.OrderByComparator;
030    import com.liferay.portal.kernel.util.StringPool;
031    import com.liferay.portal.kernel.util.StringUtil;
032    import com.liferay.portal.kernel.util.Validator;
033    import com.liferay.portal.model.Group;
034    import com.liferay.portal.model.Layout;
035    import com.liferay.portal.model.ResourceConstants;
036    import com.liferay.portal.model.Role;
037    import com.liferay.portal.model.RoleConstants;
038    import com.liferay.portal.model.Team;
039    import com.liferay.portal.model.User;
040    import com.liferay.portal.security.permission.PermissionCacheUtil;
041    import com.liferay.portal.service.base.RoleLocalServiceBaseImpl;
042    import com.liferay.portal.util.PortalUtil;
043    import com.liferay.portal.util.PropsUtil;
044    import com.liferay.portlet.enterpriseadmin.util.EnterpriseAdminUtil;
045    
046    import java.util.ArrayList;
047    import java.util.Collections;
048    import java.util.HashMap;
049    import java.util.LinkedHashMap;
050    import java.util.List;
051    import java.util.Locale;
052    import java.util.Map;
053    
054    /**
055     * @author Brian Wing Shun Chan
056     */
057    public class RoleLocalServiceImpl extends RoleLocalServiceBaseImpl {
058    
059            public Role addRole(
060                            long userId, long companyId, String name,
061                            Map<Locale, String> titleMap, String description, int type)
062                    throws PortalException, SystemException {
063    
064                    return addRole(
065                            userId, companyId, name, titleMap, description, type, null, 0);
066            }
067    
068            public Role addRole(
069                            long userId, long companyId, String name,
070                            Map<Locale, String> titleMap, String description,
071                            int type, String className, long classPK)
072                    throws PortalException, SystemException {
073    
074                    // Role
075    
076                    className = GetterUtil.getString(className);
077                    long classNameId = PortalUtil.getClassNameId(className);
078    
079                    long roleId = counterLocalService.increment();
080    
081                    if ((classNameId <= 0) || className.equals(Role.class.getName())) {
082                            classNameId = PortalUtil.getClassNameId(Role.class);
083                            classPK = roleId;
084                    }
085    
086                    validate(0, companyId, classNameId, name);
087    
088                    Role role = rolePersistence.create(roleId);
089    
090                    role.setCompanyId(companyId);
091                    role.setClassNameId(classNameId);
092                    role.setClassPK(classPK);
093                    role.setName(name);
094                    role.setTitleMap(titleMap);
095                    role.setDescription(description);
096                    role.setType(type);
097    
098                    rolePersistence.update(role, false);
099    
100                    // Resources
101    
102                    if (userId > 0) {
103                            resourceLocalService.addResources(
104                                    companyId, 0, userId, Role.class.getName(), role.getRoleId(),
105                                    false, false, false);
106    
107                            Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
108    
109                            indexer.reindex(userId);
110                    }
111    
112                    return role;
113            }
114    
115            public void addUserRoles(long userId, long[] roleIds)
116                    throws PortalException, SystemException {
117    
118                    userPersistence.addRoles(userId, roleIds);
119    
120                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
121    
122                    indexer.reindex(userId);
123    
124                    PermissionCacheUtil.clearCache();
125            }
126    
127            @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
128            public void checkSystemRoles(long companyId)
129                    throws PortalException, SystemException {
130    
131                    for (Role role : roleFinder.findBySystem(companyId)) {
132                            _systemRolesMap.put(companyId + role.getName(), role);
133                    }
134    
135                    // Regular roles
136    
137                    String[] systemRoles = PortalUtil.getSystemRoles();
138    
139                    for (String name : systemRoles) {
140                            String description = PropsUtil.get(
141                                    "system.role." + StringUtil.replace(name, " ", ".") +
142                                            ".description");
143                            int type = RoleConstants.TYPE_REGULAR;
144    
145                            checkSystemRole(companyId, name, description, type);
146                    }
147    
148                    // Community roles
149    
150                    String[] systemCommunityRoles = PortalUtil.getSystemCommunityRoles();
151    
152                    for (String name : systemCommunityRoles) {
153                            String description = PropsUtil.get(
154                                    "system.community.role." +
155                                            StringUtil.replace(name, " ", ".") + ".description");
156                            int type = RoleConstants.TYPE_COMMUNITY;
157    
158                            checkSystemRole(companyId, name, description, type);
159                    }
160    
161                    // Organization roles
162    
163                    String[] systemOrganizationRoles =
164                            PortalUtil.getSystemOrganizationRoles();
165    
166                    for (String name : systemOrganizationRoles) {
167                            String description = PropsUtil.get(
168                                    "system.organization.role." +
169                                            StringUtil.replace(name, " ", ".") + ".description");
170                            int type = RoleConstants.TYPE_ORGANIZATION;
171    
172                            checkSystemRole(companyId, name, description, type);
173                    }
174            }
175    
176            public void deleteRole(long roleId)
177                    throws PortalException, SystemException {
178    
179                    Role role = rolePersistence.findByPrimaryKey(roleId);
180    
181                    if (PortalUtil.isSystemRole(role.getName())) {
182                            throw new RequiredRoleException();
183                    }
184    
185                    // Resources
186    
187                    String className = role.getClassName();
188                    long classNameId = role.getClassNameId();
189    
190                    if ((classNameId <= 0) || className.equals(Role.class.getName())) {
191                            resourceLocalService.deleteResource(
192                                    role.getCompanyId(), Role.class.getName(),
193                                    ResourceConstants.SCOPE_INDIVIDUAL, role.getRoleId());
194                    }
195    
196                    if ((role.getType() == RoleConstants.TYPE_COMMUNITY) ||
197                            (role.getType() == RoleConstants.TYPE_ORGANIZATION)) {
198    
199                            userGroupRoleLocalService.deleteUserGroupRolesByRoleId(
200                                    role.getRoleId());
201    
202                            userGroupGroupRoleLocalService.deleteUserGroupGroupRolesByRoleId(
203                                    role.getRoleId());
204                    }
205    
206                    // Role
207    
208                    rolePersistence.remove(role);
209    
210                    // Permission cache
211    
212                    PermissionCacheUtil.clearCache();
213            }
214    
215            public Role getDefaultGroupRole(long groupId)
216                    throws PortalException, SystemException {
217    
218                    Group group = groupPersistence.findByPrimaryKey(groupId);
219    
220                    if (group.isLayout()) {
221                            Layout layout = layoutLocalService.getLayout(group.getClassPK());
222    
223                            group = layout.getGroup();
224                    }
225    
226                    if (group.isStagingGroup()) {
227                            group = group.getLiveGroup();
228                    }
229    
230                    Role role = null;
231    
232                    if (group.isCommunity() || group.isLayoutPrototype() ||
233                            group.isLayoutSetPrototype()) {
234    
235                            role = getRole(
236                                    group.getCompanyId(), RoleConstants.COMMUNITY_MEMBER);
237                    }
238                    else if (group.isCompany()) {
239                            role = getRole(group.getCompanyId(), RoleConstants.ADMINISTRATOR);
240                    }
241                    else if (group.isOrganization()) {
242                            role = getRole(
243                                    group.getCompanyId(), RoleConstants.ORGANIZATION_MEMBER);
244                    }
245                    else if (group.isUser() || group.isUserGroup()) {
246                            role = getRole(group.getCompanyId(), RoleConstants.POWER_USER);
247                    }
248    
249                    return role;
250            }
251    
252            public List<Role> getGroupRoles(long groupId) throws SystemException {
253                    return groupPersistence.getRoles(groupId);
254            }
255    
256            public Map<String, List<String>> getResourceRoles(
257                            long companyId, String name, int scope, String primKey)
258                    throws SystemException {
259    
260                    return roleFinder.findByC_N_S_P(companyId, name, scope, primKey);
261            }
262    
263            public Role getRole(long roleId) throws PortalException, SystemException {
264                    return rolePersistence.findByPrimaryKey(roleId);
265            }
266    
267            public Role getRole(long companyId, String name)
268                    throws PortalException, SystemException {
269    
270                    Role role = _systemRolesMap.get(companyId + name);
271    
272                    if (role != null) {
273                            return role;
274                    }
275    
276                    return rolePersistence.findByC_N(companyId, name);
277            }
278    
279            public List<Role> getRoles(long companyId) throws SystemException {
280                    return rolePersistence.findByCompanyId(companyId);
281            }
282    
283            public List<Role> getRoles(long[] roleIds)
284                    throws PortalException, SystemException {
285    
286                    List<Role> roles = new ArrayList<Role>(roleIds.length);
287    
288                    for (long roleId : roleIds) {
289                            Role role = getRole(roleId);
290    
291                            roles.add(role);
292                    }
293    
294                    return roles;
295            }
296    
297            public List<Role> getRoles(int type, String subtype)
298                    throws SystemException {
299    
300                    return rolePersistence.findByT_S(type, subtype);
301            }
302    
303            public List<Role> getSubtypeRoles(String subtype) throws SystemException {
304                    return rolePersistence.findBySubtype(subtype);
305            }
306    
307            public int getSubtypeRolesCount(String subtype) throws SystemException {
308                    return rolePersistence.countBySubtype(subtype);
309            }
310    
311            public Role getTeamRole(long companyId, long teamId)
312                    throws PortalException, SystemException {
313    
314                    long classNameId = PortalUtil.getClassNameId(Team.class);
315    
316                    return rolePersistence.findByC_C_C(companyId, classNameId, teamId);
317            }
318    
319            public List<Role> getUserGroupGroupRoles(long userId, long groupId)
320                    throws SystemException {
321    
322                    return roleFinder.findByUserGroupGroupRole(userId, groupId);
323            }
324    
325            public List<Role> getUserGroupRoles(long userId, long groupId)
326                    throws SystemException {
327    
328                    return roleFinder.findByUserGroupRole(userId, groupId);
329            }
330    
331            public List<Role> getUserRelatedRoles(long userId, long groupId)
332                    throws SystemException {
333    
334                    return roleFinder.findByU_G(userId, groupId);
335            }
336    
337            public List<Role> getUserRelatedRoles(long userId, long[] groupIds)
338                    throws SystemException {
339    
340                    return roleFinder.findByU_G(userId, groupIds);
341            }
342    
343            public List<Role> getUserRelatedRoles(long userId, List<Group> groups)
344                    throws SystemException {
345    
346                    if ((groups == null) || groups.isEmpty()) {
347                            return Collections.EMPTY_LIST;
348                    }
349    
350                    return roleFinder.findByU_G(userId, groups);
351            }
352    
353            public List<Role> getUserRoles(long userId) throws SystemException {
354                    return userPersistence.getRoles(userId);
355            }
356    
357            public boolean hasUserRole(long userId, long roleId)
358                    throws SystemException {
359    
360                    return userPersistence.containsRole(userId, roleId);
361            }
362    
363            /**
364             * Returns <code>true</code> if the user has the regular role.
365             *
366             * @return <code>true</code> if the user has the regular role
367             */
368            @ThreadLocalCachable
369            public boolean hasUserRole(
370                            long userId, long companyId, String name, boolean inherited)
371                    throws PortalException, SystemException {
372    
373                    Role role = rolePersistence.findByC_N(companyId, name);
374    
375                    if (role.getType() != RoleConstants.TYPE_REGULAR) {
376                            throw new IllegalArgumentException(name + " is not a regular role");
377                    }
378    
379                    if (inherited) {
380                            if (roleFinder.countByR_U(role.getRoleId(), userId) > 0) {
381                                    return true;
382                            }
383                            else {
384                                    return false;
385                            }
386                    }
387                    else {
388                            return userPersistence.containsRole(userId, role.getRoleId());
389                    }
390            }
391    
392            /**
393             * Returns <code>true</code> if the user has any one of the specified
394             * regular roles.
395             *
396             * @return <code>true</code> if the user has the regular role
397             */
398            public boolean hasUserRoles(
399                            long userId, long companyId, String[] names, boolean inherited)
400                    throws PortalException, SystemException {
401    
402                    for (String name : names) {
403                            if (hasUserRole(userId, companyId, name, inherited)) {
404                                    return true;
405                            }
406                    }
407    
408                    return false;
409            }
410    
411            public List<Role> search(
412                            long companyId, String name, String description, Integer[] types,
413                            int start, int end, OrderByComparator obc)
414                    throws SystemException {
415    
416                    return search(
417                            companyId, name, description, types,
418                            new LinkedHashMap<String, Object>(), start, end, obc);
419            }
420    
421            public List<Role> search(
422                            long companyId, String name, String description, Integer[] types,
423                            LinkedHashMap<String, Object> params, int start, int end,
424                            OrderByComparator obc)
425                    throws SystemException {
426    
427                    return roleFinder.findByC_N_D_T(
428                            companyId, name, description, types, params, start, end, obc);
429            }
430    
431            public int searchCount(
432                            long companyId, String name, String description, Integer[] types)
433                    throws SystemException {
434    
435                    return searchCount(
436                            companyId, name, description, types,
437                            new LinkedHashMap<String, Object>());
438            }
439    
440            public int searchCount(
441                            long companyId, String name, String description, Integer[] types,
442                            LinkedHashMap<String, Object> params)
443                    throws SystemException {
444    
445                    return roleFinder.countByC_N_D_T(
446                            companyId, name, description, types, params);
447            }
448    
449            public void setUserRoles(long userId, long[] roleIds)
450                    throws PortalException, SystemException {
451    
452                    roleIds = EnterpriseAdminUtil.addRequiredRoles(userId, roleIds);
453    
454                    userPersistence.setRoles(userId, roleIds);
455    
456                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
457    
458                    indexer.reindex(userId);
459    
460                    PermissionCacheUtil.clearCache();
461            }
462    
463            public void unsetUserRoles(long userId, long[] roleIds)
464                    throws PortalException, SystemException {
465    
466                    roleIds = EnterpriseAdminUtil.removeRequiredRoles(userId, roleIds);
467    
468                    userPersistence.removeRoles(userId, roleIds);
469    
470                    Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
471    
472                    indexer.reindex(userId);
473    
474                    PermissionCacheUtil.clearCache();
475            }
476    
477            public Role updateRole(
478                            long roleId, String name, Map<Locale, String> titleMap,
479                            String description, String subtype)
480                    throws PortalException, SystemException {
481    
482                    Role role = rolePersistence.findByPrimaryKey(roleId);
483    
484                    validate(roleId, role.getCompanyId(), role.getClassNameId(), name);
485    
486                    if (PortalUtil.isSystemRole(role.getName())) {
487                            name = role.getName();
488                            subtype = null;
489                    }
490    
491                    role.setName(name);
492                    role.setTitleMap(titleMap);
493                    role.setDescription(description);
494                    role.setSubtype(subtype);
495    
496                    rolePersistence.update(role, false);
497    
498                    return role;
499            }
500    
501            protected void checkSystemRole(
502                            long companyId, String name, String description, int type)
503                    throws PortalException, SystemException {
504    
505                    Role role = _systemRolesMap.get(companyId + name);
506    
507                    try {
508                            if (role == null) {
509                                    role = rolePersistence.findByC_N(companyId, name);
510                            }
511    
512                            if (!role.getDescription().equals(description)) {
513                                    role.setDescription(description);
514    
515                                    roleLocalService.updateRole(role, false);
516                            }
517                    }
518                    catch (NoSuchRoleException nsre) {
519                            role = roleLocalService.addRole(
520                                    0, companyId, name, null, description, type);
521                    }
522    
523                    _systemRolesMap.put(companyId + name, role);
524            }
525    
526            protected void validate(
527                            long roleId, long companyId, long classNameId, String name)
528                    throws PortalException, SystemException {
529    
530                    if ((classNameId == PortalUtil.getClassNameId(Role.class)) &&
531                            ((Validator.isNull(name)) || (Validator.isNumber(name)) ||
532                             (name.indexOf(StringPool.COMMA) != -1) ||
533                             (name.indexOf(StringPool.STAR) != -1))) {
534    
535                            throw new RoleNameException();
536                    }
537    
538                    try {
539                            Role role = roleFinder.findByC_N(companyId, name);
540    
541                            if (role.getRoleId() != roleId) {
542                                    throw new DuplicateRoleException();
543                            }
544                    }
545                    catch (NoSuchRoleException nsge) {
546                    }
547            }
548    
549            private Map<String, Role> _systemRolesMap = new HashMap<String, Role>();
550    
551    }