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