1   /**
2    * Copyright (c) 2000-2010 Liferay, Inc. All rights reserved.
3    *
4    * This library is free software; you can redistribute it and/or modify it under
5    * the terms of the GNU Lesser General Public License as published by the Free
6    * Software Foundation; either version 2.1 of the License, or (at your option)
7    * any later version.
8    *
9    * This library is distributed in the hope that it will be useful, but WITHOUT
10   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11   * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
12   * details.
13   */
14  
15  package com.liferay.portal.service.impl;
16  
17  import com.liferay.portal.DuplicateRoleException;
18  import com.liferay.portal.NoSuchRoleException;
19  import com.liferay.portal.RequiredRoleException;
20  import com.liferay.portal.RoleNameException;
21  import com.liferay.portal.kernel.annotation.Propagation;
22  import com.liferay.portal.kernel.annotation.Transactional;
23  import com.liferay.portal.kernel.cache.ThreadLocalCachable;
24  import com.liferay.portal.kernel.exception.PortalException;
25  import com.liferay.portal.kernel.exception.SystemException;
26  import com.liferay.portal.kernel.search.Indexer;
27  import com.liferay.portal.kernel.search.IndexerRegistryUtil;
28  import com.liferay.portal.kernel.util.GetterUtil;
29  import com.liferay.portal.kernel.util.OrderByComparator;
30  import com.liferay.portal.kernel.util.StringPool;
31  import com.liferay.portal.kernel.util.StringUtil;
32  import com.liferay.portal.kernel.util.Validator;
33  import com.liferay.portal.model.Group;
34  import com.liferay.portal.model.Layout;
35  import com.liferay.portal.model.ResourceConstants;
36  import com.liferay.portal.model.Role;
37  import com.liferay.portal.model.RoleConstants;
38  import com.liferay.portal.model.Team;
39  import com.liferay.portal.model.User;
40  import com.liferay.portal.security.permission.PermissionCacheUtil;
41  import com.liferay.portal.service.base.RoleLocalServiceBaseImpl;
42  import com.liferay.portal.util.PortalUtil;
43  import com.liferay.portal.util.PropsUtil;
44  import com.liferay.portlet.enterpriseadmin.util.EnterpriseAdminUtil;
45  
46  import java.util.ArrayList;
47  import java.util.Collections;
48  import java.util.HashMap;
49  import java.util.LinkedHashMap;
50  import java.util.List;
51  import java.util.Locale;
52  import java.util.Map;
53  
54  /**
55   * <a href="RoleLocalServiceImpl.java.html"><b><i>View Source</i></b></a>
56   *
57   * @author Brian Wing Shun Chan
58   */
59  public class RoleLocalServiceImpl extends RoleLocalServiceBaseImpl {
60  
61      public Role addRole(
62              long userId, long companyId, String name,
63              Map<Locale, String> titleMap, String description, int type)
64          throws PortalException, SystemException {
65  
66          return addRole(
67              userId, companyId, name, titleMap, description, type, null, 0);
68      }
69  
70      public Role addRole(
71              long userId, long companyId, String name,
72              Map<Locale, String> titleMap, String description,
73              int type, String className, long classPK)
74          throws PortalException, SystemException {
75  
76          // Role
77  
78          className = GetterUtil.getString(className);
79          long classNameId = PortalUtil.getClassNameId(className);
80  
81          long roleId = counterLocalService.increment();
82  
83          if ((classNameId <= 0) || className.equals(Role.class.getName())) {
84              classNameId = PortalUtil.getClassNameId(Role.class);
85              classPK = roleId;
86          }
87  
88          validate(0, companyId, classNameId, name);
89  
90          Role role = rolePersistence.create(roleId);
91  
92          role.setCompanyId(companyId);
93          role.setClassNameId(classNameId);
94          role.setClassPK(classPK);
95          role.setName(name);
96          role.setTitleMap(titleMap);
97          role.setDescription(description);
98          role.setType(type);
99  
100         rolePersistence.update(role, false);
101 
102         // Resources
103 
104         if (userId > 0) {
105             resourceLocalService.addResources(
106                 companyId, 0, userId, Role.class.getName(), role.getRoleId(),
107                 false, false, false);
108 
109             Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
110 
111             indexer.reindex(userId);
112         }
113 
114         return role;
115     }
116 
117     public void addUserRoles(long userId, long[] roleIds)
118         throws PortalException, SystemException {
119 
120         userPersistence.addRoles(userId, roleIds);
121 
122         Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
123 
124         indexer.reindex(userId);
125 
126         PermissionCacheUtil.clearCache();
127     }
128 
129     @Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
130     public void checkSystemRoles(long companyId)
131         throws PortalException, SystemException {
132 
133         for (Role role : roleFinder.findBySystem(companyId)) {
134             _systemRolesMap.put(companyId + role.getName(), role);
135         }
136 
137         // Regular roles
138 
139         String[] systemRoles = PortalUtil.getSystemRoles();
140 
141         for (String name : systemRoles) {
142             String description = PropsUtil.get(
143                 "system.role." + StringUtil.replace(name, " ", ".") +
144                     ".description");
145             int type = RoleConstants.TYPE_REGULAR;
146 
147             checkSystemRole(companyId, name, description, type);
148         }
149 
150         // Community roles
151 
152         String[] systemCommunityRoles = PortalUtil.getSystemCommunityRoles();
153 
154         for (String name : systemCommunityRoles) {
155             String description = PropsUtil.get(
156                 "system.community.role." +
157                     StringUtil.replace(name, " ", ".") + ".description");
158             int type = RoleConstants.TYPE_COMMUNITY;
159 
160             checkSystemRole(companyId, name, description, type);
161         }
162 
163         // Organization roles
164 
165         String[] systemOrganizationRoles =
166             PortalUtil.getSystemOrganizationRoles();
167 
168         for (String name : systemOrganizationRoles) {
169             String description = PropsUtil.get(
170                 "system.organization.role." +
171                     StringUtil.replace(name, " ", ".") + ".description");
172             int type = RoleConstants.TYPE_ORGANIZATION;
173 
174             checkSystemRole(companyId, name, description, type);
175         }
176     }
177 
178     public void deleteRole(long roleId)
179         throws PortalException, SystemException {
180 
181         Role role = rolePersistence.findByPrimaryKey(roleId);
182 
183         if (PortalUtil.isSystemRole(role.getName())) {
184             throw new RequiredRoleException();
185         }
186 
187         // Resources
188 
189         String className = role.getClassName();
190         long classNameId = role.getClassNameId();
191 
192         if ((classNameId <= 0) || className.equals(Role.class.getName())) {
193             resourceLocalService.deleteResource(
194                 role.getCompanyId(), Role.class.getName(),
195                 ResourceConstants.SCOPE_INDIVIDUAL, role.getRoleId());
196         }
197 
198         if ((role.getType() == RoleConstants.TYPE_COMMUNITY) ||
199             (role.getType() == RoleConstants.TYPE_ORGANIZATION)) {
200 
201             userGroupRoleLocalService.deleteUserGroupRolesByRoleId(
202                 role.getRoleId());
203 
204             userGroupGroupRoleLocalService.deleteUserGroupGroupRolesByRoleId(
205                 role.getRoleId());
206         }
207 
208         // Role
209 
210         rolePersistence.remove(role);
211 
212         // Permission cache
213 
214         PermissionCacheUtil.clearCache();
215     }
216 
217     public Role getDefaultGroupRole(long groupId)
218         throws PortalException, SystemException {
219 
220         Group group = groupPersistence.findByPrimaryKey(groupId);
221 
222         if (group.isLayout()) {
223             Layout layout = layoutLocalService.getLayout(group.getClassPK());
224 
225             group = layout.getGroup();
226         }
227 
228         Role role = null;
229 
230         if (group.isCommunity() || group.isLayoutPrototype() ||
231             group.isLayoutSetPrototype()) {
232 
233             role = getRole(
234                 group.getCompanyId(), RoleConstants.COMMUNITY_MEMBER);
235         }
236         else if (group.isCompany()) {
237             role = getRole(group.getCompanyId(), RoleConstants.ADMINISTRATOR);
238         }
239         else if (group.isOrganization()) {
240             role = getRole(
241                 group.getCompanyId(), RoleConstants.ORGANIZATION_MEMBER);
242         }
243         else if (group.isUser() || group.isUserGroup()) {
244             role = getRole(group.getCompanyId(), RoleConstants.POWER_USER);
245         }
246 
247         return role;
248     }
249 
250     public List<Role> getGroupRoles(long groupId) throws SystemException {
251         return groupPersistence.getRoles(groupId);
252     }
253 
254     public Map<String, List<String>> getResourceRoles(
255             long companyId, String name, int scope, String primKey)
256         throws SystemException {
257 
258         return roleFinder.findByC_N_S_P(companyId, name, scope, primKey);
259     }
260 
261     public Role getRole(long roleId) throws PortalException, SystemException {
262         return rolePersistence.findByPrimaryKey(roleId);
263     }
264 
265     public Role getRole(long companyId, String name)
266         throws PortalException, SystemException {
267 
268         Role role = _systemRolesMap.get(companyId + name);
269 
270         if (role != null) {
271             return role;
272         }
273 
274         return rolePersistence.findByC_N(companyId, name);
275     }
276 
277     public List<Role> getRoles(long companyId) throws SystemException {
278         return rolePersistence.findByCompanyId(companyId);
279     }
280 
281     public List<Role> getRoles(long[] roleIds)
282         throws PortalException, SystemException {
283 
284         List<Role> roles = new ArrayList<Role>(roleIds.length);
285 
286         for (long roleId : roleIds) {
287             Role role = getRole(roleId);
288 
289             roles.add(role);
290         }
291 
292         return roles;
293     }
294 
295     public List<Role> getRoles(int type, String subtype)
296         throws SystemException {
297 
298         return rolePersistence.findByT_S(type, subtype);
299     }
300 
301     public List<Role> getSubtypeRoles(String subtype) throws SystemException {
302         return rolePersistence.findBySubtype(subtype);
303     }
304 
305     public int getSubtypeRolesCount(String subtype) throws SystemException {
306         return rolePersistence.countBySubtype(subtype);
307     }
308 
309     public Role getTeamRole(long companyId, long teamId)
310         throws PortalException, SystemException {
311 
312         long classNameId = PortalUtil.getClassNameId(Team.class);
313 
314         return rolePersistence.findByC_C_C(companyId, classNameId, teamId);
315     }
316 
317     public List<Role> getUserGroupGroupRoles(long userId, long groupId)
318         throws SystemException {
319 
320         return roleFinder.findByUserGroupGroupRole(userId, groupId);
321     }
322 
323     public List<Role> getUserGroupRoles(long userId, long groupId)
324         throws SystemException {
325 
326         return roleFinder.findByUserGroupRole(userId, groupId);
327     }
328 
329     public List<Role> getUserRelatedRoles(long userId, long groupId)
330         throws SystemException {
331 
332         return roleFinder.findByU_G(userId, groupId);
333     }
334 
335     public List<Role> getUserRelatedRoles(long userId, long[] groupIds)
336         throws SystemException {
337 
338         return roleFinder.findByU_G(userId, groupIds);
339     }
340 
341     public List<Role> getUserRelatedRoles(long userId, List<Group> groups)
342         throws SystemException {
343 
344         if ((groups == null) || groups.isEmpty()) {
345             return Collections.EMPTY_LIST;
346         }
347 
348         return roleFinder.findByU_G(userId, groups);
349     }
350 
351     public List<Role> getUserRoles(long userId) throws SystemException {
352         return userPersistence.getRoles(userId);
353     }
354 
355     public boolean hasUserRole(long userId, long roleId)
356         throws SystemException {
357 
358         return userPersistence.containsRole(userId, roleId);
359     }
360 
361     /**
362      * Returns true if the user has the regular role.
363      *
364      * @return true if the user has the regular role
365      */
366     @ThreadLocalCachable
367     public boolean hasUserRole(
368             long userId, long companyId, String name, boolean inherited)
369         throws PortalException, SystemException {
370 
371         Role role = rolePersistence.findByC_N(companyId, name);
372 
373         if (role.getType() != RoleConstants.TYPE_REGULAR) {
374             throw new IllegalArgumentException(name + " is not a regular role");
375         }
376 
377         if (inherited) {
378             if (roleFinder.countByR_U(role.getRoleId(), userId) > 0) {
379                 return true;
380             }
381             else {
382                 return false;
383             }
384         }
385         else {
386             return userPersistence.containsRole(userId, role.getRoleId());
387         }
388     }
389 
390     /**
391      * Returns true if the user has any one of the specified regular roles.
392      *
393      * @return true if the user has the regular role
394      */
395     public boolean hasUserRoles(
396             long userId, long companyId, String[] names, boolean inherited)
397         throws PortalException, SystemException {
398 
399         for (int i = 0; i < names.length; i++) {
400             if (hasUserRole(userId, companyId, names[i], inherited)) {
401                 return true;
402             }
403         }
404 
405         return false;
406     }
407 
408     public List<Role> search(
409             long companyId, String name, String description, Integer[] types,
410             int start, int end, OrderByComparator obc)
411         throws SystemException {
412 
413         return search(
414             companyId, name, description, types,
415             new LinkedHashMap<String, Object>(), start, end, obc);
416     }
417 
418     public List<Role> search(
419             long companyId, String name, String description, Integer[] types,
420             LinkedHashMap<String, Object> params, int start, int end,
421             OrderByComparator obc)
422         throws SystemException {
423 
424         return roleFinder.findByC_N_D_T(
425             companyId, name, description, types, params, start, end, obc);
426     }
427 
428     public int searchCount(
429             long companyId, String name, String description, Integer[] types)
430         throws SystemException {
431 
432         return searchCount(
433             companyId, name, description, types,
434             new LinkedHashMap<String, Object>());
435     }
436 
437     public int searchCount(
438             long companyId, String name, String description, Integer[] types,
439             LinkedHashMap<String, Object> params)
440         throws SystemException {
441 
442         return roleFinder.countByC_N_D_T(
443             companyId, name, description, types, params);
444     }
445 
446     public void setUserRoles(long userId, long[] roleIds)
447         throws PortalException, SystemException {
448 
449         roleIds = EnterpriseAdminUtil.addRequiredRoles(userId, roleIds);
450 
451         userPersistence.setRoles(userId, roleIds);
452 
453         Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
454 
455         indexer.reindex(userId);
456 
457         PermissionCacheUtil.clearCache();
458     }
459 
460     public void unsetUserRoles(long userId, long[] roleIds)
461         throws PortalException, SystemException {
462 
463         roleIds = EnterpriseAdminUtil.removeRequiredRoles(userId, roleIds);
464 
465         userPersistence.removeRoles(userId, roleIds);
466 
467         Indexer indexer = IndexerRegistryUtil.getIndexer(User.class);
468 
469         indexer.reindex(userId);
470 
471         PermissionCacheUtil.clearCache();
472     }
473 
474     public Role updateRole(
475             long roleId, String name, Map<Locale, String> titleMap,
476             String description, String subtype)
477         throws PortalException, SystemException {
478 
479         Role role = rolePersistence.findByPrimaryKey(roleId);
480 
481         validate(roleId, role.getCompanyId(), role.getClassNameId(), name);
482 
483         if (PortalUtil.isSystemRole(role.getName())) {
484             name = role.getName();
485             subtype = null;
486         }
487 
488         role.setName(name);
489         role.setTitleMap(titleMap);
490         role.setDescription(description);
491         role.setSubtype(subtype);
492 
493         rolePersistence.update(role, false);
494 
495         return role;
496     }
497 
498     protected void checkSystemRole(
499             long companyId, String name, String description, int type)
500         throws PortalException, SystemException {
501 
502         Role role = _systemRolesMap.get(companyId + name);
503 
504         try {
505             if (role == null) {
506                 role = rolePersistence.findByC_N(companyId, name);
507             }
508 
509             if (!role.getDescription().equals(description)) {
510                 role.setDescription(description);
511 
512                 roleLocalService.updateRole(role, false);
513             }
514         }
515         catch (NoSuchRoleException nsre) {
516             role = roleLocalService.addRole(
517                 0, companyId, name, null, description, type);
518         }
519 
520         _systemRolesMap.put(companyId + name, role);
521     }
522 
523     protected void validate(
524             long roleId, long companyId, long classNameId, String name)
525         throws PortalException, SystemException {
526 
527         if ((classNameId == PortalUtil.getClassNameId(Role.class)) &&
528             ((Validator.isNull(name)) || (Validator.isNumber(name)) ||
529              (name.indexOf(StringPool.COMMA) != -1) ||
530              (name.indexOf(StringPool.STAR) != -1))) {
531 
532             throw new RoleNameException();
533         }
534 
535         try {
536             Role role = roleFinder.findByC_N(companyId, name);
537 
538             if (role.getRoleId() != roleId) {
539                 throw new DuplicateRoleException();
540             }
541         }
542         catch (NoSuchRoleException nsge) {
543         }
544     }
545 
546     private Map<String, Role> _systemRolesMap = new HashMap<String, Role>();
547 
548 }