--- /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.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URI;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.GregorianCalendar;
+import java.util.HashSet;
+import java.util.List;
+import java.util.ResourceBundle;
+import java.util.Set;
+import java.util.zip.Deflater;
+import java.util.zip.ZipOutputStream;
+
+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 net.fortuna.ical4j.data.CalendarBuilder;
+import net.fortuna.ical4j.model.Component;
+import net.fortuna.ical4j.model.ComponentList;
+import net.fortuna.ical4j.model.DateTime;
+import net.fortuna.ical4j.model.Property;
+import net.fortuna.ical4j.model.TimeZone;
+import net.fortuna.ical4j.model.TimeZoneRegistry;
+import net.fortuna.ical4j.model.TimeZoneRegistryFactory;
+import net.fortuna.ical4j.model.component.VEvent;
+import net.fortuna.ical4j.model.component.VTimeZone;
+import net.fortuna.ical4j.model.property.CalScale;
+import net.fortuna.ical4j.model.property.Description;
+import net.fortuna.ical4j.model.property.Location;
+import net.fortuna.ical4j.model.property.ProdId;
+import net.fortuna.ical4j.model.property.Uid;
+import net.fortuna.ical4j.model.property.Url;
+import net.fortuna.ical4j.model.property.Version;
+
+import org.joda.time.Days;
+import org.joda.time.LocalDate;
+
+import com.google.ical.compat.jodatime.LocalDateIterable;
+import com.google.ical.compat.jodatime.LocalDateIteratorFactory;
+import com.liferay.contacts.util.ListFicheFactory;
+import com.liferay.contacts.util.ProxyFiche;
+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.JSONException;
+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.repository.model.FileEntry;
+import com.liferay.portal.kernel.repository.model.Folder;
+import com.liferay.portal.kernel.util.ContentTypes;
+import com.liferay.portal.kernel.util.MimeTypesOverrideUtil;
+import com.liferay.portal.kernel.util.ParamUtil;
+import com.liferay.portal.kernel.util.WebKeys;
+import com.liferay.portal.model.Role;
+import com.liferay.portal.model.User;
+import com.liferay.portal.service.ServiceContext;
+import com.liferay.portal.service.UserLocalServiceUtil;
+import com.liferay.portal.theme.ThemeDisplay;
+import com.liferay.portal.util.PortalUtil;
+import com.liferay.portlet.documentlibrary.DuplicateFileException;
+import com.liferay.portlet.documentlibrary.service.DLAppLocalServiceUtil;
+import com.pentila.entSavoie.ENTRoleUtilFactory;
+import com.pentila.entSavoie.ENTRolesConstants;
+import com.pentila.entSavoie.ENTRolesUtil;
+import com.pentila.entSavoie.agenda.model.EventAgenda;
+import com.pentila.entSavoie.agenda.model.Ressource;
+import com.pentila.entSavoie.agenda.model.RessourceRole;
+import com.pentila.entSavoie.agenda.model.RessourceUser;
+import com.pentila.entSavoie.agenda.service.EventAgendaLocalServiceUtil;
+import com.pentila.entSavoie.agenda.service.RessourceLocalServiceUtil;
+import com.pentila.entSavoie.agenda.service.RessourceRoleLocalServiceUtil;
+import com.pentila.entSavoie.agenda.service.RessourceUserLocalServiceUtil;
+import com.pentila.entSavoie.amis.model.Relationship;
+import com.pentila.entSavoie.amis.service.RelationshipLocalServiceUtil;
+import com.pentila.entSavoie.cahierDeTexte.util.CDTUtil;
+import com.pentila.entSavoie.carnetDAdresses.model.Liste;
+import com.pentila.entSavoie.carnetDAdresses.service.ListeLocalServiceUtil;
+import com.pentila.entSavoie.cartable.service.CasierEntryLocalServiceUtil;
+import com.pentila.entSavoie.directory.OrganizationFinderServiceUtil;
+import com.pentila.entSavoie.userProperties.model.UserProperties;
+import com.pentila.entSavoie.userProperties.service.UserPropertiesLocalServiceUtil;
+import com.pentila.entSavoie.utils.DLAppUtil;
+import com.pentila.entSavoie.utils.ENTMainUtilsLocalServiceUtil;
+import com.pentila.entSavoie.utils.FoldersUtil;
+import com.pentila.entSavoie.utils.JSPPortletUtil;
+import com.pentila.entSavoie.utils.ZipUtil;
+
+
+/**
+ * <a href="JSPPortlet.java.html"><b><i>View Source</i></b></a>
+ *
+ * @author Brian Wing Shun Chan
+ *
+ */
+public class JSPPortlet extends GenericPortlet {
+
+
+ static SimpleDateFormat dfZ = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'");
+ static SimpleDateFormat localdf = new SimpleDateFormat("yyyy-MM-dd");
+ static SimpleDateFormat localdfAllDay = new SimpleDateFormat("yyyyMMdd");
+
+ 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);
+
+ if (cmd.equals("addRessource")) {
+ result = this.addRessource(resourceRequest);
+ }
+ else if (cmd.equals("deleteRessource")) {
+ result = this.deleteRessource(resourceRequest);
+ }
+ else if (cmd.equals("unsubscribeRessource")) {
+ result = this.unsubscribeRessource(resourceRequest);
+ }
+ else if (cmd.equals("modifyRessource")) {
+ result = this.modifyRessource(resourceRequest);
+ }
+ else if (cmd.equals("getSingleUser")) {
+ result = this.getSingleUser(resourceRequest);
+ }
+ else if (cmd.equals("updateRessourceUser")) {
+ result = this.updateRessourceUser(resourceRequest);
+ }
+ else if (cmd.equals("subscribeRessources")) {
+ result = this.subscribeRessources(resourceRequest);
+ }
+ else if (cmd.equals("getRessourceRoles")) {
+ result = this.getRessourceRoles(resourceRequest);
+ }
+ else if (cmd.equals("exportRessource")) {
+ result = this.exportRessource(resourceRequest);
+ }
+ else if (cmd.equals("setAgendaView")) {
+ result = setAgendaView(resourceRequest);
+ }
+ else if (cmd.equals("sendToCasier")) {
+ try{
+ result = this.sendToCasier(resourceRequest);
+ } catch(Exception e){
+ _log.error(e);
+ }
+ }
+ else if (cmd.equals("uploadAgenda") || cmd.equals("agendaChoosed")) {
+ try {
+ result = this.uploadAgenda(resourceRequest);
+ } catch (PortalException e) {
+ _log.error(e);
+ } catch (SystemException e) {
+ _log.error(e);
+ }
+ }
+ else if (cmd.equals("processImport")) {
+ try {
+ result = this.processImport(resourceRequest);
+ } catch (Exception e) {
+ _log.error(e);
+ }
+ }
+ else if (cmd.equals("createMessage")) {
+ try {
+ result = this.createMessage(resourceRequest);
+ } catch (NamingException e) {
+ _log.error(e);
+ } catch (Exception e) {
+ _log.error(e);
+ }
+ }
+ else if(cmd.equals("showOrHideCalendar")){
+ try {
+ result = this.showOrHideCalendar(resourceRequest);
+ } catch (PortalException e) {
+ _log.error(e);
+ } catch (SystemException e) {
+ _log.error(e);
+ }
+ }
+ //get the max file upload size
+ else if (cmd.equals("getMaxFileUploadSize")) {
+ try {
+ User user = PortalUtil.getUser(resourceRequest);
+ long uploadMaxSize = ENTMainUtilsLocalServiceUtil.getUploadServletRequestMaxSize(user.getCompanyId());
+ result.put("uploadMaxSize", JSPPortletUtil.getSizeInMegaOctet(uploadMaxSize));
+ 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 {
+
+ }
+
+ private JSONObject subscribeRessources(ResourceRequest resourceRequest) {
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ try {
+
+ final long userId = PortalUtil.getUserId(resourceRequest);
+
+ JSONArray ressourceIdArray = JSONFactoryUtil.createJSONArray(ParamUtil.getString(resourceRequest, "ressourceIds", ""));
+
+ for (int i=0; i<ressourceIdArray.length(); i++) {
+ long idRes = ressourceIdArray.getLong(i);
+ Ressource res = RessourceLocalServiceUtil.getRessource(idRes);
+ RessourceUserLocalServiceUtil.getOrCreateRessourceUserByRessourceIdUserId(idRes, userId, res.isEcriture());
+
+ }
+
+ result.put("success", true);
+
+ } catch (Exception e) {
+ if (_log.isErrorEnabled()) {
+ _log.error(e);
+ }
+ result.put("success", false);
+ }
+
+ return result;
+ }
+
+ private static JSONObject getEventCDT(JSONObject evt, User user, Ressource res){
+ return getEventCDT(evt, user, res, true);
+ }
+
+ private static JSONObject getEventCDT(JSONObject evt, User user, Ressource res, boolean withAttachment){
+ SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ JSONObject e = JSONFactoryUtil.createJSONObject();
+
+ e.put("id", ""+evt.getLong("id") +res.getIdRessource() );
+ e.put("cid", res.getIdRessource());
+
+ Calendar cal = new GregorianCalendar();
+ String[] startEvt = evt.getString("ymd").split("-");
+ int intYear = Integer.valueOf(startEvt[0]);
+ int intMonth = Integer.valueOf(startEvt[1]) - 1;
+ int intDay = Integer.valueOf(startEvt[2]);
+
+ String[] startHour = evt.getString("startTime").split(":");
+ int intHour = Integer.valueOf(startHour[0]);
+ int intMinute = Integer.valueOf(startHour[1]);
+ int intSecond = 0;
+
+ cal.set(intYear, intMonth, intDay, intHour, intMinute, intSecond);
+ e.put("start", df.format(cal.getTime()));
+
+
+ String[] endEvt = evt.getString("eymd").split("-");
+ intYear = Integer.valueOf(endEvt[0]);
+ intMonth = Integer.valueOf(endEvt[1]) - 1;
+ intDay = Integer.valueOf(endEvt[2]);
+
+ String[] endHour = null;
+ try {
+ endHour = evt.getString("endTime").split(":");
+ intHour = Integer.valueOf(endHour[0]);
+ intMinute = Integer.valueOf(endHour[1]);
+ intSecond = 0;
+ cal.set(intYear, intMonth, intDay, intHour, intMinute, intSecond);
+ }
+ catch(Exception exc) {
+ // on a pas d'heure de fin
+ endHour = evt.getString("startTime").split(":");
+ intHour = Integer.valueOf(startHour[0]);
+ intMinute = Integer.valueOf(startHour[1]);
+ intSecond = 0;
+ cal.set(intYear, intMonth, intDay, intHour, intMinute, intSecond);
+ cal.add(Calendar.HOUR, 1);
+ }
+
+ e.put("end", df.format(cal.getTime()));
+
+ e.put("title", evt.getString("subject"));
+ e.put("notes", getDescription(user, evt, withAttachment));
+ e.put("url", "");
+ e.put("loc", "");
+ e.put("ad", false);
+ e.put("rem", "");
+ e.put("recur_rule", "");
+ e.put("recurrenceId", 0);
+ e.put("recurrenceScope", "one"); // par defaut on ne modifie que l'evt
+
+ e.put("isEditable", false);
+
+ // auteur de l'evt
+
+ long authorId = evt.getLong("creatorId");
+
+ String author = evt.getString("creatorName");
+
+
+ e.put("author", author);
+ e.put("authorId", authorId);
+ e.put("userId", user.getUserId());
+ e.put("token", new Date().getTime());
+
+ return e;
+ }
+
+ public static String getDescription(User user, JSONObject evt){
+ return getDescription(user, evt, true);
+ }
+
+ public static String getDescription(User user, JSONObject evt, boolean withAttachment){
+ String result = "";
+
+ result += "<b>" + evt.getString("matiereLabel") + "</b> - ";
+
+ result += evt.getString("classeName") + "<br/>";
+
+ String description = evt.getString("description");
+
+ if(!description.equals("")){
+ result += description + "<br/>";
+ }
+
+ String annotation = evt.getString("annotation");
+
+ if(!annotation.equals("")){
+ result += "<b>Annotation :</b> " + annotation + "<br/><br/>";
+ }
+
+ if(withAttachment){
+ String attachText = evt.getString("attachments");
+ if(attachText.length() > 2){
+ JSONArray attach = JSONFactoryUtil.createJSONArray();
+ try {
+ attach = JSONFactoryUtil.createJSONArray(attachText);
+ } catch (JSONException e) {
+ _log.error(e);
+ }
+
+ result += "<b>piece(s) jointe(s) :</b> <ul>";
+ for(int i=0; i<attach.length(); i++){
+ result += "<li>" + attach.getJSONObject(i).getString("fileHref").replace("showMenuAttachment(", "showMenuAttachment(event.x,event.y,") + "</li>";
+ }
+ result += "</ul>";
+ }
+ }
+
+ return result;
+ }
+
+ public static JSONArray getCDTEvents(User user, Date startDate, Date endDate, Ressource res, ThemeDisplay themeDisplay){
+ JSONObject result;
+ JSONArray listEvents = JSONFactoryUtil.createJSONArray();
+ JSONArray events = JSONFactoryUtil.createJSONArray();
+ ResourceBundle messages = ResourceBundle.getBundle("content.Language", user.getLocale());
+
+ try {
+ result = CDTUtil.calendarEvent_listJSON(user.getUserId(), res.getCdtUserId(), res.getFiltreCours(), res.getClasse(), res.getMatiere(), res.getOnlyMyClass(), startDate, endDate, 0, themeDisplay, messages);
+ listEvents = result.getJSONArray("results");
+ } catch (PortalException e) {
+ _log.error(e);
+ } catch (SystemException e) {
+ _log.error(e);
+ }
+
+ for(int i=0; i<listEvents.length(); i++){
+ events.put(getEventCDT(listEvents.getJSONObject(i), user, res));
+ }
+
+ return events;
+ }
+
+ private JSONObject getSingleUser(ResourceRequest resourceRequest) {
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ try {
+ final Long ressourceId = ParamUtil.getLong(resourceRequest, "ressourceId");
+
+ List<RessourceUser> ressourceUsers = RessourceUserLocalServiceUtil.getRessourceUserByRessourceIdShared(ressourceId, true);
+
+ JSONArray singleUsers = JSONFactoryUtil.createJSONArray();
+
+ for (RessourceUser ru : ressourceUsers) {
+ User u = null;
+ try {
+ u = UserLocalServiceUtil.getUser(ru.getIdUser());
+ }
+ catch(Exception e) {
+ // le user a été supprimé!!!
+ JSONObject curr = JSONFactoryUtil.createJSONObject();
+ curr.put("id", ru.getIdUser());
+ curr.put("name", "Utilisateur inconnu");
+ curr.put("isRedacteur", false);
+ singleUsers.put(curr);
+ continue;
+ }
+ JSONObject curr = JSONFactoryUtil.createJSONObject();
+ curr.put("id", u.getUserId());
+ curr.put("name", u.getLastName() + " " + u.getFirstName());
+ curr.put("isRedacteur", ru.isRedacteur());
+ singleUsers.put(curr);
+ }
+
+ result.put("singleUsers", singleUsers);
+ result.put("success", true);
+
+ } catch (Exception e) {
+ if (_log.isErrorEnabled()) {
+ _log.error(e);
+ }
+ result.put("success", false);
+ }
+
+ return result;
+ }
+
+ // Création d'un nouveau message
+ private JSONObject createMessage(ResourceRequest resourceRequest) throws NamingException, Exception {
+ return JSPPortletUtil.createMessage(resourceRequest);
+ }
+
+ //Envoie de la piece jointe dans le casier du user
+ private JSONObject sendToCasier(ResourceRequest resourceRequest) throws SystemException, PortalException, IOException {
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ User user = PortalUtil.getUser(resourceRequest);
+
+ final Folder receiverDropBox = FoldersUtil.getDropBox(user.getUserId());
+
+ JSONArray attachFiles = JSONFactoryUtil.createJSONArray(ParamUtil.getString(resourceRequest, "attachFiles", ""));
+
+ for (int i=0; i<attachFiles.length(); i++) {
+ JSONObject pjobj = attachFiles.getJSONObject(i);
+ String path = "cahierdetexte/" + pjobj.getLong("eventId");
+ FileEntry fileEntry = DLAppUtil.addFileEntry(user, receiverDropBox, path, pjobj.getString("name"));
+ CasierEntryLocalServiceUtil.addCasierEntry(receiverDropBox.getCompanyId(), receiverDropBox.getGroupId(), fileEntry.getFileEntryId(), user.getUserId(), "", true);
+ }
+
+ result.put("success", true);
+
+ return result;
+ }
+
+ private JSONObject getRessourceRoles(ResourceRequest resourceRequest) {
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ try {
+
+ final Long ressourceId = ParamUtil.getLong(resourceRequest, "ressourceId");
+
+ List<RessourceRole> ressourceRole = RessourceRoleLocalServiceUtil.getRessourceRoleByRessourceId(ressourceId);
+
+ final JSONArray roleList = JSONFactoryUtil.createJSONArray();
+
+ result.put("success", true);
+
+ for (RessourceRole rr : ressourceRole) {
+ roleList.put(rr.getIdRole());
+ }
+
+ if(roleList.length() == 0){
+ roleList.put(0);
+ }
+
+ result.put("ressourceRoles", roleList);
+ result.put("success", true);
+
+ } catch (Exception e) {
+ if (_log.isErrorEnabled()) {
+ _log.error(e);
+ }
+ result.put("success", false);
+ }
+
+ return result;
+ }
+
+ private JSONObject updateRessourceUser(ResourceRequest resourceRequest) {
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ try {
+ final long currentUserId = PortalUtil.getUserId(resourceRequest);
+ final User user = UserLocalServiceUtil.getUser(currentUserId);
+
+ final Long ressourceId = ParamUtil.getLong(resourceRequest, "ressourceId");
+
+ //***on recup les single users
+ Set<Long> singleUserIds = new HashSet<Long>();
+ Set<ProxyFiche> lesFiches = new HashSet<ProxyFiche>();
+ JSONArray singleUserArray = JSONFactoryUtil.createJSONArray(ParamUtil.getString(resourceRequest, "singleUsers", ""));
+
+ Set<Long> redacteurIds = new HashSet<Long>();
+
+ for (int i=0; i<singleUserArray.length(); i++) {
+
+ JSONObject jobj = singleUserArray.getJSONObject(i);
+ String mbrtype = jobj.getString("type");
+
+ boolean isRedacteur = jobj.getBoolean("admin");
+
+ if (!mbrtype.equals("")) {
+ List<ProxyFiche> tempListProxy = null;
+
+ // cas d'une liste
+ if (mbrtype.equals("all")) {
+ // cas de tous mes contacts
+ tempListProxy = ListFicheFactory.createAllContacts(user);
+ }
+ else if (mbrtype.equals("perso")) {
+ // cas de tous mes contacts personnels
+ tempListProxy = ListFicheFactory.createPersoContacts(user);
+ }
+ else if (mbrtype.equals("inst")) {
+ // cas de tous mes contact inst
+ tempListProxy = ListFicheFactory.createInstContacts(user);
+ }
+ else if (mbrtype.equals("local")) {
+ // cas d'une liste perso
+ 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")) {
+ // cas d'une organisation
+ 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")));
+ //}
+ else {
+ // ce cas ne doit jamais arriver
+ }
+
+ if (tempListProxy != null) {
+ if (isRedacteur) {
+ for (ProxyFiche f : tempListProxy) {
+ String typeUser = f.getType();
+ if (typeUser.equals("user")) {
+ long idUser = Long.valueOf(f.getId());
+ redacteurIds.add(idUser);
+ } else {
+ long relUserId = Long.valueOf(f.getRelUserId());
+ if (relUserId!=0) {
+ redacteurIds.add(relUserId);
+ }
+ }
+ }
+ }
+
+
+ lesFiches.addAll(tempListProxy);
+ }
+
+ }
+ else {
+ // cas d'un user
+ long uId = Long.valueOf(jobj.getString("id"));
+ lesFiches.add(new ProxyFiche(
+ user,
+ UserLocalServiceUtil.getUser(uId)));
+ // si redacteur on l 'ajoute!
+ if (isRedacteur) {
+ redacteurIds.add(uId);
+ }
+ }
+ }
+
+ long idUser = 0;
+ for (ProxyFiche f : lesFiches) {
+ String typeUser = f.getType();
+ if (typeUser.equals("user")) {
+ idUser = Long.valueOf(f.getId());
+ } else {
+ idUser = Long.valueOf(f.getRelUserId());
+ if (idUser==0) {
+ continue;
+ }
+ }
+ if (!singleUserIds.contains(idUser)) {
+ singleUserIds.add(idUser);
+ }
+
+ }
+
+ List<RessourceUser> rUser = RessourceUserLocalServiceUtil.getRessourceUserByRessourceIdShared(ressourceId, true);
+
+ for (RessourceUser ru : rUser){
+ // afin de ne pas pouvoir se supprimer!!!!
+ Ressource res = RessourceLocalServiceUtil.getRessource(ressourceId);
+ if (ru.getIdUser() != res.getIdcreator()){
+ //delete all single users from DB
+ RessourceUserLocalServiceUtil.deleteRessourceUserAndDep(ru);
+ }
+ }
+
+ //put new single users in DB
+ for (Long userId: singleUserIds) {
+ RessourceUserLocalServiceUtil.addRessourceUser(ressourceId, userId, redacteurIds.contains(userId), true);
+ }
+
+ result.put("success", true);
+ } catch (Exception e) {
+ if (_log.isErrorEnabled()) {
+ _log.error(e);
+ }
+ result.put("success", false);
+ }
+
+ return result;
+ }
+
+ private JSONObject addRessource(ResourceRequest resourceRequest) {
+
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ try {
+
+ final long currentUserId = PortalUtil.getUserId(resourceRequest);
+ User user = UserLocalServiceUtil.getUser(currentUserId);
+
+ final String ressourceName = ParamUtil.getString(resourceRequest, "ressourceName", "");
+ final int kind = ParamUtil.getInteger(resourceRequest, "kind", 1);
+ final long targetId = ParamUtil.getLong(resourceRequest, "targetId", user.getUserId());
+ final boolean isParentOrEleve = ParamUtil.getBoolean(resourceRequest, "isParentOrEleve", false);
+ final boolean isRessource = ParamUtil.getBoolean(resourceRequest, "isRessource", false);
+
+ long etabId = OrganizationFinderServiceUtil.getEtabRatachement(user).getOrganizationId();
+ // on creer la ressource
+ Ressource ressource = RessourceLocalServiceUtil.addRessource(ressourceName, etabId, user.getUserId(), kind, targetId);
+
+ ressource.setRessource(isRessource);
+
+ if(isParentOrEleve){
+ ressource.setOnlyMyClass(false);
+ ressource.setFiltreCours(1);
+ }
+ RessourceLocalServiceUtil.updateRessource(ressource);
+
+ // comme on est le createur on s ajoute en ressourceUser
+ if(kind == 2) {
+ RessourceUserLocalServiceUtil.addRessourceUser(ressource.getIdRessource(), user.getUserId(), false);
+ }
+ else {
+ RessourceUserLocalServiceUtil.addRessourceUser(ressource.getIdRessource(), user.getUserId(), true);
+ }
+
+ result.put("idRessource", ressource.getIdRessource());
+ result.put("name", ressource.getName());
+ result.put("description", ressource.getDescription());
+ result.put("ressourceType", ressource.getRessourceType());
+ result.put("scope", ressource.getScope());
+ result.put("creator", PortalUtil.getUserName(ressource.getIdcreator(), "Utilisateur supprime"));
+ result.put("isCreator", true);
+ result.put("isRessource", ressource.isRessource());
+ result.put("isWritable", ressource.isEcriture());
+ result.put("color", ressource.getColor());
+ result.put("kind", ressource.getKind());
+ result.put("forcePubli", ressource.getForcePubli());
+ result.put("cdtUserId", ressource.getCdtUserId());
+ result.put("filtreCours", ressource.getFiltreCours());
+ result.put("matiere", ressource.getMatiere());
+ result.put("classe", ressource.getClasse());
+ result.put("onlyMyClass", ressource.isOnlyMyClass());
+ result.put("success", true);
+
+ } catch (Exception e) {
+ if (_log.isErrorEnabled()) {
+ _log.error(e);
+ }
+ result.put("success", false);
+ }
+ return result;
+ }
+
+ private JSONObject modifyRessource(ResourceRequest resourceRequest) {
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ try {
+
+ final long userId = PortalUtil.getUserId(resourceRequest);
+ final User user = UserLocalServiceUtil.getUser(userId);
+ final long ressourceId = ParamUtil.getLong(resourceRequest, "ressourceId");
+ final String name = ParamUtil.getString(resourceRequest, "name", "");
+ String description = ParamUtil.getString(resourceRequest, "description", "");
+ final int type = ParamUtil.getInteger(resourceRequest, "type");
+ final int scope = ParamUtil.getInteger(resourceRequest, "scope");
+ final String color = ParamUtil.getString(resourceRequest, "color", "");
+ final Boolean isRessource = ParamUtil.getBoolean(resourceRequest, "isRessource");
+ final Boolean isWritable = ParamUtil.getBoolean(resourceRequest, "isWritable");
+ final Boolean forcePubli = ParamUtil.getBoolean(resourceRequest, "forcePubli");
+ final int filtreCours = ParamUtil.getInteger(resourceRequest, "filtreCours");
+ final int classe = ParamUtil.getInteger(resourceRequest, "classe");
+ final String matiere = ParamUtil.getString(resourceRequest, "matiere", "");
+ final boolean onlyMyClass = ParamUtil.getBoolean(resourceRequest, "onlyMyClass");
+ final long cdtUserId = ParamUtil.getLong(resourceRequest, "cdtUserId");
+
+
+ JSONArray rolesArray = JSONFactoryUtil.createJSONArray(ParamUtil.getString(resourceRequest, "roleIds", ""));
+
+
+ // on prends la ressource
+ Ressource ressource = RessourceLocalServiceUtil.getRessource(ressourceId);
+ ressource.setName(name);
+ if (description.length() >= 1000){
+ description = description.substring(0, 995);
+ description += "...";
+ }
+ ressource.setDescription(description);
+ ressource.setRessourceType(type);
+ ressource.setScope(scope);
+ ressource.setColor(color);
+ ressource.setRessource(isRessource);
+ ressource.setEcriture(isWritable);
+ ressource.setForcePubli(forcePubli);
+ ressource.setFiltreCours(filtreCours);
+ ressource.setClasse(classe);
+ ressource.setMatiere(matiere);
+ ressource.setOnlyMyClass(onlyMyClass);
+ ressource.setCdtUserId(cdtUserId);
+
+ RessourceLocalServiceUtil.updateRessource(ressource);
+
+ // on supprime tous les roles
+ RessourceRoleLocalServiceUtil.deleteRessourceRoleAndDepByRessourceId(ressourceId);
+
+ //The agenda is public (ressource Type)
+ final int PUBLIC = 1;
+ //If the agenda is not public anymore we remove all the subscribers but the one we shared the agenda with
+ if(type != PUBLIC){
+ List<RessourceUser> rUser = RessourceUserLocalServiceUtil.getRessourceUserByRessourceIdShared(ressourceId, false);
+ for (RessourceUser ru : rUser){
+ //We do not want to delete the owner, don't we ?
+ if (ru.getIdUser() != userId){
+ RessourceUserLocalServiceUtil.deleteRessourceUser(ru.getIdRessourceUser());
+ }
+ }
+ }
+ else if (rolesArray.length() > 0){
+ List<RessourceUser> rUser = RessourceUserLocalServiceUtil.getRessourceUserByRessourceIdShared(ressourceId, false);
+ final int SCOPEALLETAB = 2;
+ boolean isEtabRessource = false;
+ boolean roleShared = false;
+
+ //if all the roles are concerned
+ if (rolesArray.getLong(0) == 0){
+ ENTRolesUtil eru = ENTRoleUtilFactory.getInstance(user.getCompanyId());
+ //On ajoute tous les rôles
+ for(String roleName : ENTRolesConstants.getCodesFiltered(user.getCompanyId())){
+ Role r = eru.getRole(roleName);
+ RessourceRoleLocalServiceUtil.addRessourceRole(ressourceId, r.getRoleId());
+ }
+ }
+ else {
+ //We add the selected roles
+ for (int i=0; i<rolesArray.length(); i++) {
+ long roleId = rolesArray.getLong(i);
+ if(roleId == 0){
+ continue;
+ }
+ RessourceRoleLocalServiceUtil.addRessourceRole(ressourceId, roleId);
+ }
+ }
+
+ //We delete the ressourceUser now disallowed. We do not want to delete the owner
+ for (RessourceUser ru : rUser){
+ if (ru.getIdUser() != userId){
+ //We check that the user belong to the school
+ User subscriber = UserLocalServiceUtil.getUser(ru.getIdUser());
+ if (ressource.getScope() != SCOPEALLETAB){
+ for (long orgId : subscriber.getOrganizationIds()){
+ if (orgId == ressource.getEtabId()){
+ isEtabRessource = true;
+ break;
+ }
+ }
+ }
+ else{
+ isEtabRessource = true;
+ }
+
+ //If the school not match we delete the ressourceUser else we check that the subscribers still have a role which is allowed
+ if (!isEtabRessource){
+ RessourceUserLocalServiceUtil.deleteRessourceUser(ru.getIdRessourceUser());
+ }
+ else if (rolesArray.getLong(0) != 0){
+ roleShared = false;
+ for(Role role : subscriber.getRoles()){
+ for (int i=0; i<rolesArray.length(); i++) {
+ if (rolesArray.getLong(i) == role.getRoleId()){
+ roleShared = true;
+ break;
+ }
+ }
+ }
+
+ if (!roleShared){
+ RessourceUserLocalServiceUtil.deleteRessourceUser(ru.getIdRessourceUser());
+ }
+ }
+ }
+ }
+ }
+
+ result.put("success", true);
+
+ } catch (Exception e) {
+ if (_log.isErrorEnabled()) {
+ _log.error(e);
+ }
+ result.put("success", false);
+ }
+
+ return result;
+ }
+
+ private JSONObject deleteRessource(ResourceRequest resourceRequest) {
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ try {
+ final long ressourceId = ParamUtil.getLong(resourceRequest, "ressourceId");
+
+ // on doit juste supprimer via le service car les dependances sont supprimées au niveau du service
+ Ressource res = RessourceLocalServiceUtil.getRessource(ressourceId);
+ RessourceLocalServiceUtil.deleteRessourceAndDep(res);
+
+ result.put("success", true);
+
+ } catch (Exception e) {
+ if (_log.isErrorEnabled()) {
+ _log.error(e);
+ }
+ result.put("success", false);
+ }
+
+ return result;
+ }
+
+ private JSONObject unsubscribeRessource(ResourceRequest resourceRequest) {
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ try {
+
+ final long userId = PortalUtil.getUserId(resourceRequest);
+
+ final long ressourceId = ParamUtil.getLong(resourceRequest, "ressourceId");
+
+ // on doit juste supprimer via le lien user <--> ressource
+ RessourceUserLocalServiceUtil.deleteRessourceUserAndDepByRessourceIdUserId(ressourceId, userId);
+
+ result.put("success", true);
+
+ } catch (Exception e) {
+ if (_log.isErrorEnabled()) {
+ _log.error(e);
+ }
+ result.put("success", false);
+ }
+
+ return result;
+ }
+
+ private JSONObject exportRessource(final ResourceRequest resourceRequest) {
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ try {
+ SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+
+ ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest.getAttribute(WebKeys.THEME_DISPLAY);
+ final long currentUserId = PortalUtil.getUserId(resourceRequest);
+ final User user = UserLocalServiceUtil.getUser(currentUserId);
+
+ JSONArray ressourceIdArray = JSONFactoryUtil.createJSONArray(ParamUtil.getString(resourceRequest, "ressourceId", ""));
+ JSONArray ressourceNameArray = JSONFactoryUtil.createJSONArray(ParamUtil.getString(resourceRequest, "ressourceName", ""));
+ long ressourceId;
+
+// List <FileOutputStream> listFile = new ArrayList<FileOutputStream>();
+ List <net.fortuna.ical4j.model.Calendar> listCalendar = new ArrayList<net.fortuna.ical4j.model.Calendar>();
+ for (int i=0; i < ressourceIdArray.length(); i++) {
+ ressourceId = ressourceIdArray.getLong(i);
+ // on doit juste supprimer via le service car les dependances sont supprimées au niveau du service
+ Ressource res = RessourceLocalServiceUtil.getRessource(ressourceId);
+
+ if (res.getKind() != 2) {
+ List <EventAgenda> listEvent = EventAgendaLocalServiceUtil.getEventAgendaByCallId(res.getIdRessource());
+
+ net.fortuna.ical4j.model.Calendar calendar = new net.fortuna.ical4j.model.Calendar();
+ calendar.getProperties().add(new ProdId("-//Ben Fortuna//iCal4j 1.0//EN"));
+ calendar.getProperties().add(Version.VERSION_2_0);
+ calendar.getProperties().add(CalScale.GREGORIAN);
+
+
+ TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
+ TimeZone timezone = registry.getTimeZone("Europe/Paris");
+ VTimeZone tz = timezone.getVTimeZone();
+ calendar.getComponents().add(tz);
+
+ for (final EventAgenda evt : listEvent) {
+
+ net.fortuna.ical4j.model.Date startAllDay = new net.fortuna.ical4j.model.Date(evt.getStartEvt().getTime() + (3600*2000));
+
+ System.out.println(startAllDay + " / " + evt.getStartEvt());
+
+ net.fortuna.ical4j.model.Date endAllDay = new net.fortuna.ical4j.model.Date(evt.getEndEvt().getTime() + (3600*2000));
+
+ Calendar c = Calendar.getInstance();
+ c.setTime(endAllDay);
+ c.add(Calendar.DATE, 1);
+ endAllDay = new net.fortuna.ical4j.model.Date(c.getTime());
+
+ DateTime start = new DateTime(evt.getStartEvt());
+ start.setTimeZone(timezone);
+ start.setUtc(false);
+ DateTime end = new DateTime(evt.getEndEvt());
+ end.setTimeZone(timezone);
+ end.setUtc(false);
+
+ VEvent e;
+ if(evt.getIsAllDay()) {
+ e = new VEvent(startAllDay, endAllDay, evt.getTitle());
+ } else {
+ e = new VEvent(start, end, evt.getTitle());
+ }
+
+
+ Uid uid = new Uid(""+evt.getEvtId());
+ Description desc = new Description(evt.getNotes());
+ Location loc = new Location(evt.getLocation());
+ Url url = new Url(new URI(evt.getUrl()));
+ e.getProperties().add(uid);
+ e.getProperties().add(loc);
+ e.getProperties().add(desc);
+ e.getProperties().add(url);
+
+ calendar.getComponents().add(e);
+ }
+ listCalendar.add(calendar);
+ } else {
+ JSONArray listEvents = JSONFactoryUtil.createJSONArray();
+ JSONArray events = JSONFactoryUtil.createJSONArray();
+ ResourceBundle messages = ResourceBundle.getBundle("content.Language", user.getLocale());
+ try {
+
+ Date startDate = new Date();
+ Calendar c = Calendar.getInstance();
+ c.setTime(startDate);
+ c.add(Calendar.YEAR, -1);
+ startDate = c.getTime();
+
+ Date endDate = new Date();
+ c = Calendar.getInstance();
+ c.setTime(endDate);
+ c.add(Calendar.YEAR, 10);
+ endDate = c.getTime();
+
+ result = CDTUtil.calendarEvent_listJSON(currentUserId, res.getCdtUserId(), res.getFiltreCours(), res.getClasse(), res.getMatiere(), res.getOnlyMyClass(), startDate, endDate, 0, themeDisplay, messages);
+ listEvents = result.getJSONArray("results");
+ } catch (final PortalException e) {
+ _log.error(e);
+ } catch (final SystemException e) {
+ _log.error(e);
+ }
+
+ for(int j=0; j<listEvents.length(); j++) {
+ events.put(getEventCDT(listEvents.getJSONObject(j), user, res, false));
+ }
+
+ net.fortuna.ical4j.model.Calendar calendar = new net.fortuna.ical4j.model.Calendar();
+ calendar.getProperties().add(new ProdId("-//Ben Fortuna//iCal4j 1.0//EN"));
+ calendar.getProperties().add(Version.VERSION_2_0);
+ calendar.getProperties().add(CalScale.GREGORIAN);
+
+
+ TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
+ TimeZone timezone = registry.getTimeZone("Europe/Paris");
+ VTimeZone tz = timezone.getVTimeZone();
+ calendar.getComponents().add(tz);
+
+ for(int j=0; j<events.length(); j++) {
+
+ JSONObject e = events.getJSONObject(j);
+
+
+ DateTime start = new DateTime(df.parse(e.getString("start")));
+ start.setTimeZone(timezone);
+ start.setUtc(false);
+ DateTime end = new DateTime(df.parse(e.getString("end")));
+ end.setTimeZone(timezone);
+ end.setUtc(false);
+
+ VEvent vEvent = new VEvent(start, end, e.getString("title"));
+
+ Uid uid = new Uid(e.getString("id") + "@Nero");
+ Description desc = new Description(e.getString("notes"));
+ Location loc = new Location(e.getString("location"));
+ Url url = new Url(new URI(e.getString("url")));
+ vEvent.getProperties().add(uid);
+ vEvent.getProperties().add(loc);
+ vEvent.getProperties().add(desc);
+ vEvent.getProperties().add(url);
+
+
+ calendar.getComponents().add(vEvent);
+ }
+ listCalendar.add(calendar);
+ }
+ }
+
+ FileEntry newEntry;
+ Folder cible = FoldersUtil.getDropBox(user.getUserId());
+
+ boolean fichierEnvoye = false;
+ int count = 0;
+ String suffixe = "";
+ String name;
+
+ if(listCalendar.size() > 1){
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ZipOutputStream zipOut = new ZipOutputStream(baos);
+ // Niveau de compression des fichiers
+ zipOut.setLevel(Deflater.BEST_COMPRESSION);
+
+ int i=0;
+ for (final net.fortuna.ical4j.model.Calendar cal: listCalendar) {
+ ZipUtil.addStringFileToZip (cal.toString(), ressourceNameArray.getString(i) + ".ics", "", zipOut);
+ i++;
+ }
+
+ zipOut.close();
+ baos.close();
+ //return baos;
+
+ while (!fichierEnvoye && count < 100) {
+ try {
+ name = "Export_calendar" + suffixe + ".zip";
+ newEntry = DLAppLocalServiceUtil.addFileEntry(
+ user.getUserId(),
+ cible.getGroupId(),
+ cible.getFolderId(),
+ name,
+ MimeTypesOverrideUtil.getContentType(name),
+ name,
+ "",
+ "",
+ baos.toByteArray(),
+ new ServiceContext());
+ CasierEntryLocalServiceUtil.addCasierEntry(user.getCompanyId(), cible.getGroupId(), newEntry.getFileEntryId(), user.getUserId(), "", false);
+ String hrefStats = "<a href=\"" + themeDisplay.getURLPortal().toString() + "/" + themeDisplay.getPathMain() + "/document_library/get_file?p_l_id=" + themeDisplay.getPlid() + "&fileEntryId=" + newEntry.getFileEntryId() + "\" target=\"_blank\"> <br /> <br /> <u> "+ name + "</u> </a>";
+
+ result.put("msg", "Un ficher a été déposé dans votre casier. "+ hrefStats);
+ result.put("success", true);
+ fichierEnvoye = true;
+ } catch (final DuplicateFileException e) {
+ count ++;
+ suffixe = " (" + count + ")";
+ System.out.println("------------ DuplicateFileException : " + suffixe);
+ fichierEnvoye = false;
+ }
+ }
+ } else {
+ while (!fichierEnvoye && count < 100) {
+ try {
+ String cal = listCalendar.get(0).toString();
+ name = ressourceNameArray.getString(0) + suffixe + ".ics";
+
+ newEntry = DLAppLocalServiceUtil.addFileEntry(
+ user.getUserId(),
+ cible.getGroupId(),
+ cible.getFolderId(),
+ name,
+ MimeTypesOverrideUtil.getContentType(name),
+ name,
+ "",
+ "",
+ cal.getBytes(),
+ new ServiceContext());
+ CasierEntryLocalServiceUtil.addCasierEntry(user.getCompanyId(), cible.getGroupId(), newEntry.getFileEntryId(), user.getUserId(), "", false);
+ String hrefStats = "<a href=\"" + themeDisplay.getURLPortal().toString() + "/" + themeDisplay.getPathMain() + "/document_library/get_file?p_l_id=" + themeDisplay.getPlid() + "&fileEntryId=" + newEntry.getFileEntryId() + "\" target=\"_blank\"> <br /> <br /> <u> " + name + "</u> </a>";
+
+ result.put("msg", "Un ficher a été déposé dans votre casier. "+ hrefStats);
+ result.put("success", true);
+ fichierEnvoye = true;
+ } catch (final DuplicateFileException e) {
+ count ++;
+ suffixe = " (" + count + ")";
+ System.out.println("------------ DuplicateFileException : " + suffixe);
+ fichierEnvoye = false;
+ }
+ }
+ }
+
+ } catch (Exception e) {
+ if (_log.isErrorEnabled()) {
+ _log.error(e);
+ }
+ _log.error(e);
+ result.put("success", false);
+ }
+
+ return result;
+ }
+
+ private JSONObject processImport(ResourceRequest resourceRequest) throws Exception {
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
+ final long agendaId = ParamUtil.getLong(resourceRequest, "agendaId", 0);
+ long ressourceId = ParamUtil.getLong(resourceRequest, "ressourceId", 0);
+ final String agendaName = ParamUtil.getString(resourceRequest, "agendaName", "");
+
+ long userId = PortalUtil.getUserId(resourceRequest);
+
+ User user;
+ try {
+ user = UserLocalServiceUtil.getUser(userId);
+
+ //On récupère les vcards
+ InputStream is = null;
+
+ FileEntry ldFileVcard = DLAppLocalServiceUtil.getFileEntry(agendaId);
+ is = ldFileVcard.getContentStream();
+
+ CalendarBuilder builder = new CalendarBuilder();
+
+ net.fortuna.ical4j.model.Calendar calendar = builder.build(is);
+
+ try {
+ is.close();
+ } catch (IOException e) {}
+
+ TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();
+ TimeZone timezone = registry.getTimeZone("Europe/Paris");
+ VTimeZone tz = timezone.getVTimeZone();
+ calendar.getComponents().add(tz);
+
+ ComponentList list = calendar.getComponents();
+
+ long etabId = OrganizationFinderServiceUtil.getEtabRatachement(user).getOrganizationId();
+
+ Ressource ressource;
+ if(ressourceId == -1){
+ ressource = RessourceLocalServiceUtil.addRessource(agendaName, etabId, user.getUserId(), 1, user.getUserId());
+ RessourceUserLocalServiceUtil.addRessourceUser(ressource.getIdRessource(), user.getUserId(), true);
+ ressourceId = ressource.getIdRessource();
+ }else{
+ ressource = RessourceLocalServiceUtil.getRessource(ressourceId);
+
+ }
+
+ ComponentList listEvtRecur = new ComponentList();
+ ComponentList listEvt = new ComponentList();
+ for(int i=0; i < list.size(); i++){
+ Component comp = (Component) list.get(i);
+ if(comp.getProperty(Property.RRULE) != null){
+ listEvtRecur.add(comp);
+ }else{
+ listEvt.add(comp);
+ }
+ }
+
+ list.clear();
+ list.addAll(listEvtRecur);
+ list.addAll(listEvt);
+
+ for(int i=0; i < list.size(); i++){
+ Component comp = (Component) list.get(i);
+
+ if(comp.getName().equals("VEVENT")){
+ DateTime startDateTime;
+ DateTime endDateTime = null;
+ boolean allDay;
+ if(comp.getProperty(Property.DTSTART).toString().contains("VALUE")){
+ startDateTime = new DateTime(localdfAllDay.parse(comp.getProperty(Property.DTSTART).getValue()));
+ if(comp.getProperty(Property.DTEND) != null){
+ endDateTime = new DateTime(localdfAllDay.parse(comp.getProperty(Property.DTEND).getValue()));
+ }else{
+ endDateTime = startDateTime;
+ }
+
+ Calendar c = Calendar.getInstance();
+ c.setTime(endDateTime);
+ c.add(Calendar.DATE, -1);
+ endDateTime = new DateTime(c.getTimeInMillis());
+
+ allDay = true;
+ }else{
+ startDateTime = new DateTime(comp.getProperty(Property.DTSTART).getValue());
+ endDateTime = new DateTime(comp.getProperty(Property.DTEND).getValue());
+ allDay = false;
+ }
+
+ Calendar calendarStart = GregorianCalendar.getInstance();
+ calendarStart.setTime(startDateTime);
+ Calendar calendarEnd = GregorianCalendar.getInstance();
+ calendarEnd.setTime(endDateTime);
+
+ String title = "";
+ String notes = "";
+ String location = "";
+ String url = "";
+ String uid = "";
+ String rRule = "";
+ String recurId = "";
+ boolean haveRecurId = false;
+ if(comp.getProperty(Property.SUMMARY) != null){
+ title = comp.getProperty(Property.SUMMARY).getValue();
+ //truncate the title if too long for the database
+ if (title.length() >= 100) {
+ title = title.substring(0, 95);
+ title += "...";
+ }
+ }
+ if(comp.getProperty(Property.DESCRIPTION) != null){
+ notes = comp.getProperty(Property.DESCRIPTION).getValue();
+ //truncate the description if too long for the database
+ if (notes.length() >= 400) {
+ notes = notes.substring(0, 395);
+ notes += "...";
+ }
+ }
+ if(comp.getProperty(Property.LOCATION) != null){
+ location = comp.getProperty(Property.LOCATION).getValue();
+ //truncate the location if too long for the database
+ if (location.length() >= 150) {
+ location = location.substring(0, 145);
+ location += "...";
+ }
+ }
+ if(comp.getProperty(Property.URL) != null){
+ url = comp.getProperty(Property.URL).getValue();
+ //truncate the url if too long for the database
+ if (url.length() >= 75) {
+ url = url.substring(0, 70);
+ url += "...";
+ }
+ }
+ if(comp.getProperty(Property.UID) != null){
+ uid = comp.getProperty(Property.UID).getValue();
+ //truncate the uid if too long for the database
+ if (uid.length() >= 150) {
+ uid = uid.substring(0, 145);
+ uid += "...";
+ }
+ }
+ if(comp.getProperty(Property.RRULE) != null){
+ rRule = comp.getProperty(Property.RRULE).toString();
+ //truncate the rRule if too long for the database
+ if (rRule.length() >= 75) {
+ rRule = rRule.substring(0, 70);
+ rRule += "...";
+ }
+ }
+ if(comp.getProperty(Property.RECURRENCE_ID) != null){
+ recurId = comp.getProperty(Property.RECURRENCE_ID).toString();
+ haveRecurId = true;
+ //truncate the recurId if too long for the database
+ if (recurId.length() >= 75) {
+ recurId = recurId.substring(0, 70);
+ recurId += "...";
+ }
+ }
+
+
+ EventAgenda evt = null;
+ List<EventAgenda> listEvent = EventAgendaLocalServiceUtil.getEventAgendaByUidCallId(uid, ressourceId);
+ if(listEvent.size() > 0){
+ if(haveRecurId){
+ for(EventAgenda e : listEvent){
+ Date startEvt = e.getStartEvt();
+ Date recurDate;
+ if(e.getIsAllDay()){
+ recurDate = localdfAllDay.parse(comp.getProperty(Property.RECURRENCE_ID).getValue());
+ }else{
+ recurDate = df.parse(comp.getProperty(Property.RECURRENCE_ID).getValue());
+ }
+ if(startEvt.compareTo(recurDate) == 0){
+
+
+ e.setStartEvt(startDateTime);
+ e.setEndEvt(endDateTime);
+
+ e.setNotes(notes);
+ e.setTitle(title);
+ e.setLocation(location);
+ e.setUrl(url);
+ e.setUid(uid);
+ e.setIsAllDay(allDay);
+ EventAgendaLocalServiceUtil.updateEventAgenda(e);
+ evt = e;
+ }
+ }
+ }else{
+ if(listEvent.size() == 1){
+
+ EventAgenda e = listEvent.get(0);
+ e.setStartEvt(startDateTime);
+ e.setEndEvt(endDateTime);
+ e.setNotes(notes);
+ e.setTitle(title);
+ e.setLocation(location);
+ e.setUrl(url);
+ e.setUid(uid);
+ e.setRepeatEvtRRule(rRule);
+ EventAgendaLocalServiceUtil.updateEventAgenda(e);
+ evt = e;
+ }else{
+ for(EventAgenda e : listEvent){
+ EventAgendaLocalServiceUtil.deleteEvent(e);
+ }
+
+ evt = EventAgendaLocalServiceUtil.addEventAgenda(
+ user.getCompanyId(), user.getUserId(), ressource.getIdRessource(), startDateTime,
+ endDateTime, title,
+ location, notes,
+ url, allDay, "", rRule, 0, uid);
+ }
+ }
+ }else{
+
+ evt = EventAgendaLocalServiceUtil.addEventAgenda(
+ user.getCompanyId(), user.getUserId(), ressource.getIdRessource(), startDateTime,
+ endDateTime, title,
+ location, notes,
+ url, allDay, "", rRule, 0, uid);
+ }
+
+
+ if (rRule!=null && !rRule.isEmpty()) {
+ long repeatEvtId = evt.getEvtId();
+ LocalDate lStart = new LocalDate(localdf.format(startDateTime));
+ LocalDate lEnd = new LocalDate(localdf.format(endDateTime));
+
+ Days d = Days.daysBetween(lStart, lEnd);
+ int deltaDays = d.getDays();
+
+ LocalDateIterable ldi = LocalDateIteratorFactory.createLocalDateIterable(rRule, lStart, true);
+ int nbMaxEvt = 0;
+ for (LocalDate ldate: ldi) {
+ // pour ne pas créer en double la première!!!
+ if (ldate.equals(lStart)) {
+ // on crée tjs sur des dates differentes...
+ continue;
+ }
+ // on créer les réccurences
+ // date de debut
+ Date rStart = ldate.toDate();
+ rStart.setHours(calendarStart.get(Calendar.HOUR_OF_DAY));
+ rStart.setMinutes(calendarStart.get(Calendar.MINUTE));
+
+ //date de fin
+ ldate.plusDays(deltaDays);
+ Date rEnd = ldate.toDate();
+ rEnd.setHours(calendarEnd.get(Calendar.HOUR_OF_DAY));
+ rEnd.setMinutes(calendarEnd.get(Calendar.MINUTE));
+
+ EventAgendaLocalServiceUtil.addEventAgenda(
+ user.getCompanyId(), user.getUserId(), ressource.getIdRessource(), rStart,
+ rEnd, title,
+ location, notes,
+ url, allDay, "", rRule, repeatEvtId, uid);
+
+ if(!rRule.contains("COUNT") && !rRule.contains("UNTIL")){
+ nbMaxEvt++;
+ if(nbMaxEvt > 100){
+ break;
+ }
+ }
+
+ }
+ }
+ }
+ }
+ result.put("success", true);
+
+ } catch (Exception e) {
+ _log.error(e);
+ if (_log.isErrorEnabled()) {
+ _log.error(e);
+ }
+ result.put("success", false);
+ }
+
+ return result;
+ }
+
+ private JSONObject uploadAgenda(ResourceRequest resourceRequest) throws PortalException, SystemException {
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ final User user = PortalUtil.getUser(resourceRequest);
+ ResourceBundle messages = ResourceBundle.getBundle("content.Language", user.getLocale());
+
+ result = JSPPortletUtil.addFileEntry(resourceRequest, messages);
+
+ if(!result.getBoolean("error")){
+ result.put("agendaId", result.getString("id"));
+ result.put("agendaName", result.getString("name"));
+ }
+
+ return result;
+ }
+
+ private static JSONObject setAgendaView(ResourceRequest resourceRequest) {
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ try {
+ final long userId = PortalUtil.getUserId(resourceRequest);
+ final User user = UserLocalServiceUtil.getUser(userId);
+
+ final String agendaView = ParamUtil.getString(resourceRequest, "agendaView", "");
+
+ UserProperties up = null;
+ try{
+ up = UserPropertiesLocalServiceUtil.getUserPropertiesByUserId(user.getUserId());
+ up.setAgendaView(agendaView);
+ UserPropertiesLocalServiceUtil.updateUserProperties(up);
+
+ result.put("success", true);
+ } catch(Exception e){
+ if (_log.isErrorEnabled()) {
+ _log.error(e);
+ }
+ result.put("success", false);
+ }
+ } catch (Exception e) {
+ if (_log.isErrorEnabled()) {
+ _log.error(e);
+ }
+ result.put("success", false);
+ }
+
+ return result;
+ }
+
+ public static int getAgendaView(User user){
+ UserProperties up = null;
+ try{
+ up = UserPropertiesLocalServiceUtil.getUserPropertiesByUserId(user.getUserId());
+ } catch(Exception e){
+ _log.error(e);
+ }
+ String view = up.getAgendaView();
+ if(view.equals("day")){
+ return 0;
+ }else if(view.equals("fiveDay")){
+ return 1;
+ }else if(view.equals("week")){
+ return 2;
+ }else if(view.equals("twoWeek")){
+ return 3;
+ }else if(view.equals("month")){
+ return 4;
+ }else{
+ return -1;
+ }
+ }
+
+ private JSONObject showOrHideCalendar(ResourceRequest resourceRequest) throws PortalException, SystemException{
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+ final User user = PortalUtil.getUser(resourceRequest);
+
+ final long ressourceId = ParamUtil.getLong(resourceRequest, "ressourceId");
+ final boolean visible = ParamUtil.getBoolean(resourceRequest, "isVisible");
+
+ List<RessourceUser> listRessourceUser = RessourceUserLocalServiceUtil.getRessourceUserByRessourceId(ressourceId);
+
+ for(RessourceUser ru : listRessourceUser){
+ if(ru.getIdUser() == user.getUserId()){
+ ru.setVisible(visible);
+ RessourceUserLocalServiceUtil.updateRessourceUser(ru);
+ }
+ }
+ result.put("success", true);
+
+ return result;
+ }
+
+ 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);
+ }
+ }
+
+ protected String editJSP;
+ protected String helpJSP;
+ protected String viewJSP;
+
+ private static Log _log = LogFactoryUtil.getLog(JSPPortlet.class);
+
+}