File: UIxMailListActions.m

package info (click to toggle)
sogo 2.2.9%2Bgit20141017-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 43,812 kB
  • sloc: objc: 115,592; python: 5,696; sh: 1,380; perl: 861; makefile: 240; xml: 114; sql: 53; php: 43
file content (873 lines) | stat: -rw-r--r-- 24,328 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
/*
  Copyright (C) 2004-2005 SKYRIX Software AG
  Copyright (C) 2006-2013 Inverse inc.

  This file is part of SOGo

  SOGo is free software; you can redistribute it and/or modify it under
  the terms of the GNU Lesser General Public License as published by the
  Free Software Foundation; either version 2, or (at your option) any
  later version.

  SOGo is distributed in the hope that it will be useful, but WITHOUT ANY
  WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
  License for more details.

  You should have received a copy of the GNU Lesser General Public
  License along with OGo; see the file COPYING.  If not, write to the
  Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
  02111-1307, USA.
*/

/*
  UIxMailListActions
  
  This component represent a list of mails and is attached to an SOGoMailFolder
  object.
*/

#import <Foundation/NSCalendarDate.h>
#import <Foundation/NSCharacterSet.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSEnumerator.h>
#import <Foundation/NSTimeZone.h>
#import <Foundation/NSValue.h>

#import <NGObjWeb/WOContext+SoObjects.h>
#import <NGObjWeb/WOResponse.h>
#import <NGObjWeb/WORequest.h>
#import <NGObjWeb/SoObject+SoDAV.h>
#import <NGObjWeb/NSException+HTTP.h>
#import <NGExtensions/NSNull+misc.h>
#import <NGExtensions/NSString+misc.h>
#import <NGExtensions/NSObject+Logs.h>
#import <NGImap4/NGImap4Envelope.h>

#import <EOControl/EOQualifier.h>

#import <Mailer/NSString+Mail.h>
#import <Mailer/SOGoDraftsFolder.h>
#import <Mailer/SOGoMailAccount.h>
#import <Mailer/SOGoMailFolder.h>
#import <Mailer/SOGoMailObject.h>
#import <Mailer/SOGoSentFolder.h>
#import <SOGo/NSArray+Utilities.h>
#import <SOGo/NSDictionary+Utilities.h>
#import <SOGo/NSString+Utilities.h>
#import <SOGo/SOGoDateFormatter.h>
#import <SOGo/SOGoUser.h>
#import <SOGo/SOGoUserDefaults.h>
#import <SOGo/SOGoUserSettings.h>

#import <UI/Common/WODirectAction+SOGo.h>
#import <UI/MailPartViewers/UIxMailSizeFormatter.h>

#import "WOContext+UIxMailer.h"
#import "UIxMailFormatter.h"

#import "UIxMailListActions.h"

// The maximum number of headers to prefetch when querying the UIDs list
#define headersPrefetchMaxSize 100

@implementation UIxMailListActions

- (id) initWithRequest: (WORequest *) newRequest
{
  SOGoUser *user;

  if ((self = [super initWithRequest: newRequest]))
    {
      user = [[self context] activeUser];
      ASSIGN (dateFormatter, [user dateFormatterInContext: context]);
      ASSIGN (userTimeZone, [[user userDefaults] timeZone]);
      sortByThread = [[user userDefaults] mailSortByThreads];
      folderType = 0;
      specificMessageNumber = 0;
    }

  return self;
}

- (void) dealloc 
{
  [sortedUIDs release];
  [messages release];
  [message release];
  [dateFormatter release];
  [userTimeZone release];
  [super dealloc];
}

/* accessors */

- (void) setMessage: (id) _msg
{
  ASSIGN (message, _msg);
}

- (id) message 
{
  return message;
}

- (NSString *) messageDate
{
  NSCalendarDate *messageDate;

  messageDate = [[message valueForKey: @"envelope"] date];
  [messageDate setTimeZone: userTimeZone];

  return [dateFormatter formattedDateAndTime: messageDate];
}

- (UIxMailSizeFormatter *) sizeFormatter
{
  return [UIxMailSizeFormatter sharedMailSizeFormatter];
}

//
// Priorities are defined like this:
//
// X-Priority: 1 (Highest)
// X-Priority: 2 (High)
// X-Priority: 3 (Normal)
// X-Priority: 4 (Low)
// X-Priority: 5 (Lowest)
//
// Sometimes, the MUAs don't send over the string in () so we ignore it.
//
- (NSString *) messagePriority
{
  NSString *result;
  NSData *data;
    
  data = [message objectForKey: @"header"];
  result = @"";

  if (data)
    {
      NSString *s;
      
      s = [[NSString alloc] initWithData: data
			    encoding: NSASCIIStringEncoding];

      if (s)
	{
	  NSRange r;

	  [s autorelease];
	  r = [s rangeOfString: @":"];

	  if (r.length)
	    {
	      s = [[s substringFromIndex: r.location+1]
		    stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];

	      if ([s hasPrefix: @"1"]) result = [self labelForKey: @"highest"];
	      else if ([s hasPrefix: @"2"]) result = [self labelForKey: @"high"];
	      else if ([s hasPrefix: @"4"]) result = [self labelForKey: @"low"];
	      else if ([s hasPrefix: @"5"]) result = [self labelForKey: @"lowest"];
	    }
	}
    }
  
  return result;
}

- (NSString *) messageSubject
{
  id baseSubject;
  NSString *subject;

  baseSubject = [[message valueForKey: @"envelope"] subject];
  subject = [baseSubject decodedHeader];
  if (![subject length])
    subject = @"";

  return [[subject safeString] stringByEscapingHTMLString];
}

- (BOOL) showToAddress 
{
  SOGoMailFolder *co;

  if (!folderType)
    {
      co = [self clientObject];
      if ([co isKindOfClass: [SOGoSentFolder class]]
	  || [co isKindOfClass: [SOGoDraftsFolder class]])
	folderType = 1;
      else
	folderType = -1;
    }

  return (folderType == 1);
}

/* title */

- (NSString *) objectTitle 
{
  return [[self clientObject] nameInContainer];
}

- (NSString *) panelTitle 
{
  NSString *s;
  
  s = [self labelForKey:@"View Mail Folder"];
  s = [s stringByAppendingString:@": "];
  s = [s stringByAppendingString:[self objectTitle]];
  return s;
}

/* derived accessors */

- (BOOL) isMessageDeleted
{
  NSArray *flags;
  
  flags = [[self message] valueForKey:@"flags"];
  return [flags containsObject:@"deleted"];
}

- (BOOL) isMessageRead
{
  NSArray *flags;
  
  flags = [[self message] valueForKey:@"flags"];
  return [flags containsObject:@"seen"];
}

- (BOOL) isMessageFlagged
{
  NSArray *flags;
  
  flags = [[self message] valueForKey:@"flags"];
  return [flags containsObject:@"flagged"];
}

- (NSString *) messageUidString 
{
  return [[[self message] valueForKey:@"uid"] stringValue];
}

- (NSString *) messageRowStyleClass 
{
  NSArray *flags;
  NSString *cellClass = @"";

  flags = [[self message] valueForKey:@"flags"];

  if ([self isMessageDeleted])
    cellClass = [cellClass stringByAppendingString: @"mailer_listcell_deleted "];

  if (![self isMessageRead])
    cellClass = [cellClass stringByAppendingString: @"mailer_unreadmail "];
  
  if ([flags containsObject: @"answered"])
    {
      if ([flags containsObject: @"$forwarded"])
	cellClass = [cellClass stringByAppendingString: @"mailer_forwardedrepliedmailsubject"];
      else
	cellClass = [cellClass stringByAppendingString: @"mailer_repliedmailsubject"];
    }
  else if ([flags containsObject: @"$forwarded"])
    cellClass = [cellClass stringByAppendingString: @"mailer_forwardedmailsubject"];
  else
    cellClass = [cellClass stringByAppendingString: @"mailer_readmailsubject"];

  return cellClass;
}

- (BOOL) hasMessageAttachment 
{
  NSArray *parts;
  NSEnumerator *dispositions;
  NSDictionary *currentDisp;
  BOOL hasAttachment;

  hasAttachment = NO;

  parts = [[message objectForKey: @"bodystructure"] objectForKey: @"parts"];
  if ([parts count] > 1)
    {
      dispositions = [[parts objectsForKey: @"disposition"
			     notFoundMarker: nil] objectEnumerator];
      while (!hasAttachment
	     && (currentDisp = [dispositions nextObject]))
	hasAttachment = ([[currentDisp objectForKey: @"type"] length]);
    }

  return hasAttachment;
}

/* fetching messages */

- (NSArray *) fetchKeys 
{
  /* Note: see SOGoMailManager.m for allowed IMAP4 keys */
  static NSArray *keys = nil;

  if (!keys)
    keys = [[NSArray alloc] initWithObjects: @"UID",
    			    @"FLAGS", @"ENVELOPE", @"RFC822.SIZE",
    			    @"BODYSTRUCTURE", @"BODY.PEEK[HEADER.FIELDS (X-PRIORITY)]", nil];
  return keys;
}

- (NSString *) defaultSortKey
{
  return @"ARRIVAL";
}

- (NSString *) imap4SortOrdering 
{
  WORequest *request;
  NSString *sort, *module;
  NSMutableDictionary *moduleSettings;
  NSDictionary *urlParams, *sortingAttributes;
  SOGoUser *activeUser;
  SOGoUserSettings *us;
  BOOL asc;

  request = [context request];
  urlParams = [[request contentAsString] objectFromJSONString];
  sortingAttributes = [urlParams objectForKey:@"sortingAttributes"];
  sort = [[sortingAttributes objectForKey:@"sort"] uppercaseString];
  asc = [[sortingAttributes objectForKey:@"asc"] boolValue];

  activeUser = [context activeUser];
  module = @"Mail";
  us = [activeUser userSettings];
  moduleSettings = [us objectForKey: module];

  if ([sort length])
    {
      if ([sort isEqualToString: [self defaultSortKey]] && !asc)
	{
	  if (moduleSettings)
	    {
	      [moduleSettings removeObjectForKey: @"SortingState"];
	      [us synchronize];
	    }
	}
      else
	{
	  // Save the sorting state in the user settings
	  if (!moduleSettings)
	    {
	      moduleSettings = [NSMutableDictionary dictionary];
	      [us setObject: moduleSettings forKey: module];
	    }
	  [moduleSettings setObject: [NSArray arrayWithObjects: [sort lowercaseString], [NSString stringWithFormat: @"%d", (asc?1:0)], nil]
			     forKey: @"SortingState"];
	  [us synchronize];
	}
    }
  else if (moduleSettings)
    {
      NSArray *sortState = [moduleSettings objectForKey: @"SortingState"];
      if ([sortState count])
	{
	  sort = [[sortState objectAtIndex: 0] uppercaseString];
	  asc = [[sortState objectAtIndex: 1] boolValue];
	}
    }
  if (![sort length])
    sort = [self defaultSortKey];
  
  // Construct and return the final IMAP ordering constraint
  if (!asc)
    sort = [@"REVERSE " stringByAppendingString: sort];

  return sort;
}

- (EOQualifier *) searchQualifier
{
  EOQualifier *qualifier, *searchQualifier;
  WORequest *request;
  NSDictionary *sortingAttributes, *content;
  NSArray *filters;
  NSString *searchBy, *searchArgument, *searchInput, *searchString, *match;
  NSMutableArray *searchArray;
  int nbFilters, i;
  
  request = [context request];
  content = [[request contentAsString] objectFromJSONString];
  qualifier = nil;
  searchString = nil;
  match = nil;
  filters = [content objectForKey: @"filters"];

  if (filters)
    {
      nbFilters = [filters count];
      if (nbFilters > 0) {
        searchArray = [NSMutableArray arrayWithCapacity: nbFilters];
        sortingAttributes = [content objectForKey: @"sortingAttributes"];
        if (sortingAttributes)
          match = [sortingAttributes objectForKey :@"match"]; // AND, OR
        for (i = 0; i < nbFilters; i++)
          {
            searchBy = [NSString stringWithString: [[filters objectAtIndex:i] objectForKey: @"searchBy"]];
            searchArgument = [NSString stringWithString: [[filters objectAtIndex:i] objectForKey: @"searchArgument"]];
            searchInput = [NSString stringWithString: [[filters objectAtIndex:i] objectForKey: @"searchInput"]];
        
            if ([[[filters objectAtIndex:i] objectForKey: @"negative"] boolValue])
              searchString = [NSString stringWithFormat: @"(not (%@ %@: '%@'))", searchBy, searchArgument, searchInput];
            else
              searchString = [NSString stringWithFormat: @"(%@ %@: '%@')", searchBy, searchArgument, searchInput];
        
            searchQualifier = [EOQualifier qualifierWithQualifierFormat: searchString];
            [searchArray addObject: searchQualifier];
          }
        if ([match isEqualToString: @"OR"])
          qualifier = [[EOOrQualifier alloc] initWithQualifierArray: searchArray];
        else
          qualifier = [[EOAndQualifier alloc] initWithQualifierArray: searchArray];
      }
    }
    
  return qualifier;
}

- (NSArray *) getSortedUIDsInFolder: (SOGoMailFolder *) mailFolder
{
  EOQualifier *qualifier, *fetchQualifier, *notDeleted;

  if (!sortedUIDs)
    {
      notDeleted = [EOQualifier qualifierWithQualifierFormat: @"(not (flags = %@))", @"deleted"];
      qualifier = [self searchQualifier];
      if (qualifier)
        {
          fetchQualifier = [[EOAndQualifier alloc] initWithQualifiers: notDeleted, qualifier, nil];
          [fetchQualifier autorelease];
        }
      else
        fetchQualifier = notDeleted;
    
      sortedUIDs = [mailFolder fetchUIDsMatchingQualifier: fetchQualifier
                                             sortOrdering: [self imap4SortOrdering]
                                                 threaded: sortByThread];
    
      [sortedUIDs retain];
    }

  return sortedUIDs;
}

/**
 * Returns a 
 of the messages threads as triples of
 * metadata, including the message UID, thread level and root position.
 * @param _sortedUIDs the interleaved arrays representation of the messages UIDs
 * @return an flatten array representation of the messages UIDs
 */
- (NSArray *) threadedUIDs: (NSArray *) _sortedUIDs
{
  NSMutableArray *threads;
  NSMutableArray *currentThreads;
  NSEnumerator *rootThreads;
  id thread;
  int count;
  int i;
  BOOL first;
  BOOL expected;
  int previousLevel;

  count = 0;
  i = 0;
  previousLevel = 0;
  expected = YES;
  threads = [NSMutableArray arrayWithObject: [NSArray arrayWithObjects: @"uid", @"level", @"first", nil]];
  rootThreads  = [_sortedUIDs objectEnumerator];
  thread = [rootThreads nextObject];

  // Make sure rootThreads starts with an NSArray
  if (![thread respondsToSelector: @selector(objectEnumerator)])
    return nil;

  first = [thread count] > 1;
  thread = [thread objectEnumerator];

  currentThreads = [NSMutableArray array];

  while (thread)
    {
      unsigned int ecount = 0;
      id t;

      if ([thread isKindOfClass: [NSEnumerator class]])
        {
          t = [thread nextObject];
        }
      else
        t = thread; // never happen?
      while (t && ![t isKindOfClass: [NSArray class]])
        {
          BOOL currentFirst;
          int currentLevel;
          NSArray *currentThread;

          currentFirst = (first && ecount == 0) || (i == 0  && count > 0) || (count > 0 && previousLevel < 0);
          currentLevel = (first && ecount == 0)? 0 : (count > 0? count : -1);
          currentThread = [NSArray arrayWithObjects: t,
                            [NSNumber numberWithInt: currentLevel],
                            [NSNumber numberWithInt: currentFirst], nil];
          [threads addObject: currentThread];
          i++;
          count++;
          ecount++;
          expected = NO;
          previousLevel = currentLevel;
          t = [thread nextObject];
        }
      if (t)
        {
          // If t is defined, it has to be an NSArray
          if (expected)
            {
              count++;
              expected = NO;
            }
          thread = [thread allObjects];
          if ([thread count] > 0)
            [currentThreads addObject: [thread objectEnumerator]];
          thread = [t objectEnumerator];
        }
      else if ([currentThreads count] > 0)
        {
          thread = [currentThreads objectAtIndex: 0];
          [currentThreads removeObjectAtIndex: 0];
          count -= ecount;
        }
      else
        {
          thread = [[rootThreads nextObject] objectEnumerator]; // assume all objects of rootThreads are NSArrays
          count = 0;
          expected = YES;
        }

      // Prepare next iteration
      thread = [thread allObjects];
      first = !first && (thread != nil) && [thread count] > 1;
      thread = [thread objectEnumerator];
    }

  return threads;
}

- (int) indexOfMessageUID: (int) messageNbr
{
  NSArray *messageNbrs;
  int index;

  messageNbrs = [self getSortedUIDsInFolder: [self clientObject]];
  index
    = [messageNbrs indexOfObject: [NSNumber numberWithInt: messageNbr]];
//   if (index < 0)
//     index = 0;

  return index;
}

/* JavaScript */

- (NSString *) msgRowID
{
  return [@"row_" stringByAppendingString:[self messageUidString]];
}

- (NSString *) msgIconReadImgID
{
  return [@"readdiv_" stringByAppendingString:[self messageUidString]];
}

- (NSString *) msgIconUnreadImgID
{
  return [@"unreaddiv_" stringByAppendingString:[self messageUidString]];
}

/* error redirects */

/*
- (id) redirectToViewWithError: (id) _error 
{
  // TODO: DUP in UIxMailAccountView
  // TODO: improve, localize
  // TODO: there is a bug in the treeview which preserves the current URL for
  //       the active object (displaying the error again)
  id url;
  
  if (![_error isNotNull])
    return [self redirectToLocation:@"view"];
  
  if ([_error isKindOfClass:[NSException class]])
    _error = [_error reason];
  else if ([_error isKindOfClass:[NSString class]])
    _error = [_error stringValue];
  
  url = [_error stringByEscapingURL];
  url = [@"view?error=" stringByAppendingString:url];
  return [self redirectToLocation:url];
}
*/

- (NSDictionary *) getUIDsInFolder: (SOGoMailFolder *) folder
                       withHeaders: (BOOL) includeHeaders
{
  NSMutableDictionary *data;
  NSArray *uids, *threadedUids, *headers;
  NSRange r;
  SOGoMailAccount *account;
  id quota;
  int count;

  data = [NSMutableDictionary dictionary];
  
  // TODO: we might want to flush the caches?
  //[folder flushMailCaches];
  [folder expungeLastMarkedFolder];

  // Retrieve messages UIDs using form parameters "sort" and "asc"
  uids = [self getSortedUIDsInFolder: folder];
  
  // Get rid of the extra parenthesis
   // uids = [[[[uids stringValue] stringByReplacingOccurrencesOfString:@"(" withString:@""] stringByReplacingOccurrencesOfString:@")" withString:@""] componentsSeparatedByString:@","];

  if (includeHeaders)
    {
      // Also retrieve the first headers, up to 'headersPrefetchMaxSize'
      count = [[uids flattenedArray] count];
      if (count > headersPrefetchMaxSize) count = headersPrefetchMaxSize;
      r = NSMakeRange(0, count);
      headers = [self getHeadersForUIDs: [[uids flattenedArray] subarrayWithRange: r]
                               inFolder: folder];

      [data setObject: headers forKey: @"headers"];
    }

  if (sortByThread)
    {
      // Add threads information
      threadedUids = [self threadedUIDs: uids];
      if (threadedUids != nil)
        uids = threadedUids;
      else
        sortByThread = NO;
    }
  if (uids != nil)
    [data setObject: uids forKey: @"uids"];
  [data setObject: [NSNumber numberWithBool: sortByThread] forKey: @"threaded"];

  // We also return the inbox quota
  account = [folder mailAccountFolder];
  quota = [account getInboxQuota];
  if (quota != nil)
    [data setObject: quota forKey: @"quotas"];

  return data;
}

/* Module actions */

- (id <WOActionResults>) getUIDsAction
{
  NSDictionary *data, *requestContent;
  NSString *noHeaders;
  SOGoMailFolder *folder;
  WORequest *request;
  WOResponse *response;

  request = [context request];
  response = [context response];
  requestContent = [[request contentAsString] objectFromJSONString];
  
  [response setHeader: @"text/plain; charset=utf-8"
                      forKey: @"content-type"];

  folder = [self clientObject];
  
  noHeaders = [[requestContent objectForKey: @"sortingAttributes"] objectForKey:@"no_headers"];
  data = [self getUIDsInFolder: folder
                   withHeaders: ([noHeaders length] == 0)];

  [response appendContentString: [data jsonRepresentation]];

  return response;
}

- (NSArray *) getHeadersForUIDs: (NSArray *) uids
		       inFolder: (SOGoMailFolder *) mailFolder
{
  NSArray *to, *from;
  NSDictionary *msgs;
  NSMutableArray *headers, *msg;
  NSEnumerator *msgsList;
  NSString *msgIconStatus, *msgDate;
  UIxEnvelopeAddressFormatter *addressFormatter;
  
  headers = [NSMutableArray arrayWithCapacity: [uids count]];
  addressFormatter = [context mailEnvelopeAddressFormatter];
  
  // Fetch headers
  msgs = (NSDictionary *)[mailFolder fetchUIDs: uids
					 parts: [self fetchKeys]];

  msgsList = [[msgs objectForKey: @"fetch"] objectEnumerator];
  [self setMessage: [msgsList nextObject]];

  msg = [NSMutableArray arrayWithObjects: @"To", @"Attachment", @"Flagged", @"Subject", @"From", @"Unread", @"Priority", @"Date", @"Size", @"rowClasses", @"labels", @"rowID", @"uid", nil];
  [headers addObject: msg];
  while (message)
    {
      // We must check for "umimportant" untagged responses.
      //
      // It's generally caused by IMAP server processes sending untagged IMAP responses to SOGo in differnent IMAP
      // connections (SOGo might use 2-3 per user). Say you ask your messages:
      //
      // 127.000.000.001.40725-127.000.000.001.00143: 59 uid fetch 62 (UID FLAGS ENVELOPE RFC822.SIZE BODYSTRUCTURE BODY.PEEK[HEADER.FIELDS (X-PRIORITY)])
      // 127.000.000.001.00143-127.000.000.001.40725: * 62 FETCH (UID 62 FLAGS (\Seen) RFC822.SIZE 854 ENVELOPE  .... (
      // * 61 FETCH (FLAGS (\Deleted \Seen))
      // * 62 FETCH (FLAGS (\Deleted \Seen))
      // * 63 FETCH (FLAGS (\Deleted \Seen))
      // 59 OK Fetch completed.
      //
      // We must ignore the * 61 .. * 63 untagged responses.
      //
      if (![message objectForKey: @"uid"])
	{
	  [self setMessage: [msgsList nextObject]];
	  continue;
	}

      msg = [NSMutableArray arrayWithCapacity: 12];

      // Columns data

      // To
      to = [[message objectForKey: @"envelope"] to];
      if ([to count] > 0)
	[msg addObject: [[addressFormatter stringForArray: to] stringByEscapingHTMLString]];
      else
	[msg addObject: @""];

      // Attachment
      if ([self hasMessageAttachment])
	[msg addObject: [NSString stringWithFormat: @"<img src=\"%@\"/>", [self urlForResourceFilename: @"title_attachment_14x14.png"]]];
      else
	[msg addObject: @""];

      // Flagged
      if ([self isMessageFlagged])
	[msg addObject: [NSString stringWithFormat: @"<img src=\"%@\" class=\"messageIsFlagged\">",
				  [self urlForResourceFilename: @"flag.png"]]];
      else
	[msg addObject: [NSString stringWithFormat: @"<img src=\"%@\">",
				  [self urlForResourceFilename: @"dot.png"]]];

      // Subject
      [msg addObject: [NSString stringWithFormat: @"<span>%@</span>",
				[self messageSubject]]];
      
      // From
      from = [[message objectForKey: @"envelope"] from];
      if ([from count] > 0)
	[msg addObject: [[addressFormatter stringForArray: from] stringByEscapingHTMLString]];
      else
	[msg addObject: @""];
      

      // Unread
      if ([self isMessageRead])
	msgIconStatus = @"dot.png";
      else
	msgIconStatus = @"unread.png";
      
      [msg addObject: [NSString stringWithFormat: @"<img src=\"%@\" class=\"mailerReadIcon\" title=\"%@\" title-markread=\"%@\" title-markunread=\"%@\" id=\"%@\"/>",
				[self urlForResourceFilename: msgIconStatus],
 			       [self labelForKey: @"Mark Unread"],
 			       [self labelForKey: @"Mark Read"],
 			       [self labelForKey: @"Mark Unread"],
 				[self msgIconReadImgID]]];
      
      // Priority
      [msg addObject: [self messagePriority]];

      // Date
      msgDate = [self messageDate];
      if (msgDate == nil)
	msgDate = @"";
      [msg addObject: msgDate];

      // Size
      [msg addObject: [[self sizeFormatter] stringForObjectValue: [message objectForKey: @"size"]]];
      
      // rowClasses
      [msg addObject: [self messageRowStyleClass]];

      // labels
      [msg addObject: [self msgLabels]];

      // rowID
      [msg addObject: [self msgRowID]];

      // uid
      [msg addObject: [message objectForKey: @"uid"]];
      [headers addObject: msg];
      
      [self setMessage: [msgsList nextObject]];
    }

  return headers;
}

- (id <WOActionResults>) getHeadersAction
{
  NSArray *uids, *headers;
  WORequest *request;
  WOResponse *response;

  request = [context request];
  if ([request formValueForKey: @"uids"] == nil)
    {
      return [NSException exceptionWithHTTPStatus: 404
					   reason: @"No UID specified"];
    }

  uids = [[request formValueForKey: @"uids"] componentsSeparatedByString: @","]; // Should we support ranges? ie "x-y"
  headers = [self getHeadersForUIDs: uids
			   inFolder: [self clientObject]];
  response = [context response];
  [response setHeader: @"text/plain; charset=utf-8"
	    forKey: @"content-type"];
  [response appendContentString: [headers jsonRepresentation]];

  return response;
}

- (NSString *) msgLabels
{
  NSMutableArray *labels;
  NSEnumerator *flags;
  NSString *currentFlag;

  labels = [NSMutableArray array];

  flags = [[message objectForKey: @"flags"] objectEnumerator];
  while ((currentFlag = [flags nextObject]))
    {
      [labels addObject: currentFlag];
    }
  
  return [labels componentsJoinedByString: @" "];
}

@end

/* UIxMailListActions */