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