001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.service.impl;
016    
017    import com.liferay.portal.DuplicateUserGroupException;
018    import com.liferay.portal.RequiredUserGroupException;
019    import com.liferay.portal.UserGroupNameException;
020    import com.liferay.portal.kernel.dao.orm.QueryUtil;
021    import com.liferay.portal.kernel.exception.PortalException;
022    import com.liferay.portal.kernel.exception.SystemException;
023    import com.liferay.portal.kernel.lar.PortletDataHandlerKeys;
024    import com.liferay.portal.kernel.lar.UserIdStrategy;
025    import com.liferay.portal.kernel.search.Hits;
026    import com.liferay.portal.kernel.search.Indexer;
027    import com.liferay.portal.kernel.search.IndexerRegistryUtil;
028    import com.liferay.portal.kernel.search.QueryConfig;
029    import com.liferay.portal.kernel.search.SearchContext;
030    import com.liferay.portal.kernel.search.Sort;
031    import com.liferay.portal.kernel.systemevent.SystemEvent;
032    import com.liferay.portal.kernel.util.CharPool;
033    import com.liferay.portal.kernel.util.OrderByComparator;
034    import com.liferay.portal.kernel.util.Validator;
035    import com.liferay.portal.kernel.workflow.WorkflowConstants;
036    import com.liferay.portal.model.Group;
037    import com.liferay.portal.model.GroupConstants;
038    import com.liferay.portal.model.ResourceConstants;
039    import com.liferay.portal.model.SystemEventConstants;
040    import com.liferay.portal.model.Team;
041    import com.liferay.portal.model.User;
042    import com.liferay.portal.model.UserGroup;
043    import com.liferay.portal.model.UserGroupConstants;
044    import com.liferay.portal.security.ldap.LDAPUserGroupTransactionThreadLocal;
045    import com.liferay.portal.security.permission.PermissionCacheUtil;
046    import com.liferay.portal.service.ServiceContext;
047    import com.liferay.portal.service.base.UserGroupLocalServiceBaseImpl;
048    import com.liferay.portal.util.PropsValues;
049    
050    import java.io.File;
051    import java.io.Serializable;
052    
053    import java.util.ArrayList;
054    import java.util.Date;
055    import java.util.HashMap;
056    import java.util.LinkedHashMap;
057    import java.util.List;
058    import java.util.Map;
059    
060    /**
061     * Provides the local service for accessing, adding, deleting, and updating user
062     * groups.
063     *
064     * @author Charles May
065     */
066    public class UserGroupLocalServiceImpl extends UserGroupLocalServiceBaseImpl {
067    
068            /**
069             * Adds the user groups to the group.
070             *
071             * @param  groupId the primary key of the group
072             * @param  userGroupIds the primary keys of the user groups
073             * @throws SystemException if a system exception occurred
074             */
075            @Override
076            public void addGroupUserGroups(long groupId, long[] userGroupIds)
077                    throws SystemException {
078    
079                    groupPersistence.addUserGroups(groupId, userGroupIds);
080    
081                    PermissionCacheUtil.clearCache();
082            }
083    
084            /**
085             * Adds the user groups to the team.
086             *
087             * @param  teamId the primary key of the team
088             * @param  userGroupIds the primary keys of the user groups
089             * @throws SystemException if a system exception occurred
090             */
091            @Override
092            public void addTeamUserGroups(long teamId, long[] userGroupIds)
093                    throws SystemException {
094    
095                    teamPersistence.addUserGroups(teamId, userGroupIds);
096    
097                    PermissionCacheUtil.clearCache();
098            }
099    
100            /**
101             * Adds a user group.
102             *
103             * <p>
104             * This method handles the creation and bookkeeping of the user group,
105             * including its resources, metadata, and internal data structures. It is
106             * not necessary to make subsequent calls to setup default groups and
107             * resources for the user group.
108             * </p>
109             *
110             * @param      userId the primary key of the user
111             * @param      companyId the primary key of the user group's company
112             * @param      name the user group's name
113             * @param      description the user group's description
114             * @return     the user group
115             * @throws     PortalException if the user group's information was invalid
116             * @throws     SystemException if a system exception occurred
117             * @deprecated As of 6.2.0, replaced by {@link #addUserGroup(long, long,
118             *             String, String, ServiceContext)}
119             */
120            @Override
121            public UserGroup addUserGroup(
122                            long userId, long companyId, String name, String description)
123                    throws PortalException, SystemException {
124    
125                    return addUserGroup(userId, companyId, name, description, null);
126            }
127    
128            /**
129             * Adds a user group.
130             *
131             * <p>
132             * This method handles the creation and bookkeeping of the user group,
133             * including its resources, metadata, and internal data structures. It is
134             * not necessary to make subsequent calls to setup default groups and
135             * resources for the user group.
136             * </p>
137             *
138             * @param  userId the primary key of the user
139             * @param  companyId the primary key of the user group's company
140             * @param  name the user group's name
141             * @param  description the user group's description
142             * @param  serviceContext the service context to be applied (optionally
143             *         <code>null</code>). Can set expando bridge attributes for the
144             *         user group.
145             * @return the user group
146             * @throws PortalException if the user group's information was invalid
147             * @throws SystemException if a system exception occurred
148             */
149            @Override
150            public UserGroup addUserGroup(
151                            long userId, long companyId, String name, String description,
152                            ServiceContext serviceContext)
153                    throws PortalException, SystemException {
154    
155                    // User group
156    
157                    Date now = new Date();
158    
159                    validate(0, companyId, name);
160    
161                    User user = userPersistence.findByPrimaryKey(userId);
162    
163                    long userGroupId = counterLocalService.increment();
164    
165                    UserGroup userGroup = userGroupPersistence.create(userGroupId);
166    
167                    if (serviceContext != null) {
168                            userGroup.setUuid(serviceContext.getUuid());
169                    }
170    
171                    userGroup.setCompanyId(companyId);
172                    userGroup.setUserId(user.getUserId());
173                    userGroup.setUserName(user.getFullName());
174    
175                    if (serviceContext != null) {
176                            userGroup.setCreateDate(serviceContext.getCreateDate(now));
177                            userGroup.setModifiedDate(serviceContext.getModifiedDate(now));
178                    }
179                    else {
180                            userGroup.setCreateDate(now);
181                            userGroup.setModifiedDate(now);
182                    }
183    
184                    userGroup.setParentUserGroupId(
185                            UserGroupConstants.DEFAULT_PARENT_USER_GROUP_ID);
186                    userGroup.setName(name);
187                    userGroup.setDescription(description);
188                    userGroup.setAddedByLDAPImport(
189                            LDAPUserGroupTransactionThreadLocal.isOriginatesFromLDAP());
190                    userGroup.setExpandoBridgeAttributes(serviceContext);
191    
192                    userGroupPersistence.update(userGroup);
193    
194                    // Group
195    
196                    groupLocalService.addGroup(
197                            userId, GroupConstants.DEFAULT_PARENT_GROUP_ID,
198                            UserGroup.class.getName(), userGroup.getUserGroupId(),
199                            GroupConstants.DEFAULT_LIVE_GROUP_ID, String.valueOf(userGroupId),
200                            null, 0, true, GroupConstants.DEFAULT_MEMBERSHIP_RESTRICTION, null,
201                            false, true, null);
202    
203                    // Resources
204    
205                    resourceLocalService.addResources(
206                            companyId, 0, userId, UserGroup.class.getName(),
207                            userGroup.getUserGroupId(), false, false, false);
208    
209                    // Indexer
210    
211                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
212                            UserGroup.class);
213    
214                    indexer.reindex(userGroup);
215    
216                    return userGroup;
217            }
218    
219            /**
220             * Clears all associations between the user and its user groups and clears
221             * the permissions cache.
222             *
223             * @param  userId the primary key of the user
224             * @throws SystemException if a system exception occurred
225             */
226            @Override
227            public void clearUserUserGroups(long userId) throws SystemException {
228                    userPersistence.clearUserGroups(userId);
229    
230                    PermissionCacheUtil.clearCache(userId);
231            }
232    
233            /**
234             * Copies the user group's layout to the user.
235             *
236             * @param      userGroupId the primary key of the user group
237             * @param      userId the primary key of the user
238             * @throws     PortalException if a user with the primary key could not be
239             *             found or if a portal exception occurred
240             * @throws     SystemException if a system exception occurred
241             * @deprecated As of 6.2.0
242             */
243            @Override
244            public void copyUserGroupLayouts(long userGroupId, long userId)
245                    throws PortalException, SystemException {
246    
247                    Map<String, String[]> parameterMap = getLayoutTemplatesParameters();
248    
249                    File[] files = exportLayouts(userGroupId, parameterMap);
250    
251                    try {
252                            importLayouts(userId, parameterMap, files[0], files[1]);
253                    }
254                    finally {
255                            if (files[0] != null) {
256                                    files[0].delete();
257                            }
258    
259                            if (files[1] != null) {
260                                    files[1].delete();
261                            }
262                    }
263            }
264    
265            /**
266             * Copies the user group's layouts to the users who are not already members
267             * of the user group.
268             *
269             * @param      userGroupId the primary key of the user group
270             * @param      userIds the primary keys of the users
271             * @throws     PortalException if any one of the users could not be found or
272             *             if a portal exception occurred
273             * @throws     SystemException if a system exception occurred
274             * @deprecated As of 6.1.0
275             */
276            @Override
277            public void copyUserGroupLayouts(long userGroupId, long[] userIds)
278                    throws PortalException, SystemException {
279    
280                    Map<String, String[]> parameterMap = getLayoutTemplatesParameters();
281    
282                    File[] files = exportLayouts(userGroupId, parameterMap);
283    
284                    try {
285                            for (long userId : userIds) {
286                                    if (!userGroupPersistence.containsUser(userGroupId, userId)) {
287                                            importLayouts(userId, parameterMap, files[0], files[1]);
288                                    }
289                            }
290                    }
291                    finally {
292                            if (files[0] != null) {
293                                    files[0].delete();
294                            }
295    
296                            if (files[1] != null) {
297                                    files[1].delete();
298                            }
299                    }
300            }
301    
302            /**
303             * Copies the user groups' layouts to the user.
304             *
305             * @param      userGroupIds the primary keys of the user groups
306             * @param      userId the primary key of the user
307             * @throws     PortalException if a user with the primary key could not be
308             *             found or if a portal exception occurred
309             * @throws     SystemException if a system exception occurred
310             * @deprecated As of 6.1.0
311             */
312            @Override
313            public void copyUserGroupLayouts(long[] userGroupIds, long userId)
314                    throws PortalException, SystemException {
315    
316                    for (long userGroupId : userGroupIds) {
317                            if (!userGroupPersistence.containsUser(userGroupId, userId)) {
318                                    copyUserGroupLayouts(userGroupId, userId);
319                            }
320                    }
321            }
322    
323            /**
324             * Deletes the user group.
325             *
326             * @param  userGroupId the primary key of the user group
327             * @return the deleted user group
328             * @throws PortalException if a user group with the primary key could not be
329             *         found or if the user group had a workflow in approved status
330             * @throws SystemException if a system exception occurred
331             */
332            @Override
333            public UserGroup deleteUserGroup(long userGroupId)
334                    throws PortalException, SystemException {
335    
336                    UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
337                            userGroupId);
338    
339                    return userGroupLocalService.deleteUserGroup(userGroup);
340            }
341    
342            /**
343             * Deletes the user group.
344             *
345             * @param  userGroup the user group
346             * @return the deleted user group
347             * @throws PortalException if the organization had a workflow in approved
348             *         status
349             * @throws SystemException if a system exception occurred
350             */
351            @Override
352            @SystemEvent(
353                    action = SystemEventConstants.ACTION_SKIP,
354                    type = SystemEventConstants.TYPE_DELETE)
355            public UserGroup deleteUserGroup(UserGroup userGroup)
356                    throws PortalException, SystemException {
357    
358                    LinkedHashMap<String, Object> params =
359                            new LinkedHashMap<String, Object>();
360    
361                    params.put("usersUserGroups", Long.valueOf(userGroup.getUserGroupId()));
362    
363                    int count = userFinder.countByKeywords(
364                            userGroup.getCompanyId(), null, WorkflowConstants.STATUS_APPROVED,
365                            params);
366    
367                    if (count > 0) {
368                            throw new RequiredUserGroupException();
369                    }
370    
371                    // Expando
372    
373                    expandoRowLocalService.deleteRows(userGroup.getUserGroupId());
374    
375                    // Group
376    
377                    Group group = userGroup.getGroup();
378    
379                    groupLocalService.deleteGroup(group);
380    
381                    // User group roles
382    
383                    userGroupGroupRoleLocalService.deleteUserGroupGroupRolesByUserGroupId(
384                            userGroup.getUserGroupId());
385    
386                    // Resources
387    
388                    resourceLocalService.deleteResource(
389                            userGroup.getCompanyId(), UserGroup.class.getName(),
390                            ResourceConstants.SCOPE_INDIVIDUAL, userGroup.getUserGroupId());
391    
392                    // User group
393    
394                    userGroupPersistence.remove(userGroup);
395    
396                    // Permission cache
397    
398                    PermissionCacheUtil.clearCache();
399    
400                    return userGroup;
401            }
402    
403            @Override
404            public void deleteUserGroups(long companyId)
405                    throws PortalException, SystemException {
406    
407                    List<UserGroup> userGroups = userGroupPersistence.findByCompanyId(
408                            companyId);
409    
410                    for (UserGroup userGroup : userGroups) {
411                            userGroupLocalService.deleteUserGroup(userGroup);
412                    }
413            }
414    
415            @Override
416            public UserGroup fetchUserGroup(long companyId, String name)
417                    throws SystemException {
418    
419                    return userGroupPersistence.fetchByC_N(companyId, name);
420            }
421    
422            /**
423             * Returns the user group with the name.
424             *
425             * @param  companyId the primary key of the user group's company
426             * @param  name the user group's name
427             * @return Returns the user group with the name
428             * @throws PortalException if a user group with the name could not be found
429             * @throws SystemException if a system exception occurred
430             */
431            @Override
432            public UserGroup getUserGroup(long companyId, String name)
433                    throws PortalException, SystemException {
434    
435                    return userGroupPersistence.findByC_N(companyId, name);
436            }
437    
438            /**
439             * Returns all the user groups belonging to the company.
440             *
441             * @param  companyId the primary key of the user groups' company
442             * @return the user groups belonging to the company
443             * @throws SystemException if a system exception occurred
444             */
445            @Override
446            public List<UserGroup> getUserGroups(long companyId)
447                    throws SystemException {
448    
449                    return userGroupPersistence.findByCompanyId(companyId);
450            }
451    
452            /**
453             * Returns all the user groups with the primary keys.
454             *
455             * @param  userGroupIds the primary keys of the user groups
456             * @return the user groups with the primary keys
457             * @throws PortalException if any one of the user groups could not be found
458             * @throws SystemException if a system exception occurred
459             */
460            @Override
461            public List<UserGroup> getUserGroups(long[] userGroupIds)
462                    throws PortalException, SystemException {
463    
464                    List<UserGroup> userGroups = new ArrayList<UserGroup>(
465                            userGroupIds.length);
466    
467                    for (long userGroupId : userGroupIds) {
468                            UserGroup userGroup = getUserGroup(userGroupId);
469    
470                            userGroups.add(userGroup);
471                    }
472    
473                    return userGroups;
474            }
475    
476            /**
477             * Returns an ordered range of all the user groups that match the keywords.
478             *
479             * <p>
480             * Useful when paginating results. Returns a maximum of <code>end -
481             * start</code> instances. <code>start</code> and <code>end</code> are not
482             * primary keys, they are indexes in the result set. Thus, <code>0</code>
483             * refers to the first result in the set. Setting both <code>start</code>
484             * and <code>end</code> to {@link
485             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
486             * result set.
487             * </p>
488             *
489             * @param  companyId the primary key of the user group's company
490             * @param  keywords the keywords (space separated), which may occur in the
491             *         user group's name or description (optionally <code>null</code>)
492             * @param  params the finder params (optionally <code>null</code>). For more
493             *         information see {@link
494             *         com.liferay.portal.service.persistence.UserGroupFinder}
495             * @param  start the lower bound of the range of user groups to return
496             * @param  end the upper bound of the range of user groups to return (not
497             *         inclusive)
498             * @param  obc the comparator to order the user groups (optionally
499             *         <code>null</code>)
500             * @return the matching user groups ordered by comparator <code>obc</code>
501             * @throws SystemException if a system exception occurred
502             * @see    com.liferay.portal.service.persistence.UserGroupFinder
503             */
504            @Override
505            public List<UserGroup> search(
506                            long companyId, String keywords,
507                            LinkedHashMap<String, Object> params, int start, int end,
508                            OrderByComparator obc)
509                    throws SystemException {
510    
511                    return userGroupFinder.findByKeywords(
512                            companyId, keywords, params, start, end, obc);
513            }
514    
515            /**
516             * Returns an ordered range of all the user groups that match the keywords,
517             * using the indexer. It is preferable to use this method instead of the
518             * non-indexed version whenever possible for performance reasons.
519             *
520             * <p>
521             * Useful when paginating results. Returns a maximum of <code>end -
522             * start</code> instances. <code>start</code> and <code>end</code> are not
523             * primary keys, they are indexes in the result set. Thus, <code>0</code>
524             * refers to the first result in the set. Setting both <code>start</code>
525             * and <code>end</code> to {@link
526             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
527             * result set.
528             * </p>
529             *
530             * @param  companyId the primary key of the user group's company
531             * @param  keywords the keywords (space separated), which may occur in the
532             *         user group's name or description (optionally <code>null</code>)
533             * @param  params the finder params (optionally <code>null</code>). For more
534             *         information see {@link
535             *         com.liferay.portlet.usergroupsadmin.util.UserGroupIndexer}
536             * @param  start the lower bound of the range of user groups to return
537             * @param  end the upper bound of the range of user groups to return (not
538             *         inclusive)
539             * @param  sort the field and direction by which to sort (optionally
540             *         <code>null</code>)
541             * @return the matching user groups ordered by sort
542             * @throws SystemException if a system exception occurred
543             * @see    com.liferay.portlet.usergroupsadmin.util.UserGroupIndexer
544             */
545            @Override
546            public Hits search(
547                            long companyId, String keywords,
548                            LinkedHashMap<String, Object> params, int start, int end, Sort sort)
549                    throws SystemException {
550    
551                    String name = null;
552                    String description = null;
553                    boolean andOperator = false;
554    
555                    if (Validator.isNotNull(keywords)) {
556                            name = keywords;
557                            description = keywords;
558                    }
559                    else {
560                            andOperator = true;
561                    }
562    
563                    if (params != null) {
564                            params.put("keywords", keywords);
565                    }
566    
567                    return search(
568                            companyId, name, description, params, andOperator, start, end,
569                            sort);
570            }
571    
572            /**
573             * Returns an ordered range of all the user groups that match the name and
574             * description. It is preferable to use this method instead of the
575             * non-indexed version whenever possible for performance reasons.
576             *
577             * <p>
578             * Useful when paginating results. Returns a maximum of <code>end -
579             * start</code> instances. <code>start</code> and <code>end</code> are not
580             * primary keys, they are indexes in the result set. Thus, <code>0</code>
581             * refers to the first result in the set. Setting both <code>start</code>
582             * and <code>end</code> to {@link
583             * com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full
584             * result set.
585             * </p>
586             *
587             * @param  companyId the primary key of the user group's company
588             * @param  name the user group's name (optionally <code>null</code>)
589             * @param  description the user group's description (optionally
590             *         <code>null</code>)
591             * @param  params the finder params (optionally <code>null</code>). For more
592             *         information see {@link
593             *         com.liferay.portlet.usergroupsadmin.util.UserGroupIndexer}
594             * @param  andSearch whether every field must match its keywords or just one
595             *         field
596             * @param  start the lower bound of the range of user groups to return
597             * @param  end the upper bound of the range of user groups to return (not
598             *         inclusive)
599             * @param  sort the field and direction by which to sort (optionally
600             *         <code>null</code>)
601             * @return the matching user groups ordered by sort
602             * @throws SystemException if a system exception occurred
603             * @see    com.liferay.portal.service.persistence.UserGroupFinder
604             */
605            @Override
606            public Hits search(
607                            long companyId, String name, String description,
608                            LinkedHashMap<String, Object> params, boolean andSearch, int start,
609                            int end, Sort sort)
610                    throws SystemException {
611    
612                    try {
613                            SearchContext searchContext = buildSearchContext(
614                                    companyId, name, description, params, andSearch, start, end,
615                                    sort);
616    
617                            Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
618                                    UserGroup.class);
619    
620                            return indexer.search(searchContext);
621                    }
622                    catch (Exception e) {
623                            throw new SystemException(e);
624                    }
625            }
626    
627            /**
628             * Returns the number of user groups that match the keywords
629             *
630             * @param  companyId the primary key of the user group's company
631             * @param  keywords the keywords (space separated), which may occur in the
632             *         user group's name or description (optionally <code>null</code>)
633             * @param  params the finder params (optionally <code>null</code>). For more
634             *         information see {@link
635             *         com.liferay.portal.service.persistence.UserGroupFinder}
636             * @return the number of matching user groups
637             * @throws SystemException if a system exception occurred
638             * @see    com.liferay.portal.service.persistence.UserGroupFinder
639             */
640            @Override
641            public int searchCount(
642                            long companyId, String keywords,
643                            LinkedHashMap<String, Object> params)
644                    throws SystemException {
645    
646                    if (!PropsValues.USER_GROUPS_INDEXER_ENABLED ||
647                            !PropsValues.USER_GROUPS_SEARCH_WITH_INDEX ||
648                            isUseCustomSQL(params)) {
649    
650                            return userGroupFinder.countByKeywords(companyId, keywords, params);
651                    }
652    
653                    String name = null;
654                    String description = null;
655                    boolean andOperator = false;
656    
657                    if (Validator.isNotNull(keywords)) {
658                            name = keywords;
659                            description = keywords;
660                    }
661                    else {
662                            andOperator = true;
663                    }
664    
665                    if (params != null) {
666                            params.put("keywords", keywords);
667                    }
668    
669                    try {
670                            Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
671                                    UserGroup.class);
672    
673                            SearchContext searchContext = buildSearchContext(
674                                    companyId, name, description, params, andOperator,
675                                    QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
676    
677                            Hits hits = indexer.search(searchContext);
678    
679                            return hits.getLength();
680                    }
681                    catch (Exception e) {
682                            throw new SystemException(e);
683                    }
684            }
685    
686            /**
687             * Sets the user groups associated with the user copying the user group
688             * layouts and removing and adding user group associations for the user as
689             * necessary.
690             *
691             * @param  userId the primary key of the user
692             * @param  userGroupIds the primary keys of the user groups
693             * @throws PortalException if a portal exception occurred
694             * @throws SystemException if a system exception occurred
695             */
696            @Override
697            public void setUserUserGroups(long userId, long[] userGroupIds)
698                    throws PortalException, SystemException {
699    
700                    if (PropsValues.USER_GROUPS_COPY_LAYOUTS_TO_USER_PERSONAL_SITE) {
701                            copyUserGroupLayouts(userGroupIds, userId);
702                    }
703    
704                    userPersistence.setUserGroups(userId, userGroupIds);
705    
706                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(User.class);
707    
708                    indexer.reindex(userId);
709    
710                    PermissionCacheUtil.clearCache(userId);
711            }
712    
713            /**
714             * Removes the user groups from the group.
715             *
716             * @param  groupId the primary key of the group
717             * @param  userGroupIds the primary keys of the user groups
718             * @throws SystemException if a system exception occurred
719             */
720            @Override
721            public void unsetGroupUserGroups(long groupId, long[] userGroupIds)
722                    throws SystemException {
723    
724                    List<Team> teams = teamPersistence.findByGroupId(groupId);
725    
726                    for (Team team : teams) {
727                            teamPersistence.removeUserGroups(team.getTeamId(), userGroupIds);
728                    }
729    
730                    userGroupGroupRoleLocalService.deleteUserGroupGroupRoles(
731                            userGroupIds, groupId);
732    
733                    groupPersistence.removeUserGroups(groupId, userGroupIds);
734    
735                    PermissionCacheUtil.clearCache();
736            }
737    
738            /**
739             * Removes the user groups from the team.
740             *
741             * @param  teamId the primary key of the team
742             * @param  userGroupIds the primary keys of the user groups
743             * @throws SystemException if a system exception occurred
744             */
745            @Override
746            public void unsetTeamUserGroups(long teamId, long[] userGroupIds)
747                    throws SystemException {
748    
749                    teamPersistence.removeUserGroups(teamId, userGroupIds);
750    
751                    PermissionCacheUtil.clearCache();
752            }
753    
754            /**
755             * Updates the user group.
756             *
757             * @param      companyId the primary key of the user group's company
758             * @param      userGroupId the primary key of the user group
759             * @param      name the user group's name
760             * @param      description the user group's description
761             * @return     the user group
762             * @throws     PortalException if a user group with the primary key could
763             *             not be found or if the new information was invalid
764             * @throws     SystemException if a system exception occurred
765             * @deprecated As of 6.2.0, replaced by {@link #updateUserGroup(long, long,
766             *             String, String, ServiceContext)}
767             */
768            @Override
769            public UserGroup updateUserGroup(
770                            long companyId, long userGroupId, String name, String description)
771                    throws PortalException, SystemException {
772    
773                    return updateUserGroup(companyId, userGroupId, name, description, null);
774            }
775    
776            /**
777             * Updates the user group.
778             *
779             * @param  companyId the primary key of the user group's company
780             * @param  userGroupId the primary key of the user group
781             * @param  name the user group's name
782             * @param  description the user group's description
783             * @param  serviceContext the service context to be applied (optionally
784             *         <code>null</code>). Can set expando bridge attributes for the
785             *         user group.
786             * @return the user group
787             * @throws PortalException if a user group with the primary key could not be
788             *         found or if the new information was invalid
789             * @throws SystemException if a system exception occurred
790             */
791            @Override
792            public UserGroup updateUserGroup(
793                            long companyId, long userGroupId, String name, String description,
794                            ServiceContext serviceContext)
795                    throws PortalException, SystemException {
796    
797                    // User group
798    
799                    validate(userGroupId, companyId, name);
800    
801                    UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
802                            userGroupId);
803    
804                    userGroup.setModifiedDate(new Date());
805                    userGroup.setName(name);
806                    userGroup.setDescription(description);
807                    userGroup.setExpandoBridgeAttributes(serviceContext);
808    
809                    userGroupPersistence.update(userGroup);
810    
811                    // Indexer
812    
813                    Indexer indexer = IndexerRegistryUtil.nullSafeGetIndexer(
814                            UserGroup.class);
815    
816                    indexer.reindex(userGroup);
817    
818                    return userGroup;
819            }
820    
821            protected SearchContext buildSearchContext(
822                    long companyId, String name, String description,
823                    LinkedHashMap<String, Object> params, boolean andSearch, int start,
824                    int end, Sort sort) {
825    
826                    SearchContext searchContext = new SearchContext();
827    
828                    searchContext.setAndSearch(andSearch);
829    
830                    Map<String, Serializable> attributes =
831                            new HashMap<String, Serializable>();
832    
833                    attributes.put("description", description);
834                    attributes.put("name", name);
835    
836                    searchContext.setAttributes(attributes);
837    
838                    searchContext.setCompanyId(companyId);
839                    searchContext.setEnd(end);
840    
841                    if (params != null) {
842                            String keywords = (String)params.remove("keywords");
843    
844                            if (Validator.isNotNull(keywords)) {
845                                    searchContext.setKeywords(keywords);
846                            }
847                    }
848    
849                    QueryConfig queryConfig = new QueryConfig();
850    
851                    queryConfig.setHighlightEnabled(false);
852                    queryConfig.setScoreEnabled(false);
853    
854                    searchContext.setQueryConfig(queryConfig);
855    
856                    if (sort != null) {
857                            searchContext.setSorts(sort);
858                    }
859    
860                    searchContext.setStart(start);
861    
862                    return searchContext;
863            }
864    
865            protected File[] exportLayouts(
866                            long userGroupId, Map<String, String[]> parameterMap)
867                    throws PortalException, SystemException {
868    
869                    File[] files = new File[2];
870    
871                    UserGroup userGroup = userGroupPersistence.findByPrimaryKey(
872                            userGroupId);
873    
874                    Group group = userGroup.getGroup();
875    
876                    if (userGroup.hasPrivateLayouts()) {
877                            files[0] = layoutLocalService.exportLayoutsAsFile(
878                                    group.getGroupId(), true, null, parameterMap, null, null);
879                    }
880    
881                    if (userGroup.hasPublicLayouts()) {
882                            files[1] = layoutLocalService.exportLayoutsAsFile(
883                                    group.getGroupId(), false, null, parameterMap, null, null);
884                    }
885    
886                    return files;
887            }
888    
889            protected Map<String, String[]> getLayoutTemplatesParameters() {
890                    Map<String, String[]> parameterMap =
891                            new LinkedHashMap<String, String[]>();
892    
893                    parameterMap.put(
894                            PortletDataHandlerKeys.CATEGORIES,
895                            new String[] {Boolean.TRUE.toString()});
896                    parameterMap.put(
897                            PortletDataHandlerKeys.DATA_STRATEGY,
898                            new String[] {PortletDataHandlerKeys.DATA_STRATEGY_MIRROR});
899                    parameterMap.put(
900                            PortletDataHandlerKeys.DELETE_MISSING_LAYOUTS,
901                            new String[] {Boolean.FALSE.toString()});
902                    parameterMap.put(
903                            PortletDataHandlerKeys.DELETE_PORTLET_DATA,
904                            new String[] {Boolean.FALSE.toString()});
905                    parameterMap.put(
906                            PortletDataHandlerKeys.LAYOUT_SET_SETTINGS,
907                            new String[] {Boolean.FALSE.toString()});
908                    parameterMap.put(
909                            PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE,
910                            new String[] {PortletDataHandlerKeys.
911                                    LAYOUTS_IMPORT_MODE_CREATED_FROM_PROTOTYPE});
912                    parameterMap.put(
913                            PortletDataHandlerKeys.LOGO,
914                            new String[] {Boolean.FALSE.toString()});
915                    parameterMap.put(
916                            PortletDataHandlerKeys.PERMISSIONS,
917                            new String[] {Boolean.TRUE.toString()});
918                    parameterMap.put(
919                            PortletDataHandlerKeys.PORTLET_CONFIGURATION,
920                            new String[] {Boolean.TRUE.toString()});
921                    parameterMap.put(
922                            PortletDataHandlerKeys.PORTLET_CONFIGURATION_ALL,
923                            new String[] {Boolean.TRUE.toString()});
924                    parameterMap.put(
925                            PortletDataHandlerKeys.PORTLET_DATA,
926                            new String[] {Boolean.TRUE.toString()});
927                    parameterMap.put(
928                            PortletDataHandlerKeys.PORTLET_DATA_ALL,
929                            new String[] {Boolean.TRUE.toString()});
930                    parameterMap.put(
931                            PortletDataHandlerKeys.PORTLET_SETUP_ALL,
932                            new String[] {Boolean.TRUE.toString()});
933                    parameterMap.put(
934                            PortletDataHandlerKeys.PORTLETS_MERGE_MODE,
935                            new String[] {PortletDataHandlerKeys.
936                                    PORTLETS_MERGE_MODE_ADD_TO_BOTTOM});
937                    parameterMap.put(
938                            PortletDataHandlerKeys.THEME_REFERENCE,
939                            new String[] {Boolean.TRUE.toString()});
940                    parameterMap.put(
941                            PortletDataHandlerKeys.UPDATE_LAST_PUBLISH_DATE,
942                            new String[] {Boolean.FALSE.toString()});
943                    parameterMap.put(
944                            PortletDataHandlerKeys.USER_ID_STRATEGY,
945                            new String[] {UserIdStrategy.CURRENT_USER_ID});
946    
947                    return parameterMap;
948            }
949    
950            protected void importLayouts(
951                            long userId, Map<String, String[]> parameterMap,
952                            File privateLayoutsFile, File publicLayoutsFile)
953                    throws PortalException, SystemException {
954    
955                    User user = userPersistence.findByPrimaryKey(userId);
956    
957                    long groupId = user.getGroupId();
958    
959                    if (privateLayoutsFile != null) {
960                            layoutLocalService.importLayouts(
961                                    userId, groupId, true, parameterMap, privateLayoutsFile);
962                    }
963    
964                    if (publicLayoutsFile != null) {
965                            layoutLocalService.importLayouts(
966                                    userId, groupId, false, parameterMap, publicLayoutsFile);
967                    }
968            }
969    
970            protected boolean isUseCustomSQL(LinkedHashMap<String, Object> params) {
971                    if ((params == null) || params.isEmpty()) {
972                            return false;
973                    }
974    
975                    return true;
976            }
977    
978            protected void validate(long userGroupId, long companyId, String name)
979                    throws PortalException, SystemException {
980    
981                    if (Validator.isNull(name) ||
982                            (name.indexOf(CharPool.COMMA) != -1) ||
983                            (name.indexOf(CharPool.STAR) != -1)) {
984    
985                            throw new UserGroupNameException();
986                    }
987    
988                    if (Validator.isNumber(name) &&
989                            !PropsValues.USER_GROUPS_NAME_ALLOW_NUMERIC) {
990    
991                            throw new UserGroupNameException();
992                    }
993    
994                    UserGroup userGroup = fetchUserGroup(companyId, name);
995    
996                    if ((userGroup != null) &&
997                            (userGroup.getUserGroupId() != userGroupId)) {
998    
999                            throw new DuplicateUserGroupException("{name=" + name + "}");
1000                    }
1001            }
1002    
1003    }