--- /dev/null
+/*******************************************************************************
+ * Copyright � Igor Barma, Alexandre Desoubeaux, Christian Martel, Eric Brun, Mathieu Amblard, Gwenael Gevet, Pierre Guillot, 2012
+ * Copyright Alexandre Desoubeaux, Christian Martel, Cedric Lecarpentier, Alexandre Lefevre, Marc Salvat 2014-2016
+ * Copyright Alexandre Desoubeaux, Christian Martel, Cedric Lecarpentier, Marc Salvat, Marc Suarez, Harifetra Ramamonjy 2017
+ *
+ * This file is part of the work and learning management system Pentila Nero.
+ *
+ * Pentila Nero is free software. You can redistribute it and/or modify since
+ * you respect the terms of either (at least one of the both license) :
+ * - under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ * - the CeCILL-C as published by CeCILL-C; either version 1 of the
+ * License, or any later version
+ * - the GNU Lesser General Public License as published by the
+ * Free Software Foundation, either version 3 of the license,
+ * or (at your option) any later version.
+ *
+ * There are special exceptions to the terms and conditions of the
+ * licenses as they are applied to this software. View the full text of
+ * the exception in file LICENSE-PROJECT.txt in the directory of this software
+ * distribution.
+ *
+ * Pentila Nero is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * Licenses for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * and the CeCILL-C and the GNU Lesser General Public License along with
+ * Pentila Nero. If not, see :
+ * <http://www.gnu.org/licenses/> and
+ * <http://www.cecill.info/licences.fr.html>.
+ ******************************************************************************/
+/**
+ * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ */
+
+package com.sample.jsp.portlet;
+
+import java.io.IOException;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.ResourceBundle;
+import java.util.Set;
+
+import javax.naming.NamingException;
+import javax.portlet.ActionRequest;
+import javax.portlet.ActionResponse;
+import javax.portlet.GenericPortlet;
+import javax.portlet.PortletException;
+import javax.portlet.PortletRequestDispatcher;
+import javax.portlet.RenderRequest;
+import javax.portlet.RenderResponse;
+import javax.portlet.ResourceRequest;
+import javax.portlet.ResourceResponse;
+import javax.servlet.http.HttpServletResponse;
+
+import com.liferay.contacts.util.ListFicheFactory;
+import com.liferay.contacts.util.ProxyFiche;
+import com.liferay.portal.DuplicateGroupException;
+import com.liferay.portal.GroupNameException;
+import com.liferay.portal.kernel.dao.orm.QueryUtil;
+import com.liferay.portal.kernel.exception.PortalException;
+import com.liferay.portal.kernel.exception.SystemException;
+import com.liferay.portal.kernel.json.JSONArray;
+import com.liferay.portal.kernel.json.JSONFactoryUtil;
+import com.liferay.portal.kernel.json.JSONObject;
+import com.liferay.portal.kernel.log.Log;
+import com.liferay.portal.kernel.log.LogFactoryUtil;
+import com.liferay.portal.kernel.util.ContentTypes;
+import com.liferay.portal.kernel.util.OrderByComparator;
+import com.liferay.portal.kernel.util.ParamUtil;
+import com.liferay.portal.kernel.util.StringPool;
+import com.liferay.portal.kernel.util.WebKeys;
+import com.liferay.portal.kernel.workflow.WorkflowConstants;
+import com.liferay.portal.model.Group;
+import com.liferay.portal.model.GroupConstants;
+import com.liferay.portal.model.Role;
+import com.liferay.portal.model.RoleConstants;
+import com.liferay.portal.model.User;
+import com.liferay.portal.service.GroupLocalServiceUtil;
+import com.liferay.portal.service.MembershipRequestLocalServiceUtil;
+import com.liferay.portal.service.OrganizationLocalServiceUtil;
+import com.liferay.portal.service.RoleLocalServiceUtil;
+import com.liferay.portal.service.ServiceContext;
+import com.liferay.portal.service.ServiceContextFactory;
+import com.liferay.portal.service.UserGroupRoleLocalServiceUtil;
+import com.liferay.portal.service.UserLocalServiceUtil;
+import com.liferay.portal.theme.ThemeDisplay;
+import com.liferay.portal.util.PortalUtil;
+import com.liferay.portal.util.comparator.UserLastNameComparator;
+import com.pentila.entSavoie.ENTRoleUtilFactory;
+import com.pentila.entSavoie.ENTRolesConstants;
+import com.pentila.entSavoie.amis.model.Relationship;
+import com.pentila.entSavoie.amis.service.RelationshipLocalServiceUtil;
+import com.pentila.entSavoie.carnetDAdresses.model.Liste;
+import com.pentila.entSavoie.carnetDAdresses.service.ListeLocalServiceUtil;
+import com.pentila.entSavoie.communityInfos.model.CommunityInfos;
+import com.pentila.entSavoie.communityInfos.service.CommunityInfosLocalServiceUtil;
+import com.pentila.entSavoie.communityInfos.service.GroupInfosLocalServiceUtil;
+import com.pentila.entSavoie.directory.OrganizationFinderServiceUtil;
+import com.pentila.entSavoie.internalMessaging.IMUtils;
+import com.pentila.entSavoie.utils.ENTMainUtilsLocalServiceUtil;
+import com.pentila.entSavoie.utils.GroupCacheUtil;
+import com.pentila.entSavoie.utils.PermissionsUtils;
+import com.pentila.entSavoie.utils.PortletConstant;
+
+/**
+ * <a href="JSPPortlet.java.html"><b><i>View Source</i></b></a>
+ *
+ * @author Brian Wing Shun Chan
+ *
+ */
+public class JSPPortlet extends GenericPortlet {
+
+ public void init() throws PortletException {
+ editJSP = getInitParameter("edit-jsp");
+ helpJSP = getInitParameter("help-jsp");
+ viewJSP = getInitParameter("view-jsp");
+ }
+
+ public void doDispatch(
+ RenderRequest renderRequest, RenderResponse renderResponse)
+ throws IOException, PortletException {
+
+ String jspPage = renderRequest.getParameter("jspPage");
+
+ if (jspPage != null) {
+ include(jspPage, renderRequest, renderResponse);
+ }
+ else {
+ super.doDispatch(renderRequest, renderResponse);
+ }
+ }
+
+ public void doEdit(
+ RenderRequest renderRequest, RenderResponse renderResponse)
+ throws IOException, PortletException {
+
+ if (renderRequest.getPreferences() == null) {
+ super.doEdit(renderRequest, renderResponse);
+ }
+ else {
+ include(editJSP, renderRequest, renderResponse);
+ }
+ }
+
+ public void doHelp(
+ RenderRequest renderRequest, RenderResponse renderResponse)
+ throws IOException, PortletException {
+
+ include(helpJSP, renderRequest, renderResponse);
+ }
+
+ public void doView(
+ RenderRequest renderRequest, RenderResponse renderResponse)
+ throws IOException, PortletException {
+
+ include(viewJSP, renderRequest, renderResponse);
+ }
+
+ @Override
+ public void serveResource(ResourceRequest resourceRequest, ResourceResponse resourceResponse)
+ throws PortletException, IOException {
+
+
+ final String cmd = ParamUtil.getString(resourceRequest, "cmd");
+
+ HttpServletResponse httpResponse = PortalUtil.getHttpServletResponse(resourceResponse);
+ httpResponse.setContentType(ContentTypes.APPLICATION_JSON);
+
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+ result.put("success", false);
+
+ User user = null;
+
+ try {
+ user = PortalUtil.getUser(resourceRequest);
+ } catch (Exception e) {
+ _log.error(e);
+ }
+
+ ResourceBundle messages = ResourceBundle.getBundle("content.Language", user.getLocale());
+
+ if (cmd.equals("addCommunaute")) {
+ try {
+ result = this.createCommunaute(resourceRequest, messages);
+ } catch (DuplicateGroupException e) {
+ result.put("errorType", messages.getString("erreur-groupe-deja-existant"));
+ _log.error(e);
+ } catch (GroupNameException e){
+ result.put("errorType", messages.getString("erreur-groupe-nom-non-valide"));
+ _log.error(e);
+ } catch (Exception e) {
+ _log.error(e);
+ }
+
+ }
+ else if (cmd.equals("isGroupNameValid")) {
+ try {
+ Group existingGroup = GroupLocalServiceUtil.fetchGroup(user.getCompanyId(), ParamUtil.getString(resourceRequest, "title"));
+ if(existingGroup == null ){
+ // no group exist with this name
+ result.put("success", true);
+ }
+ else{
+ result.put("error", messages.getString("erreur-groupe-deja-existant"));
+ }
+ } catch (Exception e) {
+ _log.error(e);
+ }
+
+ }
+ // Approbation d'une creation
+ else if (cmd.equals("approved")) {
+ try {
+ result = this.validateGroup(resourceRequest, messages);
+ } catch (Exception e) {
+ _log.error(e);
+ }
+ }
+ // Refus d'une creation
+ else if (cmd.equals("refused")) {
+ try {
+ result = this.refusedGroup(resourceRequest, messages);
+ } catch (Exception e) {
+ _log.error(e);
+ }
+ }
+ // Approbation de la demande de prolongation de durée de vie
+ else if (cmd.equals("approvedRequestLifeExtension")) {
+ try {
+ result = this.approvedRequestLifeExtension(resourceRequest, messages);
+ } catch (Exception e) {
+ _log.error(e);
+ }
+ }
+ // Refus de la demande de prolongation de durée de vie
+ else if (cmd.equals("refusedRequestLifeExtension")) {
+ try {
+ result = this.refusedRequestLifeExtension(resourceRequest, messages);
+ } catch (Exception e) {
+ _log.error(e);
+ }
+ }
+ // Annulation d'une demande de creation
+ else if (cmd.equals("delete")) {
+ try {
+ final long groupId = Long.valueOf(ParamUtil.getString(resourceRequest, "groupId"));
+ Group grp = GroupLocalServiceUtil.getGroup(groupId);
+
+ GroupLocalServiceUtil.deleteGroup(grp);
+
+ // Delete associated community info
+ CommunityInfos ci = CommunityInfosLocalServiceUtil.getCommunityInfosByGroupId(groupId);
+ CommunityInfosLocalServiceUtil.deleteCommunityInfos(ci);
+
+ result.put("success", true);
+
+ GroupCacheUtil.removeGroupCache(user);
+ } catch (Exception e) {
+ _log.error(e);
+ }
+ }
+ // join to a group
+ else if (cmd.equals("joinGrp")) {
+ try {
+ final long groupId = Long.valueOf(ParamUtil.getString(resourceRequest, "groupId"));
+ String comments = ParamUtil.getString(resourceRequest, "comments");
+
+ Group grp = GroupLocalServiceUtil.getGroup(groupId);
+
+ if(grp.getType()==GroupConstants.TYPE_SITE_OPEN) {
+ // on inscrit la personne
+ UserLocalServiceUtil.addGroupUsers( groupId, new long[] {user.getUserId()});
+ GroupCacheUtil.removeGroupCache(user.getUserId());
+ result.put("success", true);
+ }
+ else if(grp.getType()==GroupConstants.TYPE_SITE_RESTRICTED) {
+ // Membership request
+ MembershipRequestLocalServiceUtil.addMembershipRequest(user.getUserId(), groupId, comments, new ServiceContext());
+
+ // Notification
+ Group currentGroup = GroupLocalServiceUtil.getGroup(groupId);
+ String subject = messages.getString("demande-adhesion-au-groupe") + " " + currentGroup.getName();
+ String content = messages.getString("vous-avez-une-demande-adhesion-au-groupe") + " " + currentGroup.getName() + ".<br /> <br />";
+ if (!comments.isEmpty()) {
+ content += messages.getString("commentaire-du-demandeur") + " <br /> " + comments;
+ }
+
+ content += "<br /> <br /> <a href=\"#/group" + currentGroup.getFriendlyURL() + "?p_p_id=gestionGroups_WAR_gestionGroupsportlet&tab=1\">" + messages.getString("acces-a-l-interface-de-validation") + " </a>";
+ result = this.notifyGroupAdministrators(user, groupId, subject, content, false);
+ }
+ } catch (Exception e) {
+ _log.error(e);
+ }
+ }
+ // Suppression definitive d'un groupe
+ else if (cmd.equals("deleteGroup")) {
+ // une suppression de groupe revient a passer son status à 3 !!!!!!
+ try {
+ //supprime le groupe
+ final long groupId = Long.valueOf(ParamUtil.getString(resourceRequest, "groupId"));
+
+ CommunityInfos ci = CommunityInfosLocalServiceUtil.getCommunityInfosByGroupId(groupId);
+ ci.setStatus(3);
+ CommunityInfosLocalServiceUtil.updateCommunityInfos(ci);
+
+ GroupCacheUtil.removeGroupCache(user);
+
+ result.put("success", true);
+ } catch (Exception e) {
+ _log.error(e);
+ }
+ }
+ // Desinscription du groupe
+ else if (cmd.equals("unsubscribeGroup")) {
+ try {
+ //supprime le groupe
+ final long groupId = Long.valueOf(ParamUtil.getString(resourceRequest, "groupId"));
+
+ UserLocalServiceUtil.unsetGroupUsers(groupId, new long[] {user.getUserId()}, new ServiceContext());
+ GroupCacheUtil.removeGroupCache(user);
+
+ result.put("success", true);
+ } catch (Exception e) {
+ _log.error(e);
+ }
+ }
+ else if (cmd.equals("updatePermissions")) {
+ try {
+ PermissionsUtils.updatePermissionAtelier(user);
+ result.put("success", true);
+ } catch (Exception e) {
+ _log.error(e);
+ }
+ }
+
+ httpResponse.getWriter().write(result.toString());
+
+ }
+
+ public void processAction(
+ ActionRequest actionRequest, ActionResponse actionResponse)
+ throws IOException, PortletException {
+
+ }
+
+ protected void include(
+ String path, RenderRequest renderRequest,
+ RenderResponse renderResponse)
+ throws IOException, PortletException {
+
+ PortletRequestDispatcher portletRequestDispatcher =
+ getPortletContext().getRequestDispatcher(path);
+
+ if (portletRequestDispatcher == null) {
+ _log.error(path + " is not a valid include");
+ }
+ else {
+ portletRequestDispatcher.include(renderRequest, renderResponse);
+ }
+ }
+
+ /**
+ * Create personal group
+ */
+ private JSONObject createCommunaute(ResourceRequest resourceRequest,
+ ResourceBundle messages) throws PortalException, SystemException {
+
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ SimpleDateFormat classicDateFormat = new SimpleDateFormat("yyyy-MM-dd");
+ boolean moderationNeeded = true;
+ User user = PortalUtil.getUser(resourceRequest);
+
+ Role adminGrpRole = ENTRoleUtilFactory.getInstance(user.getCompanyId()).getRole(ENTRolesConstants.GROUP_ADMIN);
+ Role parentRole = RoleLocalServiceUtil.getRole(user.getCompanyId(), ENTRolesConstants.NATIONAL_2);
+ Role eleveRole = RoleLocalServiceUtil.getRole(user.getCompanyId(), ENTRolesConstants.NATIONAL_1);
+ Role ownerRole = RoleLocalServiceUtil.getRole(user.getCompanyId(), RoleConstants.SITE_OWNER);
+ Role managerRole = RoleLocalServiceUtil.getRole(user.getCompanyId(), RoleConstants.SITE_ADMINISTRATOR);
+
+ Boolean isGrpAdmin = RoleLocalServiceUtil.hasUserRole(user.getUserId(), adminGrpRole.getRoleId());
+ Boolean isEleve = RoleLocalServiceUtil.hasUserRole(user.getUserId(), eleveRole.getRoleId());
+ Boolean isParent = RoleLocalServiceUtil.hasUserRole(user.getUserId(), parentRole.getRoleId());
+
+ // Get group parameters
+ final String name = ParamUtil.getString(resourceRequest, "title");
+ String description = ParamUtil.getString(resourceRequest, "desc");
+ final int type = ParamUtil.getInteger(resourceRequest, "type");
+ final int scope = ParamUtil.getInteger(resourceRequest, "scope");
+ final int politic = ParamUtil.getInteger(resourceRequest, "politic");
+ final boolean viewInCDT = ParamUtil.getBoolean(resourceRequest, "viewInCDT");
+ final boolean groupContactList = ParamUtil.getBoolean(resourceRequest, "groupContactList");
+ final boolean isNewsActive = ParamUtil.getBoolean(resourceRequest, "isNewsActive", true);
+ final boolean isDocumentsActive = ParamUtil.getBoolean(resourceRequest, "isDocumentsActive", true);
+ final boolean isForumActive = ParamUtil.getBoolean(resourceRequest, "isForumActive", true);
+ final boolean isWikiActive = ParamUtil.getBoolean(resourceRequest, "isWikiActive", true);
+ final boolean isEtherpadActive = ParamUtil.getBoolean(resourceRequest, "isEtherpadActive", true);
+
+ if (!isNewsActive && !isDocumentsActive && !isForumActive && !isWikiActive && !isEtherpadActive) {
+ _log.error("All applications are disabled");
+ result.put("needModeration", false);
+ result.put("success", false);
+ return result;
+ }
+
+ // Parse expiration date
+ Date expirationDate = null;
+ try {
+ expirationDate = classicDateFormat.parse(resourceRequest.getParameter("expDate"));
+ } catch (ParseException e1) {}
+
+ // Create the group
+ ServiceContext serviceContext = ServiceContextFactory.getInstance(Group.class.getName(), resourceRequest);
+ serviceContext.setAddGroupPermissions(true);
+ Group group = GroupLocalServiceUtil.addGroup(user.getUserId(), null, 0, name, description, type, "", true, true, serviceContext);
+
+ ThemeDisplay themeDisplay = (ThemeDisplay)resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);
+
+ CommunityInfos ci = CommunityInfosLocalServiceUtil.getCommunityInfosByGroupId(group.getGroupId());
+
+ ci.setCreationDate(new Date());
+ ci.setCreatorId(user.getUserId());
+ ci.setExpirationDate(expirationDate);
+ ci.setGroupId(group.getGroupId());
+ ci.setScope(scope);
+ ci.setPolitic(politic);
+ ci.setViewInCDT(viewInCDT);
+ ci.setGroupContactList(groupContactList);
+ ci.setIsNewsActive(isNewsActive);
+ ci.setIsDocumentsActive(isDocumentsActive);
+ ci.setIsForumActive(isForumActive);
+ ci.setIsWikiActive(isWikiActive);
+ ci.setIsEtherpadActive(isEtherpadActive);
+
+ // Default home page if not news
+ if (!isNewsActive) {
+ List<String> pagesAvailabled = new ArrayList<String>();
+
+ if (isDocumentsActive) {
+ pagesAvailabled.add(PortletConstant.CARTABLE_PORTLET_ID);
+ }
+ if (isForumActive) {
+ pagesAvailabled.add(PortletConstant.FORUM_GROUP_ID);
+ }
+ if (isWikiActive) {
+ pagesAvailabled.add(PortletConstant.WIKI_GROUP_ID);
+ }
+ if (isEtherpadActive) {
+ pagesAvailabled.add(PortletConstant.ETHERPAD_PORTLET_ID);
+ }
+ // Check if the default page was already changed to an other application or if the news service is not available anymore (default service when not changed)
+ try {
+ String view = GroupInfosLocalServiceUtil.getDefaultViewFromGroup(group.getGroupId());
+ if(view != null && !view.equals("")){
+ if (!pagesAvailabled.contains(view)) {
+ GroupInfosLocalServiceUtil.setGroupDefaultView(group.getGroupId(), pagesAvailabled.get(0));
+ }
+ }
+ else if (!isNewsActive) {
+ GroupInfosLocalServiceUtil.setGroupDefaultView(group.getGroupId(), pagesAvailabled.get(0));
+ }
+ } catch (SystemException e) {
+ _log.error("No GroupInfos with groupId="+group.getGroupId(), e);
+ }
+ }
+
+ try {
+ ci.setEtabId(OrganizationFinderServiceUtil.getEtabRatachement(user).getOrganizationId());
+ } catch (Exception e1) {
+ _log.error("Error when setting community infos schoolId");
+ ci.setEtabId(0);
+ }
+
+ // Moderation ?
+ if (isEleve || isParent) {
+ moderationNeeded = true;
+ ci.setStatus(1);
+ result = this.notifyGroupCreation(user, group.getGroupId(), description, messages, themeDisplay, true);
+ }
+ else {
+ moderationNeeded = false;
+ ci.setStatus(0);
+ result = this.notifyGroupCreation(user, group.getGroupId(), description, messages, themeDisplay, false);
+ }
+
+ CommunityInfosLocalServiceUtil.updateCommunityInfos(ci);
+
+ // Get members
+ Set<Long> orgs = new HashSet<Long>();
+
+ Set<Long> membresFinal = new HashSet<Long>();
+ Set<Long> adminUsers = new HashSet<Long>();
+ Set<ProxyFiche> lesFiches = new HashSet<ProxyFiche>();
+ final String membresString = ParamUtil.getString(resourceRequest, "membres");
+ JSONArray membres = JSONFactoryUtil.createJSONArray(membresString);
+
+ for (int i=0; i<membres.length(); i++) {
+
+ JSONObject jobj = membres.getJSONObject(i);
+ String mbrtype = jobj.getString("type");
+
+ Boolean isAdmin = jobj.getBoolean("admin");
+
+ if (!mbrtype.equals("")) {
+
+ List<ProxyFiche> tempListProxy = null;
+
+ // cas d'une liste
+ if (mbrtype.equals("all")) {
+ tempListProxy = ListFicheFactory.createAllContacts(user);
+ }
+ else if (mbrtype.equals("perso")) {
+ tempListProxy = ListFicheFactory.createPersoContacts(user);
+ }
+ else if (mbrtype.equals("inst")) {
+ tempListProxy = ListFicheFactory.createInstContacts(user);
+ }
+ else if (mbrtype.equals("local")) {
+ long listId = jobj.getLong("listId");
+ Liste userListe = ListeLocalServiceUtil.getListe(listId);
+ tempListProxy = ListFicheFactory.createUserListContacts(user, userListe);
+ }
+ else if (mbrtype.equals("amis")) {
+ long listId = jobj.getLong("listId");
+ List<Relationship> listRel = RelationshipLocalServiceUtil.getRelationshipByUserIdFriendFolderIdStateId(user.getUserId(), listId, 2, QueryUtil.ALL_POS, QueryUtil.ALL_POS);
+ List<Long> lesAmis = new ArrayList<Long>();
+ for(Relationship rel : listRel){
+ lesAmis.add(rel.getFriendId());
+ }
+ tempListProxy = ListFicheFactory.createAmisContacts(user, lesAmis);
+ }
+ else if (mbrtype.equals("allAmis")) {
+ List<Relationship> listAllRel = RelationshipLocalServiceUtil.getRelationshipByUserIdStateId(user.getUserId(), 2, QueryUtil.ALL_POS, QueryUtil.ALL_POS);
+ List<Long> lesAmis = new ArrayList<Long>();
+ for(Relationship rel : listAllRel){
+ lesAmis.add(rel.getFriendId());
+ }
+ tempListProxy = ListFicheFactory.createAmisContacts(user, lesAmis);
+ }
+ else if (mbrtype.equals("search")) {
+ // Organization
+ String roleId = jobj.getString("roleId");
+ String orgId = jobj.getString("orgId");
+ long listId = jobj.getLong("listId");
+
+ Long roleIdL = new Long(0);
+ Long orgIdL = new Long(0);
+
+ if (!roleId.equals("")) {
+ roleIdL = Long.valueOf(roleId);
+ }
+ if (!orgId.equals("")) {
+ orgIdL = Long.valueOf(orgId);
+ }
+
+ tempListProxy = ListFicheFactory.createSearchContacts(user, orgIdL, roleIdL, listId);
+ }
+ else if (mbrtype.equals("organization")) {
+ orgs.add(Long.valueOf(jobj.getString("id")));
+ }
+
+ if (tempListProxy != null) {
+ if (isAdmin) {
+ for (ProxyFiche f : tempListProxy) {
+ String typeUser = f.getType();
+ if (typeUser.equals("user")) {
+ long idUser = Long.valueOf(f.getId());
+ if (!adminUsers.contains(idUser))
+ adminUsers.add(idUser);
+ } else {
+ long relUserId = Long.valueOf(f.getRelUserId());
+ if (relUserId!=0) {
+ if (!adminUsers.contains(relUserId))
+ adminUsers.add(relUserId);
+ }
+ }
+ }
+ }
+ lesFiches.addAll(tempListProxy);
+ }
+ } else {
+ // Specific user
+ if (isAdmin) {
+ adminUsers.add(Long.valueOf(jobj.getString("id")));
+ }
+ lesFiches.add(new ProxyFiche(user, UserLocalServiceUtil.getUser(Long.valueOf(jobj.getString("id")))));
+ }
+ }
+
+ for (ProxyFiche f : lesFiches) {
+ String typeUser = f.getType();
+ if (typeUser.equals("user")) {
+ long idUser = Long.valueOf(f.getId());
+ if (!membresFinal.contains(idUser))
+ membresFinal.add(idUser);
+ } else {
+ long relUserId = Long.valueOf(f.getRelUserId());
+ if (relUserId!=0) {
+ if (!membresFinal.contains(relUserId))
+ membresFinal.add(relUserId);
+ }
+ }
+ }
+
+ // Add members to the group and empty their group cache so that they see the new group immediately
+ long[] addUserIds = new long[membresFinal.size()] ;
+ int i = 0;
+ for (Long memberId : membresFinal){
+ addUserIds[i] = memberId;
+ i++;
+ GroupCacheUtil.removeGroupCache(memberId);
+ }
+ UserLocalServiceUtil.addGroupUsers(group.getGroupId(), addUserIds);
+
+
+ // Give admin users the group admin role
+ long[] managerUserIds = new long[adminUsers.size()] ;
+ i = 0;
+ for (Long l : adminUsers){
+ managerUserIds[i] = l;
+ i++;
+ }
+ UserGroupRoleLocalServiceUtil.addUserGroupRoles(managerUserIds, group.getGroupId(), ownerRole.getRoleId());
+
+ // If creator is groupAdmin => give him group admin role
+ if (isGrpAdmin) {
+ UserGroupRoleLocalServiceUtil.addUserGroupRoles(user.getUserId(), group.getGroupId(), new long[] {managerRole.getRoleId()} );
+ }
+
+ // Organizations
+ long[] orgIds = new long[orgs.size()] ;
+ int j = 0;
+ for (Long l : orgs){
+ orgIds[j] = l;
+ j++;
+ }
+ OrganizationLocalServiceUtil.addGroupOrganizations(group.getGroupId(), orgIds);
+
+ GroupCacheUtil.removeGroupCache(user);
+
+ result.put("needModeration", moderationNeeded);
+
+ return result;
+ }
+
+ // Validation d'un groupe et notification aux administrateurs et owner du groupe
+ private JSONObject validateGroup(ResourceRequest resourceRequest, ResourceBundle messages) throws NamingException, Exception {
+
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ final User validator = PortalUtil.getUser(resourceRequest);
+ final long groupId = Long.valueOf(ParamUtil.getString(resourceRequest, "groupId"));
+
+ try {
+ // Add the validator to the group and give him the group administration right
+ Role managerRole = RoleLocalServiceUtil.getRole(validator.getCompanyId(), RoleConstants.SITE_ADMINISTRATOR);
+ UserLocalServiceUtil.addGroupUsers(groupId, new long[] {validator.getUserId()});
+ UserGroupRoleLocalServiceUtil.addUserGroupRoles(validator.getUserId(), groupId, new long[] {managerRole.getRoleId()});
+
+ // Enable the group
+ CommunityInfos ci = CommunityInfosLocalServiceUtil.getCommunityInfosByGroupId(groupId);
+ ci.setStatus(0);
+ CommunityInfosLocalServiceUtil.updateCommunityInfos(ci);
+
+ // Notification
+ Group currentGroup = GroupLocalServiceUtil.getGroup(groupId);
+ String subject = messages.getString("validation-du-groupe") + " " + currentGroup.getName();
+ String content= messages.getString("la-creation-du-groupe") + " " + currentGroup.getName() + " " + messages.getString("a-ete-validee") + validator.getFullName() + ".";
+ this.notifyGroupAdministrators(validator, groupId, subject, content, true);
+
+ GroupCacheUtil.removeGroupCache(currentGroup.getCreatorUserId());
+
+ _log.info("User "+validator.getFullName()+" has validated the creation of group "+currentGroup.getName()+" (id "+currentGroup.getGroupId()+")");
+
+ } catch (Exception e) {
+ if (_log.isErrorEnabled()) {
+ _log.error(e);
+ }
+ result.put("success", false);
+ }
+
+ return result;
+ }
+
+ // Refus d'un groupe et notification aux administrateurs du groupe
+ private JSONObject refusedGroup(ResourceRequest resourceRequest, ResourceBundle messages) throws NamingException, Exception {
+
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ final User user = PortalUtil.getUser(resourceRequest);
+ final long groupId = Long.valueOf(ParamUtil.getString(resourceRequest, "groupId"));
+
+ try {
+ // Notification
+ Group currentGroup = GroupLocalServiceUtil.getGroup(groupId);
+ String subject = messages.getString("refus-de-creation-du-groupe") + " " + currentGroup.getName();
+ String content= messages.getString("la-creation-du-groupe") + " " + currentGroup.getName() + " " + messages.getString("a-ete-refusee") + user.getFullName() + ".";
+ this.notifyGroupAdministrators(user, groupId, subject, content, true);
+ GroupCacheUtil.removeGroupCache(currentGroup.getCreatorUserId());
+
+ // Suppression du group (+ community infos in group listener)
+ _log.info("User "+user.getFullName()+" has refused the creation of group "+currentGroup.getName()+" (id "+currentGroup.getGroupId()+")");
+ GroupLocalServiceUtil.deleteGroup(currentGroup);
+
+ result.put("success", true);
+
+ _log.info("User "+user.getFullName()+" has refused the creation of group "+currentGroup.getName()+" (id "+currentGroup.getGroupId()+")");
+
+ } catch (Exception e) {
+ if (_log.isErrorEnabled()) {
+ _log.error(e);
+ }
+ result.put("success", false);
+ }
+
+ return result;
+ }
+
+ // Approbation de la demande de prolongation de durée de vie
+ private JSONObject approvedRequestLifeExtension(ResourceRequest resourceRequest, ResourceBundle messages) throws NamingException, Exception {
+
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ final User user = PortalUtil.getUser(resourceRequest);
+ final long groupId = Long.valueOf(ParamUtil.getString(resourceRequest, "groupId"));
+
+ try {
+ // Valide la demande de prolongation
+ CommunityInfos ci = CommunityInfosLocalServiceUtil.getCommunityInfosByGroupId(groupId);
+ ci.setExpirationDate(ci.getDesiredExtension());
+ ci.setRequestLifeExtension(false);
+ CommunityInfosLocalServiceUtil.updateCommunityInfos(ci);
+
+ // Notification
+ Group currentGroup = GroupLocalServiceUtil.getGroup(groupId);
+ String subject = messages.getString("demande-de-prolongation") + " " + currentGroup.getName();
+ String content = messages.getString("la-demande-de-prolongation") + " " + currentGroup.getName() + " " + messages.getString("a-ete-acceptee");
+ result = this.notifyGroupAdministrators(user, groupId, subject, content, true);
+ } catch (Exception e) {
+ if (_log.isErrorEnabled()) {
+ _log.error(e);
+ }
+ result.put("success", false);
+ }
+
+ return result;
+ }
+
+ // Refus de la demande de prolongation de durée de vie
+ private JSONObject refusedRequestLifeExtension(ResourceRequest resourceRequest, ResourceBundle messages) throws NamingException, Exception {
+
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ final User user = PortalUtil.getUser(resourceRequest);
+ final long groupId = Long.valueOf(ParamUtil.getString(resourceRequest, "groupId"));
+
+ try {
+ // Valide la demande de prolongation
+ CommunityInfos ci = CommunityInfosLocalServiceUtil.getCommunityInfosByGroupId(groupId);
+ ci.setRequestLifeExtension(false);
+ CommunityInfosLocalServiceUtil.updateCommunityInfos(ci);
+
+ // Notification
+ Group currentGroup = GroupLocalServiceUtil.getGroup(groupId);
+ String subject = messages.getString("demande-de-prolongation") + " " + currentGroup.getName();
+ String content = messages.getString("la-demande-de-prolongation") + " " + currentGroup.getName() + " " + messages.getString("a-ete-refusee");
+ result = this.notifyGroupAdministrators(user, groupId, subject, content, true);
+ } catch (Exception e) {
+ if (_log.isErrorEnabled()) {
+ _log.error(e);
+ }
+ result.put("success", false);
+ }
+
+ return result;
+ }
+
+ /**
+ * Send a notification to local admins and/or to direction when a group is created
+ * @param currUser
+ * @param groupId
+ * @param description
+ * @param messages
+ * @param themeDisplay
+ * @param isTeacher
+ * @param isGrpAdmin
+ */
+ private JSONObject notifyGroupCreation(User currUser, long groupId, String description, ResourceBundle messages, ThemeDisplay themeDisplay, boolean needModeration) {
+
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ try {
+
+ long etabId = OrganizationFinderServiceUtil.getEtabRatachement(currUser).getOrganizationId();
+
+ LinkedHashMap<String, Object> userParams = new LinkedHashMap<String, Object>();
+ OrderByComparator odb = new UserLastNameComparator(true);
+
+ // Filter on etab
+ userParams.put("usersOrgs", etabId);
+
+ Role schoolAdminRole = RoleLocalServiceUtil.getRole(currUser.getCompanyId(), ENTRolesConstants.GROUP_ADMIN);
+ userParams.put("usersRoles", new Long(schoolAdminRole.getRoleId()));
+
+ // Local admins or direction members
+ List<User> admins = UserLocalServiceUtil.search(
+ currUser.getCompanyId(),
+ StringPool.PERCENT,
+ StringPool.PERCENT,
+ StringPool.PERCENT,
+ null,
+ StringPool.PERCENT,
+ WorkflowConstants.STATUS_APPROVED,
+ userParams,
+ true,
+ QueryUtil.ALL_POS,
+ QueryUtil.ALL_POS,
+ odb);
+
+ // Empty group cache for admin users so that they see the group creation request immediately
+ for (User admin : admins) {
+ GroupCacheUtil.removeGroupCache(admin);
+ }
+
+ Group currentGroup = GroupLocalServiceUtil.getGroup(groupId);
+
+ // Build message
+ String subject = messages.getString("creation-du-groupe") + " " + currentGroup.getName();
+ String content = "";
+
+ if (needModeration) {
+ content = messages.getString("le-groupe") + " " + currentGroup.getName() + " " + messages.getString("a-ete-cree-necessite-validation") + " <br /> <br />";
+ } else {
+ content = messages.getString("le-groupe") + " " + currentGroup.getName() + " " + messages.getString("par") + " " + currUser.getFullName() + " <br /> <br />";
+ }
+
+ // Add description if not empty
+ if (!description.isEmpty()) {
+ content += messages.getString("description-du-groupe") + " <br /> " + description;
+ }
+
+ final JSONArray attachFile = JSONFactoryUtil.createJSONArray();
+
+ try {
+ // Send message
+ if (!needModeration){
+ // Send the same message to all group admins
+ Set<Long> destFinal = new HashSet<Long>();
+ for (User admin : admins) {
+ destFinal.add(admin.getUserId());
+ }
+ IMUtils.sendMessage(currUser, destFinal, subject, content, attachFile);
+ _log.info("Sent message for group creation notification to "+destFinal.size()+" school admins");
+ } else {
+ // Moderation is needed : content is different for each recipient => send as much messages as recipients
+ for (User admin : admins) {
+ Set<Long> destFinal = new HashSet<Long>();
+ destFinal.add(admin.getUserId());
+ String url = "<br /> <a href=\""+ themeDisplay.getURLPortal() + "/user/" + admin.getLogin() + ENTMainUtilsLocalServiceUtil.getLoginDefaultPageLanding(admin.getCompanyId()) + "#" + ENTMainUtilsLocalServiceUtil.getPortletUrlGroup(admin.getCompanyId())
+ + "?validTab=0\"> <u> " + messages.getString("cliquez-ici-pour-acceder-a-l-interface-de-validation") + " </u> </a>";
+ String contentTotal = content + url;
+ IMUtils.sendMessage(currUser, destFinal, subject, contentTotal, attachFile);
+ _log.info("Sent message for group '"+currentGroup.getName()+"' creation validation to admin "+admin.getFullName());
+ }
+ }
+ result.put("success", true);
+ }
+ catch(Exception e) {
+ _log.error("Error when sending notification message for group creation", e);
+ result.put("success", false);
+ }
+ } catch (Exception e) {
+ result.put("success", false);
+ }
+
+ return result;
+ }
+
+ /**
+ * Notify group administrators and group owner
+ */
+ private JSONObject notifyGroupAdministrators(User user, long groupId, String subject, String content, boolean addSchoolAdmins) throws SystemException, PortalException {
+
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+ result.put("success", false);
+ Set<Long> destFinal = new HashSet<Long>();
+
+ // Group members
+ long[] existingUsers = UserLocalServiceUtil.getGroupUserIds(groupId);
+
+ // Get all group administrators and group owner
+ Role groupAdministratorRole = RoleLocalServiceUtil.getRole(user.getCompanyId(), RoleConstants.SITE_ADMINISTRATOR);
+ Role groupOwnerRole = RoleLocalServiceUtil.getRole(user.getCompanyId(), RoleConstants.SITE_OWNER);
+
+ for (long userId : existingUsers) {
+
+ Boolean isAdministrator = UserGroupRoleLocalServiceUtil.hasUserGroupRole(userId, groupId, groupAdministratorRole.getRoleId());
+ Boolean isOwner = UserGroupRoleLocalServiceUtil.hasUserGroupRole(userId, groupId, groupOwnerRole.getRoleId());
+ if (isAdministrator || isOwner) {
+ destFinal.add(userId);
+ }
+ }
+
+ if (addSchoolAdmins) {
+
+ // Add local admins as recipients
+ try {
+ LinkedHashMap<String, Object> userParams = new LinkedHashMap<String, Object>();
+ OrderByComparator odb = new UserLastNameComparator(true);
+
+ long etabId = OrganizationFinderServiceUtil.getEtabRatachement(user).getOrganizationId();
+ userParams.put("usersOrgs", etabId);
+
+ Role schoolAdminRole = RoleLocalServiceUtil.getRole(user.getCompanyId(), ENTRolesConstants.GROUP_ADMIN);
+ userParams.put("usersRoles", new Long(schoolAdminRole.getRoleId()));
+
+ // Local admins
+ List<User> admins = UserLocalServiceUtil.search(
+ user.getCompanyId(),
+ StringPool.PERCENT,
+ StringPool.PERCENT,
+ StringPool.PERCENT,
+ null,
+ StringPool.PERCENT,
+ WorkflowConstants.STATUS_APPROVED,
+ userParams,
+ true,
+ QueryUtil.ALL_POS,
+ QueryUtil.ALL_POS,
+ odb);
+
+ for (User admin : admins) {
+ destFinal.add(admin.getUserId());
+ _log.info("Sending notification message to "+admin.getFullName());
+ GroupCacheUtil.removeGroupCache(admin.getUserId());
+ }
+ } catch (Exception e) {
+ _log.error("Error when getting all local admins for user "+user.getFullName()+" school", e);
+ }
+ }
+ final JSONArray attachFile = JSONFactoryUtil.createJSONArray();
+
+ // Send message
+ try {
+ IMUtils.sendMessage(user, destFinal, subject, content, attachFile);
+
+ _log.info("Sent notification message for group "+groupId+" to "+destFinal.size()+" recipients");
+ result.put("success", true);
+ }
+ catch(Exception e) {
+ _log.error(e);
+ }
+
+ return result;
+ }
+
+ // Retourne si le user est manager
+ public static Boolean isManager(User u) {
+ try {
+ if (RoleLocalServiceUtil.hasUserRole(u.getUserId(), u.getCompanyId(), "Administrator", false)) {
+ return true;
+ }
+ } catch (PortalException e) {
+ _log.error(e);
+ } catch (SystemException e) {
+ _log.error(e);
+ }
+ return false;
+ }
+
+ protected String editJSP;
+ protected String helpJSP;
+ protected String viewJSP;
+
+ private static Log _log = LogFactoryUtil.getLog(JSPPortlet.class);
+
+}