--- /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>.
+ ******************************************************************************/
+package com.pentila.entSavoie.internalMessaging;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Set;
+
+import javax.mail.internet.InternetAddress;
+
+import com.liferay.mail.service.MailServiceUtil;
+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.io.FileCacheOutputStream;
+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.mail.MailMessage;
+import com.liferay.portal.kernel.repository.model.FileEntry;
+import com.liferay.portal.kernel.repository.model.Folder;
+import com.liferay.portal.kernel.util.FileUtil;
+import com.liferay.portal.kernel.util.HtmlUtil;
+import com.liferay.portal.kernel.util.OrderByComparator;
+import com.liferay.portal.kernel.util.StringPool;
+import com.liferay.portal.kernel.util.Validator;
+import com.liferay.portal.kernel.workflow.WorkflowConstants;
+import com.liferay.portal.model.Group;
+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.RoleLocalServiceUtil;
+import com.liferay.portal.service.ServiceContext;
+import com.liferay.portal.service.UserLocalServiceUtil;
+import com.liferay.portal.util.comparator.UserLastNameComparator;
+import com.liferay.portlet.documentlibrary.service.DLAppLocalServiceUtil;
+import com.pentila.entSavoie.ENTRolesConstants;
+import com.pentila.entSavoie.cartable.NoSuchDlLinkException;
+import com.pentila.entSavoie.cartable.model.DlLink;
+import com.pentila.entSavoie.cartable.service.DlLinkLocalServiceUtil;
+import com.pentila.entSavoie.internalMessaging.model.InternalAttachFile;
+import com.pentila.entSavoie.internalMessaging.model.InternalAutoResponse;
+import com.pentila.entSavoie.internalMessaging.model.InternalFolderMessage;
+import com.pentila.entSavoie.internalMessaging.model.InternalMessage;
+import com.pentila.entSavoie.internalMessaging.service.InternalAttachFileLocalServiceUtil;
+import com.pentila.entSavoie.internalMessaging.service.InternalAutoResponseLocalServiceUtil;
+import com.pentila.entSavoie.internalMessaging.service.InternalContentLocalServiceUtil;
+import com.pentila.entSavoie.internalMessaging.service.InternalFolderMessageLocalServiceUtil;
+import com.pentila.entSavoie.internalMessaging.service.InternalMessageLocalServiceUtil;
+import com.pentila.entSavoie.internalMessaging.service.InternalReceiversLocalServiceUtil;
+import com.pentila.entSavoie.service.DiskUsageUserLocalServiceUtil;
+import com.pentila.entSavoie.userProperties.model.UserProperties;
+import com.pentila.entSavoie.userProperties.service.UserPropertiesLocalServiceUtil;
+import com.pentila.entSavoie.utils.DLEntryUtil;
+import com.pentila.entSavoie.utils.ENTMainUtilsLocalServiceUtil;
+import com.pentila.entSavoie.utils.FoldersUtil;
+import com.pentila.entSavoie.utils.PortletConstant;
+import com.pentila.entSavoie.utils.ZipUtil;
+
+public class IMUtils {
+
+ private static Log logger = LogFactoryUtil.getLog(IMUtils.class);
+
+ public static boolean isGeneratedEmailAddress(User user, String userEmailAddress) {
+ String suffixe = ENTMainUtilsLocalServiceUtil.getENTOrgRootSuffixeMail(user.getCompanyId());
+ if(userEmailAddress.equals(user.getScreenName() + suffixe)){
+ return true;
+ }
+
+ return false;
+ }
+
+ public static void sendMessage(User sender, Set<Long> receiversFinal, String messageSubject, String messageContent, JSONArray attachFiles, long messageId) {
+ if(sendMessage(sender, receiversFinal, messageSubject, messageContent, attachFiles)){
+ if(messageId>0){
+ try {
+ long draftFolderId = InternalFolderMessageLocalServiceUtil.getUserFolderTypeMessages(sender.getUserId(), InternalMessagingConstants.DRAFT_FOLDER_TYPE).get(0).getFolderMessageId();
+ InternalMessage im = InternalMessageLocalServiceUtil.getInternalMessage(messageId);
+ long folderId = im.getFolderMessageId();
+ // Si on est dans les brouillons on le supprime
+ if(draftFolderId == folderId){
+ // on supprime definitivement
+ // delete file attach and set the memory free
+ if(im.getPjFolderId()>0){
+ DiskUsageUserLocalServiceUtil.substractDiskUsage(DLAppLocalServiceUtil.getFolder(im.getPjFolderId()), sender.getUserId(), PortletConstant.MESSAGERIE_PORTLET_ID);
+ }
+ InternalMessageLocalServiceUtil.deleteMessageAndDependencies(im);
+ }
+ } catch(Exception e){
+ logger.error("Exception when deleting dependencies.");
+ logger.error(e);
+ }
+ }
+ }
+ }
+
+ /**
+ * Envoi d'un message dans la messagerie
+ */
+ public static boolean sendMessage(User sender, Set<Long> receiversFinal, String messageSubject, String messageContent, JSONArray attachFiles) {
+ JSONArray errorDest = JSONFactoryUtil.createJSONArray();
+
+ boolean errorCopyFile = false;
+ String firstNameReceiver="";
+ Set<Long> filteredReceivers = new HashSet<Long>();
+
+ if (receiversFinal.size() > 0) {
+
+ // Limit the number of receivers if it reaches the limit
+ filteredReceivers = filterReceivers(sender, receiversFinal);
+
+ try {
+ User firstReceiverUser = UserLocalServiceUtil.getUser((Long) filteredReceivers.toArray()[0]);
+ firstNameReceiver = firstReceiverUser.getLastName() + " " + firstReceiverUser.getFirstName();
+ } catch (Exception e) {
+ logger.error("Error : exception when getting first receiver.");
+ logger.error(e);
+ }
+ }
+
+ String senderName = sender.getLastName()+" "+sender.getFirstName();
+ long senderId = sender.getUserId();
+
+ boolean isENTMailSenderUseForward = ENTMainUtilsLocalServiceUtil.isENTMailSenderUseForward(sender.getCompanyId());
+ String mailNoReply = ENTMainUtilsLocalServiceUtil.getMailNoReply(sender.getCompanyId());
+ String mailRedirectSubject = ENTMainUtilsLocalServiceUtil.getMailRedirectSubject(sender.getCompanyId());
+ String mailRedirectBody = ENTMainUtilsLocalServiceUtil.getMailRedirectBody(sender.getCompanyId());
+ long messageSenderId = 0;
+ long pjFolderId = 0;
+
+ // on prepare les pieces jointes pour la creation de liens
+ JSONArray attachFilesProcessed = JSONFactoryUtil.createJSONArray();
+ if (attachFiles.length() > 0) {
+ try {
+ attachFilesProcessed = preprareAttachFiles(senderId, attachFiles);
+ } catch (Exception e) {
+ logger.error("Error : exception when preparing attached files.");
+ logger.error(e);
+ }
+ }
+ // remove emoticone in UT8-MB4 from content and subject
+ String replacedContent = (messageContent == null)?"":messageContent.replaceAll("[^\\u0000-\\uFFFF]", "");
+ String replacedSubject = (messageSubject == null)?"":messageSubject.replaceAll("[^\\u0000-\\uFFFF]", "");
+
+ try {
+ // Envoi du message dans la boite d'envoi de l'envoyeur
+ InternalFolderMessage sendFolder = InternalFolderMessageLocalServiceUtil.getUserFolderTypeMessages(senderId, InternalMessagingConstants.SENDING_FOLDER_TYPE).get(0);
+
+ // First create the message with the content, so that the index can index the content
+ InternalMessage message = InternalMessageLocalServiceUtil.addMessage(sender.getCompanyId(), sendFolder.getFolderMessageId(), senderId, senderName, firstNameReceiver, new Date(), replacedSubject, replacedContent, false,0);
+ InternalContentLocalServiceUtil.addContent(message.getMessageId(), replacedContent);
+ // Then update the message with empty content, reindexing is commented so no problem
+ message.setMessageContent("");
+ InternalMessageLocalServiceUtil.updateInternalMessage(message);
+
+ // Gestion des destinataires
+ InternalReceiversLocalServiceUtil.addInternalReceivers(message.getMessageId(), filteredReceivers);
+
+ if (attachFilesProcessed.length()>0) {
+ try{
+ // Gestion des pièces jointes
+ //Long
+ pjFolderId = copyAttachFile(senderId, senderId, message.getMessageId(), attachFilesProcessed);
+ message.setPjFolderId(pjFolderId);
+ } catch(Exception e){
+ logger.error("Error : exception when copying attached files.");
+ logger.error(e);
+ errorCopyFile = true;
+ }
+ InternalMessageLocalServiceUtil.updateInternalMessage(message);
+ }
+
+ messageSenderId = message.getPrimaryKey();
+ }
+ catch (Exception e) {
+ logger.error("Error : Cannot add the message in the receiver box.");
+ logger.error(e);
+ }
+
+ String mailFromSender = mailNoReply;
+ // test si on utilise le noreply ou l adresse du mec
+ if (isENTMailSenderUseForward) {
+ try {
+ UserProperties up = UserPropertiesLocalServiceUtil.getUserPropertiesByUserId(senderId);
+ if (up != null && up.getForwardByMail() && !up.getForwardMail().isEmpty()) {
+ mailFromSender = up.getForwardMail();
+ }
+ } catch (Exception e) {
+ logger.error(e);
+ }
+ }
+
+ InternalFolderMessage sendFolder = null;
+ try {
+ sendFolder = InternalFolderMessageLocalServiceUtil.getUserFolderTypeMessages(senderId, InternalMessagingConstants.INCOMMING_FOLDER_TYPE).get(0);
+ } catch (SystemException e1) {
+ // TODO Auto-generated catch block
+ e1.printStackTrace();
+ }
+ //-------------------------------------------------------------------------------------------------------------------------------------------
+ // get the receiverbox
+ for (long receiverId: filteredReceivers) {
+ try {
+ // Envoie des reponses automatiques
+ InternalAutoResponse internalAutoResponse = InternalAutoResponseLocalServiceUtil.getInternalAutoResponse(receiverId, sender.getUserId());
+ if(Validator.isNotNull(internalAutoResponse)){
+ if(Validator.isNotNull(sendFolder)){
+ User receiver = UserLocalServiceUtil.getUser(receiverId);
+ String receiverName = receiver.getLastName() + " " + receiver.getFirstName();
+
+ // remove emoticone in UT8-MB4 from content and subject
+ String autoResponseContent = (internalAutoResponse.getContent() == null)?"":internalAutoResponse.getContent().replaceAll("[^\\u0000-\\uFFFF]", "");
+ String autoResponseSubject = (internalAutoResponse.getSubject() == null)?"":internalAutoResponse.getSubject().replaceAll("[^\\u0000-\\uFFFF]", "");
+
+ InternalMessage message = InternalMessageLocalServiceUtil.addMessage(sender.getCompanyId(), sendFolder.getFolderMessageId(), receiverId, receiverName, senderName, new Date(), autoResponseSubject, autoResponseContent, true, 0);
+ InternalContentLocalServiceUtil.addContent(message.getMessageId(), autoResponseContent);
+ // Then update the message with empty content, reindexing is commented so no problem
+ message.setMessageContent("");
+ InternalMessageLocalServiceUtil.updateInternalMessage(message);
+
+ // Gestion des destinataires
+ Set<Long> dest = new HashSet<Long>();
+ dest.add(sender.getUserId());
+ InternalReceiversLocalServiceUtil.addInternalReceivers(message.getMessageId(), dest);
+ }
+ // Si l'utilisteur ne souhaite pas recevoir le message
+ // On envoi simplement la reponse automatique
+ if(!internalAutoResponse.getReceive()){
+ continue;
+ }
+ }
+
+ InternalFolderMessage destFolder = InternalFolderMessageLocalServiceUtil.getUserFolderTypeMessages(receiverId, InternalMessagingConstants.INCOMMING_FOLDER_TYPE).get(0);
+
+ InternalMessage message = InternalMessageLocalServiceUtil.addMessage(sender.getCompanyId(), destFolder.getFolderMessageId(), senderId,
+ senderName, firstNameReceiver, new Date(), replacedSubject, replacedContent, true, messageSenderId);
+ // Then update the message with empty content, reindexing is commented so no problem
+ message.setMessageContent("");
+ InternalMessageLocalServiceUtil.updateInternalMessage(message);
+
+
+ if (attachFilesProcessed.length()>0) {
+ try{
+ // Take care of the attachments by setting the right folderID
+ message.setPjFolderId(pjFolderId);
+ InternalMessageLocalServiceUtil.updateInternalMessage(message);
+ } catch(Exception e){
+ errorCopyFile = true;
+ }
+ }
+
+ /* On notifie la personne sur son téléphone mobile (Non fonctionnel/Not working anymore)
+ ThreadMobileNotification notifThread = new ThreadMobileNotification(receiverId, "Vous avez recu un nouveau message de " + PortalUtil.getUserName(sender.getUserId(), "ENT"));
+ notifThread.start();
+ */
+
+ // Send the redirections if exists
+ UserProperties up = UserPropertiesLocalServiceUtil.getUserPropertiesByUserId(receiverId);
+ if (up != null && up.getForwardByMail() && !up.getForwardMail().isEmpty()) {
+ InternetAddress iaTo = new InternetAddress(up.getForwardMail());
+
+ InternetAddress iaFrom = new InternetAddress(mailFromSender);
+
+ //Gestion des copies par mail
+ MailMessage mailMessage = new MailMessage();
+
+ mailMessage.setFrom(iaFrom);
+ mailMessage.setTo(iaTo);
+
+ mailMessage.setHTMLFormat(true);
+
+ String subjectForward = HtmlUtil.extractText(replacedSubject);
+ mailMessage.setSubject(mailRedirectSubject + " " + subjectForward);
+ mailMessage.setBody(String.format(mailRedirectBody, senderName) + replacedContent);
+
+ for (int i = 0 ; i<attachFiles.length(); i++) {
+
+ Long fileId = attachFiles.getJSONObject(i).getLong("id");
+ String type = attachFiles.getJSONObject(i).getString("type");
+
+ if (type.equals("Fichier")) {
+ FileEntry dlFile = DLAppLocalServiceUtil.getFileEntry(fileId);
+ InputStream fileStream = dlFile.getContentStream();
+ File finalFile = FileUtil.createTempFile(dlFile.getTitle());
+ FileUtil.write(finalFile, fileStream);
+
+ mailMessage.addFileAttachment(finalFile);
+
+ try {
+ fileStream.close();
+ } catch (IOException e) {}
+ } else {
+ //Cas d'un dossier, on le zip
+ long[] folderIdArray = new long[] { fileId };
+
+ try {
+
+ Folder folder = DLAppLocalServiceUtil.getFolder(fileId);
+ FileCacheOutputStream zipStream = ZipUtil.createZipStream(sender, folderIdArray, new long[0]);
+ File finalFile = FileUtil.createTempFile(folder.getName() + ".zip");
+ FileUtil.write(finalFile, zipStream.getBytes());
+
+ mailMessage.addFileAttachment(finalFile);
+ }
+ catch (Exception e) {}
+ }
+ }
+
+ MailServiceUtil.sendEmail(mailMessage);
+ }
+ }
+ catch (Exception e) {
+ logger.error("Error during sending message \"" + replacedSubject + "\" from sender : "
+ + senderName + "(user id:" + senderId + ") to user " + receiverId + " at date : " + new Date(), e );
+ errorDest.put(receiverId);
+ }
+
+ }
+ // If errors dectected, we send a warning message to the original sender
+ if (errorDest.length()!=0) {
+ // on envoie un message pour l'informer
+ Set<Long> errorSender = new HashSet<Long>();
+ errorSender.add(sender.getUserId());
+ try {
+ String message = "Une erreur s'est produite durant l'envoi de votre message.<br>Celui-ci n'a pu être transmis aux personnes suivantes: <br><ul>";
+ for (int i=0; i<errorDest.length(); i++) {
+ Long idDest = errorDest.getLong(i);
+ User userDest = UserLocalServiceUtil.getUser(idDest);
+ message += "<li>"+userDest.getFirstName() + " " + userDest.getLastName() + "</li>";
+ }
+ message += "</ul>";
+ if(errorCopyFile){
+ message += "<br /> Cette erreur semble venir des documents attachés au message.";
+ }
+
+ message += "<br />";
+ message += "<br />";
+ message += "Message non transmis aux différents destinataires : <br />";
+ message += "<b>Sujet : </b>" + replacedSubject + "<br />";
+ message += "<b>Contenu : </b><br />" + replacedContent + "<br />";
+
+ sendMessage(sender,
+ errorSender,
+ "Erreur lors de l'envoi du message: " + replacedSubject,
+ message,
+ JSONFactoryUtil.createJSONArray());
+ return false;
+ }
+ catch (Exception e) {
+ // impossible d'ajouter le message dans la boite d'envoi de l 'expediteur
+ // --> ON NE PEUT PAS FAIRE GRAND CHOSE DANS CE CAS !!!
+ logger.error(e);
+ return false;
+ }
+ }
+
+ return true;
+
+ }
+
+
+ /**
+ * Limit the number of receivers to the max limits defined in the portal-ext.properties file depending on its role
+ * @param sender
+ * @param receivers
+ * @return
+ */
+ private static Set<Long> filterReceivers(User sender, Set<Long> receivers) {
+
+ int maxStudentReceivers = ENTMainUtilsLocalServiceUtil.getMessagingStudentMaxReceivers();
+ int maxParentReceivers = ENTMainUtilsLocalServiceUtil.getMessagingParentMaxReceivers();
+ int maxPersonalReceivers = ENTMainUtilsLocalServiceUtil.getMessagingPersonalMaxReceivers();
+ int min = Math.min(maxStudentReceivers, Math.min(maxParentReceivers, maxPersonalReceivers));
+
+ // If no max limit is reached, return the init receivers list
+ if (receivers.size() < min) {
+ return receivers;
+ }
+ try {
+ Role studentRole = RoleLocalServiceUtil.getRole(sender.getCompanyId(), ENTRolesConstants.ELEVE);
+ Role parentRole = RoleLocalServiceUtil.getRole(sender.getCompanyId(), ENTRolesConstants.PARENT);
+ if (RoleLocalServiceUtil.hasUserRole(sender.getUserId(), studentRole.getRoleId()) && receivers.size() > maxStudentReceivers) {
+ logger.error("Student "+sender.getFullName()+" tries to send an internal message to "+receivers.size()+" users => limit this number to "+maxStudentReceivers);
+ return filterMaxReceivers(receivers, maxStudentReceivers);
+ } else if (RoleLocalServiceUtil.hasUserRole(sender.getUserId(), parentRole.getRoleId()) && receivers.size() > maxParentReceivers) {
+ logger.error("Parent "+sender.getFullName()+" tries to send an internal message to "+receivers.size()+" users => limit this number to "+maxParentReceivers);
+ return filterMaxReceivers(receivers, maxParentReceivers);
+ } else {
+ logger.error("User "+sender.getFullName()+" tries to send an internal message to "+receivers.size()+" users => limit this number to "+maxPersonalReceivers);
+ return filterMaxReceivers(receivers, maxPersonalReceivers);
+ }
+ } catch (Exception e) {
+ logger.error("Error when filtering the number of receivers for message sent by user "+sender.getUserId(), e);
+ }
+ return receivers;
+ }
+
+
+ private static Set<Long> filterMaxReceivers(Set<Long> receivers, int max) {
+
+ Set<Long> filteredReceivers = new HashSet<Long>();
+
+ if (receivers.size() > max) {
+ int nbReceivers = 0;
+ for (Long receiverId : receivers) {
+ if (nbReceivers < max) {
+ filteredReceivers.add(receiverId);
+ nbReceivers++;
+ }
+ }
+ } else {
+ filteredReceivers = receivers;
+ }
+ return filteredReceivers;
+ }
+
+ /**
+ * Gestion des pièces jointes
+ * @throws SystemException
+ * @throws PortalException
+ * @throws IOException
+ */
+ private static JSONArray preprareAttachFiles(long senderId, JSONArray attachFiles) throws PortalException, SystemException, IOException {
+ JSONArray copyResults = JSONFactoryUtil.createJSONArray();
+ // boite d'envoi de la personne
+ final Folder senderTmpBox = FoldersUtil.getSendingBox(senderId);
+ // on cree un dossier pour chaque message
+ Date stamp = new Date();
+ Folder messageSendingFolder = DLAppLocalServiceUtil.addFolder(
+ senderId,
+ senderTmpBox.getGroupId(),
+ senderTmpBox.getFolderId(),
+ ""+stamp.getTime(),
+ "PJ du message " + stamp.getTime(),
+ new ServiceContext());
+
+ for (int i=0; i<attachFiles.length(); i++) {
+ JSONObject pjobj = attachFiles.getJSONObject(i);
+ try{
+ if (pjobj.getString("type").equals("Fichier")) {
+ // cas d'un fichier
+ Long sourceFileId = pjobj.getLong("id");
+ try {
+ DlLink dll = DlLinkLocalServiceUtil.getDlFileLinkByTarget(sourceFileId);
+ sourceFileId = dll.getSourceId();
+ }
+ catch(NoSuchDlLinkException nsdle) {
+ // no link so we have an original
+ }
+
+ FileEntry referenceFile = DLEntryUtil.copyFileEntry(senderId, sourceFileId, messageSendingFolder.getFolderId());
+ //add disk usage to sender because the folder or/and file is store on it's output box
+ DiskUsageUserLocalServiceUtil.addDiskUsage(referenceFile, senderId, PortletConstant.MESSAGERIE_PORTLET_ID);
+ JSONObject fileObj = JSONFactoryUtil.createJSONObject();
+ fileObj.put("type", "Fichier");
+ fileObj.put("id", referenceFile.getFileEntryId());
+ copyResults.put(fileObj);
+ }
+ else if (pjobj.getString("type").equals("Dossier")) {
+ // cas d'un dossier
+ Long sourceFolderId = pjobj.getLong("id");
+ try {
+ DlLink dll = DlLinkLocalServiceUtil.getDlFolderLinkByTarget(sourceFolderId);
+ sourceFolderId = dll.getSourceId();
+ }
+ catch(NoSuchDlLinkException nsdle) {
+ // no link so we have an original
+ }
+ Folder referenceFolder = DLEntryUtil.copyFolder(senderId, sourceFolderId, messageSendingFolder.getFolderId());
+ // add disk usage to sender because the folder or/and file is store on it's output box
+ DiskUsageUserLocalServiceUtil.addDiskUsage(referenceFolder, senderId, PortletConstant.MESSAGERIE_PORTLET_ID);
+ JSONObject fileObj = JSONFactoryUtil.createJSONObject();
+ fileObj.put("type", "Dossier");
+ fileObj.put("id", referenceFolder.getFolderId());
+ copyResults.put(fileObj);
+ }
+ }
+ catch (NullPointerException e) {
+ // cas d'un fichier
+ Long sourceFileId = attachFiles.getLong(i);
+ try {
+ DlLink dll = DlLinkLocalServiceUtil.getDlFileLinkByTarget(sourceFileId);
+ sourceFileId = dll.getSourceId();
+ }
+ catch(NoSuchDlLinkException nsdle) {
+ // no link so we have an original
+ }
+ FileEntry referenceFile = DLEntryUtil.copyFileEntry(senderId, sourceFileId, messageSendingFolder.getFolderId());
+ // add disk usage to sender because the folder or/and file is store on it's output box
+ DiskUsageUserLocalServiceUtil.addDiskUsage(referenceFile, senderId, PortletConstant.MESSAGERIE_PORTLET_ID);
+ JSONObject fileObj = JSONFactoryUtil.createJSONObject();
+ fileObj.put("type", "Fichier");
+ fileObj.put("id", referenceFile.getFileEntryId());
+ copyResults.put(fileObj);
+ }
+ }
+ return copyResults;
+ }
+
+ private static Long copyAttachFile(long senderId, long receiverId, long messageId, JSONArray attachFiles) throws PortalException, SystemException, IOException {
+ final Folder receiverDropBox = FoldersUtil.getIMBox(receiverId);
+ // on cree un dossier pour chaque message
+ Folder messageFolder = DLAppLocalServiceUtil.addFolder(
+ receiverId,
+ receiverDropBox.getGroupId(),
+ receiverDropBox.getFolderId(),
+ String.valueOf(messageId),
+ "PJ du message " + messageId,
+ new ServiceContext());
+
+ for (int i=0; i<attachFiles.length(); i++) {
+ JSONObject pjobj = attachFiles.getJSONObject(i);
+ try{
+ if (pjobj.getString("type").equals("Fichier")) {
+ // cas d'un fichier
+ FileEntry newEntry = DLEntryUtil.copyLinkedFileEntry(receiverId, pjobj.getLong("id"), messageFolder.getFolderId(), PortletConstant.MESSAGERIE_PORTLET_ID);
+
+ InternalAttachFile pjFile = InternalAttachFileLocalServiceUtil.addAttachFile();
+ pjFile.setAttachFileType("Fichier");
+ pjFile.setMessageId(messageId);
+ pjFile.setAttachFileId(newEntry.getFileEntryId());
+ InternalAttachFileLocalServiceUtil.updateInternalAttachFile(pjFile);
+ }
+ else if (pjobj.getString("type").equals("Dossier")) {
+ // cas d'un dossier
+
+ Folder newFolder = DLEntryUtil.copyLinkedFolder(receiverId, pjobj.getLong("id"), messageFolder.getFolderId(), PortletConstant.MESSAGERIE_PORTLET_ID);
+ InternalAttachFile pjFolder = InternalAttachFileLocalServiceUtil.addAttachFile();
+ pjFolder.setAttachFileType("Dossier");
+ pjFolder.setMessageId(messageId);
+ pjFolder.setAttachFileId(newFolder.getFolderId());
+ InternalAttachFileLocalServiceUtil.updateInternalAttachFile(pjFolder);
+ }
+ }
+ catch (NullPointerException e) {
+ // cas d'un fichier
+ FileEntry newEntry = DLEntryUtil.copyLinkedFileEntry(receiverId, attachFiles.getLong(i), messageFolder.getFolderId(), PortletConstant.MESSAGERIE_PORTLET_ID);
+
+ InternalAttachFile pjFile = InternalAttachFileLocalServiceUtil.addAttachFile();
+ pjFile.setAttachFileType("Fichier");
+ pjFile.setMessageId(messageId);
+ pjFile.setAttachFileId(newEntry.getFileEntryId());
+ InternalAttachFileLocalServiceUtil.updateInternalAttachFile(pjFile);
+ }
+ }
+
+ return messageFolder.getFolderId();
+ }
+}