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  public class RoleLocalServiceImpl extends RoleLocalServiceBaseImpl {
63  
64      public Role addRole(
65              long userId, long companyId, String name, String description,
66              int type)
67          throws PortalException, SystemException {
68  
69          return addRole(userId, companyId, name, description, type, null, 0);
70      }
71  
72      public Role addRole(
73              long userId, long companyId, String name, String description,
74              int type, String className, long classPK)
75          throws PortalException, SystemException {
76  
77          // Role
78  
79          className = GetterUtil.getString(className);
80          long classNameId = PortalUtil.getClassNameId(className);
81  
82          validate(0, companyId, name);
83  
84          long roleId = counterLocalService.increment();
85  
86          if ((classNameId <= 0) || className.equals(Role.class.getName())) {
87              classNameId = PortalUtil.getClassNameId(Role.class);
88              classPK = roleId;
89          }
90  
91          Role role = rolePersistence.create(roleId);
92  
93          role.setCompanyId(companyId);
94          role.setClassNameId(classNameId);
95          role.setClassPK(classPK);
96          role.setName(name);
97          role.setDescription(description);
98          role.setType(type);
99  
100         rolePersistence.update(role, false);
101 
102         // Resources
103 
104         if (userId > 0) {
105             resourceLocalService.addResources(
106                 companyId, 0, userId, Role.class.getName(), role.getRoleId(),
107                 false, false, false);
108 
109             userLocalService.reIndex(userId);
110         }
111 
112         return role;
113     }
114 
115     public void addUserRoles(long userId, long[] roleIds)
116         throws SystemException {
117 
118         userPersistence.addRoles(userId, roleIds);
119 
120         userLocalService.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         userLocalService.reIndex(userId);
412 
413         PermissionCacheUtil.clearCache();
414     }
415 
416     public void unsetUserRoles(long userId, long[] roleIds)
417         throws PortalException, SystemException {
418 
419         roleIds = EnterpriseAdminUtil.removeRequiredRoles(userId, roleIds);
420 
421         userPersistence.removeRoles(userId, roleIds);
422 
423         userLocalService.reIndex(userId);
424 
425         PermissionCacheUtil.clearCache();
426     }
427 
428     public Role updateRole(
429             long roleId, String name, Map<Locale, String> localeTitlesMap,
430             String description, String subtype)
431         throws PortalException, SystemException {
432 
433         Role role = rolePersistence.findByPrimaryKey(roleId);
434 
435         validate(roleId, role.getCompanyId(), name);
436 
437         if (PortalUtil.isSystemRole(role.getName())) {
438             name = role.getName();
439             subtype = null;
440         }
441 
442         role.setName(name);
443         role.setDescription(description);
444         role.setSubtype(subtype);
445 
446         setLocalizedAttributes(role, localeTitlesMap);
447 
448         rolePersistence.update(role, false);
449 
450         return role;
451     }
452 
453     protected void checkSystemRole(
454             long companyId, String name, String description, int type)
455         throws PortalException, SystemException {
456 
457         Role role = _systemRolesMap.get(companyId + name);
458 
459         try {
460             if (role == null) {
461                 role = rolePersistence.findByC_N(companyId, name);
462             }
463 
464             if (!role.getDescription().equals(description)) {
465                 role.setDescription(description);
466 
467                 roleLocalService.updateRole(role, false);
468             }
469         }
470         catch (NoSuchRoleException nsre) {
471             role = roleLocalService.addRole(
472                 0, companyId, name, description, type);
473         }
474 
475         _systemRolesMap.put(companyId + name, role);
476     }
477 
478     protected void setLocalizedAttributes(
479         Role role, Map<Locale, String> localeTitlesMap) {
480 
481         if (localeTitlesMap == null) {
482             return;
483         }
484 
485         ClassLoader portalClassLoader = PortalClassLoaderUtil.getClassLoader();
486 
487         Thread currentThread = Thread.currentThread();
488 
489         ClassLoader contextClassLoader = currentThread.getContextClassLoader();
490 
491         try {
492             if (contextClassLoader != portalClassLoader) {
493                 currentThread.setContextClassLoader(portalClassLoader);
494             }
495 
496             Locale[] locales = LanguageUtil.getAvailableLocales();
497 
498             for (Locale locale : locales) {
499                 String title = localeTitlesMap.get(locale);
500 
501                 role.setTitle(title, locale);
502             }
503         }
504         finally {
505             if (contextClassLoader != portalClassLoader) {
506                 currentThread.setContextClassLoader(contextClassLoader);
507             }
508         }
509     }
510 
511     protected void validate(long roleId, long companyId, String name)
512         throws PortalException, SystemException {
513 
514         if ((Validator.isNull(name)) || (Validator.isNumber(name)) ||
515             (name.indexOf(StringPool.COMMA) != -1) ||
516             (name.indexOf(StringPool.STAR) != -1)) {
517 
518             throw new RoleNameException();
519         }
520 
521         try {
522             Role role = roleFinder.findByC_N(companyId, name);
523 
524             if (role.getRoleId() != roleId) {
525                 throw new DuplicateRoleException();
526             }
527         }
528         catch (NoSuchRoleException nsge) {
529         }
530     }
531 
532     private Map<String, Role> _systemRolesMap = new HashMap<String, Role>();
533 
534 }