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