1   /**
2    * Copyright (c) 2000-2008 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.service.impl;
24  
25  import com.liferay.portal.DuplicateRoleException;
26  import com.liferay.portal.NoSuchRoleException;
27  import com.liferay.portal.PortalException;
28  import com.liferay.portal.RequiredRoleException;
29  import com.liferay.portal.RoleNameException;
30  import com.liferay.portal.SystemException;
31  import com.liferay.portal.kernel.util.OrderByComparator;
32  import com.liferay.portal.kernel.util.StringPool;
33  import com.liferay.portal.kernel.util.StringUtil;
34  import com.liferay.portal.kernel.util.Validator;
35  import com.liferay.portal.model.Group;
36  import com.liferay.portal.model.ResourceConstants;
37  import com.liferay.portal.model.Role;
38  import com.liferay.portal.model.impl.RoleImpl;
39  import com.liferay.portal.security.permission.PermissionCacheUtil;
40  import com.liferay.portal.service.base.RoleLocalServiceBaseImpl;
41  import com.liferay.portal.util.PortalUtil;
42  import com.liferay.portal.util.PropsUtil;
43  
44  import java.util.LinkedHashMap;
45  import java.util.List;
46  import java.util.Map;
47  
48  /**
49   * <a href="RoleLocalServiceImpl.java.html"><b><i>View Source</i></b></a>
50   *
51   * @author Brian Wing Shun Chan
52   *
53   */
54  public class RoleLocalServiceImpl extends RoleLocalServiceBaseImpl {
55  
56      public Role addRole(
57              long userId, long companyId, String name, String description,
58              int type)
59          throws PortalException, SystemException {
60  
61          return addRole(userId, companyId, name, description, type, null, 0);
62      }
63  
64      public Role addRole(
65              long userId, long companyId, String name, String description,
66              int type, String className, long classPK)
67          throws PortalException, SystemException {
68  
69          // Role
70  
71          long classNameId = PortalUtil.getClassNameId(className);
72  
73          validate(0, companyId, name);
74  
75          long roleId = counterLocalService.increment();
76  
77          Role role = rolePersistence.create(roleId);
78  
79          role.setCompanyId(companyId);
80          role.setClassNameId(classNameId);
81          role.setClassPK(classPK);
82          role.setName(name);
83          role.setDescription(description);
84          role.setType(type);
85  
86          rolePersistence.update(role, false);
87  
88          // Resources
89  
90          if (userId > 0) {
91              resourceLocalService.addResources(
92                  companyId, 0, userId, Role.class.getName(), role.getRoleId(),
93                  false, false, false);
94          }
95  
96          return role;
97      }
98  
99      public void addUserRoles(long userId, long[] roleIds)
100         throws SystemException {
101 
102         userPersistence.addRoles(userId, roleIds);
103 
104         PermissionCacheUtil.clearCache();
105     }
106 
107     public void checkSystemRoles(long companyId)
108         throws PortalException, SystemException {
109 
110         // Regular roles
111 
112         String[] systemRoles = PortalUtil.getSystemRoles();
113 
114         for (int i = 0; i < systemRoles.length; i++) {
115             String roleName = systemRoles[i];
116             String roleDescription = PropsUtil.get(
117                 "system.role." + StringUtil.replace(roleName, " ", ".") +
118                     ".description");
119             int roleType = RoleImpl.TYPE_REGULAR;
120 
121             try {
122                 Role role = roleFinder.findByC_N(companyId, roleName);
123 
124                 if (!role.getDescription().equals(roleDescription)) {
125                     role.setDescription(roleDescription);
126 
127                     rolePersistence.update(role, false);
128                 }
129             }
130             catch (NoSuchRoleException nsre) {
131                 addRole(0, companyId, roleName, roleDescription, roleType);
132             }
133         }
134 
135         // Community roles
136 
137         String[] systemCommunityRoles = PortalUtil.getSystemCommunityRoles();
138 
139         for (int i = 0; i < systemCommunityRoles.length; i++) {
140             String roleName = systemCommunityRoles[i];
141             String roleDescription = PropsUtil.get(
142                 "system.community.role." +
143                     StringUtil.replace(roleName, " ", ".") + ".description");
144             int roleType = RoleImpl.TYPE_COMMUNITY;
145 
146             try {
147                 Role role = roleFinder.findByC_N(companyId, roleName);
148 
149                 if (!role.getDescription().equals(roleDescription)) {
150                     role.setDescription(roleDescription);
151 
152                     rolePersistence.update(role, false);
153                 }
154             }
155             catch (NoSuchRoleException nsre) {
156                 addRole(0, companyId, roleName, roleDescription, roleType);
157             }
158         }
159 
160         // Organization roles
161 
162         String[] systemOrganizationRoles =
163             PortalUtil.getSystemOrganizationRoles();
164 
165         for (int i = 0; i < systemOrganizationRoles.length; i++) {
166             String roleName = systemOrganizationRoles[i];
167             String roleDescription = PropsUtil.get(
168                 "system.organization.role." +
169                     StringUtil.replace(roleName, " ", ".") + ".description");
170             int roleType = RoleImpl.TYPE_ORGANIZATION;
171 
172             try {
173                 Role role = roleFinder.findByC_N(companyId, roleName);
174 
175                 if (!role.getDescription().equals(roleDescription)) {
176                     role.setDescription(roleDescription);
177 
178                     rolePersistence.update(role, false);
179                 }
180             }
181             catch (NoSuchRoleException nsre) {
182                 addRole(0, companyId, roleName, roleDescription, roleType);
183             }
184         }
185     }
186 
187     public void deleteRole(long roleId)
188         throws PortalException, SystemException {
189 
190         Role role = rolePersistence.findByPrimaryKey(roleId);
191 
192         if (PortalUtil.isSystemRole(role.getName())) {
193             throw new RequiredRoleException();
194         }
195 
196         // Resources
197 
198         if ((role.getClassNameId() <= 0) && (role.getClassPK() <= 0)) {
199             resourceLocalService.deleteResource(
200                 role.getCompanyId(), Role.class.getName(),
201                 ResourceConstants.SCOPE_INDIVIDUAL, role.getRoleId());
202         }
203 
204         if ((role.getType() == RoleImpl.TYPE_COMMUNITY) ||
205             (role.getType() == RoleImpl.TYPE_ORGANIZATION)) {
206 
207             userGroupRoleLocalService.deleteUserGroupRolesByRoleId(
208                 role.getRoleId());
209         }
210 
211         // Role
212 
213         rolePersistence.remove(roleId);
214 
215         // Permission cache
216 
217         PermissionCacheUtil.clearCache();
218     }
219 
220     public Role getGroupRole(long companyId, long groupId)
221         throws PortalException, SystemException {
222 
223         long classNameId = PortalUtil.getClassNameId(Group.class);
224 
225         return rolePersistence.findByC_C_C(companyId, classNameId, groupId);
226     }
227 
228     public List<Role> getGroupRoles(long groupId) throws SystemException {
229         return groupPersistence.getRoles(groupId);
230     }
231 
232     public Map<String, List<String>> getResourceRoles(
233             long companyId, String name, int scope, String primKey)
234         throws SystemException {
235 
236         return roleFinder.findByC_N_S_P(companyId, name, scope, primKey);
237     }
238 
239     public Role getRole(long roleId) throws PortalException, SystemException {
240         return rolePersistence.findByPrimaryKey(roleId);
241     }
242 
243     public Role getRole(long companyId, String name)
244         throws PortalException, SystemException {
245 
246         return roleFinder.findByC_N(companyId, name);
247     }
248 
249     public List<Role> getRoles(long companyId) throws SystemException {
250         return rolePersistence.findByCompanyId(companyId);
251     }
252 
253     public List<Role> getUserGroupRoles(long userId, long groupId)
254         throws SystemException {
255 
256         return roleFinder.findByUserGroupRole(userId, groupId);
257     }
258 
259     public List<Role> getUserRelatedRoles(long userId, long groupId)
260         throws SystemException {
261 
262         return roleFinder.findByU_G(userId, groupId);
263     }
264 
265     public List<Role> getUserRelatedRoles(long userId, long[] groupIds)
266         throws SystemException {
267 
268         return roleFinder.findByU_G(userId, groupIds);
269     }
270 
271     public List<Role> getUserRelatedRoles(long userId, List<Group> groups)
272         throws SystemException {
273 
274         return roleFinder.findByU_G(userId, groups);
275     }
276 
277     public List<Role> getUserRoles(long userId) throws SystemException {
278         return userPersistence.getRoles(userId);
279     }
280 
281     public boolean hasUserRole(long userId, long roleId)
282         throws SystemException {
283 
284         return userPersistence.containsRole(userId, roleId);
285     }
286 
287     /**
288      * Returns true if the user has the role.
289      *
290      * @param       userId the user id of the user
291      * @param       companyId the company id of the company
292      * @param       name the name of the role
293      * @param       inherited boolean value for whether to check roles inherited
294      *              from the community, organization, location, or user group
295      * @return      true if the user has the role
296      */
297     public boolean hasUserRole(
298             long userId, long companyId, String name, boolean inherited)
299         throws PortalException, SystemException {
300 
301         Role role = roleFinder.findByC_N(companyId, name);
302 
303         if (inherited) {
304             if (roleFinder.countByR_U(role.getRoleId(), userId) > 0) {
305                 return true;
306             }
307             else {
308                 return false;
309             }
310         }
311         else {
312             return userPersistence.containsRole(userId, role.getRoleId());
313         }
314     }
315 
316     /**
317      * Returns true if the user has any one of the specified roles.
318      *
319      * @param       userId the user id of the user
320      * @param       companyId the company id of the company
321      * @param       names an array of role names
322      * @param       inherited boolean value for whether to check roles inherited
323      *              from the community, organization, location, or user group
324      * @return      true if the user has the role
325      */
326     public boolean hasUserRoles(
327             long userId, long companyId, String[] names, boolean inherited)
328         throws PortalException, SystemException {
329 
330         for (int i = 0; i < names.length; i++) {
331             if (hasUserRole(userId, companyId, names[i], inherited)) {
332                 return true;
333             }
334         }
335 
336         return false;
337     }
338 
339     public List<Role> search(
340             long companyId, String name, String description, Integer type,
341             int start, int end, OrderByComparator obc)
342         throws SystemException {
343 
344         return search(
345             companyId, name, description, type,
346             new LinkedHashMap<String, Object>(), start, end, obc);
347     }
348 
349     public List<Role> search(
350             long companyId, String name, String description, Integer type,
351             LinkedHashMap<String, Object> params, int start, int end,
352             OrderByComparator obc)
353         throws SystemException {
354 
355         return roleFinder.findByC_N_D_T(
356             companyId, name, description, type, params, start, end, obc);
357     }
358 
359     public int searchCount(
360             long companyId, String name, String description, Integer type)
361         throws SystemException {
362 
363         return searchCount(
364             companyId, name, description, type,
365             new LinkedHashMap<String, Object>());
366     }
367 
368     public int searchCount(
369             long companyId, String name, String description, Integer type,
370             LinkedHashMap<String, Object> params)
371         throws SystemException {
372 
373         return roleFinder.countByC_N_D_T(
374             companyId, name, description, type, params);
375     }
376 
377     public void setUserRoles(long userId, long[] roleIds)
378         throws SystemException {
379 
380         userPersistence.setRoles(userId, roleIds);
381 
382         PermissionCacheUtil.clearCache();
383     }
384 
385     public void unsetUserRoles(long userId, long[] roleIds)
386         throws SystemException {
387 
388         userPersistence.removeRoles(userId, roleIds);
389 
390         PermissionCacheUtil.clearCache();
391     }
392 
393     public Role updateRole(long roleId, String name, String description)
394         throws PortalException, SystemException {
395 
396         Role role = rolePersistence.findByPrimaryKey(roleId);
397 
398         validate(roleId, role.getCompanyId(), name);
399 
400         if (PortalUtil.isSystemRole(role.getName())) {
401             throw new RequiredRoleException();
402         }
403 
404         role.setName(name);
405         role.setDescription(description);
406 
407         rolePersistence.update(role, false);
408 
409         return role;
410     }
411 
412     protected void validate(long roleId, long companyId, String name)
413         throws PortalException, SystemException {
414 
415         if ((Validator.isNull(name)) || (Validator.isNumber(name)) ||
416             (name.indexOf(StringPool.COMMA) != -1) ||
417             (name.indexOf(StringPool.STAR) != -1)) {
418 
419             throw new RoleNameException();
420         }
421 
422         try {
423             Role role = roleFinder.findByC_N(companyId, name);
424 
425             if (role.getRoleId() != roleId) {
426                 throw new DuplicateRoleException();
427             }
428         }
429         catch (NoSuchRoleException nsge) {
430         }
431     }
432 
433 }