View Javadoc
1   /*
2    * DavMail POP/IMAP/SMTP/CalDav/LDAP Exchange Gateway
3    * Copyright (C) 2009  Mickael Guessant
4    *
5    * This program is free software; you can redistribute it and/or
6    * modify it under the terms of the GNU General Public License
7    * as published by the Free Software Foundation; either version 2
8    * of the License, or (at your option) any later version.
9    *
10   * This program is distributed in the hope that it will be useful,
11   * but WITHOUT ANY WARRANTY; without even the implied warranty of
12   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13   * GNU General Public License for more details.
14   *
15   * You should have received a copy of the GNU General Public License
16   * along with this program; if not, write to the Free Software
17   * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18   */
19  package davmail.exchange;
20  
21  import davmail.BundleMessage;
22  import davmail.Settings;
23  import davmail.exception.DavMailException;
24  import davmail.exception.HttpForbiddenException;
25  import davmail.exception.HttpNotFoundException;
26  import davmail.http.URIUtil;
27  import davmail.ui.NotificationDialog;
28  import davmail.util.StringUtil;
29  import org.apache.log4j.Logger;
30  
31  import javax.mail.MessagingException;
32  import javax.mail.internet.InternetAddress;
33  import javax.mail.internet.InternetHeaders;
34  import javax.mail.internet.MimeMessage;
35  import javax.mail.internet.MimeMultipart;
36  import javax.mail.internet.MimePart;
37  import javax.mail.util.SharedByteArrayInputStream;
38  import javax.net.ssl.SSLException;
39  import java.io.ByteArrayOutputStream;
40  import java.io.File;
41  import java.io.IOException;
42  import java.io.InputStream;
43  import java.io.OutputStreamWriter;
44  import java.io.StringReader;
45  import java.net.NoRouteToHostException;
46  import java.net.SocketTimeoutException;
47  import java.net.UnknownHostException;
48  import java.nio.charset.StandardCharsets;
49  import java.nio.file.Files;
50  import java.nio.file.Paths;
51  import java.text.ParseException;
52  import java.text.SimpleDateFormat;
53  import java.util.ArrayList;
54  import java.util.Arrays;
55  import java.util.Calendar;
56  import java.util.Collections;
57  import java.util.Date;
58  import java.util.Enumeration;
59  import java.util.HashMap;
60  import java.util.HashSet;
61  import java.util.List;
62  import java.util.Locale;
63  import java.util.Map;
64  import java.util.Properties;
65  import java.util.ResourceBundle;
66  import java.util.Set;
67  import java.util.SimpleTimeZone;
68  import java.util.TimeZone;
69  import java.util.TreeMap;
70  import java.util.UUID;
71  
72  /**
73   * Exchange session through Outlook Web Access (DAV)
74   */
75  public abstract class ExchangeSession {
76  
77      protected static final Logger LOGGER = Logger.getLogger("davmail.exchange.ExchangeSession");
78  
79      /**
80       * Reference GMT timezone to format dates
81       */
82      public static final SimpleTimeZone GMT_TIMEZONE = new SimpleTimeZone(0, "GMT");
83  
84      protected static final int FREE_BUSY_INTERVAL = 15;
85  
86      protected static final String PUBLIC_ROOT = "/public/";
87      protected static final String CALENDAR = "calendar";
88      protected static final String TASKS = "tasks";
89      /**
90       * Contacts folder logical name
91       */
92      public static final String CONTACTS = "contacts";
93      protected static final String ADDRESSBOOK = "addressbook";
94      protected static final String ARCHIVE = "Archive";
95      protected static final String INBOX = "INBOX";
96      protected static final String LOWER_CASE_INBOX = "inbox";
97      protected static final String MIXED_CASE_INBOX = "Inbox";
98      protected static final String SENT = "Sent";
99      protected static final String SENDMSG = "##DavMailSubmissionURI##";
100     protected static final String DRAFTS = "Drafts";
101     protected static final String TRASH = "Trash";
102     protected static final String JUNK = "Junk";
103     protected static final String UNSENT = "Unsent Messages";
104 
105     protected static final List<String> SPECIAL = Arrays.asList(SENT, DRAFTS, TRASH, JUNK, ARCHIVE);
106 
107     // see https://learn.microsoft.com/en-us/openspecs/exchange_server_protocols/ms-oxomsg/87a8b6b8-59a4-4859-9dcd-8b0f36e3d729
108     protected static final String REPLYTOSENDER = "102";
109     protected static final String REPLYTOALL = "103";
110     protected static final String FORWARD = "104";
111 
112     protected static final String REPLIED_ICON = "261";
113     protected static final String FORWARDED_ICON = "262";
114 
115     static {
116         // Adjust Mime decoder settings
117         System.setProperty("mail.mime.ignoreunknownencoding", "true");
118         System.setProperty("mail.mime.decodetext.strict", "false");
119     }
120 
121     protected String publicFolderUrl;
122 
123     /**
124      * Base user mailboxes path (used to select folder)
125      */
126     protected String mailPath;
127     protected String rootPath;
128     protected String email;
129     protected String alias;
130     /**
131      * Lower case Caldav path to the current user mailbox.
132      * /users/<i>email</i>
133      */
134     protected String currentMailboxPath;
135 
136     protected String userName;
137 
138     protected String serverVersion;
139 
140     protected static final String YYYY_MM_DD_HH_MM_SS = "yyyy/MM/dd HH:mm:ss";
141     private static final String YYYYMMDD_T_HHMMSS_Z = "yyyyMMdd'T'HHmmss'Z'";
142     protected static final String YYYY_MM_DD_T_HHMMSS_Z = "yyyy-MM-dd'T'HH:mm:ss'Z'";
143     private static final String YYYY_MM_DD = "yyyy-MM-dd";
144     private static final String YYYY_MM_DD_T_HHMMSS_SSS_Z = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
145 
146     public ExchangeSession() {
147         // empty constructor
148     }
149 
150     /**
151      * Close session.
152      * Shutdown http client connection manager
153      */
154     public abstract void close();
155 
156     /**
157      * Format date to exchange search format.
158      *
159      * @param date date object
160      * @return formatted search date
161      */
162     public abstract String formatSearchDate(Date date);
163 
164     /**
165      * Return standard zulu date formatter.
166      *
167      * @return zulu date formatter
168      */
169     public static SimpleDateFormat getZuluDateFormat() {
170         SimpleDateFormat dateFormat = new SimpleDateFormat(YYYYMMDD_T_HHMMSS_Z, Locale.ENGLISH);
171         dateFormat.setTimeZone(GMT_TIMEZONE);
172         return dateFormat;
173     }
174 
175     protected static SimpleDateFormat getVcardBdayFormat() {
176         SimpleDateFormat dateFormat = new SimpleDateFormat(YYYY_MM_DD, Locale.ENGLISH);
177         dateFormat.setTimeZone(GMT_TIMEZONE);
178         return dateFormat;
179     }
180 
181     protected static SimpleDateFormat getExchangeDateFormat(String value) {
182         SimpleDateFormat dateFormat;
183         if (value.length() == 8) {
184             dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
185             dateFormat.setTimeZone(GMT_TIMEZONE);
186         } else if (value.length() == 15) {
187             dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ENGLISH);
188             dateFormat.setTimeZone(GMT_TIMEZONE);
189         } else if (value.length() == 16) {
190             dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss'Z'", Locale.ENGLISH);
191             dateFormat.setTimeZone(GMT_TIMEZONE);
192         } else {
193             dateFormat = ExchangeSession.getExchangeZuluDateFormat();
194         }
195         return dateFormat;
196     }
197 
198     protected static SimpleDateFormat getExchangeZuluDateFormat() {
199         SimpleDateFormat dateFormat = new SimpleDateFormat(YYYY_MM_DD_T_HHMMSS_Z, Locale.ENGLISH);
200         dateFormat.setTimeZone(GMT_TIMEZONE);
201         return dateFormat;
202     }
203 
204     protected static SimpleDateFormat getExchangeZuluDateFormatMillisecond() {
205         SimpleDateFormat dateFormat = new SimpleDateFormat(YYYY_MM_DD_T_HHMMSS_SSS_Z, Locale.ENGLISH);
206         dateFormat.setTimeZone(GMT_TIMEZONE);
207         return dateFormat;
208     }
209 
210     protected static Date parseDate(String dateString) throws ParseException {
211         SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
212         dateFormat.setTimeZone(GMT_TIMEZONE);
213         return dateFormat.parse(dateString);
214     }
215 
216 
217     /**
218      * Test if the session expired.
219      *
220      * @return true if this session expired
221      * @throws IOException on transport-level network error
222      */
223     public boolean isExpired() throws IOException {
224         boolean isExpired = false;
225         try {
226             getFolder("");
227         } catch (UnknownHostException | NoRouteToHostException |
228                  SocketTimeoutException | SSLException exc) {
229             // rethrow on network error to avoid reauthentication
230             throw exc;
231         } catch (IOException e) {
232             isExpired = true;
233         }
234 
235         return isExpired;
236     }
237 
238     protected abstract void buildSessionInfo(java.net.URI uri) throws IOException;
239 
240     /**
241      * Create a message in the specified folder.
242      * Will overwrite an existing message with the same subject in the same folder
243      *
244      * @param folderPath  Exchange folder path
245      * @param messageName message name
246      * @param properties  message properties (flags)
247      * @param mimeMessage MIME message
248      * @throws IOException when unable to create message
249      */
250     public abstract Message createMessage(String folderPath, String messageName, HashMap<String, String> properties, MimeMessage mimeMessage) throws IOException;
251 
252     /**
253      * Update given properties on message.
254      *
255      * @param message    Exchange message
256      * @param properties Webdav properties map
257      * @throws IOException on error
258      */
259     public abstract void updateMessage(Message message, Map<String, String> properties) throws IOException;
260 
261 
262     /**
263      * Delete Exchange message.
264      *
265      * @param message Exchange message
266      * @throws IOException on error
267      */
268     public abstract void deleteMessage(Message message) throws IOException;
269 
270     /**
271      * Get raw MIME message content
272      *
273      * @param message Exchange message
274      * @return message body
275      * @throws IOException on error
276      */
277     protected abstract byte[] getContent(Message message) throws IOException;
278 
279     protected static final Set<String> POP_MESSAGE_ATTRIBUTES = new HashSet<>();
280 
281     static {
282         POP_MESSAGE_ATTRIBUTES.add("uid");
283         POP_MESSAGE_ATTRIBUTES.add("imapUid");
284         POP_MESSAGE_ATTRIBUTES.add("messageSize");
285     }
286 
287     /**
288      * Return folder message list with id and size only (for POP3 listener).
289      *
290      * @param folderName Exchange folder name
291      * @return folder message list
292      * @throws IOException on error
293      */
294     public MessageList getAllMessageUidAndSize(String folderName) throws IOException {
295         return searchMessages(folderName, POP_MESSAGE_ATTRIBUTES, null);
296     }
297 
298     protected static final Set<String> IMAP_MESSAGE_ATTRIBUTES = new HashSet<>();
299 
300     static {
301         IMAP_MESSAGE_ATTRIBUTES.add("permanenturl");
302         IMAP_MESSAGE_ATTRIBUTES.add("urlcompname");
303         IMAP_MESSAGE_ATTRIBUTES.add("uid");
304         IMAP_MESSAGE_ATTRIBUTES.add("messageSize");
305         IMAP_MESSAGE_ATTRIBUTES.add("imapUid");
306         IMAP_MESSAGE_ATTRIBUTES.add("junk");
307         IMAP_MESSAGE_ATTRIBUTES.add("flagStatus");
308         IMAP_MESSAGE_ATTRIBUTES.add("messageFlags");
309         IMAP_MESSAGE_ATTRIBUTES.add("lastVerbExecuted");
310         IMAP_MESSAGE_ATTRIBUTES.add("read");
311         IMAP_MESSAGE_ATTRIBUTES.add("deleted");
312         IMAP_MESSAGE_ATTRIBUTES.add("date");
313         IMAP_MESSAGE_ATTRIBUTES.add("lastmodified");
314         // OSX IMAP requests content-class
315         IMAP_MESSAGE_ATTRIBUTES.add("contentclass");
316         IMAP_MESSAGE_ATTRIBUTES.add("keywords");
317     }
318 
319     protected static final Set<String> UID_MESSAGE_ATTRIBUTES = new HashSet<>();
320 
321     static {
322         UID_MESSAGE_ATTRIBUTES.add("uid");
323     }
324 
325     /**
326      * Get all folder messages.
327      *
328      * @param folderPath Exchange folder name
329      * @return message list
330      * @throws IOException on error
331      */
332     public MessageList searchMessages(String folderPath) throws IOException {
333         return searchMessages(folderPath, IMAP_MESSAGE_ATTRIBUTES, null);
334     }
335 
336     /**
337      * Search folder for messages matching conditions, with attributes needed by IMAP listener.
338      *
339      * @param folderName Exchange folder name
340      * @param condition  search filter
341      * @return message list
342      * @throws IOException on error
343      */
344     public MessageList searchMessages(String folderName, Condition condition) throws IOException {
345         return searchMessages(folderName, IMAP_MESSAGE_ATTRIBUTES, condition);
346     }
347 
348     /**
349      * Search folder for messages matching conditions, with given attributes.
350      *
351      * @param folderName Exchange folder name
352      * @param attributes requested Webdav attributes
353      * @param condition  search filter
354      * @return message list
355      * @throws IOException on error
356      */
357     public abstract MessageList searchMessages(String folderName, Set<String> attributes, Condition condition) throws IOException;
358 
359     /**
360      * Get server version (Exchange2003, Exchange2007 or Exchange2010)
361      *
362      * @return server version
363      */
364     public String getServerVersion() {
365         return serverVersion;
366     }
367 
368     public enum Operator {
369         Or, And, Not, IsEqualTo,
370         IsGreaterThan, IsGreaterThanOrEqualTo,
371         IsLessThan, IsLessThanOrEqualTo,
372         IsNull, IsTrue, IsFalse,
373         Like, StartsWith, Contains
374     }
375 
376     /**
377      * Exchange search filter.
378      */
379     public interface Condition {
380         /**
381          * Append condition to buffer.
382          *
383          * @param buffer search filter buffer
384          */
385         void appendTo(StringBuilder buffer);
386 
387         /**
388          * True if condition is empty.
389          *
390          * @return true if condition is empty
391          */
392         boolean isEmpty();
393 
394         /**
395          * Test if the contact matches current condition.
396          *
397          * @param contact Exchange Contact
398          * @return true if contact matches condition
399          */
400         boolean isMatch(ExchangeSession.Contact contact);
401     }
402 
403     /**
404      * Attribute condition.
405      */
406     public abstract static class AttributeCondition implements Condition {
407         protected final String attributeName;
408         protected final Operator operator;
409         protected final String value;
410 
411         protected AttributeCondition(String attributeName, Operator operator, String value) {
412             this.attributeName = attributeName;
413             this.operator = operator;
414             this.value = value;
415         }
416 
417         public boolean isEmpty() {
418             return false;
419         }
420 
421         /**
422          * Get attribute name.
423          *
424          * @return attribute name
425          */
426         public String getAttributeName() {
427             return attributeName;
428         }
429 
430         /**
431          * Condition value.
432          *
433          * @return value
434          */
435         public String getValue() {
436             return value;
437         }
438 
439     }
440 
441     /**
442      * Multiple condition.
443      */
444     public abstract static class MultiCondition implements Condition {
445         protected final Operator operator;
446         protected final List<Condition> conditions;
447 
448         protected MultiCondition(Operator operator, Condition... conditions) {
449             this.operator = operator;
450             this.conditions = new ArrayList<>();
451             for (Condition condition : conditions) {
452                 if (condition != null) {
453                     this.conditions.add(condition);
454                 }
455             }
456         }
457 
458         /**
459          * Conditions list.
460          *
461          * @return conditions
462          */
463         public List<Condition> getConditions() {
464             return conditions;
465         }
466 
467         /**
468          * Condition operator.
469          *
470          * @return operator
471          */
472         public Operator getOperator() {
473             return operator;
474         }
475 
476         /**
477          * Add a new condition.
478          *
479          * @param condition single condition
480          */
481         public void add(Condition condition) {
482             if (condition != null) {
483                 conditions.add(condition);
484             }
485         }
486 
487         @Override
488         public boolean isEmpty() {
489             return getActualConditionCount() == 0;
490         }
491 
492         protected int getActualConditionCount() {
493             int count = 0;
494             for (Condition condition : conditions) {
495                 if (!condition.isEmpty()) {
496                     count++;
497                 }
498             }
499             return count;
500         }
501 
502         public boolean isMatch(ExchangeSession.Contact contact) {
503             if (operator == Operator.And) {
504                 for (Condition condition : conditions) {
505                     if (!condition.isMatch(contact)) {
506                         return false;
507                     }
508                 }
509                 return true;
510             } else if (operator == Operator.Or) {
511                 for (Condition condition : conditions) {
512                     if (condition.isMatch(contact)) {
513                         return true;
514                     }
515                 }
516                 return false;
517             } else {
518                 return false;
519             }
520         }
521 
522     }
523 
524     /**
525      * Not condition.
526      */
527     public abstract static class NotCondition implements Condition {
528         protected final Condition condition;
529 
530         protected NotCondition(Condition condition) {
531             this.condition = condition;
532         }
533 
534         public boolean isEmpty() {
535             return condition.isEmpty();
536         }
537 
538         public boolean isMatch(ExchangeSession.Contact contact) {
539             return !condition.isMatch(contact);
540         }
541     }
542 
543     /**
544      * Single search filter condition.
545      */
546     public abstract static class MonoCondition implements Condition {
547         protected final String attributeName;
548         protected final Operator operator;
549 
550         protected MonoCondition(String attributeName, Operator operator) {
551             this.attributeName = attributeName;
552             this.operator = operator;
553         }
554 
555         public boolean isEmpty() {
556             return false;
557         }
558 
559         public boolean isMatch(ExchangeSession.Contact contact) {
560             String actualValue = contact.get(attributeName);
561             return (operator == Operator.IsNull && actualValue == null) ||
562                     (operator == Operator.IsFalse && "false".equals(actualValue)) ||
563                     (operator == Operator.IsTrue && "true".equals(actualValue));
564         }
565     }
566 
567     /**
568      * And search filter.
569      *
570      * @param condition search conditions
571      * @return condition
572      */
573     public abstract MultiCondition and(Condition... condition);
574 
575     /**
576      * Or search filter.
577      *
578      * @param condition search conditions
579      * @return condition
580      */
581     public abstract MultiCondition or(Condition... condition);
582 
583     /**
584      * Not search filter.
585      *
586      * @param condition search condition
587      * @return condition
588      */
589     public abstract Condition not(Condition condition);
590 
591     /**
592      * Equals condition.
593      *
594      * @param attributeName logical Exchange attribute name
595      * @param value         attribute value
596      * @return condition
597      */
598     public abstract Condition isEqualTo(String attributeName, String value);
599 
600     /**
601      * Equals condition.
602      *
603      * @param attributeName logical Exchange attribute name
604      * @param value         attribute value
605      * @return condition
606      */
607     public abstract Condition isEqualTo(String attributeName, int value);
608 
609     /**
610      * MIME header equals condition.
611      *
612      * @param headerName MIME header name
613      * @param value      attribute value
614      * @return condition
615      */
616     public abstract Condition headerIsEqualTo(String headerName, String value);
617 
618     /**
619      * Greater than or equals condition.
620      *
621      * @param attributeName logical Exchange attribute name
622      * @param value         attribute value
623      * @return condition
624      */
625     public abstract Condition gte(String attributeName, String value);
626 
627     /**
628      * Greater than condition.
629      *
630      * @param attributeName logical Exchange attribute name
631      * @param value         attribute value
632      * @return condition
633      */
634     public abstract Condition gt(String attributeName, String value);
635 
636     /**
637      * Lower than condition.
638      *
639      * @param attributeName logical Exchange attribute name
640      * @param value         attribute value
641      * @return condition
642      */
643     public abstract Condition lt(String attributeName, String value);
644 
645     /**
646      * Lower than or equals condition.
647      *
648      * @param attributeName logical Exchange attribute name
649      * @param value         attribute value
650      * @return condition
651      */
652     @SuppressWarnings({"UnusedDeclaration"})
653     public abstract Condition lte(String attributeName, String value);
654 
655     /**
656      * Contains condition.
657      *
658      * @param attributeName logical Exchange attribute name
659      * @param value         attribute value
660      * @return condition
661      */
662     public abstract Condition contains(String attributeName, String value);
663 
664     /**
665      * Starts with condition.
666      *
667      * @param attributeName logical Exchange attribute name
668      * @param value         attribute value
669      * @return condition
670      */
671     public abstract Condition startsWith(String attributeName, String value);
672 
673     /**
674      * Is null condition.
675      *
676      * @param attributeName logical Exchange attribute name
677      * @return condition
678      */
679     public abstract Condition isNull(String attributeName);
680 
681     /**
682      * Exists condition.
683      *
684      * @param attributeName logical Exchange attribute name
685      * @return condition
686      */
687     public abstract Condition exists(String attributeName);
688 
689     /**
690      * Is true condition.
691      *
692      * @param attributeName logical Exchange attribute name
693      * @return condition
694      */
695     public abstract Condition isTrue(String attributeName);
696 
697     /**
698      * Is false condition.
699      *
700      * @param attributeName logical Exchange attribute name
701      * @return condition
702      */
703     public abstract Condition isFalse(String attributeName);
704 
705     /**
706      * Search mail and generic folders under given folder.
707      * Exclude calendar and contacts folders
708      *
709      * @param folderName Exchange folder name
710      * @param recursive  deep search if true
711      * @return list of folders
712      * @throws IOException on error
713      */
714     public List<Folder> getSubFolders(String folderName, boolean recursive, boolean wildcard) throws IOException {
715         MultiCondition folderCondition = and();
716         if (!Settings.getBooleanProperty("davmail.imapIncludeSpecialFolders", false)) {
717             folderCondition.add(or(isEqualTo("folderclass", "IPF.Note"),
718                     isEqualTo("folderclass", "IPF.Note.Microsoft.Conversation"),
719                     isNull("folderclass")));
720         }
721         if (wildcard) {
722             folderCondition.add(startsWith("displayname", folderName));
723             folderName = "";
724         }
725         List<Folder> results = getSubFolders(folderName, folderCondition,
726                 recursive);
727         // need to include base folder in recursive search, except on root on personal and shared mailboxes
728         if (recursive && !getSubfolderPath(folderName).isEmpty()) {
729             results.add(getFolder(folderName));
730         }
731 
732         return results;
733     }
734 
735     /**
736      * Search calendar folders under given folder.
737      *
738      * @param folderName Exchange folder name
739      * @param recursive  deep search if true
740      * @return list of folders
741      * @throws IOException on error
742      */
743     public List<Folder> getSubCalendarFolders(String folderName, boolean recursive) throws IOException {
744         return getSubFolders(folderName, isEqualTo("folderclass", "IPF.Appointment"), recursive);
745     }
746 
747     /**
748      * Get contact sub folders.
749      *
750      * @param folderName Exchange folder name
751      * @param recursive  deep search if true
752      * @return list of folders
753      * @throws IOException on error
754      */
755     public List<Folder> getSubContactFolders(String folderName, boolean recursive) throws IOException {
756         return getSubFolders(folderName, isEqualTo("folderclass", "IPF.Contact"), recursive);
757     }
758 
759 
760     /**
761      * Extract sub folder path from folder path.
762      * Removed shared folder absolute path prefix.
763      * @param folderPath input folder path
764      * @return actual folder path inside mailbox
765      */
766     public String getSubfolderPath(String folderPath) {
767         String baseFolderPath = folderPath;
768         if (baseFolderPath.startsWith("/users/")) {
769             int index = baseFolderPath.indexOf('/', "/users/".length());
770             if (index >= 0) {
771                 baseFolderPath = baseFolderPath.substring(index + 1);
772             }
773         }
774         return baseFolderPath;
775     }
776     
777     /**
778      * Search folders under given folder matching filter.
779      *
780      * @param folderName Exchange folder name
781      * @param condition  search filter
782      * @param recursive  deep search if true
783      * @return list of folders
784      * @throws IOException on error
785      */
786     public abstract List<Folder> getSubFolders(String folderName, Condition condition, boolean recursive) throws IOException;
787 
788     /**
789      * Delete oldest messages in trash.
790      * keepDelay is the number of days to keep messages in trash before delete
791      *
792      * @throws IOException when unable to purge messages
793      */
794     public void purgeOldestTrashAndSentMessages() throws IOException {
795         int keepDelay = Settings.getIntProperty("davmail.keepDelay");
796         if (keepDelay != 0) {
797             purgeOldestFolderMessages(TRASH, keepDelay);
798         }
799         // this is a new feature, default is : do nothing
800         int sentKeepDelay = Settings.getIntProperty("davmail.sentKeepDelay");
801         if (sentKeepDelay != 0) {
802             purgeOldestFolderMessages(SENT, sentKeepDelay);
803         }
804     }
805 
806     protected void purgeOldestFolderMessages(String folderPath, int keepDelay) throws IOException {
807         Calendar cal = Calendar.getInstance();
808         cal.add(Calendar.DAY_OF_MONTH, -keepDelay);
809         LOGGER.debug("Delete messages in " + folderPath + " not modified since " + cal.getTime());
810 
811         MessageList messages = searchMessages(folderPath, UID_MESSAGE_ATTRIBUTES,
812                 lt("lastmodified", formatSearchDate(cal.getTime())));
813 
814         for (Message message : messages) {
815             message.delete();
816         }
817     }
818 
819     /**
820      * Moves Resent headers to standard headers
821      */
822     protected void convertResentHeader(MimeMessage mimeMessage, String headerName) throws MessagingException {
823         String[] resentHeader = mimeMessage.getHeader("Resent-" + headerName);
824         if (resentHeader != null) {
825             mimeMessage.removeHeader("Resent-" + headerName);
826             mimeMessage.removeHeader(headerName);
827             for (String value : resentHeader) {
828                 mimeMessage.addHeader(headerName, value);
829             }
830         }
831     }
832 
833     protected String lastSentMessageId;
834     protected List<String> lastRcptToRecipients;
835 
836     /**
837      * Send the provided message to recipients.
838      * Detect visible recipients in the message body to determine bcc recipients
839      *
840      * @param rcptToRecipients recipient list
841      * @param mimeMessage      mime message
842      * @throws IOException        on error
843      * @throws MessagingException on error
844      */
845     public void sendMessage(List<String> rcptToRecipients, MimeMessage mimeMessage) throws IOException, MessagingException {
846         // detect duplicate send command
847         String messageId = mimeMessage.getMessageID();
848         if (lastSentMessageId != null && lastSentMessageId.equals(messageId)) {
849             // Resends duplicate message if allowed or recipients differ
850             if (Settings.getBooleanProperty("davmail.smtpAllowDuplicateSend", false)) {
851                 LOGGER.debug("Detected duplicate message id " + messageId + " but smtpAllowDuplicateSend is enabled, resending message");
852             } else if (lastRcptToRecipients != null && !lastRcptToRecipients.equals(rcptToRecipients)) {
853                 LOGGER.debug("Detected duplicate message id " + messageId + " but recipients differ, resending message");
854             } else {
855                 LOGGER.debug("Dropping message id " + messageId + ": already sent");
856                 return;
857             }
858         }
859         LOGGER.debug("Sending message id " + messageId);
860 
861         lastSentMessageId = messageId;
862         lastRcptToRecipients = rcptToRecipients;
863 
864         convertResentHeader(mimeMessage, "From");
865         convertResentHeader(mimeMessage, "To");
866         convertResentHeader(mimeMessage, "Cc");
867         convertResentHeader(mimeMessage, "Bcc");
868         convertResentHeader(mimeMessage, "Message-Id");
869 
870         // do not allow send as another user on Exchange 2003
871         if ("Exchange2003".equals(serverVersion) || Settings.getBooleanProperty("davmail.smtpStripFrom", false)) {
872             mimeMessage.removeHeader("From");
873         }
874 
875         // remove visible recipients from list
876         Set<String> visibleRecipients = new HashSet<>();
877         List<InternetAddress> recipients = getAllRecipients(mimeMessage);
878         for (InternetAddress address : recipients) {
879             visibleRecipients.add((address.getAddress().toLowerCase()));
880         }
881         for (String recipient : rcptToRecipients) {
882             if (!visibleRecipients.contains(recipient.toLowerCase())) {
883                 mimeMessage.addRecipient(javax.mail.Message.RecipientType.BCC, new InternetAddress(recipient));
884             }
885         }
886         sendMessage(mimeMessage);
887 
888     }
889 
890     static final String[] RECIPIENT_HEADERS = {"to", "cc", "bcc"};
891 
892     protected List<InternetAddress> getAllRecipients(MimeMessage mimeMessage) throws MessagingException {
893         List<InternetAddress> recipientList = new ArrayList<>();
894         for (String recipientHeader : RECIPIENT_HEADERS) {
895             final String recipientHeaderValue = mimeMessage.getHeader(recipientHeader, ",");
896             if (recipientHeaderValue != null) {
897                 // parse headers in non strict mode
898                 recipientList.addAll(Arrays.asList(InternetAddress.parseHeader(recipientHeaderValue, false)));
899             }
900 
901         }
902         return recipientList;
903     }
904 
905     /**
906      * Send Mime message.
907      *
908      * @param mimeMessage MIME message
909      * @throws IOException        on error
910      * @throws MessagingException on error
911      */
912     public abstract void sendMessage(MimeMessage mimeMessage) throws IOException, MessagingException;
913 
914     /**
915      * Get folder object.
916      * Folder name can be logical names INBOX, Drafts, Trash or calendar,
917      * or a path relative to user base folder or absolute path.
918      *
919      * @param folderPath folder path
920      * @return Folder object
921      * @throws IOException on error
922      */
923     public ExchangeSession.Folder getFolder(String folderPath) throws IOException {
924         Folder folder = internalGetFolder(folderPath);
925         if (isMainCalendar(folderPath)) {
926             Folder taskFolder = internalGetFolder(TASKS);
927             folder.ctag += taskFolder.ctag;
928         }
929         return folder;
930     }
931 
932     protected abstract Folder internalGetFolder(String folderName) throws IOException;
933 
934     /**
935      * Check folder ctag and reload messages as needed.
936      *
937      * @param currentFolder current folder
938      * @return true if folder changed
939      * @throws IOException on error
940      */
941     public boolean refreshFolder(Folder currentFolder) throws IOException {
942         Folder newFolder = getFolder(currentFolder.folderPath);
943         if (currentFolder.ctag == null || !currentFolder.ctag.equals(newFolder.ctag)
944                 // ctag stamp is limited to second, check message count
945                 || !(currentFolder.messageCount == newFolder.messageCount)
946         ) {
947             if (LOGGER.isDebugEnabled()) {
948                 LOGGER.debug("Contenttag or count changed on " + currentFolder.folderPath +
949                         " ctag: " + currentFolder.ctag + " => " + newFolder.ctag +
950                         " count: " + currentFolder.messageCount + " => " + newFolder.messageCount
951                         + ", reloading messages");
952             }
953             currentFolder.hasChildren = newFolder.hasChildren;
954             currentFolder.noInferiors = newFolder.noInferiors;
955             currentFolder.unreadCount = newFolder.unreadCount;
956             currentFolder.ctag = newFolder.ctag;
957             currentFolder.etag = newFolder.etag;
958             if (newFolder.uidNext > currentFolder.uidNext) {
959                 currentFolder.uidNext = newFolder.uidNext;
960             }
961             currentFolder.refreshMessages();
962             return true;
963         } else {
964             return false;
965         }
966     }
967 
968     /**
969      * Create Exchange message folder.
970      *
971      * @param folderName logical folder name
972      * @throws IOException on error
973      */
974     public void createMessageFolder(String folderName) throws IOException {
975         createFolder(folderName, "IPF.Note", null);
976     }
977 
978     /**
979      * Create Exchange calendar folder.
980      *
981      * @param folderName logical folder name
982      * @param properties folder properties
983      * @return status
984      * @throws IOException on error
985      */
986     public int createCalendarFolder(String folderName, Map<String, String> properties) throws IOException {
987         return createFolder(folderName, "IPF.Appointment", properties);
988     }
989 
990     /**
991      * Create Exchange contact folder.
992      *
993      * @param folderName logical folder name
994      * @param properties folder properties
995      * @throws IOException on error
996      */
997     public void createContactFolder(String folderName, Map<String, String> properties) throws IOException {
998         createFolder(folderName, "IPF.Contact", properties);
999     }
1000 
1001     /**
1002      * Create Exchange folder with given folder class.
1003      *
1004      * @param folderName  logical folder name
1005      * @param folderClass folder class
1006      * @param properties  folder properties
1007      * @return status
1008      * @throws IOException on error
1009      */
1010     public abstract int createFolder(String folderName, String folderClass, Map<String, String> properties) throws IOException;
1011 
1012     /**
1013      * Update Exchange folder properties.
1014      *
1015      * @param folderName logical folder name
1016      * @param properties folder properties
1017      * @return status
1018      * @throws IOException on error
1019      */
1020     public abstract int updateFolder(String folderName, Map<String, String> properties) throws IOException;
1021 
1022     /**
1023      * Delete Exchange folder.
1024      *
1025      * @param folderName logical folder name
1026      * @throws IOException on error
1027      */
1028     public abstract void deleteFolder(String folderName) throws IOException;
1029 
1030     /**
1031      * Copy message to target folder
1032      *
1033      * @param message      Exchange message
1034      * @param targetFolder target folder
1035      * @throws IOException on error
1036      */
1037     public abstract void copyMessage(Message message, String targetFolder) throws IOException;
1038 
1039     public void copyMessages(List<Message> messages, String targetFolder) throws IOException {
1040         for (Message message : messages) {
1041             copyMessage(message, targetFolder);
1042         }
1043     }
1044 
1045 
1046     /**
1047      * Move message to target folder
1048      *
1049      * @param message      Exchange message
1050      * @param targetFolder target folder
1051      * @throws IOException on error
1052      */
1053     public abstract void moveMessage(Message message, String targetFolder) throws IOException;
1054 
1055     public void moveMessages(List<Message> messages, String targetFolder) throws IOException {
1056         for (Message message : messages) {
1057             moveMessage(message, targetFolder);
1058         }
1059     }
1060 
1061     /**
1062      * Move folder to target name.
1063      *
1064      * @param folderName current folder name/path
1065      * @param targetName target folder name/path
1066      * @throws IOException on error
1067      */
1068     public abstract void moveFolder(String folderName, String targetName) throws IOException;
1069 
1070     /**
1071      * Move item from source path to target path.
1072      *
1073      * @param sourcePath item source path
1074      * @param targetPath item target path
1075      * @throws IOException on error
1076      */
1077     public abstract void moveItem(String sourcePath, String targetPath) throws IOException;
1078 
1079     protected abstract void moveToTrash(Message message) throws IOException;
1080 
1081     /**
1082      * Convert keyword value to IMAP flag.
1083      *
1084      * @param value keyword value
1085      * @return IMAP flag
1086      */
1087     public String convertKeywordToFlag(String value) {
1088         // first test for keyword in settings
1089         Properties flagSettings = Settings.getSubProperties("davmail.imapFlags");
1090         Enumeration<?> flagSettingsEnum = flagSettings.propertyNames();
1091         while (flagSettingsEnum.hasMoreElements()) {
1092             String key = (String) flagSettingsEnum.nextElement();
1093             if (value.equalsIgnoreCase(flagSettings.getProperty(key))) {
1094                 return key;
1095             }
1096         }
1097 
1098         ResourceBundle flagBundle = ResourceBundle.getBundle("imapflags");
1099         Enumeration<String> flagBundleEnum = flagBundle.getKeys();
1100         while (flagBundleEnum.hasMoreElements()) {
1101             String key = flagBundleEnum.nextElement();
1102             if (value.equalsIgnoreCase(flagBundle.getString(key))) {
1103                 return key;
1104             }
1105         }
1106 
1107         // fall back to raw value
1108         return value;
1109     }
1110 
1111     /**
1112      * Convert IMAP flag to keyword value.
1113      *
1114      * @param value IMAP flag
1115      * @return keyword value
1116      */
1117     public String convertFlagToKeyword(String value) {
1118         // first test for flag in settings
1119         Properties flagSettings = Settings.getSubProperties("davmail.imapFlags");
1120         // case insensitive lookup
1121         for (String key : flagSettings.stringPropertyNames()) {
1122             if (key.equalsIgnoreCase(value)) {
1123                 return flagSettings.getProperty(key);
1124             }
1125         }
1126 
1127         // fall back to predefined flags
1128         ResourceBundle flagBundle = ResourceBundle.getBundle("imapflags");
1129         for (String key : flagBundle.keySet()) {
1130             if (key.equalsIgnoreCase(value)) {
1131                 return flagBundle.getString(key);
1132             }
1133         }
1134 
1135         // fall back to raw value
1136         return value;
1137     }
1138 
1139     /**
1140      * Convert IMAP flags to keyword value.
1141      *
1142      * @param flags IMAP flags
1143      * @return keyword value
1144      */
1145     public String convertFlagsToKeywords(HashSet<String> flags) {
1146         HashSet<String> keywordSet = new HashSet<>();
1147         for (String flag : flags) {
1148             keywordSet.add(decodeKeyword(convertFlagToKeyword(flag)));
1149         }
1150         return StringUtil.join(keywordSet, ",");
1151     }
1152 
1153     protected String decodeKeyword(String keyword) {
1154         String result = keyword;
1155         if (keyword.contains("_x0028_") || keyword.contains("_x0029_")) {
1156             result = result.replace("_x0028_", "(")
1157                     .replace("_x0029_", ")");
1158         }
1159         return result;
1160     }
1161 
1162     protected String encodeKeyword(String keyword) {
1163         String result = keyword;
1164         if (keyword.indexOf('(') >= 0|| keyword.indexOf(')') >= 0) {
1165             result = result.replaceAll("\\(", "_x0028_")
1166                     .replaceAll("\\)", "_x0029_" );
1167         }
1168         return result;
1169     }
1170 
1171     /**
1172      * Exchange folder with IMAP properties
1173      */
1174     public class Folder {
1175         /**
1176          * Logical (IMAP) folder path.
1177          */
1178         public String folderPath;
1179 
1180         /**
1181          * Display Name.
1182          */
1183         public String displayName;
1184         /**
1185          * Folder class (PR_CONTAINER_CLASS).
1186          */
1187         public String folderClass;
1188         /**
1189          * Folder message count.
1190          */
1191         public int messageCount;
1192         /**
1193          * Folder unread message count.
1194          */
1195         public int unreadCount;
1196         /**
1197          * true if folder has subfolders (DAV:hassubs).
1198          */
1199         public boolean hasChildren;
1200         /**
1201          * true if folder has no subfolders (DAV:nosubs).
1202          */
1203         public boolean noInferiors;
1204         /**
1205          * Folder content tag (to detect folder content changes).
1206          */
1207         public String ctag;
1208         /**
1209          * Folder etag (to detect folder object changes).
1210          */
1211         public String etag;
1212         /**
1213          * Next IMAP uid
1214          */
1215         public long uidNext;
1216         /**
1217          * recent count
1218          */
1219         public int recent;
1220 
1221         /**
1222          * Folder message list, empty before loadMessages call.
1223          */
1224         public ExchangeSession.MessageList messages;
1225         /**
1226          * Permanent uid (PR_SEARCH_KEY) to IMAP UID map.
1227          */
1228         private final HashMap<String, Long> permanentUrlToImapUidMap = new HashMap<>();
1229 
1230         /**
1231          * Get IMAP folder flags.
1232          *
1233          * @return folder flags in IMAP format
1234          */
1235         public String getFlags() {
1236             String specialFlag = "";
1237             if (isSpecial()) {
1238                 specialFlag = "\\" + folderPath + " ";
1239             }
1240             if (noInferiors) {
1241                 return specialFlag + "\\NoInferiors";
1242             } else if (hasChildren) {
1243                 return specialFlag + "\\HasChildren";
1244             } else {
1245                 return specialFlag + "\\HasNoChildren";
1246             }
1247         }
1248 
1249         /**
1250          * Special folder flag (Sent, Drafts, Trash, Junk).
1251          * @return true if folder is special
1252          */
1253         public boolean isSpecial() {
1254             return SPECIAL.contains(folderPath);
1255         }
1256 
1257         /**
1258          * Load folder messages.
1259          *
1260          * @throws IOException on error
1261          */
1262         public void loadMessages() throws IOException {
1263             messages = ExchangeSession.this.searchMessages(folderPath, null);
1264             fixUids(messages);
1265             computeAttributes();
1266         }
1267 
1268         public void computeAttributes() {
1269             recent = 0;
1270             for (Message message : messages) {
1271                 if (message.recent) {
1272                     recent++;
1273                 }
1274             }
1275             long computedUidNext = 1;
1276             if (!messages.isEmpty()) {
1277                 computedUidNext = messages.get(messages.size() - 1).getImapUid() + 1;
1278             }
1279             if (computedUidNext > uidNext) {
1280                 uidNext = computedUidNext;
1281             }
1282             // make sure message count matches current list count
1283             messageCount = messages.size();
1284 
1285             buildImapFlagMap();
1286         }
1287 
1288         public void refreshMessages() throws IOException {
1289             loadMessages();
1290         }
1291 
1292         /**
1293          * Search messages in folder matching query.
1294          *
1295          * @param condition search query
1296          * @return message list
1297          * @throws IOException on error
1298          */
1299         public MessageList searchMessages(Condition condition) throws IOException {
1300             MessageList localMessages = ExchangeSession.this.searchMessages(folderPath, condition);
1301             fixUids(localMessages);
1302             return localMessages;
1303         }
1304 
1305         /**
1306          * Restore previous uids changed by a PROPPATCH (flag change).
1307          *
1308          * @param messages message list
1309          */
1310         protected void fixUids(MessageList messages) {
1311             boolean sortNeeded = false;
1312             for (Message message : messages) {
1313                 if (permanentUrlToImapUidMap.containsKey(message.getPermanentId())) {
1314                     long previousUid = permanentUrlToImapUidMap.get(message.getPermanentId());
1315                     if (message.getImapUid() != previousUid) {
1316                         LOGGER.debug("Restoring IMAP uid " + message.getImapUid() + " -> " + previousUid + " for message " + message.getPermanentId());
1317                         message.setImapUid(previousUid);
1318                         sortNeeded = true;
1319                     }
1320                 } else {
1321                     // add message to uid map
1322                     permanentUrlToImapUidMap.put(message.getPermanentId(), message.getImapUid());
1323                 }
1324             }
1325             if (sortNeeded) {
1326                 Collections.sort(messages);
1327             }
1328         }
1329 
1330         /**
1331          * Folder message count.
1332          *
1333          * @return message count
1334          */
1335         public int count() {
1336             if (messages == null) {
1337                 return messageCount;
1338             } else {
1339                 return messages.size();
1340             }
1341         }
1342 
1343         /**
1344          * Compute IMAP uidnext.
1345          *
1346          * @return max(messageuids)+1
1347          */
1348         public long getUidNext() {
1349             return uidNext;
1350         }
1351 
1352         /**
1353          * Get message at index.
1354          *
1355          * @param index message index
1356          * @return message
1357          */
1358         public Message get(int index) {
1359             return messages.get(index);
1360         }
1361 
1362         private TreeMap<Long, String> imapFlagMap = new TreeMap<>();
1363 
1364         /**
1365          * Get current folder messages imap uids and flags
1366          *
1367          * @return imap uid list
1368          */
1369         public TreeMap<Long, String> getImapFlagMap() {
1370             return imapFlagMap;
1371         }
1372 
1373         public void buildImapFlagMap() {
1374             int previousMessageCount = imapFlagMap.size();
1375             // recreate an empty map to avoid erasing previous values in ImapConnection
1376             imapFlagMap = new TreeMap<>();
1377             for (ExchangeSession.Message message : messages) {
1378                 imapFlagMap.put(message.getImapUid(), message.getImapFlags());
1379             }
1380             if (previousMessageCount != imapFlagMap.size()) {
1381                 LOGGER.debug("imapFlagMap size: " + previousMessageCount + " -> " + imapFlagMap.size());
1382             }
1383         }
1384 
1385         /**
1386          * Calendar folder flag.
1387          *
1388          * @return true if this is a calendar folder
1389          */
1390         public boolean isCalendar() {
1391             return "IPF.Appointment".equals(folderClass);
1392         }
1393 
1394         /**
1395          * Contact folder flag.
1396          *
1397          * @return true if this is a calendar folder
1398          */
1399         public boolean isContact() {
1400             return "IPF.Contact".equals(folderClass);
1401         }
1402 
1403         /**
1404          * Task folder flag.
1405          *
1406          * @return true if this is a task folder
1407          */
1408         public boolean isTask() {
1409             return "IPF.Task".equals(folderClass);
1410         }
1411 
1412         /**
1413          * drop cached message
1414          */
1415         public void clearCache() {
1416             messages.cachedMimeContent = null;
1417             messages.cachedMimeMessage = null;
1418             messages.cachedMessageImapUid = 0;
1419         }
1420     }
1421 
1422     /**
1423      * Exchange message.
1424      */
1425     public abstract class Message implements Comparable<Message> {
1426         /**
1427          * enclosing message list
1428          */
1429         public MessageList messageList;
1430         /**
1431          * Message url.
1432          */
1433         public String messageUrl;
1434         /**
1435          * Message permanent url (does not change on message move).
1436          */
1437         public String permanentUrl;
1438         /**
1439          * Message uid.
1440          */
1441         public String uid;
1442         /**
1443          * Message content class.
1444          */
1445         public String contentClass;
1446         /**
1447          * Message keywords (categories).
1448          */
1449         public String keywords;
1450         /**
1451          * Message IMAP uid, unique in folder (x0e230003).
1452          */
1453         public long imapUid;
1454         /**
1455          * MAPI message size.
1456          */
1457         public int size;
1458         /**
1459          * Message date (urn:schemas:mailheader:date).
1460          */
1461         public String date;
1462 
1463         /**
1464          * Message flag: read.
1465          */
1466         public boolean read;
1467         /**
1468          * Message flag: deleted.
1469          */
1470         public boolean deleted;
1471         /**
1472          * Message flag: junk.
1473          */
1474         public boolean junk;
1475         /**
1476          * Message flag: flagged.
1477          */
1478         public boolean flagged;
1479         /**
1480          * Message flag: recent.
1481          */
1482         public boolean recent;
1483         /**
1484          * Message flag: draft.
1485          */
1486         public boolean draft;
1487         /**
1488          * Message flag: answered.
1489          */
1490         public boolean answered;
1491         /**
1492          * Message flag: forwarded.
1493          */
1494         public boolean forwarded;
1495 
1496         /**
1497          * Unparsed message content.
1498          */
1499         protected byte[] mimeContent;
1500 
1501         /**
1502          * Message content parsed in a MIME message.
1503          */
1504         protected MimeMessage mimeMessage;
1505 
1506         /**
1507          * Get permanent message id.
1508          * permanentUrl over WebDav or ItemId over EWS
1509          *
1510          * @return permanent id
1511          */
1512         public abstract String getPermanentId();
1513 
1514         /**
1515          * IMAP uid , unique in folder (x0e230003)
1516          *
1517          * @return IMAP uid
1518          */
1519         public long getImapUid() {
1520             return imapUid;
1521         }
1522 
1523         /**
1524          * Set IMAP uid.
1525          *
1526          * @param imapUid new uid
1527          */
1528         public void setImapUid(long imapUid) {
1529             this.imapUid = imapUid;
1530         }
1531 
1532         /**
1533          * Exchange uid.
1534          *
1535          * @return uid
1536          */
1537         public String getUid() {
1538             return uid;
1539         }
1540 
1541         /**
1542          * Return message flags in IMAP format.
1543          *
1544          * @return IMAP flags
1545          */
1546         public String getImapFlags() {
1547             StringBuilder buffer = new StringBuilder();
1548             if (read) {
1549                 buffer.append("\\Seen ");
1550             }
1551             if (deleted) {
1552                 buffer.append("\\Deleted ");
1553             }
1554             if (recent) {
1555                 buffer.append("\\Recent ");
1556             }
1557             if (flagged) {
1558                 buffer.append("\\Flagged ");
1559             }
1560             if (junk) {
1561                 buffer.append("Junk ");
1562             }
1563             if (draft) {
1564                 buffer.append("\\Draft ");
1565             }
1566             if (answered) {
1567                 buffer.append("\\Answered ");
1568             }
1569             if (forwarded) {
1570                 buffer.append("$Forwarded ");
1571             }
1572             if (keywords != null) {
1573                 for (String keyword : keywords.split(",")) {
1574                     buffer.append(encodeKeyword(convertKeywordToFlag(keyword))).append(" ");
1575                 }
1576             }
1577             return buffer.toString().trim();
1578         }
1579 
1580         /**
1581          * Load message content in a Mime message
1582          *
1583          * @throws IOException        on error
1584          * @throws MessagingException on error
1585          */
1586         public void loadMimeMessage() throws IOException, MessagingException {
1587             if (mimeMessage == null) {
1588                 // try to get message content from cache
1589                 if (this.imapUid == messageList.cachedMessageImapUid
1590                         // make sure we never return null even with broken 0 uid message
1591                         && messageList.cachedMimeContent != null
1592                         && messageList.cachedMimeMessage != null) {
1593                     mimeContent = messageList.cachedMimeContent;
1594                     mimeMessage = messageList.cachedMimeMessage;
1595                     LOGGER.debug("Got message content for " + imapUid + " from cache");
1596                 } else {
1597                     // load and parse message
1598                     mimeContent = getContent(this);
1599                     mimeMessage = new MimeMessage(null, new SharedByteArrayInputStream(mimeContent));
1600                     // workaround for Exchange 2003 ActiveSync bug
1601                     if (mimeMessage.getHeader("MAIL FROM") != null) {
1602                         // find start of actual message
1603                         byte[] mimeContentCopy = new byte[((SharedByteArrayInputStream) mimeMessage.getRawInputStream()).available()];
1604                         int offset = mimeContent.length - mimeContentCopy.length;
1605                         // remove unwanted header
1606                         System.arraycopy(mimeContent, offset, mimeContentCopy, 0, mimeContentCopy.length);
1607                         mimeContent = mimeContentCopy;
1608                         mimeMessage = new MimeMessage(null, new SharedByteArrayInputStream(mimeContent));
1609                     }
1610                     LOGGER.debug("Downloaded full message content for IMAP UID " + imapUid + " (" + mimeContent.length + " bytes)");
1611                 }
1612             }
1613         }
1614 
1615         /**
1616          * Get message content as a Mime message.
1617          *
1618          * @return mime message
1619          * @throws IOException        on error
1620          * @throws MessagingException on error
1621          */
1622         public MimeMessage getMimeMessage() throws IOException, MessagingException {
1623             loadMimeMessage();
1624             return mimeMessage;
1625         }
1626 
1627         public Enumeration<?> getMatchingHeaderLinesFromHeaders(String[] headerNames) throws MessagingException {
1628             Enumeration<?> result = null;
1629             if (mimeMessage == null) {
1630                 // message not loaded, try to get headers only
1631                 InputStream headers = getMimeHeaders();
1632                 if (headers != null) {
1633                     InternetHeaders internetHeaders = new InternetHeaders(headers);
1634                     if (internetHeaders.getHeader("Subject") == null) {
1635                         // invalid header content
1636                         return null;
1637                     }
1638                     if (headerNames == null) {
1639                         result = internetHeaders.getAllHeaderLines();
1640                     } else {
1641                         result = internetHeaders.getMatchingHeaderLines(headerNames);
1642                     }
1643                 }
1644             }
1645             return result;
1646         }
1647 
1648         public Enumeration<?> getMatchingHeaderLines(String[] headerNames) throws MessagingException, IOException {
1649             Enumeration<?> result = getMatchingHeaderLinesFromHeaders(headerNames);
1650             if (result == null) {
1651                 if (headerNames == null) {
1652                     result = getMimeMessage().getAllHeaderLines();
1653                 } else {
1654                     result = getMimeMessage().getMatchingHeaderLines(headerNames);
1655                 }
1656 
1657             }
1658             return result;
1659         }
1660 
1661         protected abstract InputStream getMimeHeaders();
1662 
1663         /**
1664          * Get message body size.
1665          *
1666          * @return mime message size
1667          * @throws IOException        on error
1668          * @throws MessagingException on error
1669          */
1670         public int getMimeMessageSize() throws IOException, MessagingException {
1671             loadMimeMessage();
1672             return mimeContent.length;
1673         }
1674 
1675         /**
1676          * Get message body input stream.
1677          *
1678          * @return mime message InputStream
1679          * @throws IOException        on error
1680          * @throws MessagingException on error
1681          */
1682         public InputStream getRawInputStream() throws IOException, MessagingException {
1683             loadMimeMessage();
1684             return new SharedByteArrayInputStream(mimeContent);
1685         }
1686 
1687 
1688         /**
1689          * Drop mime message to avoid keeping message content in memory,
1690          * keep a single message in MessageList cache to handle chunked fetch.
1691          */
1692         public void dropMimeMessage() {
1693             // update single message cache
1694             if (mimeMessage != null) {
1695                 messageList.cachedMessageImapUid = imapUid;
1696                 messageList.cachedMimeContent = mimeContent;
1697                 messageList.cachedMimeMessage = mimeMessage;
1698             }
1699             // drop current message body to save memory
1700             mimeMessage = null;
1701             mimeContent = null;
1702         }
1703 
1704         public boolean isLoaded() {
1705             // check and retrieve cached content
1706             if (imapUid == messageList.cachedMessageImapUid) {
1707                 mimeContent = messageList.cachedMimeContent;
1708                 mimeMessage = messageList.cachedMimeMessage;
1709             }
1710             return mimeMessage != null;
1711         }
1712 
1713         /**
1714          * Delete message.
1715          *
1716          * @throws IOException on error
1717          */
1718         public void delete() throws IOException {
1719             deleteMessage(this);
1720         }
1721 
1722         /**
1723          * Move message to trash, mark message read.
1724          *
1725          * @throws IOException on error
1726          */
1727         public void moveToTrash() throws IOException {
1728             markRead();
1729 
1730             ExchangeSession.this.moveToTrash(this);
1731         }
1732 
1733         /**
1734          * Mark message as read.
1735          *
1736          * @throws IOException on error
1737          */
1738         public void markRead() throws IOException {
1739             HashMap<String, String> properties = new HashMap<>();
1740             properties.put("read", "1");
1741             updateMessage(this, properties);
1742         }
1743 
1744         /**
1745          * Comparator to sort messages by IMAP uid
1746          *
1747          * @param message other message
1748          * @return imapUid comparison result
1749          */
1750         public int compareTo(Message message) {
1751             long compareValue = (imapUid - message.imapUid);
1752             if (compareValue > 0) {
1753                 return 1;
1754             } else if (compareValue < 0) {
1755                 return -1;
1756             } else {
1757                 return 0;
1758             }
1759         }
1760 
1761         /**
1762          * Override equals, compare IMAP uids
1763          *
1764          * @param message other message
1765          * @return true if IMAP uids are equal
1766          */
1767         @Override
1768         public boolean equals(Object message) {
1769             return message instanceof Message && imapUid == ((Message) message).imapUid;
1770         }
1771 
1772         /**
1773          * Override hashCode, return imapUid hashcode.
1774          *
1775          * @return imapUid hashcode
1776          */
1777         @Override
1778         public int hashCode() {
1779             return Long.hashCode(imapUid);
1780         }
1781 
1782         public String removeFlag(String flag) {
1783             if (keywords != null) {
1784                 final String exchangeFlag = convertFlagToKeyword(flag);
1785                 Set<String> keywordSet = new HashSet<>();
1786                 String[] keywordArray = keywords.split(",");
1787                 for (String value : keywordArray) {
1788                     if (!value.equalsIgnoreCase(exchangeFlag)) {
1789                         keywordSet.add(value);
1790                     }
1791                 }
1792                 keywords = StringUtil.join(keywordSet, ",");
1793             }
1794             return keywords;
1795         }
1796 
1797         public String addFlag(String flag) {
1798             final String exchangeFlag = convertFlagToKeyword(flag);
1799             HashSet<String> keywordSet = new HashSet<>();
1800             boolean hasFlag = false;
1801             if (keywords != null) {
1802                 String[] keywordArray = keywords.split(",");
1803                 for (String value : keywordArray) {
1804                     keywordSet.add(value);
1805                     if (value.equalsIgnoreCase(exchangeFlag)) {
1806                         hasFlag = true;
1807                     }
1808                 }
1809             }
1810             if (!hasFlag) {
1811                 keywordSet.add(exchangeFlag);
1812             }
1813             keywords = StringUtil.join(keywordSet, ",");
1814             return keywords;
1815         }
1816 
1817         public String setFlags(HashSet<String> flags) {
1818             keywords = convertFlagsToKeywords(flags);
1819             return keywords;
1820         }
1821 
1822     }
1823 
1824     /**
1825      * Message list, includes a single message cache
1826      */
1827     public static class MessageList extends ArrayList<Message> {
1828         /**
1829          * Cached message content parsed in a MIME message.
1830          */
1831         protected transient MimeMessage cachedMimeMessage;
1832         /**
1833          * Cached message uid.
1834          */
1835         protected transient long cachedMessageImapUid;
1836         /**
1837          * Cached unparsed message
1838          */
1839         protected transient byte[] cachedMimeContent;
1840 
1841         @Override
1842         public boolean add(Message message) {
1843             message.messageList = this;
1844             return super.add(message);
1845         }
1846     }
1847 
1848     /**
1849      * Generic folder item.
1850      */
1851     public abstract static class Item extends HashMap<String, String> {
1852         public String folderPath;
1853         protected String itemName;
1854         protected String permanentUrl;
1855         /**
1856          * Display name.
1857          */
1858         public String displayName;
1859         /**
1860          * item etag
1861          */
1862         public String etag;
1863         protected String noneMatch;
1864 
1865         /**
1866          * Build item instance.
1867          *
1868          * @param folderPath folder path
1869          * @param itemName   item name class
1870          * @param etag       item etag
1871          * @param noneMatch  none match flag
1872          */
1873         public Item(String folderPath, String itemName, String etag, String noneMatch) {
1874             this.folderPath = folderPath;
1875             this.itemName = itemName;
1876             this.etag = etag;
1877             this.noneMatch = noneMatch;
1878         }
1879 
1880         /**
1881          * Default constructor.
1882          */
1883         protected Item() {
1884         }
1885 
1886         /**
1887          * Return item content type
1888          *
1889          * @return content type
1890          */
1891         public abstract String getContentType();
1892 
1893         /**
1894          * Retrieve item body from Exchange
1895          *
1896          * @return item body
1897          * @throws IOException on error
1898          */
1899         public abstract String getBody() throws IOException;
1900 
1901         /**
1902          * Get event name (file name part in URL).
1903          *
1904          * @return event name
1905          */
1906         public String getName() {
1907             return itemName;
1908         }
1909 
1910         /**
1911          * Get event etag (last change tag).
1912          *
1913          * @return event etag
1914          */
1915         public String getEtag() {
1916             return etag;
1917         }
1918 
1919         /**
1920          * Set item href.
1921          *
1922          * @param href item href
1923          */
1924         public void setHref(String href) {
1925             int index = href.lastIndexOf('/');
1926             if (index >= 0) {
1927                 folderPath = href.substring(0, index);
1928                 itemName = href.substring(index + 1);
1929             } else {
1930                 throw new IllegalArgumentException(href);
1931             }
1932         }
1933 
1934         /**
1935          * Return item href.
1936          *
1937          * @return item href
1938          */
1939         public String getHref() {
1940             return folderPath + '/' + itemName;
1941         }
1942 
1943         public void setItemName(String itemName) {
1944             this.itemName = itemName;
1945         }
1946     }
1947 
1948     /**
1949      * Contact object
1950      */
1951     public abstract class Contact extends Item {
1952 
1953         protected ArrayList<String> distributionListMembers = null;
1954         protected String vCardVersion;
1955 
1956         public Contact(String folderPath, String itemName, Map<String, String> properties, String etag, String noneMatch) {
1957             super(folderPath, itemName.endsWith(".vcf") ? itemName.substring(0, itemName.length() - 3) + "EML" : itemName, etag, noneMatch);
1958             this.putAll(properties);
1959         }
1960 
1961         protected Contact() {
1962         }
1963 
1964         public void setVCardVersion(String vCardVersion) {
1965             this.vCardVersion = vCardVersion;
1966         }
1967 
1968         public abstract ItemResult createOrUpdate() throws IOException;
1969 
1970         /**
1971          * Convert EML extension to vcf.
1972          *
1973          * @return item name
1974          */
1975         @Override
1976         public String getName() {
1977             String name = super.getName();
1978             if (name.endsWith(".EML")) {
1979                 name = name.substring(0, name.length() - 3) + "vcf";
1980             }
1981             return name;
1982         }
1983 
1984         /**
1985          * Set contact name
1986          *
1987          * @param name contact name
1988          */
1989         public void setName(String name) {
1990             this.itemName = name;
1991         }
1992 
1993         /**
1994          * Compute vcard uid from name.
1995          *
1996          * @return uid
1997          */
1998         public String getUid() {
1999             String uid = getName();
2000             int dotIndex = uid.lastIndexOf('.');
2001             if (dotIndex > 0) {
2002                 uid = uid.substring(0, dotIndex);
2003             }
2004             return URIUtil.encodePath(uid);
2005         }
2006 
2007         @Override
2008         public String getContentType() {
2009             return "text/vcard";
2010         }
2011 
2012         public void addMember(String member) {
2013             if (distributionListMembers == null) {
2014                 distributionListMembers = new ArrayList<>();
2015             }
2016             distributionListMembers.add(member);
2017         }
2018 
2019 
2020         @Override
2021         public String getBody() {
2022             // build RFC 2426 VCard from contact information
2023             VCardWriter writer = new VCardWriter();
2024             writer.startCard(vCardVersion);
2025             writer.appendProperty("UID", getUid());
2026             // common name
2027             String cn = get("cn");
2028             if (cn == null) {
2029                 cn = get("displayname");
2030             }
2031             String sn = get("sn");
2032             if (sn == null) {
2033                 sn = cn;
2034             }
2035             writer.appendProperty("FN", cn);
2036             // RFC 2426: Family Name, Given Name, Additional Names, Honorific Prefixes, and Honorific Suffixes
2037             writer.appendProperty("N", sn, get("givenName"), get("middlename"), get("personaltitle"), get("namesuffix"));
2038 
2039             if (distributionListMembers != null) {
2040                 if ("3.0".equals(vCardVersion)) {
2041                     writer.appendProperty("X-ADDRESSBOOKSERVER-KIND", "group");
2042                     for (String member : distributionListMembers) {
2043                         writer.appendProperty("X-ADDRESSBOOKSERVER-MEMBER", member);
2044                     }
2045                 } else {
2046                     writer.appendProperty("KIND", "group");
2047                     for (String member : distributionListMembers) {
2048                         writer.appendProperty("MEMBER", member);
2049                     }
2050                 }
2051             }
2052 
2053             writer.appendProperty("TEL;TYPE=cell", get("mobile"));
2054             writer.appendProperty("TEL;TYPE=work", get("telephoneNumber"));
2055             writer.appendProperty("TEL;TYPE=home", get("homePhone"));
2056             writer.appendProperty("TEL;TYPE=fax", get("facsimiletelephonenumber"));
2057             writer.appendProperty("TEL;TYPE=pager", get("pager"));
2058             writer.appendProperty("TEL;TYPE=car", get("othermobile"));
2059             writer.appendProperty("TEL;TYPE=home,fax", get("homefax"));
2060             writer.appendProperty("TEL;TYPE=isdn", get("internationalisdnnumber"));
2061             writer.appendProperty("TEL;TYPE=msg", get("otherTelephone"));
2062 
2063             writer.appendProperty("TEL;TYPE=work", get("otherBusinessTelephoneNumber"));
2064             writer.appendProperty("TEL;TYPE=home", get("otherHomePhone"));
2065 
2066             // The structured type value corresponds, in sequence, to the post office box; the extended address;
2067             // the street address; the locality (e.g., city); the region (e.g., state or province);
2068             // the postal code; the country name
2069             writer.appendProperty("ADR;TYPE=home",
2070                     get("homepostofficebox"), null, get("homeStreet"), get("homeCity"), get("homeState"), get("homePostalCode"), get("homeCountry"));
2071             writer.appendProperty("ADR;TYPE=work",
2072                     get("postofficebox"), get("roomnumber"), get("street"), get("l"), get("st"), get("postalcode"), get("co"));
2073             writer.appendProperty("ADR;TYPE=other",
2074                     get("otherpostofficebox"), null, get("otherstreet"), get("othercity"), get("otherstate"), get("otherpostalcode"), get("othercountry"));
2075 
2076             writer.appendProperty("EMAIL;TYPE=work", get("smtpemail1"));
2077             writer.appendProperty("EMAIL;TYPE=home", get("smtpemail2"));
2078             writer.appendProperty("EMAIL;TYPE=other", get("smtpemail3"));
2079 
2080             writer.appendProperty("ORG", get("o"), get("department"));
2081             writer.appendProperty("URL;TYPE=work", get("businesshomepage"));
2082             writer.appendProperty("URL;TYPE=home", get("personalHomePage"));
2083             writer.appendProperty("TITLE", get("title"));
2084             writer.appendProperty("NOTE", get("personalNotes"));
2085 
2086             writer.appendProperty("CUSTOM1", get("extensionattribute1"));
2087             writer.appendProperty("CUSTOM2", get("extensionattribute2"));
2088             writer.appendProperty("CUSTOM3", get("extensionattribute3"));
2089             writer.appendProperty("CUSTOM4", get("extensionattribute4"));
2090 
2091             writer.appendProperty("ROLE", get("profession"));
2092             writer.appendProperty("NICKNAME", get("nickname"));
2093             writer.appendProperty("X-AIM", get("im"));
2094 
2095             writer.appendProperty("BDAY", convertZuluDateToBday(get("bday")));
2096             writer.appendProperty("ANNIVERSARY", convertZuluDateToBday(get("anniversary")));
2097 
2098             String gender = get("gender");
2099             if ("1".equals(gender)) {
2100                 writer.appendProperty("SEX", "2");
2101             } else if ("2".equals(gender)) {
2102                 writer.appendProperty("SEX", "1");
2103             }
2104 
2105             writer.appendProperty("CATEGORIES", get("keywords"));
2106 
2107             writer.appendProperty("FBURL", get("fburl"));
2108 
2109             if ("1".equals(get("private"))) {
2110                 writer.appendProperty("CLASS", "PRIVATE");
2111             }
2112 
2113             writer.appendProperty("X-ASSISTANT", get("secretarycn"));
2114             writer.appendProperty("X-MANAGER", get("manager"));
2115             writer.appendProperty("X-SPOUSE", get("spousecn"));
2116 
2117             writer.appendProperty("REV", get("lastmodified"));
2118 
2119             ContactPhoto contactPhoto = null;
2120 
2121             if (Settings.getBooleanProperty("davmail.carddavReadPhoto", true)) {
2122                 if (("true".equals(get("haspicture")))) {
2123                     try {
2124                         contactPhoto = getContactPhoto(this);
2125                     } catch (IOException e) {
2126                         LOGGER.warn("Unable to get photo from contact " + this.get("cn"));
2127                     }
2128                 }
2129 
2130                 if (contactPhoto == null) {
2131                     contactPhoto = getADPhoto(get("smtpemail1"));
2132                 }
2133             }
2134 
2135             if (contactPhoto != null) {
2136                 if ("3.0".equals(vCardVersion)) {
2137                     // vCard 3.0: use ENCODING=b and TYPE parameter
2138                     String photoType = contactPhoto.contentType;
2139                     if (photoType != null && photoType.startsWith("image/")) {
2140                         photoType = photoType.substring("image/".length()).toUpperCase();
2141                     }
2142                     writer.writeLine("PHOTO;ENCODING=b;TYPE=" + photoType + ":" + contactPhoto.content);
2143                 } else {
2144                     // vCard 4.0: use data: URI
2145                     writer.writeLine("PHOTO:data:" + contactPhoto.contentType + ";base64," + contactPhoto.content);
2146                 }
2147             }
2148 
2149             writer.appendProperty("KEY1;X509;ENCODING=BASE64", get("msexchangecertificate"));
2150             writer.appendProperty("KEY2;X509;ENCODING=BASE64", get("usersmimecertificate"));
2151 
2152             writer.endCard();
2153             return writer.toString();
2154         }
2155     }
2156 
2157     /**
2158      * Calendar event object.
2159      */
2160     public abstract class Event extends Item {
2161         protected String contentClass;
2162         protected String subject;
2163         protected VCalendar vCalendar;
2164         protected String startTimeZone;
2165 
2166         public Event(String folderPath, String itemName, String contentClass, String itemBody, String etag, String noneMatch) throws IOException {
2167             super(folderPath, itemName, etag, noneMatch);
2168             this.contentClass = contentClass;
2169             fixICS(itemBody.getBytes(StandardCharsets.UTF_8), getCalendarEmail(folderPath), false);
2170             // fix task item name
2171             if (vCalendar.isTodo() && this.itemName.endsWith(".ics")) {
2172                 this.itemName = itemName.substring(0, itemName.length() - 3) + "EML";
2173             }
2174         }
2175 
2176         protected Event() {
2177         }
2178 
2179         @Override
2180         public String getContentType() {
2181             return "text/calendar;charset=UTF-8";
2182         }
2183 
2184         @Override
2185         public String getBody() throws IOException {
2186             if (vCalendar == null) {
2187                 fixICS(getEventContent(), getCalendarEmail(folderPath), true);
2188             }
2189             return vCalendar.toString();
2190         }
2191 
2192         protected HttpNotFoundException buildHttpNotFoundException(Exception e) {
2193             String message = "Unable to get event " + getName() + " subject: " + subject + " at " + permanentUrl + ": " + e.getMessage();
2194             LOGGER.warn(message);
2195             return new HttpNotFoundException(message);
2196         }
2197 
2198         /**
2199          * Retrieve item body from Exchange
2200          *
2201          * @return item content
2202          * @throws IOException on error
2203          */
2204         public abstract byte[] getEventContent() throws IOException;
2205 
2206         protected static final String TEXT_CALENDAR = "text/calendar";
2207         protected static final String APPLICATION_ICS = "application/ics";
2208 
2209         protected boolean isCalendarContentType(String contentType) {
2210             return TEXT_CALENDAR.regionMatches(true, 0, contentType, 0, TEXT_CALENDAR.length()) ||
2211                     APPLICATION_ICS.regionMatches(true, 0, contentType, 0, APPLICATION_ICS.length());
2212         }
2213 
2214         protected MimePart getCalendarMimePart(MimeMultipart multiPart) throws IOException, MessagingException {
2215             MimePart bodyPart = null;
2216             for (int i = 0; i < multiPart.getCount(); i++) {
2217                 String contentType = multiPart.getBodyPart(i).getContentType();
2218                 if (isCalendarContentType(contentType)) {
2219                     bodyPart = (MimePart) multiPart.getBodyPart(i);
2220                     break;
2221                 } else if (contentType.startsWith("multipart")) {
2222                     Object content = multiPart.getBodyPart(i).getContent();
2223                     if (content instanceof MimeMultipart) {
2224                         bodyPart = getCalendarMimePart((MimeMultipart) content);
2225                     }
2226                 }
2227             }
2228 
2229             return bodyPart;
2230         }
2231 
2232         /**
2233          * Load ICS content from MIME message input stream
2234          *
2235          * @param mimeInputStream mime message input stream
2236          * @return mime message ics attachment body
2237          * @throws IOException        on error
2238          * @throws MessagingException on error
2239          */
2240         protected byte[] getICS(InputStream mimeInputStream) throws IOException, MessagingException {
2241             byte[] result;
2242             MimeMessage mimeMessage = new MimeMessage(null, mimeInputStream);
2243             String[] contentClassHeader = mimeMessage.getHeader("Content-class");
2244             // task item, return null
2245             if (contentClassHeader != null && contentClassHeader.length > 0 && "urn:content-classes:task".equals(contentClassHeader[0])) {
2246                 return null;
2247             }
2248             Object mimeBody = mimeMessage.getContent();
2249             MimePart bodyPart = null;
2250             if (mimeBody instanceof MimeMultipart) {
2251                 bodyPart = getCalendarMimePart((MimeMultipart) mimeBody);
2252             } else if (isCalendarContentType(mimeMessage.getContentType())) {
2253                 // no multipart, single body
2254                 bodyPart = mimeMessage;
2255             }
2256 
2257 
2258             if (bodyPart != null) {
2259                 try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
2260                     bodyPart.getDataHandler().writeTo(baos);
2261                     result = baos.toByteArray();
2262                 }
2263             } else {
2264                 try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
2265                     mimeMessage.writeTo(baos);
2266                     throw new DavMailException("EXCEPTION_INVALID_MESSAGE_CONTENT", new String(baos.toByteArray(), StandardCharsets.UTF_8));
2267                 }
2268             }
2269             return result;
2270         }
2271 
2272         protected void fixICS(byte[] icsContent, String calendarEmail, boolean fromServer) throws IOException {
2273             if (LOGGER.isDebugEnabled() && fromServer) {
2274                 dumpIndex++;
2275                 String icsBody = new String(icsContent, StandardCharsets.UTF_8);
2276                 ICSCalendarValidator.ValidationResult vr = ICSCalendarValidator.validateWithDetails(icsBody);
2277                 dumpICS(icsBody, true, false);
2278                 LOGGER.debug("Vcalendar body ValidationResult: "+ vr.isValid() +" "+ vr.showReason());
2279                 LOGGER.debug("Vcalendar body received from server:\n" + icsBody);
2280             }
2281             vCalendar = new VCalendar(icsContent, calendarEmail, getVTimezone());
2282             if (startTimeZone != null) {
2283                 vCalendar.setStartTimeZone(startTimeZone);
2284             }
2285             vCalendar.fixVCalendar(fromServer);
2286             if (LOGGER.isDebugEnabled() && !fromServer) {
2287                 String resultString = vCalendar.toString();
2288                 ICSCalendarValidator.ValidationResult vr = ICSCalendarValidator.validateWithDetails(resultString);
2289                 LOGGER.debug("Fixed Vcalendar body ValidationResult: "+ vr.isValid() +" "+ vr.showReason());
2290                 LOGGER.debug("Fixed Vcalendar body to server:\n" + resultString);
2291                 dumpICS(resultString, false, true);
2292             }
2293         }
2294 
2295         protected void dumpICS(String icsBody, boolean fromServer, boolean after) {
2296             String logFileDirectory = Settings.getLogFileDirectory();
2297 
2298             // additional setting to activate ICS dump (not available in GUI)
2299             int dumpMax = Settings.getIntProperty("davmail.dumpICS");
2300             if (dumpMax > 0) {
2301                 if (dumpIndex > dumpMax) {
2302                     // Delete the oldest dump file
2303                     final int oldest = dumpIndex - dumpMax;
2304                     try {
2305                         File[] oldestFiles = (new File(logFileDirectory)).listFiles((dir, name) -> {
2306                             if (name.endsWith(".ics")) {
2307                                 int dashIndex = name.indexOf('-');
2308                                 if (dashIndex > 0) {
2309                                     try {
2310                                         int fileIndex = Integer.parseInt(name.substring(0, dashIndex));
2311                                         return fileIndex < oldest;
2312                                     } catch (NumberFormatException nfe) {
2313                                         // ignore
2314                                     }
2315                                 }
2316                             }
2317                             return false;
2318                         });
2319                         if (oldestFiles != null) {
2320                             for (File file : oldestFiles) {
2321                                 if (!file.delete()) {
2322                                     LOGGER.warn("Unable to delete " + file.getAbsolutePath());
2323                                 }
2324                             }
2325                         }
2326                     } catch (Exception ex) {
2327                         LOGGER.warn("Error deleting ics dump: " + ex.getMessage());
2328                     }
2329                 }
2330 
2331                 StringBuilder filePath = new StringBuilder();
2332                 filePath.append(logFileDirectory).append('/')
2333                         .append(dumpIndex)
2334                         .append(after ? "-to" : "-from")
2335                         .append((after ^ fromServer) ? "-server" : "-client")
2336                         .append(".ics");
2337                 if ((icsBody != null) && (!icsBody.isEmpty())) {
2338                     try (OutputStreamWriter writer = new OutputStreamWriter(Files.newOutputStream(Paths.get(filePath.toString())), StandardCharsets.UTF_8))
2339                     {
2340                         writer.write(icsBody);
2341                     } catch (IOException e) {
2342                         LOGGER.error(e);
2343                     }
2344 
2345 
2346                 }
2347             }
2348 
2349         }
2350 
2351         /**
2352          * Build Mime body for event or event message.
2353          *
2354          * @return mimeContent as byte array or null
2355          * @throws IOException on error
2356          */
2357         public byte[] createMimeContent() throws IOException {
2358             String boundary = UUID.randomUUID().toString();
2359             ByteArrayOutputStream baos = new ByteArrayOutputStream();
2360             MimeOutputStreamWriter writer = new MimeOutputStreamWriter(baos);
2361 
2362             writer.writeHeader("Content-Transfer-Encoding", "7bit");
2363             writer.writeHeader("Content-class", contentClass);
2364             // append date
2365             writer.writeHeader("Date", new Date());
2366 
2367             // Make sure invites have a proper subject line
2368             String vEventSubject = vCalendar.getFirstVeventPropertyValue("SUMMARY");
2369             if (vEventSubject == null) {
2370                 vEventSubject = BundleMessage.format("MEETING_REQUEST");
2371             }
2372 
2373             // Write a part of the message that contains the
2374             // ICS description so that invites contain the description text
2375             String description = vCalendar.getFirstVeventPropertyValue("DESCRIPTION");
2376 
2377             // handle notifications
2378             if ("urn:content-classes:calendarmessage".equals(contentClass)) {
2379                 // need to parse attendees and organizer to build recipients
2380                 VCalendar.Recipients recipients = vCalendar.getRecipients(true);
2381                 String to;
2382                 String cc;
2383                 String notificationSubject;
2384                 if (email.equalsIgnoreCase(recipients.organizer)) {
2385                     // current user is organizer => notify all
2386                     to = recipients.attendees;
2387                     cc = recipients.optionalAttendees;
2388                     notificationSubject = subject;
2389                 } else {
2390                     String status = vCalendar.getAttendeeStatus();
2391                     // notify only organizer
2392                     to = recipients.organizer;
2393                     cc = null;
2394                     notificationSubject = (status != null) ? (BundleMessage.format(status) + vEventSubject) : subject;
2395                     description = "";
2396                 }
2397 
2398                 // Allow end user notification edit
2399                 if (Settings.getBooleanProperty("davmail.caldavEditNotifications")) {
2400                     // create notification edit dialog
2401                     NotificationDialog notificationDialog = new NotificationDialog(to,
2402                             cc, notificationSubject, description);
2403                     if (!notificationDialog.getSendNotification()) {
2404                         LOGGER.debug("Notification canceled by user");
2405                         return null;
2406                     }
2407                     // get description from dialog
2408                     to = notificationDialog.getTo();
2409                     cc = notificationDialog.getCc();
2410                     notificationSubject = notificationDialog.getSubject();
2411                     description = notificationDialog.getBody();
2412                 }
2413 
2414                 // do not send notification if no recipients found
2415                 if ((to == null || to.isEmpty()) && (cc == null || cc.isEmpty())) {
2416                     return null;
2417                 }
2418 
2419                 writer.writeHeader("To", to);
2420                 writer.writeHeader("Cc", cc);
2421                 writer.writeHeader("Subject", notificationSubject);
2422 
2423 
2424                 if (LOGGER.isDebugEnabled()) {
2425                     StringBuilder logBuffer = new StringBuilder("Sending notification ");
2426                     if (to != null) {
2427                         logBuffer.append("to: ").append(to);
2428                     }
2429                     if (cc != null) {
2430                         logBuffer.append("cc: ").append(cc);
2431                     }
2432                     LOGGER.debug(logBuffer.toString());
2433                 }
2434             } else {
2435                 // need to parse attendees and organizer to build recipients
2436                 VCalendar.Recipients recipients = vCalendar.getRecipients(false);
2437                 // storing appointment, full recipients header
2438                 if (recipients.attendees != null) {
2439                     writer.writeHeader("To", recipients.attendees);
2440                 } else {
2441                     // use current user as attendee
2442                     writer.writeHeader("To", email);
2443                 }
2444                 writer.writeHeader("Cc", recipients.optionalAttendees);
2445 
2446                 if (recipients.organizer != null) {
2447                     writer.writeHeader("From", recipients.organizer);
2448                 } else {
2449                     writer.writeHeader("From", email);
2450                 }
2451             }
2452             if (vCalendar.getMethod() == null) {
2453                 vCalendar.setPropertyValue("METHOD", "REQUEST");
2454             }
2455             writer.writeHeader("MIME-Version", "1.0");
2456             writer.writeHeader("Content-Type", "multipart/alternative;\r\n" +
2457                     "\tboundary=\"----=_NextPart_" + boundary + '\"');
2458             writer.writeLn();
2459             writer.writeLn("This is a multi-part message in MIME format.");
2460             writer.writeLn();
2461             writer.writeLn("------=_NextPart_" + boundary);
2462 
2463             if (description != null && !description.isEmpty()) {
2464                 writer.writeHeader("Content-Type", "text/plain;\r\n" +
2465                         "\tcharset=\"utf-8\"");
2466                 writer.writeHeader("content-transfer-encoding", "8bit");
2467                 writer.writeLn();
2468                 writer.flush();
2469                 baos.write(description.getBytes(StandardCharsets.UTF_8));
2470                 writer.writeLn();
2471                 writer.writeLn("------=_NextPart_" + boundary);
2472             }
2473             writer.writeHeader("Content-class", contentClass);
2474             writer.writeHeader("Content-Type", "text/calendar;\r\n" +
2475                     "\tmethod=" + vCalendar.getMethod() + ";\r\n" +
2476                     "\tcharset=\"utf-8\""
2477             );
2478             writer.writeHeader("Content-Transfer-Encoding", "8bit");
2479             writer.writeLn();
2480             writer.flush();
2481             baos.write(vCalendar.toString().getBytes(StandardCharsets.UTF_8));
2482             writer.writeLn();
2483             writer.writeLn("------=_NextPart_" + boundary + "--");
2484             writer.close();
2485             return baos.toByteArray();
2486         }
2487 
2488         /**
2489          * Create or update item
2490          *
2491          * @return action result
2492          * @throws IOException on error
2493          */
2494         public abstract ItemResult createOrUpdate() throws IOException;
2495 
2496     }
2497 
2498     protected abstract Set<String> getItemProperties();
2499 
2500     /**
2501      * Search contacts in provided folder.
2502      *
2503      * @param folderPath Exchange folder path
2504      * @param includeDistList include distribution lists
2505      * @return list of contacts
2506      * @throws IOException on error
2507      */
2508     public List<ExchangeSession.Contact> getAllContacts(String folderPath, boolean includeDistList) throws IOException {
2509         return searchContacts(folderPath, ExchangeSession.CONTACT_ATTRIBUTES, isEqualTo("outlookmessageclass", "IPM.Contact"), 0);
2510     }
2511 
2512 
2513     /**
2514      * Search contacts in provided folder matching the search query.
2515      *
2516      * @param folderPath Exchange folder path
2517      * @param attributes requested attributes
2518      * @param condition  Exchange search query
2519      * @param maxCount   maximum item count
2520      * @return list of contacts
2521      * @throws IOException on error
2522      */
2523     public abstract List<Contact> searchContacts(String folderPath, Set<String> attributes, Condition condition, int maxCount) throws IOException;
2524 
2525     /**
2526      * Search calendar messages in provided folder.
2527      *
2528      * @param folderPath Exchange folder path
2529      * @return list of calendar messages as Event objects
2530      * @throws IOException on error
2531      */
2532     public abstract List<Event> getEventMessages(String folderPath) throws IOException;
2533 
2534     /**
2535      * Search calendar events in provided folder.
2536      *
2537      * @param folderPath Exchange folder path
2538      * @return list of calendar events
2539      * @throws IOException on error
2540      */
2541     public List<Event> getAllEvents(String folderPath) throws IOException {
2542         List<Event> results = searchEvents(folderPath, getCalendarItemCondition(getPastDelayCondition("dtstart")));
2543 
2544         if (!Settings.getBooleanProperty("davmail.caldavDisableTasks", false) && isMainCalendar(folderPath)) {
2545             // retrieve tasks from main tasks folder
2546             results.addAll(searchTasksOnly(folderPath));
2547         }
2548 
2549         return results;
2550     }
2551 
2552     protected abstract Condition getCalendarItemCondition(Condition dateCondition);
2553 
2554     protected Condition getPastDelayCondition(String attribute) {
2555         int caldavPastDelay = Settings.getIntProperty("davmail.caldavPastDelay");
2556         Condition dateCondition = null;
2557         if (caldavPastDelay != 0) {
2558             Calendar cal = Calendar.getInstance();
2559             cal.add(Calendar.DAY_OF_MONTH, -caldavPastDelay);
2560             dateCondition = gt(attribute, formatSearchDate(cal.getTime()));
2561         }
2562         return dateCondition;
2563     }
2564 
2565     protected Condition getRangeCondition(String timeRangeStart, String timeRangeEnd) throws IOException {
2566         try {
2567             SimpleDateFormat parser = getZuluDateFormat();
2568             ExchangeSession.MultiCondition andCondition = and();
2569             if (timeRangeStart != null) {
2570                 andCondition.add(gt("dtend", formatSearchDate(parser.parse(timeRangeStart))));
2571             }
2572             if (timeRangeEnd != null) {
2573                 andCondition.add(lt("dtstart", formatSearchDate(parser.parse(timeRangeEnd))));
2574             }
2575             return andCondition;
2576         } catch (ParseException e) {
2577             throw new IOException(e + " " + e.getMessage());
2578         }
2579     }
2580 
2581     /**
2582      * Search events between start and end.
2583      *
2584      * @param folderPath     Exchange folder path
2585      * @param timeRangeStart date range start in zulu format
2586      * @param timeRangeEnd   date range start in zulu format
2587      * @return list of calendar events
2588      * @throws IOException on error
2589      */
2590     public List<Event> searchEvents(String folderPath, String timeRangeStart, String timeRangeEnd) throws IOException {
2591         Condition dateCondition = getRangeCondition(timeRangeStart, timeRangeEnd);
2592         Condition condition = getCalendarItemCondition(dateCondition);
2593 
2594         return searchEvents(folderPath, condition);
2595     }
2596 
2597     /**
2598      * Search events between start and end, exclude tasks.
2599      *
2600      * @param folderPath     Exchange folder path
2601      * @param timeRangeStart date range start in zulu format
2602      * @param timeRangeEnd   date range start in zulu format
2603      * @return list of calendar events
2604      * @throws IOException on error
2605      */
2606     public List<Event> searchEventsOnly(String folderPath, String timeRangeStart, String timeRangeEnd) throws IOException {
2607         Condition dateCondition = getRangeCondition(timeRangeStart, timeRangeEnd);
2608         return searchEvents(folderPath, getCalendarItemCondition(dateCondition));
2609     }
2610 
2611     /**
2612      * Search tasks only (VTODO).
2613      *
2614      * @param folderPath Exchange folder path
2615      * @return list of tasks
2616      * @throws IOException on error
2617      */
2618     public List<Event> searchTasksOnly(String folderPath) throws IOException {
2619         // can be called with vTodoOnly condition on default calendar
2620         String taskFolderPath = folderPath;
2621         if (isMainCalendar(folderPath)) {
2622             taskFolderPath = TASKS;
2623         }
2624         return searchEvents(taskFolderPath, and(isEqualTo("outlookmessageclass", "IPM.Task"),
2625                 or(isNull("datecompleted"), getPastDelayCondition("datecompleted"))));
2626     }
2627 
2628     /**
2629      * Search calendar events in the provided folder.
2630      *
2631      * @param folderPath Exchange folder path
2632      * @param filter     search filter
2633      * @return list of calendar events
2634      * @throws IOException on error
2635      */
2636     public List<Event> searchEvents(String folderPath, Condition filter) throws IOException {
2637 
2638         Condition privateCondition = null;
2639         if (isSharedFolder(folderPath) && Settings.getBooleanProperty("davmail.excludePrivateEvents", true)) {
2640             LOGGER.debug("Shared or public calendar: exclude private events");
2641             privateCondition = isEqualTo("sensitivity", 0);
2642         }
2643 
2644         return searchEvents(folderPath, getItemProperties(),
2645                 and(filter, privateCondition));
2646     }
2647 
2648     /**
2649      * Search calendar events or messages in provided folder matching the search query.
2650      *
2651      * @param folderPath Exchange folder path
2652      * @param attributes requested attributes
2653      * @param condition  Exchange search query
2654      * @return list of calendar messages as Event objects
2655      * @throws IOException on error
2656      */
2657     public abstract List<Event> searchEvents(String folderPath, Set<String> attributes, Condition condition) throws IOException;
2658 
2659     /**
2660      * convert vcf extension to EML.
2661      *
2662      * @param itemName item name
2663      * @return EML item name
2664      */
2665     protected String convertItemNameToEML(String itemName) {
2666         if (itemName.endsWith(".vcf")) {
2667             return itemName.substring(0, itemName.length() - 3) + "EML";
2668         } else {
2669             return itemName;
2670         }
2671     }
2672 
2673     /**
2674      * Get item named eventName in folder
2675      *
2676      * @param folderPath Exchange folder path
2677      * @param itemName   event name
2678      * @return event object
2679      * @throws IOException on error
2680      */
2681     public abstract Item getItem(String folderPath, String itemName) throws IOException;
2682 
2683     /**
2684      * Contact picture
2685      */
2686     public static class ContactPhoto {
2687         /**
2688          * Contact picture content type (always image/jpeg on read)
2689          */
2690         public String contentType;
2691         /**
2692          * Base64 encoded picture content
2693          */
2694         public String content;
2695     }
2696 
2697     /**
2698      * Retrieve contact photo attached to contact
2699      *
2700      * @param contact address book contact
2701      * @return contact photo
2702      * @throws IOException on error
2703      */
2704     public abstract ContactPhoto getContactPhoto(Contact contact) throws IOException;
2705 
2706     /**
2707      * Retrieve contact photo from AD
2708      *
2709      * @param email address book contact
2710      * @return contact photo
2711      */
2712     public ContactPhoto getADPhoto(String email) {
2713         return null;
2714     }
2715 
2716     /**
2717      * Delete event named itemName in folder
2718      *
2719      * @param folderPath Exchange folder path
2720      * @param itemName   item name
2721      * @throws IOException on error
2722      */
2723     public abstract void deleteItem(String folderPath, String itemName) throws IOException;
2724 
2725     /**
2726      * Mark event processed named eventName in folder
2727      *
2728      * @param folderPath Exchange folder path
2729      * @param itemName   item name
2730      * @throws IOException on error
2731      */
2732     public abstract void processItem(String folderPath, String itemName) throws IOException;
2733 
2734 
2735     private static int dumpIndex;
2736 
2737     /**
2738      * Event result object to hold HTTP status and event etag from an event creation/update.
2739      */
2740     public static class ItemResult {
2741         /**
2742          * HTTP status
2743          */
2744         public int status;
2745         /**
2746          * Event etag from response HTTP header
2747          */
2748         public String etag;
2749         /**
2750          * Created item name
2751          */
2752         public String itemName;
2753     }
2754 
2755     /**
2756      * Build and send the MIME message for the provided ICS event.
2757      *
2758      * @param icsBody event in iCalendar format
2759      * @return HTTP status
2760      * @throws IOException on error
2761      */
2762     public abstract int sendEvent(String icsBody) throws IOException;
2763 
2764     /**
2765      * Create or update item (event or contact) on the Exchange server
2766      *
2767      * @param folderPath Exchange folder path
2768      * @param itemName   event name
2769      * @param itemBody   event body in iCalendar format
2770      * @param etag       previous event etag to detect concurrent updates
2771      * @param noneMatch  if-none-match header value
2772      * @return HTTP response event result (status and etag)
2773      * @throws IOException on error
2774      */
2775     public ItemResult createOrUpdateItem(String folderPath, String itemName, String itemBody, String etag, String noneMatch) throws IOException {
2776         if (itemBody.startsWith("BEGIN:VCALENDAR")) {
2777             if (Settings.getBooleanProperty("davmail.caldavReadonly", false)) {
2778                 throw new HttpForbiddenException("Calendar is read-only");
2779             }
2780             return internalCreateOrUpdateEvent(folderPath, itemName, "urn:content-classes:appointment", itemBody, etag, noneMatch);
2781         } else if (itemBody.startsWith("BEGIN:VCARD")) {
2782             return createOrUpdateContact(folderPath, itemName, itemBody, etag, noneMatch);
2783         } else {
2784             throw new IOException(BundleMessage.format("EXCEPTION_INVALID_MESSAGE_CONTENT", itemBody));
2785         }
2786     }
2787 
2788     static final String[] VCARD_N_PROPERTIES = {"sn", "givenName", "middlename", "personaltitle", "namesuffix"};
2789     static final String[] VCARD_ADR_HOME_PROPERTIES = {"homepostofficebox", null, "homeStreet", "homeCity", "homeState", "homePostalCode", "homeCountry"};
2790     static final String[] VCARD_ADR_WORK_PROPERTIES = {"postofficebox", "roomnumber", "street", "l", "st", "postalcode", "co"};
2791     static final String[] VCARD_ADR_OTHER_PROPERTIES = {"otherpostofficebox", null, "otherstreet", "othercity", "otherstate", "otherpostalcode", "othercountry"};
2792     static final String[] VCARD_ORG_PROPERTIES = {"o", "department"};
2793 
2794     protected void convertContactProperties(Map<String, String> properties, String[] contactProperties, List<String> values) {
2795         for (int i = 0; i < values.size() && i < contactProperties.length; i++) {
2796             if (contactProperties[i] != null) {
2797                 properties.put(contactProperties[i], values.get(i));
2798             }
2799         }
2800     }
2801 
2802     /**
2803      * Select the contact field matching a vCard TEL property.
2804      * Exchange supports one value per phone type, plus a secondary business and home phone.
2805      * Specific types (fax, pager, car) are tested before generic work and home types:
2806      * a work fax is TEL;TYPE=work;TYPE=fax and is a fax, not a business phone.
2807      *
2808      * @param property   vCard TEL property
2809      * @param properties contact properties already collected, used to select primary or secondary phone
2810      * @return contact field name, or null if there is no room left for this phone number
2811      */
2812     protected static String getContactPhoneField(VProperty property, Map<String, String> properties) {
2813         if (property.hasParam("TYPE", "cell") || property.hasParam("X-GROUP", "cell")) {
2814             return "mobile";
2815         } else if (property.hasParam("TYPE", "fax")) {
2816             return property.hasParam("TYPE", "home") ? "homefax" : "facsimiletelephonenumber";
2817         } else if (property.hasParam("TYPE", "pager")) {
2818             return "pager";
2819         } else if (property.hasParam("TYPE", "car")) {
2820             return "othermobile";
2821         } else if (property.hasParam("TYPE", "work") || property.hasParam("X-GROUP", "work")) {
2822             return firstAvailable(properties, "telephoneNumber", "otherBusinessTelephoneNumber");
2823         } else if (property.hasParam("TYPE", "home") || property.hasParam("X-GROUP", "home")) {
2824             return firstAvailable(properties, "homePhone", "otherHomePhone");
2825         } else {
2826             return "otherTelephone";
2827         }
2828     }
2829 
2830     private static String firstAvailable(Map<String, String> properties, String primary, String secondary) {
2831         if (!properties.containsKey(primary)) {
2832             return primary;
2833         } else if (!properties.containsKey(secondary)) {
2834             return secondary;
2835         } else {
2836             return null;
2837         }
2838     }
2839 
2840     protected ItemResult createOrUpdateContact(String folderPath, String itemName, String itemBody, String etag, String noneMatch) throws IOException {
2841         // parse VCARD body to build contact property map
2842         Map<String, String> properties = new HashMap<>();
2843 
2844         VObject vcard = new VObject(new ICSBufferedReader(new StringReader(itemBody)));
2845         if ("group".equalsIgnoreCase(vcard.getPropertyValue("KIND"))) {
2846             properties.put("outlookmessageclass", "IPM.DistList");
2847             properties.put("displayname", vcard.getPropertyValue("FN"));
2848             properties.put("personalNotes", vcard.getPropertyValue("NOTE"));
2849         } else {
2850             properties.put("outlookmessageclass", "IPM.Contact");
2851 
2852             for (VProperty property : vcard.getProperties()) {
2853                 if ("FN".equals(property.getKey())) {
2854                     properties.put("cn", property.getValue());
2855                     properties.put("subject", property.getValue());
2856                     properties.put("fileas", property.getValue());
2857 
2858                 } else if ("N".equals(property.getKey())) {
2859                     convertContactProperties(properties, VCARD_N_PROPERTIES, property.getValues());
2860                 } else if ("NICKNAME".equals(property.getKey())) {
2861                     properties.put("nickname", property.getValue());
2862                 } else if ("TEL".equals(property.getKey())) {
2863                     String phoneField = getContactPhoneField(property, properties);
2864                     if (phoneField != null) {
2865                         properties.put(phoneField, property.getValue());
2866                     } else {
2867                         LOGGER.warn("Ignore additional phone number " + property.getValue());
2868                     }
2869                 } else if ("ADR".equals(property.getKey())) {
2870                     // address
2871                     if (property.hasParam("TYPE", "home")) {
2872                         convertContactProperties(properties, VCARD_ADR_HOME_PROPERTIES, property.getValues());
2873                     } else if (property.hasParam("TYPE", "work")) {
2874                         convertContactProperties(properties, VCARD_ADR_WORK_PROPERTIES, property.getValues());
2875                         // any other type goes to other address
2876                     } else {
2877                         convertContactProperties(properties, VCARD_ADR_OTHER_PROPERTIES, property.getValues());
2878                     }
2879                 } else if ("EMAIL".equals(property.getKey())) {
2880                     if (property.hasParam("TYPE", "home")) {
2881                         properties.put("email2", property.getValue());
2882                         properties.put("smtpemail2", property.getValue());
2883                     } else if (property.hasParam("TYPE", "other")) {
2884                         properties.put("email3", property.getValue());
2885                         properties.put("smtpemail3", property.getValue());
2886                     } else {
2887                         properties.put("email1", property.getValue());
2888                         properties.put("smtpemail1", property.getValue());
2889                     }
2890                 } else if ("ORG".equals(property.getKey())) {
2891                     convertContactProperties(properties, VCARD_ORG_PROPERTIES, property.getValues());
2892                 } else if ("URL".equals(property.getKey())) {
2893                     if (property.hasParam("TYPE", "work")) {
2894                         properties.put("businesshomepage", property.getValue());
2895                     } else if (property.hasParam("TYPE", "home")) {
2896                         properties.put("personalHomePage", property.getValue());
2897                     } else {
2898                         // default: set personal home page
2899                         properties.put("personalHomePage", property.getValue());
2900                     }
2901                 } else if ("TITLE".equals(property.getKey())) {
2902                     properties.put("title", property.getValue());
2903                 } else if ("NOTE".equals(property.getKey())) {
2904                     properties.put("personalNotes", property.getValue());
2905                 } else if ("CUSTOM1".equals(property.getKey())) {
2906                     properties.put("extensionattribute1", property.getValue());
2907                 } else if ("CUSTOM2".equals(property.getKey())) {
2908                     properties.put("extensionattribute2", property.getValue());
2909                 } else if ("CUSTOM3".equals(property.getKey())) {
2910                     properties.put("extensionattribute3", property.getValue());
2911                 } else if ("CUSTOM4".equals(property.getKey())) {
2912                     properties.put("extensionattribute4", property.getValue());
2913                 } else if ("ROLE".equals(property.getKey())) {
2914                     properties.put("profession", property.getValue());
2915                 } else if ("X-AIM".equals(property.getKey())) {
2916                     properties.put("im", property.getValue());
2917                 } else if ("BDAY".equals(property.getKey())) {
2918                     properties.put("bday", convertBDayToZulu(property.getValue()));
2919                 } else if ("ANNIVERSARY".equals(property.getKey()) || "X-ANNIVERSARY".equals(property.getKey())) {
2920                     properties.put("anniversary", convertBDayToZulu(property.getValue()));
2921                 } else if ("CATEGORIES".equals(property.getKey())) {
2922                     properties.put("keywords", property.getValue());
2923                 } else if ("CLASS".equals(property.getKey())) {
2924                     if ("PUBLIC".equals(property.getValue())) {
2925                         properties.put("sensitivity", "0");
2926                         properties.put("private", "false");
2927                     } else {
2928                         properties.put("sensitivity", "2");
2929                         properties.put("private", "true");
2930                     }
2931                 } else if ("SEX".equals(property.getKey())) {
2932                     String propertyValue = property.getValue();
2933                     if ("1".equals(propertyValue)) {
2934                         properties.put("gender", "2");
2935                     } else if ("2".equals(propertyValue)) {
2936                         properties.put("gender", "1");
2937                     }
2938                 } else if ("FBURL".equals(property.getKey())) {
2939                     properties.put("fburl", property.getValue());
2940                 } else if ("X-ASSISTANT".equals(property.getKey())) {
2941                     properties.put("secretarycn", property.getValue());
2942                 } else if ("X-MANAGER".equals(property.getKey())) {
2943                     properties.put("manager", property.getValue());
2944                 } else if ("X-SPOUSE".equals(property.getKey())) {
2945                     properties.put("spousecn", property.getValue());
2946                 } else if ("PHOTO".equals(property.getKey())) {
2947                     String value = property.getValue();
2948                     if ("data:image/jpeg".equals(value) && property.values.size() > 1) {
2949                         value = property.getValues().get(1);
2950                         if (value.startsWith("base64,")) {
2951                             value = value.substring(7);
2952                         }
2953                     }
2954                     properties.put("photo", value);
2955                     properties.put("haspicture", "true");
2956                 } else if ("KEY1".equals(property.getKey())) {
2957                     properties.put("msexchangecertificate", property.getValue());
2958                 } else if ("KEY2".equals(property.getKey())) {
2959                     properties.put("usersmimecertificate", property.getValue());
2960                 }
2961             }
2962             LOGGER.debug("Create or update contact " + itemName + ": " + properties);
2963             // reset missing properties to null
2964             for (String key : CONTACT_ATTRIBUTES) {
2965                 if (!"imapUid".equals(key) && !"etag".equals(key) && !"urlcompname".equals(key) && !"uid".equals(key)
2966                         && !"lastmodified".equals(key) && !"sensitivity".equals(key)
2967                         && !"haspicture".equals(key)
2968                         && !"usersmimecertificate".equals(key) && !"msexchangecertificate".equals(key)
2969                         && !properties.containsKey(key)) {
2970                     properties.put(key, null);
2971                 }
2972             }
2973         }
2974 
2975         Contact contact = buildContact(folderPath, itemName, properties, etag, noneMatch);
2976         for (VProperty property : vcard.getProperties()) {
2977             if ("MEMBER".equals(property.getKey())) {
2978                 String member = property.getValue();
2979                 if (member.startsWith("urn:uuid:")) {
2980                     Item item = getItem(folderPath, member.substring(9) + ".EML");
2981                     if (item != null) {
2982                         if (item.get("smtpemail1") != null) {
2983                             member = "mailto:" + item.get("smtpemail1");
2984                         } else if (item.get("smtpemail2") != null) {
2985                             member = "mailto:" + item.get("smtpemail2");
2986                         } else if (item.get("smtpemail3") != null) {
2987                             member = "mailto:" + item.get("smtpemail3");
2988                         }
2989                     }
2990                 }
2991                 contact.addMember(member);
2992             }
2993         }
2994         return contact.createOrUpdate();
2995     }
2996 
2997     protected String convertZuluDateToBday(String value) {
2998         String result = null;
2999         if (value != null && !value.isEmpty()) {
3000             try {
3001                 SimpleDateFormat parser = ExchangeSession.getZuluDateFormat();
3002                 Calendar cal = Calendar.getInstance();
3003                 cal.setTime(parser.parse(value));
3004                 cal.add(Calendar.HOUR_OF_DAY, 12);
3005                 result = ExchangeSession.getVcardBdayFormat().format(cal.getTime());
3006             } catch (ParseException e) {
3007                 LOGGER.warn("Invalid date: " + value);
3008             }
3009         }
3010         return result;
3011     }
3012 
3013     protected String convertBDayToZulu(String value) {
3014         String result = null;
3015         if (value != null && !value.isEmpty()) {
3016             try {
3017                 SimpleDateFormat parser;
3018                 if (value.length() == 8) {
3019                     parser = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);
3020                     parser.setTimeZone(GMT_TIMEZONE);
3021                 } else if (value.length() == 10) {
3022                     parser = ExchangeSession.getVcardBdayFormat();
3023                 } else if (value.length() == 15) {
3024                     parser = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ENGLISH);
3025                     parser.setTimeZone(GMT_TIMEZONE);
3026                 } else {
3027                     parser = ExchangeSession.getExchangeZuluDateFormat();
3028                 }
3029                 result = ExchangeSession.getExchangeZuluDateFormatMillisecond().format(parser.parse(value));
3030             } catch (ParseException e) {
3031                 LOGGER.warn("Invalid date: " + value);
3032             }
3033         }
3034 
3035         return result;
3036     }
3037 
3038 
3039     protected abstract Contact buildContact(String folderPath, String itemName, Map<String, String> properties, String etag, String noneMatch) throws IOException;
3040 
3041     protected abstract ItemResult internalCreateOrUpdateEvent(String folderPath, String itemName, String contentClass, String icsBody, String etag, String noneMatch) throws IOException;
3042 
3043     /**
3044      * Get current Exchange alias name from login name
3045      *
3046      * @return user name
3047      */
3048     public String getAliasFromLogin() {
3049         // login is email, not alias
3050         if (this.userName.indexOf('@') >= 0) {
3051             return null;
3052         }
3053         String result = this.userName;
3054         // remove domain name
3055         int index = Math.max(result.indexOf('\\'), result.indexOf('/'));
3056         if (index >= 0) {
3057             result = result.substring(index + 1);
3058         }
3059         return result;
3060     }
3061 
3062     /**
3063      * Test if folderPath is inside user mailbox.
3064      *
3065      * @param folderPath absolute folder path
3066      * @return true if folderPath is a public or shared folder
3067      */
3068     public abstract boolean isSharedFolder(String folderPath);
3069 
3070     /**
3071      * Test if folderPath is main calendar.
3072      *
3073      * @param folderPath absolute folder path
3074      * @return true if folderPath is a public or shared folder
3075      */
3076     public abstract boolean isMainCalendar(String folderPath) throws IOException;
3077 
3078     protected static final String MAILBOX_BASE = "/cn=";
3079 
3080     /**
3081      * Get current user email
3082      *
3083      * @return user email
3084      */
3085     public String getEmail() {
3086         return email;
3087     }
3088 
3089     /**
3090      * Get email from current calendar
3091      * @param folderPath calendar folder path
3092      * @return calendar mailbox
3093      */
3094     protected abstract String getCalendarEmail(String folderPath) throws IOException;
3095 
3096     /**
3097      * Get current user alias
3098      *
3099      * @return user email
3100      */
3101     public String getAlias() {
3102         return alias;
3103     }
3104 
3105     /**
3106      * Check if the backend supports native people/directory search (e.g. Graph People API).
3107      * When true, the LDAP layer can issue a single broad search instead of iterating A-to-Z.
3108      *
3109      * @return true if backend supports native people search
3110      */
3111     public boolean supportsPeopleSearch() {
3112         return false;
3113     }
3114 
3115     /**
3116      * Search global address list
3117      *
3118      * @param condition           search filter
3119      * @param returningAttributes returning attributes
3120      * @param sizeLimit           size limit
3121      * @return matching contacts from gal
3122      * @throws IOException on error
3123      */
3124     public abstract Map<String, Contact> galFind(Condition condition, Set<String> returningAttributes, int sizeLimit) throws IOException;
3125 
3126     /**
3127      * Full Contact attribute list
3128      */
3129     public static final Set<String> CONTACT_ATTRIBUTES = new HashSet<>();
3130 
3131     static {
3132         CONTACT_ATTRIBUTES.add("uid");
3133         CONTACT_ATTRIBUTES.add("imapUid");
3134         CONTACT_ATTRIBUTES.add("etag");
3135         CONTACT_ATTRIBUTES.add("urlcompname");
3136 
3137         CONTACT_ATTRIBUTES.add("extensionattribute1");
3138         CONTACT_ATTRIBUTES.add("extensionattribute2");
3139         CONTACT_ATTRIBUTES.add("extensionattribute3");
3140         CONTACT_ATTRIBUTES.add("extensionattribute4");
3141         CONTACT_ATTRIBUTES.add("bday");
3142         CONTACT_ATTRIBUTES.add("anniversary");
3143         CONTACT_ATTRIBUTES.add("businesshomepage");
3144         CONTACT_ATTRIBUTES.add("personalHomePage");
3145         CONTACT_ATTRIBUTES.add("cn");
3146         CONTACT_ATTRIBUTES.add("co");
3147         CONTACT_ATTRIBUTES.add("department");
3148         CONTACT_ATTRIBUTES.add("smtpemail1");
3149         CONTACT_ATTRIBUTES.add("smtpemail2");
3150         CONTACT_ATTRIBUTES.add("smtpemail3");
3151         CONTACT_ATTRIBUTES.add("facsimiletelephonenumber");
3152         CONTACT_ATTRIBUTES.add("givenName");
3153         CONTACT_ATTRIBUTES.add("internationalisdnnumber");
3154         CONTACT_ATTRIBUTES.add("homeCity");
3155         CONTACT_ATTRIBUTES.add("homeCountry");
3156         CONTACT_ATTRIBUTES.add("homefax");
3157         CONTACT_ATTRIBUTES.add("homePhone");
3158         CONTACT_ATTRIBUTES.add("homePostalCode");
3159         CONTACT_ATTRIBUTES.add("homeState");
3160         CONTACT_ATTRIBUTES.add("homeStreet");
3161         CONTACT_ATTRIBUTES.add("homepostofficebox");
3162         CONTACT_ATTRIBUTES.add("l");
3163         CONTACT_ATTRIBUTES.add("manager");
3164         CONTACT_ATTRIBUTES.add("mobile");
3165         CONTACT_ATTRIBUTES.add("namesuffix");
3166         CONTACT_ATTRIBUTES.add("nickname");
3167         CONTACT_ATTRIBUTES.add("o");
3168         CONTACT_ATTRIBUTES.add("pager");
3169         CONTACT_ATTRIBUTES.add("personaltitle");
3170         CONTACT_ATTRIBUTES.add("postalcode");
3171         CONTACT_ATTRIBUTES.add("postofficebox");
3172         CONTACT_ATTRIBUTES.add("profession");
3173         CONTACT_ATTRIBUTES.add("roomnumber");
3174         CONTACT_ATTRIBUTES.add("secretarycn");
3175         CONTACT_ATTRIBUTES.add("sn");
3176         CONTACT_ATTRIBUTES.add("spousecn");
3177         CONTACT_ATTRIBUTES.add("st");
3178         CONTACT_ATTRIBUTES.add("street");
3179         CONTACT_ATTRIBUTES.add("telephoneNumber");
3180         CONTACT_ATTRIBUTES.add("title");
3181         CONTACT_ATTRIBUTES.add("description");
3182         CONTACT_ATTRIBUTES.add("personalNotes");
3183         CONTACT_ATTRIBUTES.add("im");
3184         CONTACT_ATTRIBUTES.add("middlename");
3185         CONTACT_ATTRIBUTES.add("lastmodified");
3186         CONTACT_ATTRIBUTES.add("otherstreet");
3187         CONTACT_ATTRIBUTES.add("otherstate");
3188         CONTACT_ATTRIBUTES.add("otherpostofficebox");
3189         CONTACT_ATTRIBUTES.add("otherpostalcode");
3190         CONTACT_ATTRIBUTES.add("othercountry");
3191         CONTACT_ATTRIBUTES.add("othercity");
3192         CONTACT_ATTRIBUTES.add("haspicture");
3193         CONTACT_ATTRIBUTES.add("keywords");
3194         CONTACT_ATTRIBUTES.add("othermobile");
3195         CONTACT_ATTRIBUTES.add("otherBusinessTelephoneNumber");
3196         CONTACT_ATTRIBUTES.add("otherHomePhone");
3197         CONTACT_ATTRIBUTES.add("otherTelephone");
3198         CONTACT_ATTRIBUTES.add("gender");
3199         CONTACT_ATTRIBUTES.add("private");
3200         CONTACT_ATTRIBUTES.add("sensitivity");
3201         CONTACT_ATTRIBUTES.add("fburl");
3202         CONTACT_ATTRIBUTES.add("msexchangecertificate");
3203         CONTACT_ATTRIBUTES.add("usersmimecertificate");
3204     }
3205 
3206     protected static final Set<String> DISTRIBUTION_LIST_ATTRIBUTES = new HashSet<>();
3207 
3208     static {
3209         DISTRIBUTION_LIST_ATTRIBUTES.add("imapUid");
3210         DISTRIBUTION_LIST_ATTRIBUTES.add("etag");
3211         DISTRIBUTION_LIST_ATTRIBUTES.add("urlcompname");
3212 
3213         DISTRIBUTION_LIST_ATTRIBUTES.add("cn");
3214         DISTRIBUTION_LIST_ATTRIBUTES.add("members");
3215     }
3216 
3217     /**
3218      * Get freebusy data string from Exchange.
3219      *
3220      * @param attendee attendee email address
3221      * @param start    start date in Exchange zulu format
3222      * @param end      end date in Exchange zulu format
3223      * @param interval freebusy interval in minutes
3224      * @return freebusy data or null
3225      * @throws IOException on error
3226      */
3227     protected abstract String getFreeBusyData(String attendee, String start, String end, int interval) throws IOException;
3228 
3229     /**
3230      * Get freebusy info for attendee between start and end date.
3231      *
3232      * @param attendee       attendee email
3233      * @param startDateValue start date
3234      * @param endDateValue   end date
3235      * @return FreeBusy info
3236      * @throws IOException on error
3237      */
3238     public FreeBusy getFreebusy(String attendee, String startDateValue, String endDateValue) throws IOException {
3239         // replace ical encoded attendee name
3240         attendee = VCalendar.replaceIcal4Principal(attendee);
3241 
3242         // then check that email address is valid to avoid InvalidSmtpAddress error
3243         if (attendee == null || attendee.indexOf('@') < 0 || attendee.charAt(attendee.length() - 1) == '@') {
3244             return null;
3245         }
3246 
3247         if (attendee.startsWith("mailto:") || attendee.startsWith("MAILTO:")) {
3248             attendee = attendee.substring("mailto:".length());
3249         }
3250 
3251         SimpleDateFormat exchangeZuluDateFormat = getExchangeZuluDateFormat();
3252         SimpleDateFormat icalDateFormat = getZuluDateFormat();
3253 
3254         Date startDate;
3255         Date endDate;
3256         try {
3257             if (startDateValue.length() == 8) {
3258                 startDate = parseDate(startDateValue);
3259             } else {
3260                 startDate = icalDateFormat.parse(startDateValue);
3261             }
3262             if (endDateValue.length() == 8) {
3263                 endDate = parseDate(endDateValue);
3264             } else {
3265                 endDate = icalDateFormat.parse(endDateValue);
3266             }
3267         } catch (ParseException e) {
3268             throw new DavMailException("EXCEPTION_INVALID_DATES", e.getMessage());
3269         }
3270 
3271         FreeBusy freeBusy = null;
3272         String fbdata = getFreeBusyData(attendee, exchangeZuluDateFormat.format(startDate), exchangeZuluDateFormat.format(endDate), FREE_BUSY_INTERVAL);
3273         if (fbdata != null) {
3274             freeBusy = new FreeBusy(icalDateFormat, startDate, fbdata);
3275         }
3276 
3277         if (freeBusy != null && freeBusy.knownAttendee) {
3278             return freeBusy;
3279         } else {
3280             return null;
3281         }
3282     }
3283 
3284     /**
3285      * Exchange to iCalendar Free/Busy parser.
3286      * Free time returns 0, Tentative returns 1, Busy returns 2, and Out of Office (OOF) returns 3
3287      */
3288     public static final class FreeBusy {
3289         final SimpleDateFormat icalParser;
3290         boolean knownAttendee = true;
3291         static final HashMap<Character, String> FBTYPES = new HashMap<>();
3292 
3293         static {
3294             FBTYPES.put('1', "BUSY-TENTATIVE");
3295             FBTYPES.put('2', "BUSY");
3296             FBTYPES.put('3', "BUSY-UNAVAILABLE");
3297         }
3298 
3299         final HashMap<String, StringBuilder> busyMap = new HashMap<>();
3300 
3301         StringBuilder getBusyBuffer(char type) {
3302             String fbType = FBTYPES.get(type);
3303             return busyMap.computeIfAbsent(fbType, k -> new StringBuilder());
3304         }
3305 
3306         void startBusy(char type, Calendar currentCal) {
3307             if (type == '4') {
3308                 knownAttendee = false;
3309             } else if (type != '0') {
3310                 StringBuilder busyBuffer = getBusyBuffer(type);
3311                 if (busyBuffer.length() > 0) {
3312                     busyBuffer.append(',');
3313                 }
3314                 busyBuffer.append(icalParser.format(currentCal.getTime()));
3315             }
3316         }
3317 
3318         void endBusy(char type, Calendar currentCal) {
3319             if (type != '0' && type != '4') {
3320                 getBusyBuffer(type).append('/').append(icalParser.format(currentCal.getTime()));
3321             }
3322         }
3323 
3324         FreeBusy(SimpleDateFormat icalParser, Date startDate, String fbdata) {
3325             this.icalParser = icalParser;
3326             if (!fbdata.isEmpty()) {
3327                 Calendar currentCal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
3328                 currentCal.setTime(startDate);
3329 
3330                 startBusy(fbdata.charAt(0), currentCal);
3331                 for (int i = 1; i < fbdata.length() && knownAttendee; i++) {
3332                     currentCal.add(Calendar.MINUTE, FREE_BUSY_INTERVAL);
3333                     char previousState = fbdata.charAt(i - 1);
3334                     char currentState = fbdata.charAt(i);
3335                     if (previousState != currentState) {
3336                         endBusy(previousState, currentCal);
3337                         startBusy(currentState, currentCal);
3338                     }
3339                 }
3340                 currentCal.add(Calendar.MINUTE, FREE_BUSY_INTERVAL);
3341                 endBusy(fbdata.charAt(fbdata.length() - 1), currentCal);
3342             }
3343         }
3344 
3345         /**
3346          * Append freebusy information to provided buffer.
3347          *
3348          * @param buffer String buffer
3349          */
3350         public void appendTo(StringBuilder buffer) {
3351             for (Map.Entry<String, StringBuilder> entry : busyMap.entrySet()) {
3352                 buffer.append("FREEBUSY;FBTYPE=").append(entry.getKey())
3353                         .append(':').append(entry.getValue()).append((char) 13).append((char) 10);
3354             }
3355         }
3356     }
3357 
3358     protected VObject vTimezone;
3359 
3360     /**
3361      * Load and return current user OWA timezone.
3362      *
3363      * @return current timezone
3364      */
3365     public VObject getVTimezone() {
3366         if (vTimezone == null) {
3367             // need to load Timezone info from OWA
3368             loadVtimezone();
3369         }
3370         return vTimezone;
3371     }
3372 
3373     public String getTimezoneId() {
3374         return getVTimezone().getPropertyValue("TZID");
3375     }
3376 
3377     public void clearVTimezone() {
3378         vTimezone = null;
3379     }
3380 
3381     protected abstract void loadVtimezone();
3382 
3383     protected static final Map<String, String> importanceToPriorityMap = new HashMap<>();
3384 
3385     static {
3386         importanceToPriorityMap.put("High", "1");
3387         importanceToPriorityMap.put("Normal", "5");
3388         importanceToPriorityMap.put("Low", "9");
3389     }
3390 
3391     protected static final Map<String, String> priorityToImportanceMap = new HashMap<>();
3392 
3393     static {
3394         // 0 means undefined, map it to normal
3395         priorityToImportanceMap.put("0", "Normal");
3396 
3397         priorityToImportanceMap.put("1", "High");
3398         priorityToImportanceMap.put("2", "High");
3399         priorityToImportanceMap.put("3", "High");
3400         priorityToImportanceMap.put("4", "Normal");
3401         priorityToImportanceMap.put("5", "Normal");
3402         priorityToImportanceMap.put("6", "Normal");
3403         priorityToImportanceMap.put("7", "Low");
3404         priorityToImportanceMap.put("8", "Low");
3405         priorityToImportanceMap.put("9", "Low");
3406     }
3407 
3408     protected String convertPriorityFromExchange(String exchangeImportanceValue) {
3409         String value = null;
3410         if (exchangeImportanceValue != null) {
3411             value = importanceToPriorityMap.get(exchangeImportanceValue);
3412         }
3413         return value;
3414     }
3415 
3416     protected String convertPriorityToExchange(String vTodoPriorityValue) {
3417         String value = null;
3418         if (vTodoPriorityValue != null) {
3419             value = priorityToImportanceMap.get(vTodoPriorityValue);
3420         }
3421         return value;
3422     }
3423 
3424     /**
3425      * Possible values are: normal, personal, private, and confidential.
3426      * @param sensitivity Exchange sensitivity
3427      * @return event class
3428      */
3429     protected String convertClassFromExchange(String sensitivity) {
3430         String eventClass;
3431         if ("private".equals(sensitivity)) {
3432             eventClass = "PRIVATE";
3433         } else if ("confidential".equals(sensitivity)) {
3434             eventClass = "CONFIDENTIAL";
3435         } else if ("personal".equals(sensitivity)) {
3436             eventClass = "PRIVATE";
3437         } else {
3438             // normal
3439             eventClass = "PUBLIC";
3440         }
3441         return eventClass;
3442     }
3443 
3444 }