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