File: CWLocalStore.m

package info (click to toggle)
pantomime 1.4.0%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 2,288 kB
  • sloc: objc: 22,039; makefile: 11; sh: 4
file content (915 lines) | stat: -rw-r--r-- 27,372 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
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
/*
**  CWLocalStore.m
**
**  Copyright (c) 2001-2007 Ludovic Marcotte
**  Copyright (c) 2017-2020 Riccardo Mottola
**
**  Author: Ludovic Marcotte <ludovic@Sophos.ca>
**          Riccardo Mottola <rm@gnu.org>
**
**  This library 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.1 of the License, or (at your option) any later version.
**  
**  This library 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 General Public License
** along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#import <Pantomime/CWLocalStore.h>

#import <Pantomime/CWConstants.h>
#import <Pantomime/CWLocalCacheManager.h>
#import <Pantomime/CWLocalFolder.h>
#import <Pantomime/CWLocalFolder+mbox.h>
#import <Pantomime/CWLocalMessage.h>
#import <Pantomime/NSFileManager+Extensions.h>
#import <Pantomime/NSString+Extensions.h>
#import <Pantomime/CWURLName.h>

#import <Foundation/NSAutoreleasePool.h>
#import <Foundation/NSHost.h>
#import <Foundation/NSNotification.h>
#import <Foundation/NSPathUtilities.h>
#import <Foundation/NSValue.h>

#include <sys/types.h>
#include <time.h>
#include <unistd.h>
#include <stdlib.h> // rand()

//
// Private interface
//
@interface CWLocalStore (Private)
- (NSEnumerator *) _rebuildFolderEnumerator;
@end

//
//
//
@implementation CWLocalStore

- (void) dealloc
{
  RELEASE(_path);
  RELEASE(_openFolders);
  RELEASE(_folders);
  
  [super dealloc];
}

//
//
//
- (id) initWithPath: (NSString *) thePath
{
  self = [super init];
  if (self)
    {
      BOOL isDirectory;

      [self setPath: thePath];
  
      _openFolders = [[NSMutableDictionary alloc] init];
      _folders = [[NSMutableArray alloc] init];
      _secure = YES;

      if ([[NSFileManager defaultManager] fileExistsAtPath: thePath  isDirectory: &isDirectory])
	{
	  if (!isDirectory)
	    {
	      AUTORELEASE(self);
	      return nil;
	    }
	}
      else
	{
	  AUTORELEASE(self);
	  return nil;
	}
    }
  return self;
}

//
//
//
- (id) initWithURL: (CWURLName *) theURL
{
  return [self initWithPath: [theURL path]];
}

//
// This method will open automatically Inbox (case-insensitive).
// It may return nil if the opening failed or Inbox wasn't found.
//
- (id) defaultFolder
{
  return [self folderForName: @"Inbox"];
}

//
// This method is used to open the folder theName in the current
// directory of this local store.
//
- (id) folderForName: (NSString *) theName
{
  CWLocalFolder *cachedFolder;

  if (!theName) return nil;

  cachedFolder = [_openFolders objectForKey: theName];
  
  if (!cachedFolder)
    {
      NSEnumerator *anEnumerator;
      NSString *aString;
      
      anEnumerator = [self folderEnumerator];

      while ((aString = [anEnumerator nextObject]))
	{
	  if ([aString compare: theName] == NSOrderedSame)
	    {
	      CWLocalFolder *aFolder;

	      aFolder = [[CWLocalFolder alloc] initWithPath: [NSString stringWithFormat:@"%@/%@", _path, aString]];
	      
	      if (aFolder)
		{
		  [aFolder setStore: self];
		  [aFolder setName: theName];

		  // We now cache it and return it
		  [_openFolders setObject: aFolder  forKey: theName];

		  POST_NOTIFICATION(PantomimeFolderOpenCompleted, self, [NSDictionary dictionaryWithObject: aFolder  forKey: @"Folder"]);
		  PERFORM_SELECTOR_2(self, @selector(folderOpenCompleted:), PantomimeFolderOpenCompleted, aFolder, @"Folder");
                  
                  // tell the cache manager to read all messages
                  if (![aFolder cacheManager])
                    {
                      [aFolder setCacheManager: [[[CWLocalCacheManager alloc] initWithPath: [NSString stringWithFormat: @"%@.%@.cache", [[aFolder path] substringToIndex: ([[aFolder path] length] - [[[aFolder path] lastPathComponent] length])], [[aFolder path] lastPathComponent]]  folder: aFolder] autorelease]];
                      [(CWLocalCacheManager *)[aFolder cacheManager] readAllMessages];
                      [aFolder parse: NO];
                    }
		  RELEASE(aFolder);
		}
	      else
		{
		  POST_NOTIFICATION(PantomimeFolderOpenFailed, self, [NSDictionary dictionaryWithObject: theName  forKey: @"FolderName"]);
		  PERFORM_SELECTOR_2(self, @selector(folderOpenFailed:), PantomimeFolderOpenFailed, theName, @"FolderName");
		}

	      return aFolder;
	    }
	}
      
      return nil;
    }

  //NSLog(@"Returning cached folder!");
  return cachedFolder;
}

//
//
//
- (id) folderForURL: (NSString *) theURL;
{
  CWURLName *theURLName;
  id aFolder;

  theURLName = [[CWURLName alloc] initWithString: theURL];

  aFolder = [self folderForName: [theURLName foldername]];

  RELEASE(theURLName);
  
  return aFolder;
}

//
// This method returns the list of folders contained in 
// a specific directory. It'll currently ignore some things
// like Netscape Mail's summary files and Pantomime's local
// cache files.
//
- (NSEnumerator *) folderEnumerator
{
  if ([_folders count] > 0)
    {
      POST_NOTIFICATION(PantomimeFolderListCompleted, self, [NSDictionary dictionaryWithObject: [_folders objectEnumerator] forKey: @"NSEnumerator"]);
      PERFORM_SELECTOR_2(self, @selector(folderListCompleted:), PantomimeFolderListCompleted, [_folders objectEnumerator], @"NSEnumerator");
      return [_folders objectEnumerator];
    }

  return [self _rebuildFolderEnumerator];
}


//
//
//
- (NSEnumerator *) subscribedFolderEnumerator
{
  return [self folderEnumerator];
}


//
//
//
- (id) delegate
{
  return _delegate;
}

- (void) setDelegate: (id) theDelegate
{
  _delegate = theDelegate;
}

//
//
//
- (NSString *) path
{
  return _path;
}

//
//
//
- (void) setPath: (NSString *) thePath
{
  ASSIGN(_path, thePath);
}

//
//
//
- (void) setEnforceMode: (BOOL) theBOOL;
{
  _secure = theBOOL;
}

//
//
//
- (BOOL) isEnforcingMode
{
  return _secure;
}

//
//
//
- (void) close
{
  NSEnumerator *anEnumerator;
  CWLocalFolder *aFolder;

  anEnumerator = [self openFoldersEnumerator];
  
  while ((aFolder = [anEnumerator nextObject]))
    {
      [aFolder close];
    }
}


//
//
//
- (NSEnumerator *) openFoldersEnumerator
{
  return [_openFolders objectEnumerator];
}


//
//
//
- (void) removeFolderFromOpenFolders: (CWFolder *) theFolder
{
  [_openFolders removeObjectForKey: [(CWLocalFolder *)theFolder name]];
}


//
//
//
- (BOOL) folderForNameIsOpen: (NSString *) theName
{
  NSEnumerator *anEnumerator;
  CWLocalFolder *aFolder;
  
  anEnumerator = [self openFoldersEnumerator];

  while ((aFolder = [anEnumerator nextObject]))
    {
      if ([[aFolder name] compare: theName] == NSOrderedSame)
	{
	  return YES;
	}
    }

  return NO;
}


//
//
//
- (PantomimeFolderType) folderTypeForFolderName: (NSString *) theName
{
  NSString *aString;
  BOOL isDir;

  aString = [NSString stringWithFormat: @"%@/%@", _path, theName];
  
  [[NSFileManager defaultManager] fileExistsAtPath: aString
				  isDirectory: &isDir];
  
  if (isDir)
    {
      // This could be a maildir store. Check for maildir specific subfolders.
      aString = [NSString stringWithFormat: @"%@/%@/cur", _path, theName];
      
      if ( [[NSFileManager defaultManager] fileExistsAtPath: aString
					   isDirectory: &isDir] && isDir )
	{
	  return PantomimeHoldsMessages;
	}
      else
	{
	  return PantomimeHoldsFolders;
	}
    }

  return PantomimeHoldsMessages;
}


//
//
//
- (unichar) folderSeparator
{
  return '/';
}


//
//
//
- (void) createFolderWithName: (NSString *) theName 
			 type: (PantomimeFolderFormat) theType
		     contents: (NSData *) theContents
{
  NSString *aName, *pathToFile;
  NSFileManager *aFileManager;
  NSEnumerator *anEnumerator;
  BOOL b, is_dir;
  NSUInteger count;

  aFileManager = [NSFileManager defaultManager];
  anEnumerator = [self folderEnumerator];
  count = 0;

  pathToFile = [NSString stringWithFormat: @"%@/%@", _path, theName];
  pathToFile = [pathToFile substringToIndex: ([pathToFile length]-[[pathToFile lastPathComponent] length]-1)];
 

  // We verify if the folder with that name does already exist
  while ((aName = [anEnumerator nextObject]))
    {
      if ([aName compare: theName  options: NSCaseInsensitiveSearch] == NSOrderedSame)
	{
	  POST_NOTIFICATION(PantomimeFolderCreateFailed, self, [NSDictionary dictionaryWithObject: theName  forKey: @"Name"]);
	  PERFORM_SELECTOR_2(self, @selector(folderCreateFailed:), PantomimeFolderCreateFailed, theName, @"Name");
	  return;
	}
    }
  
  // Ok, the folder doesn't already exist.
  // Check if we want to create a simple folder/directory.
  if (theType == PantomimeFormatFolder)
    {
      NSString *aString;

      aString = [NSString stringWithFormat: @"%@/%@", _path, theName];
      b = [aFileManager createDirectoryAtPath: aString  attributes: nil];
      
      if (b)
	{
	  NSDictionary *info;
	  
	  if (_secure) [[NSFileManager defaultManager] enforceMode: 0700  atPath: aString];
	  [self _rebuildFolderEnumerator];

	  info = [NSDictionary dictionaryWithObjectsAndKeys: theName, @"Name", [NSNumber numberWithUnsignedInt: 0], @"Count", nil];
	  POST_NOTIFICATION(PantomimeFolderCreateCompleted, self, info);
	  PERFORM_SELECTOR_3(self, @selector(folderCreateCompleted:), PantomimeFolderCreateCompleted, info);
	}
      else
	{
	  POST_NOTIFICATION(PantomimeFolderCreateFailed, self, [NSDictionary dictionaryWithObject: theName  forKey: @"Name"]);
	  PERFORM_SELECTOR_2(self, @selector(folderCreateFailed:), PantomimeFolderCreateFailed, theName, @"Name");
	}
      
      return;
    }
  
  b = NO;

  // We want to create a mailbox store; check if it already exists.
  if ([aFileManager fileExistsAtPath: pathToFile  isDirectory: &is_dir])
    {
      int size;
      
      size = [[[aFileManager fileAttributesAtPath: pathToFile traverseLink: NO] objectForKey: NSFileSize] intValue];
      
      // If we got an empty file or simply a directory...
      if (size == 0 || is_dir)
	{
	  NSString *aString;
	  
	  // If the size is 0, that means we have an empty file. We first convert this
	  // file to a directory. We also remove the cache file.
	  if (size == 0)
	    {
	      [aFileManager removeFileAtPath:
			      [NSString stringWithFormat: @"%@/.%@.cache",
					[pathToFile substringToIndex: ([pathToFile length]-[[pathToFile lastPathComponent] length]-1)],
					[pathToFile lastPathComponent]]  handler: nil];
	      [aFileManager removeFileAtPath: pathToFile  handler: nil];
	      [aFileManager createDirectoryAtPath: pathToFile  attributes: nil];
	    }
	  
	  // We can now proceed with the creation of our store.
	  // Check the type of store we want to create
	  switch (theType)
	    {
	    case PantomimeFormatMaildir:
	      // Create the main maildir directory
	      aString = [NSString stringWithFormat: @"%@/%@", _path, theName];  
	      b = [aFileManager createDirectoryAtPath: aString  attributes: nil];
	      if (_secure) [[NSFileManager defaultManager] enforceMode: 0700  atPath: aString];
								    
	      // Now create the cur, new, and tmp sub-directories.
	      aString = [NSString stringWithFormat: @"%@/%@/cur", _path, theName];
	      b = b & [aFileManager createDirectoryAtPath: aString  attributes: nil];
	      if (_secure) [[NSFileManager defaultManager] enforceMode: 0700  atPath: aString];
	      
	      // new
	      aString = [NSString stringWithFormat: @"%@/%@/new", _path, theName];
	      b = b & [aFileManager createDirectoryAtPath: aString  attributes: nil];
	      if (_secure) [[NSFileManager defaultManager] enforceMode: 0700  atPath: aString];

	      // tmp
	      aString = [NSString stringWithFormat: @"%@/%@/tmp", _path, theName];
	      b = b & [aFileManager createDirectoryAtPath: aString  attributes: nil];
	      if (_secure) [[NSFileManager defaultManager] enforceMode: 0700  atPath: aString];
	      
	      // We create our fist message
	      if (theContents)
		{
		  aString = [NSString stringWithFormat: @"%@/%@/cur/%@:2,",
				_path,
				theName,
				[NSString stringWithFormat: @"%lld.%d%d.%@",
						(long long)time(NULL),
						getpid(),
						rand(),
						[[NSHost currentHost] name]]];
		  [theContents writeToFile: aString  atomically: YES];
		}
	      break;
	      
	    case PantomimeFormatMbox:
	    default:
	      b = [aFileManager createFileAtPath: [NSString stringWithFormat: @"%@/%@", _path, theName]
				contents: theContents
				attributes: nil];
	      
	      count = [CWLocalFolder numberOfMessagesFromData: theContents];
	      
	      // We now enforce the mode (0600) on this new mailbox
	      if (_secure) [[NSFileManager defaultManager] enforceMode: 0600
							   atPath: [NSString stringWithFormat: @"%@/%@", _path, theName]];
	      break;				  
	    }
	  
	  // rebuild the folder list
	  [self _rebuildFolderEnumerator];
	}
      else
	{
	  b = NO;
	}
    }
  
  if (b)
    {
      NSDictionary *info;

      info = [NSDictionary dictionaryWithObjectsAndKeys: theName, @"Name", [NSNumber numberWithUnsignedInt: (unsigned int)count], @"Count", nil];
      POST_NOTIFICATION(PantomimeFolderCreateCompleted, self, info);
      PERFORM_SELECTOR_3(self, @selector(folderCreateCompleted:), PantomimeFolderCreateCompleted, info);
    }
  else
    {
      POST_NOTIFICATION(PantomimeFolderCreateFailed, self, [NSDictionary dictionaryWithObject: theName  forKey: @"Name"]);
      PERFORM_SELECTOR_2(self, @selector(folderCreateFailed:), PantomimeFolderCreateFailed, theName, @"Name");
    }
}


//
// theName must be the full path of the mailbox.
//
- (void) deleteFolderWithName: (NSString *) theName
{
  NSFileManager *aFileManager;
  BOOL aBOOL, is_dir;
  
  aFileManager = [NSFileManager defaultManager];
  aBOOL = NO;

  if ([aFileManager fileExistsAtPath: [NSString stringWithFormat: @"%@/%@", _path, theName]
		    isDirectory: &is_dir])
    {
      if (is_dir)
	{
	  NSEnumerator *theEnumerator;
	  NSArray *theEntries;
	  
	  theEnumerator = [aFileManager enumeratorAtPath: [NSString stringWithFormat: @"%@/%@",
								    _path, theName]];
	  
	  // FIXME - Verify the Store's path.
	  // If it doesn't contain any mailboxes and it's actually not or Store's path, we remove it.
	  theEntries = [theEnumerator allObjects];
	  if ([theEntries count] == 0)
	    {
	      aBOOL = [aFileManager removeFileAtPath: [NSString stringWithFormat: @"%@/%@",
								_path, theName]
				    handler: nil];
	      
	      // Rebuild the folder tree
	      if (aBOOL)
		{
		  [self _rebuildFolderEnumerator];
		  POST_NOTIFICATION(PantomimeFolderDeleteCompleted, self, [NSDictionary dictionaryWithObject: theName  forKey: @"Name"]);
		  PERFORM_SELECTOR_1(self, @selector(folderDeleteCompleted:), PantomimeFolderDeleteCompleted);
		}
	      else
		{
		  POST_NOTIFICATION(PantomimeFolderDeleteFailed, self, [NSDictionary dictionaryWithObject: theName  forKey: @"Name"]);
		  PERFORM_SELECTOR_1(self, @selector(folderDeleteFailed:), PantomimeFolderDeleteFailed);
		}

	      return;
	    }
	  // We could also be trying to delete a maildir mailbox which
	  // has a directory structure with 3 sub-directories: cur, new, tmp
	  else if ([aFileManager fileExistsAtPath: [NSString stringWithFormat: @"%@/%@/cur", _path, theName]
				 isDirectory: &is_dir])
	    {
	      // Make sure that these are the maildir directories and not something else.
	      if (![aFileManager fileExistsAtPath: [NSString stringWithFormat: @"%@/%@/new", _path, theName]
				 isDirectory: &is_dir])
		{
		  POST_NOTIFICATION(PantomimeFolderDeleteFailed, self, [NSDictionary dictionaryWithObject: theName  forKey: @"Name"]);
		  PERFORM_SELECTOR_1(self, @selector(folderDeleteFailed:), PantomimeFolderDeleteFailed);
		  return;
		}
	      if (![aFileManager fileExistsAtPath: [NSString stringWithFormat: @"%@/%@/tmp", _path, theName]
				 isDirectory: &is_dir] )
		{
		  POST_NOTIFICATION(PantomimeFolderDeleteFailed, self, [NSDictionary dictionaryWithObject: theName  forKey: @"Name"]);
		  PERFORM_SELECTOR_1(self, @selector(folderDeleteFailed:), PantomimeFolderDeleteFailed);
		  return;
		}
	    }
	  else
	    {
	      POST_NOTIFICATION(PantomimeFolderDeleteFailed, self, [NSDictionary dictionaryWithObject: theName  forKey: @"Name"]);
	      PERFORM_SELECTOR_1(self, @selector(folderDeleteFailed:), PantomimeFolderDeleteFailed);
	      return;
	    }
	}

      // We remove the mbox or maildir store
      aBOOL = [aFileManager removeFileAtPath: [NSString stringWithFormat: @"%@/%@",
							_path, theName]
			    handler: nil];
      
      // We remove the cache, if the store deletion was successful
      if (aBOOL)
	{
	  NSString *aString;

	  aString = [theName lastPathComponent];
	  
	  [[NSFileManager defaultManager] removeFileAtPath: [NSString stringWithFormat: @"%@/%@.%@.cache",
								      _path,
								      [theName substringToIndex: ([theName length]-[aString length])],
								      aString]
					  handler: nil];
	}

      // Rebuild the folder tree
      [self _rebuildFolderEnumerator];
    }
  
  if (aBOOL)
    {
      POST_NOTIFICATION(PantomimeFolderDeleteCompleted, self, [NSDictionary dictionaryWithObject: theName  forKey: @"Name"]);
      PERFORM_SELECTOR_1(self, @selector(folderDeleteCompleted:), PantomimeFolderDeleteCompleted);
    }
  else
    {
      POST_NOTIFICATION(PantomimeFolderDeleteFailed, self, [NSDictionary dictionaryWithObject: theName  forKey: @"Name"]);
      PERFORM_SELECTOR_1(self, @selector(folderDeleteFailed:), PantomimeFolderDeleteFailed);
    }
}


//
// theName and theNewName MUST be the full path of those mailboxes.
// If they begin with the folder separator (ie., '/'), the character is
// automatically stripped.
//
// This method supports renaming mailboxes that are open.
//
- (void) renameFolderWithName: (NSString *) theName
                       toName: (NSString *) theNewName
{
  NSFileManager *aFileManager;
  NSDictionary *info;
  BOOL aBOOL, is_dir;
  
  aFileManager = [NSFileManager defaultManager];
  aBOOL = NO;
  
  theName = [theName stringByDeletingFirstPathSeparator: [self folderSeparator]];
  theNewName = [theNewName stringByDeletingFirstPathSeparator: [self folderSeparator]]; 
  info = [NSDictionary dictionaryWithObjectsAndKeys: theName, @"Name", theNewName, @"NewName", nil];

  // We do basic verifications on the passed parameters. We also verify if the destination path exists.
  // If it does, we abort the rename operation since we don't want to overwrite the folder.
  if (!theName || !theNewName || 
      [[theName stringByTrimmingWhiteSpaces] length] == 0 ||
      [[theNewName stringByTrimmingWhiteSpaces] length] == 0 ||
      [aFileManager fileExistsAtPath: [NSString stringWithFormat: @"%@/%@", _path, theNewName]])
    {
      POST_NOTIFICATION(PantomimeFolderRenameFailed, self, info);
      PERFORM_SELECTOR_3(self, @selector(folderRenameFailed:), PantomimeFolderRenameFailed, info);
      return;
    }

  // We verify if the source path is valid
  if ([aFileManager fileExistsAtPath: [NSString stringWithFormat: @"%@/%@", _path, theName]
		    isDirectory: &is_dir])
    {
      CWLocalFolder *aFolder;

      if (is_dir)
	{
	  NSEnumerator *theEnumerator;
	  NSArray *theEntries;
	  
	  theEnumerator = [aFileManager enumeratorAtPath: [NSString stringWithFormat: @"%@/%@",
								    _path, theName]];
	  
	  // FIXME - Verify the Store's path.
	  // If it doesn't contain any mailboxes and it's actually not or Store's path, we rename it.
	  theEntries = [theEnumerator allObjects];
	  
	  if ([theEntries count] == 0)
	    {
	      aBOOL = [aFileManager movePath: [NSString stringWithFormat: @"%@/%@",_path, theName]
				    toPath: [NSString stringWithFormat: @"%@/%@",  _path, theNewName]
				    handler: nil];
	      if (aBOOL)
		{
		  POST_NOTIFICATION(PantomimeFolderRenameCompleted, self, info);
		  PERFORM_SELECTOR_3(self, @selector(folderRenameCompleted:), PantomimeFolderRenameCompleted, info);
		}
	      else
		{
		  POST_NOTIFICATION(PantomimeFolderRenameFailed, self, info);
		  PERFORM_SELECTOR_3(self, @selector(folderRenameFailed:), PantomimeFolderRenameFailed, info);
		}
	    }
	  // We could also be trying to delete a maildir mailbox which
	  // has a directory structure with 3 sub-directories: cur, new, tmp
	  else if ([aFileManager fileExistsAtPath: [NSString stringWithFormat: @"%@/%@/cur", _path, theName]
				 isDirectory: &is_dir])
	    {
	      // Make sure that these are the maildir directories and not something else.
	      if (![aFileManager fileExistsAtPath: [NSString stringWithFormat: @"%@/%@/new", _path, theName]
				 isDirectory: &is_dir])
		{
		  POST_NOTIFICATION(PantomimeFolderRenameFailed, self, info);
		  PERFORM_SELECTOR_3(self, @selector(folderRenameFailed:), PantomimeFolderRenameFailed, info);
		  return;
		}
	      if (![aFileManager fileExistsAtPath: [NSString stringWithFormat: @"%@/%@/tmp", _path, theName]
				 isDirectory: &is_dir])
		{
		  POST_NOTIFICATION(PantomimeFolderRenameFailed, self, info);
		  PERFORM_SELECTOR_3(self, @selector(folderRenameFailed:), PantomimeFolderRenameFailed, info);
		  return;
		}
	  }
	  else
	    {
	      POST_NOTIFICATION(PantomimeFolderRenameFailed, self, info);
	      PERFORM_SELECTOR_3(self, @selector(folderRenameFailed:), PantomimeFolderRenameFailed, info);
	      return;
	    }
	}
      
      // If the mailbox is open, we "close" it first.
      aFolder = [_openFolders objectForKey: theName];

      if (aFolder)
	{
	  if ([aFolder type] == PantomimeFormatMbox)
	    {
	      [aFolder close_mbox];
	    }
	  [[aFolder cacheManager] synchronize];
	}
      

      // We rename the mailbox
      aBOOL = [aFileManager movePath: [NSString stringWithFormat: @"%@/%@", _path, theName]
			    toPath: [NSString stringWithFormat: @"%@/%@", _path, theNewName]
			    handler: nil];
      
      // We rename the cache, if the store rename was successful
      if (aBOOL)
	{
	  NSString *str1, *str2;
	  
	  str1 = [theName lastPathComponent];
	  str2 = [theNewName lastPathComponent];
	  
	  [[NSFileManager defaultManager] movePath: [NSString stringWithFormat: @"%@/%@.%@.cache",
							      _path,
							      [theName substringToIndex:
									 ([theName length] - [str1 length])],
							      str1]
					  toPath: [NSString stringWithFormat: @"%@/%@.%@.cache",
							    _path,
							    [theNewName substringToIndex:
									  ([theNewName length] - [str2 length])],
							    str2]
					  handler: nil];
	}
      
      // If the folder was open, we must re-open and re-lock the mbox file,
      // recache the folder, adjust some paths and more.
      if (aFolder)
	{
	  // We update its name and path
	  [aFolder setName: theNewName];
	  [aFolder setPath: [NSString stringWithFormat: @"%@/%@", _path, theNewName]];

	  [[aFolder cacheManager] setPath: [NSString stringWithFormat: @"%@/%@.%@.cache",
						     _path,
						     [theNewName substringToIndex: ([theNewName length] - [[theNewName lastPathComponent] length])],
						     [theNewName lastPathComponent]]];
	  // We recache the mailbox with its new name.
	  RETAIN(aFolder);
	  [_openFolders removeObjectForKey: theName];
	  [_openFolders setObject: aFolder  forKey: theNewName];
	  RELEASE(aFolder);

	  // We now open and lock the mbox file. If we use maildir, we must adjust the "mail filename"
	  // of every message in the maildir.
	  if ([aFolder type] == PantomimeFormatMbox)
	    {
	      [aFolder open_mbox];
	    }
	}

      // Rebuild the folder tree
      [self _rebuildFolderEnumerator];
    }
  
  if (aBOOL)
    {
      POST_NOTIFICATION(PantomimeFolderRenameCompleted, self, info);
      PERFORM_SELECTOR_3(self, @selector(folderRenameCompleted:), PantomimeFolderRenameCompleted, info);
    }
  else
    {
      POST_NOTIFICATION(PantomimeFolderRenameFailed, self, info);
      PERFORM_SELECTOR_3(self, @selector(folderRenameFailed:), PantomimeFolderRenameFailed, info);
    }
}

@end


//
// Private interface
//
@implementation CWLocalStore (Private)

- (NSEnumerator *) _rebuildFolderEnumerator
{
  NSString *aString, *lastPathComponent, *pathToFolder;	
  NSEnumerator *tmpEnumerator;
  NSArray *tmpArray;
  NSUInteger i;
  
  // Clear out our cached folder structure and refresh from the file system
  [_folders removeAllObjects];
  [_folders setArray: [[[NSFileManager defaultManager] enumeratorAtPath: _path] allObjects]];
  
  //
  // We iterate through our array. If mbox A and .A.summary (or .A.cache) exists, we
  // remove .A.summary (or .A.cache) from our mutable array.
  // We do this in two runs:
  // First run: remove maildir sub-directory structure so that is appears as a regular folder.
  // Second run: remove other stuff like *.cache, *.summary
  //
  for (i = 0; i < [_folders count]; i++)
    {
      BOOL bIsMailDir;
      
      aString = [_folders objectAtIndex: i];
      
      //
      // First run:
      // If this is a maildir directory, remove its sub-directory structure from the list,
      // so that the maildir store appears just like a regular mail store.
      //
      if ([[NSFileManager defaultManager] fileExistsAtPath:
			[NSString stringWithFormat: @"%@/%@/cur", _path, aString] 
					  isDirectory: &bIsMailDir] && bIsMailDir)
	{
	  NSArray *subpaths;
	
	  // Wust ensure 700 mode un cur/new/tmp folders and 600 on all files (ie., messages)
	  if (_secure) 
	    {
	      [[NSFileManager defaultManager] enforceMode: 0700
					      atPath: [NSString stringWithFormat: @"%@/%@/cur", _path, aString]];
	      
	      [[NSFileManager defaultManager] enforceMode: 0700
					      atPath: [NSString stringWithFormat: @"%@/%@/new", _path, aString]];
	      
	      [[NSFileManager defaultManager] enforceMode: 0700
					      atPath: [NSString stringWithFormat: @"%@/%@/tmp", _path, aString]];
	    }
	  
	  // Get all the children of this directory an remove them from our mutable array.
	  subpaths = [[NSFileManager defaultManager] subpathsAtPath:
			[NSString stringWithFormat: @"%@/%@", _path, aString]];
	  [_folders removeObjectsInRange: NSMakeRange(i+1,[subpaths count])];
	}
    }
  
  //
  // Second Run: Get rid of cache, summary and OS specific stuff
  //
  tmpArray = [[NSArray alloc] initWithArray: _folders];
  AUTORELEASE(tmpArray);
  tmpEnumerator = [tmpArray objectEnumerator];
  
  while ((aString = [tmpEnumerator nextObject]))
    {
      lastPathComponent = [aString lastPathComponent];
      pathToFolder = [aString substringToIndex: ([aString length] - [lastPathComponent length])];
      
      // We remove Netscape/Mozilla summary file.
      [_folders removeObject: [NSString stringWithFormat: @"%@.%@.summary", pathToFolder, lastPathComponent]];
      
      // We remove Pantomime's cache file. Before doing so, we ensure it's 600 mode.
      [_folders removeObject: [NSString stringWithFormat: @"%@.%@.cache", pathToFolder, lastPathComponent]];
  
      if (_secure) [[NSFileManager defaultManager] enforceMode: 0600
						   atPath: [NSString stringWithFormat: @"%@/%@.%@.cache", _path, pathToFolder, lastPathComponent]];
      
      // We also remove Apple Mac OS X .DS_Store directory
      [_folders removeObject: [NSString stringWithFormat: @"%@.DS_Store", pathToFolder]];
    }
  
  return [_folders objectEnumerator];
}

@end