]> err.no Git - sope/blob - sope-ical/versitSaxDriver/VSSaxDriver.m
added robustness
[sope] / sope-ical / versitSaxDriver / VSSaxDriver.m
1 /*
2  Copyright (C) 2003-2004 Max Berger
3  Copyright (C) 2004 OpenGroupware.org
4
5  This file is part of versitSaxDriver, written for the OpenGroupware.org 
6  project (OGo).
7  
8  OGo is free software; you can redistribute it and/or modify it under
9  the terms of the GNU Lesser General Public License as published by the
10  Free Software Foundation; either version 2, or (at your option) any
11  later version.
12  
13  OGo is distributed in the hope that it will be useful, but WITHOUT ANY
14  WARRANTY; without even the implied warranty of MERCHANTABILITY or
15  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
16  License for more details.
17  
18  You should have received a copy of the GNU Lesser General Public
19  License along with OGo; see the file COPYING.  If not, write to the
20  Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA
21  02111-1307, USA.
22 */
23 // $Id$
24
25 #include "VSSaxDriver.h"
26 #include "VSStringFormatter.h"
27 #include "common.h"
28
29 @implementation VSSaxDriver
30
31 static BOOL debugOn = NO;
32
33 static NSCharacterSet *dotCharSet = nil;
34 static NSCharacterSet *equalSignCharSet = nil;
35 static NSCharacterSet *commaCharSet = nil;
36 static NSCharacterSet *colonAndSemicolonCharSet = nil;
37 static NSCharacterSet *colonSemicolonAndDquoteCharSet = nil;
38 static NSCharacterSet *whitespaceCharSet = nil;
39
40 static VSStringFormatter *stringFormatter = nil;
41
42 + (void)initialize {
43   static BOOL didInit = NO;
44   NSUserDefaults *ud;
45
46   if(didInit)
47     return;
48   didInit = YES;
49
50   ud      = [NSUserDefaults standardUserDefaults];
51   debugOn = [ud boolForKey:@"OGoDebugVersitSaxDriver"];
52
53   dotCharSet =
54     [[NSCharacterSet characterSetWithCharactersInString:@"."] retain];
55   equalSignCharSet =
56     [[NSCharacterSet characterSetWithCharactersInString:@"="] retain];
57   commaCharSet =
58     [[NSCharacterSet characterSetWithCharactersInString:@","] retain];
59   colonAndSemicolonCharSet =
60     [[NSCharacterSet characterSetWithCharactersInString:@":;"] retain];
61   colonSemicolonAndDquoteCharSet =
62     [[NSCharacterSet characterSetWithCharactersInString:@":;\""] retain];
63   whitespaceCharSet =
64     [[NSCharacterSet whitespaceCharacterSet] retain];
65
66   stringFormatter = [VSStringFormatter sharedFormatter];
67 }
68
69
70 - (id)init {
71   if ((self = [super init])) {
72     self->prefixURI         = @"";
73     self->cardStack         = [[NSMutableArray alloc]      init];
74     self->elementList       = [[NSMutableArray alloc]      init];
75     self->attributeMapping  = [[NSMutableDictionary alloc] init];
76     self->subItemMapping    = [[NSMutableDictionary alloc] init];
77   }
78   return self;
79 }
80
81 - (void)dealloc {
82   [self->contentHandler    release];
83   [self->prefixURI         release];
84   [self->cardStack         release];
85   [self->elementList       release];
86   [self->attributeElements release];
87   [self->elementMapping    release];
88   [self->attributeMapping  release];
89   [self->subItemMapping    release];
90   [super dealloc];
91 }
92
93 /* accessors */
94
95 - (void)setFeature:(NSString *)_name to:(BOOL)_value {
96 }
97 - (BOOL)feature:(NSString *)_name {
98   return NO;
99 }
100
101 - (void)setProperty:(NSString *)_name to:(id)_value {
102 }
103 - (id)property:(NSString *)_name {
104   return nil;
105 }
106
107 /* handlers */
108
109 - (void)setContentHandler:(id<NSObject,SaxContentHandler>)_handler {
110   ASSIGN(self->contentHandler,_handler);
111 }
112
113 - (void)setDTDHandler:(id<NSObject,SaxDTDHandler>)_handler {
114   // FIXME
115 }
116
117 - (void)setErrorHandler:(id<NSObject,SaxErrorHandler>)_handler {
118   // FIXME
119 }
120 - (void)setEntityResolver:(id<NSObject,SaxEntityResolver>)_handler {
121   // FIXME
122 }
123
124 - (id<NSObject,SaxContentHandler>)contentHandler {
125   return self->contentHandler;
126 }
127
128 - (id<NSObject,SaxDTDHandler>)dtdHandler {
129   // FIXME
130   return NULL;
131 }
132
133 - (id<NSObject,SaxErrorHandler>)errorHandler {
134   // FIXME
135   return NULL;
136 }
137 - (id<NSObject,SaxEntityResolver>)entityResolver {
138   // FIXME
139   return NULL;
140 }
141
142 - (void)setPrefixURI:(NSString *)_uri {
143   ASSIGNCOPY(self->prefixURI, _uri);
144 }
145 - (NSString *)prefixURI {
146   return self->prefixURI;
147 }
148
149 - (void)setAttributeElements:(NSSet *)_elements {
150   ASSIGNCOPY(self->attributeElements, _elements);
151 }
152 - (NSSet *)attributeElements {
153   return self->attributeElements;
154 }
155
156 - (void)setElementMapping:(NSDictionary *)_mapping {
157   ASSIGNCOPY(self->elementMapping, _mapping);
158 }
159 - (NSDictionary *)elementMapping {
160   return self->elementMapping;
161 }
162
163 - (void)setAttributeMapping:(NSDictionary *)_mapping {
164   [self setAttributeMapping:_mapping forElement:@""];
165 }
166
167 - (void)setAttributeMapping:(NSDictionary *)_mapping 
168   forElement:(NSString *)_element 
169 {
170   if (!_element)
171     _element = @"";
172   [attributeMapping setObject:_mapping forKey:_element];
173 }
174
175 - (void)setSubItemMapping:(NSArray *)_mapping 
176   forElement:(NSString *)_element 
177 {
178   [subItemMapping setObject:_mapping forKey:_element];  
179 }
180
181
182
183 /* parsing */
184
185 - (NSString *)_mapTagName:(NSString *)_tagName {
186   NSString *ret;
187   NSRange  r;
188
189   if ((ret = [self->elementMapping objectForKey:_tagName]) == nil) {
190     //NSLog(@"Unknown Key: %@ in %@",_tagName,self->elementMapping);
191     ret = _tagName;
192
193     /* This is to allow parsing of vCards produced by Apple
194        Addressbook. AFAIK the .dot notation is a non-standard
195        extension */
196     r = [_tagName rangeOfCharacterFromSet:dotCharSet];
197     if (r.length > 0) {
198       ret = [self _mapTagName:[_tagName substringFromIndex:(r.location + 1)]];
199     }
200   }
201   return ret;
202 }
203
204 - (void)_addAttribute:(NSString *)_attribute
205   value:(NSString *)_value 
206   toAttrs:(SaxAttributes *)_attrs
207 {
208   [_attrs addAttribute:_attribute
209           uri:self->prefixURI 
210           rawName:_attribute
211           type:@"CDATA"
212           value:_value];
213 }
214
215 - (void)_addAttribute:(NSString *)_attribute value:(NSString *)_value {
216   NSArray *element = [cardStack lastObject];
217   SaxAttributes *attrs = [element objectAtIndex:2];
218   [self _addAttribute:_attribute value:_value toAttrs:attrs];
219 }
220
221 - (NSString *)_mapAttrName:(NSString *)_attrName forTag:(NSString *)_tagName {
222   NSString *mappedName;
223
224   mappedName = [[self->attributeMapping objectForKey:_tagName]
225                                         objectForKey:_attrName];
226   if (!mappedName) {
227     mappedName = [[self->attributeMapping objectForKey:
228                                           [self _mapTagName:_tagName]]
229                                           objectForKey:_attrName];
230   }
231   if (!mappedName) {
232     mappedName = [[self->attributeMapping objectForKey:@""]
233                                           objectForKey:_attrName];
234   }
235   if (!mappedName)
236     mappedName = _attrName;
237   
238   return mappedName;
239 }
240
241 - (void)_parseAttr:(NSString *)_attr 
242   forTag:(NSString *)_tagName
243   intoAttr:(NSString **)attr_
244   intoValue:(NSString **)value_
245 {
246   NSRange  r;
247   NSString *attrName, *attrValue, *mappedName;
248   
249   r = [_attr rangeOfCharacterFromSet:equalSignCharSet];
250   if (r.length > 0) {
251     attrName  = [[_attr substringToIndex:r.location] uppercaseString];
252     attrValue = [_attr substringFromIndex:(r.location + 1)];
253   }
254   else {
255     attrName  = @"TYPE";
256     attrValue = _attr;
257   }
258   
259 #if 0
260   // ZNeK: what's this for?
261   r = [attrValue rangeOfCharacterFromSet:commaCharSet];
262   while (r.length > 0) {
263     [attrValue replaceCharactersInRange:r withString:@" "];
264     r = [attrValue rangeOfCharacterFromSet:commaCharSet];
265   }
266 #endif
267
268   mappedName = [self _mapAttrName:attrName forTag:_tagName];
269   *attr_ = mappedName;
270   *value_ = [stringFormatter stringByUnescapingRFC2445Text:attrValue];
271 }
272
273 - (id<NSObject,SaxAttributes>)_mapAttrs:(NSArray *)_attrs 
274   forTag:(NSString *)_tagName 
275 {
276   SaxAttributes       *retAttrs;
277   NSEnumerator        *attrEnum;
278   NSString            *curAttr, *mappedAttr, *mappedValue, *oldValue;
279   NSMutableDictionary *attributes;
280
281   if (!_attrs || [_attrs count] == 0)
282     return nil;
283
284   attributes = [[NSMutableDictionary alloc] init];
285   retAttrs = [[[SaxAttributes alloc] init] autorelease];
286   attrEnum = [_attrs objectEnumerator];
287   while ((curAttr = [attrEnum nextObject])) {
288     [self _parseAttr:curAttr
289           forTag:_tagName
290           intoAttr:&mappedAttr
291           intoValue:&mappedValue];
292     if ((oldValue = [attributes objectForKey:mappedAttr])) {
293       NSString *val;
294       /* ZNeK: duh! */
295       val = [NSString stringWithFormat:@"%@ %@",oldValue, mappedValue];
296       [attributes setObject:val forKey:mappedAttr];
297     }
298     else  
299       [attributes setObject:mappedValue forKey:mappedAttr];
300   }
301
302   attrEnum = [attributes keyEnumerator];
303   while ((curAttr = [attrEnum nextObject])) {
304     [self _addAttribute:curAttr
305           value:[attributes objectForKey:curAttr]
306           toAttrs:retAttrs];
307   }
308   
309   [attributes release];
310   
311   return retAttrs;
312 }
313
314 - (NSArray *)_beginTag:(NSString *)_tagName 
315   withAttrs:(id<NSObject,SaxAttributes>)_attrs 
316 {
317   NSArray *tag = [NSArray arrayWithObjects:@"BEGIN",_tagName,_attrs,NULL];
318   [self->elementList addObject:tag];
319   return tag;
320 }
321
322 - (void)_endTag:(NSString *)_tagName {
323   [self->elementList addObject:
324          [NSArray arrayWithObjects:@"END",_tagName,NULL]];
325 }
326
327 - (void)_addSubItems:(NSArray *)_items withData:(NSString *)_content {
328   NSEnumerator *itemEnum, *contentEnum;
329   NSString *subTag;
330   NSString *subContent;
331   
332   itemEnum    = [_items objectEnumerator];
333   contentEnum = [[_content componentsSeparatedByString:@";"] objectEnumerator];
334   
335   while ((subTag=[itemEnum nextObject])) {
336     subContent = [contentEnum nextObject];
337     
338     [self _beginTag:subTag withAttrs:nil];
339     if ([subContent length]>0) 
340       [self->elementList addObject:
341         [NSArray arrayWithObjects:@"DATA", subContent, nil]];  
342     [self _endTag:subTag];
343   }
344 }
345
346 - (void)_dataTag:(NSString *)_tagName 
347   withAttrs:(id<NSObject,SaxAttributes>)_attrs 
348   andContent:(NSString *)_content 
349 {
350   NSArray *subItems;
351
352   _content = [stringFormatter stringByUnescapingRFC2445Text:_content];
353   if ([self->attributeElements containsObject:_tagName]) {
354     [self _addAttribute:_tagName value:_content];
355   } 
356   else {
357     [self _beginTag:_tagName withAttrs:_attrs];
358     if ([_content length] > 0) {
359       if ((subItems = [self->subItemMapping objectForKey:_tagName])) {
360         [self _addSubItems:subItems withData:_content];
361       }
362       else {
363         [self->elementList addObject:
364           [NSArray arrayWithObjects:@"DATA", _content, nil]];  
365       }
366     }
367     [self _endTag:_tagName];
368   }
369 }
370
371 - (void)_eventsForElements {
372   NSEnumerator *enu;
373   NSArray  *obj;
374   NSString *type;
375   NSString *name;
376   unichar  *chardata;
377   id<NSObject,SaxAttributes> attrs;
378   
379   enu = [elementList objectEnumerator];
380   while ((obj = [enu nextObject])) {
381     type = [obj objectAtIndex:0];
382     name = [obj objectAtIndex:1];
383     
384     if ([obj count] > 2) 
385       attrs = [obj objectAtIndex:2];
386     else
387       attrs = nil;
388
389     if ([type isEqualToString:@"BEGIN"]) {
390       [self->contentHandler startElement:name
391                             namespace:self->prefixURI
392                             rawName:name
393                             attributes:attrs];
394     } 
395     else if ([type isEqualToString:@"END"]) {
396       [self->contentHandler endElement:name
397                             namespace:self->prefixURI
398                             rawName:name];
399     }
400     else {
401       unsigned len = [name length];
402       chardata = malloc(len * sizeof(unichar));
403       [name getCharacters:chardata range:NSMakeRange(0, len)];
404       [self->contentHandler characters:chardata length:len];
405       if (chardata)
406         free(chardata);
407     }
408   }
409   [elementList removeAllObjects];
410 }
411
412 - (void)_parseLine:(NSString *)_line {
413   NSString       *tagName, *tagValue;
414   NSMutableArray *tagAttributes;
415   NSRange        r, todoRange;
416   unsigned       length;
417
418   length = [_line length];
419   tagAttributes = [[NSMutableArray alloc] init];
420   todoRange = NSMakeRange(0, length);
421   r = [_line rangeOfCharacterFromSet:colonAndSemicolonCharSet
422              options:0
423              range:todoRange];
424   tagName = [[_line substringToIndex:r.location] uppercaseString];
425   if([_line characterAtIndex:r.location] != ':') {
426     BOOL isAtEnd = NO, isInDquote = NO;
427     unsigned start = NSMaxRange(r);
428
429     todoRange = NSMakeRange(start, length - start);
430     while(!isAtEnd) {
431       BOOL skip = YES;
432
433       /* scan for parameters */
434       r = [_line rangeOfCharacterFromSet:colonSemicolonAndDquoteCharSet
435                  options:0
436                  range:todoRange];
437       /* first check if delimiter candidate is escaped */
438       if([_line characterAtIndex:(r.location - 1)] != '\\') {
439         unichar delimiter;
440         NSRange copyRange;
441
442         delimiter = [_line characterAtIndex:r.location];
443         if(delimiter == '\"') {
444           /* not a real delimiter - toggle isInDquote for proper escaping */
445           isInDquote = !isInDquote;
446         }
447         else {
448           if(!isInDquote) {
449             /* is a delimiter, which one? */
450             skip = NO;
451             if(delimiter == ':') {
452               isAtEnd = YES;
453             }
454             copyRange = NSMakeRange(start, r.location - start);
455             [tagAttributes addObject:[_line substringWithRange:copyRange]];
456             if(!isAtEnd) {
457               /* adjust start, todoRange */
458               start     = NSMaxRange(r);
459               todoRange = NSMakeRange(start, length - start);
460             }
461           }
462         }
463       }
464       if(skip) {
465         /* adjust todoRange */
466         unsigned offset = NSMaxRange(r);
467         todoRange = NSMakeRange(offset, length - offset);
468       }
469     }
470   }
471   tagValue = [_line substringFromIndex:NSMaxRange(r)];
472
473   if ([tagName isEqualToString:@"BEGIN"]) {
474     id tag;
475     
476     tag = [self _beginTag:[self _mapTagName:tagValue] 
477                 withAttrs:[[[SaxAttributes alloc] init] autorelease]];
478     [self->cardStack addObject:tag];
479   } 
480   else if ([tagName isEqualToString:@"END"]) {
481     [self _endTag:[self _mapTagName:tagValue]];
482     [self->cardStack removeLastObject];
483     if ([self->cardStack count] == 0)
484       [self _eventsForElements];
485   }
486   else {
487     [self _dataTag:[self _mapTagName:tagName]
488          withAttrs:[self _mapAttrs:tagAttributes forTag:tagName] 
489         andContent:tagValue];
490   }
491   [tagAttributes release];
492 }
493
494 - (void)_parseString:(NSString *)_rawString {
495   unsigned pos, length;
496   NSMutableString *line;
497   NSRange r;
498
499   [self->contentHandler startDocument];
500   [self->contentHandler startPrefixMapping:@"" uri:self->prefixURI];
501   
502   length = [_rawString length];
503   /* RFC2445:
504      contentline        = name *(";" param ) ":" value CRLF
505      ; When parsing a content line, folded lines MUST first
506      ; be unfolded
507   */
508   r = NSMakeRange(0, 0);
509   /* probably too optimistic */ 
510   line = [[NSMutableString alloc] initWithCapacity:75 + 2];
511
512   for(pos = 0; pos < length; pos++) {
513     unichar c = [_rawString characterAtIndex:pos];
514     
515     if(c == '\r') {
516       if(((length - 1) - pos) >= 1) {
517         if([_rawString characterAtIndex:pos + 1] == '\n') {
518           BOOL isAtEndOfLine = YES;
519           /* test for folding first */
520           if(((length - 1) - pos) >= 2) {
521             unichar ws = [_rawString characterAtIndex:pos + 2];
522             isAtEndOfLine = [whitespaceCharSet characterIsMember:ws] ? NO
523                                                                      : YES;
524             if(!isAtEndOfLine) {
525               /* assemble part of line up to pos */
526               if(r.length > 0) {
527                 [line appendString:[_rawString substringWithRange:r]];
528               }
529               /* unfold */
530               pos += 2;
531               r = NSMakeRange(pos + 1, 0); /* begin new range */
532             }
533           }
534           if(isAtEndOfLine) {
535             /* assemble part of line up to pos */
536             if(r.length > 0) {
537               [line appendString:[_rawString substringWithRange:r]];
538             }
539             [self _parseLine:line];
540             /* reset line */
541             [line deleteCharactersInRange:NSMakeRange(0, [line length])];
542             pos += 1;
543             r = NSMakeRange(pos + 1, 0); /* begin new range */
544           }
545         }
546       }
547       else {
548         /* garbled last line! */
549         if(debugOn) {
550           NSLog(@"%s Last line is truncated, trying to parse anyways!",
551                 __PRETTY_FUNCTION__);
552         }
553       }
554     }
555     else if(c == '\n') { /* broken, non-standard */
556       BOOL isAtEndOfLine = YES;
557       /* test for folding first */
558       if(((length - 1) - pos) >= 1) {
559         unichar ws = [_rawString characterAtIndex:pos + 1];
560         isAtEndOfLine = [whitespaceCharSet characterIsMember:ws] ? NO
561                                                                  : YES;
562         if(!isAtEndOfLine) {
563           /* assemble part of line up to pos */
564           if(r.length > 0) {
565             [line appendString:[_rawString substringWithRange:r]];
566           }
567           /* unfold */
568           pos += 1;
569           r = NSMakeRange(pos + 1, 0); /* begin new range */
570         }
571       }
572       if(isAtEndOfLine) {
573         /* assemble part of line up to pos */
574         if(r.length > 0) {
575           [line appendString:[_rawString substringWithRange:r]];
576         }
577         [self _parseLine:line];
578         /* reset line */
579         [line deleteCharactersInRange:NSMakeRange(0, [line length])];
580         r = NSMakeRange(pos + 1, 0); /* begin new range */
581       }
582     }
583     else {
584       r.length += 1;
585     }
586   }
587   if(r.length > 0) {
588     if(debugOn) {
589       NSLog(@"%s Last line of iCal string is not properly terminated!",
590             __PRETTY_FUNCTION__);
591     }
592     [line appendString:[_rawString substringWithRange:r]];
593     [self _parseLine:line];
594   }
595
596   [line release];
597   [self->contentHandler endPrefixMapping:@""];
598   [self->contentHandler endDocument];
599 }
600
601 - (void)parseFromSource:(id)_source {
602   if (debugOn)
603     NSLog(@"%s: parse: %@", __PRETTY_FUNCTION__, _source);
604   
605   if ([_source isKindOfClass:[NSURL class]]) {
606     if (debugOn) 
607       NSLog(@"%s: trying to load URL...",__PRETTY_FUNCTION__);
608     _source = [_source resourceDataUsingCache:NO];
609   }
610   
611   if ([_source isKindOfClass:[NSData class]]) {
612     // FIXME: Data is not always utf-8.....
613     if (debugOn) 
614       NSLog(@"%s: trying to decode data...",__PRETTY_FUNCTION__);
615     _source = [[[NSString alloc]
616                  initWithData:_source encoding:NSUTF8StringEncoding]
617                  autorelease];
618   }
619   
620   if ([_source isKindOfClass:[NSString class]]) {
621     if (debugOn) 
622       NSLog(@"%s: trying to parse string...",__PRETTY_FUNCTION__);
623     [self _parseString:_source];
624   } 
625   else {
626     if (debugOn) 
627       NSLog(@"%s: unrecognizable source: %@", __PRETTY_FUNCTION__,_source);
628     // FIXME: Return Error
629   }
630 }
631
632 - (void)parseFromSource:(id)_source systemId:(NSString *)_sysId {
633   [self parseFromSource:_source];
634 }
635
636 - (void)parseFromSystemId:(NSString *)_sysId {
637   NSURL *url;
638   
639   if ((url = [NSURL URLWithString:_sysId]))
640     [self parseFromSource:url systemId:_sysId];
641 }
642
643 /* debugging */
644
645 - (BOOL)isDebuggingEnabled {
646   return debugOn;
647 }
648
649 @end /* VersitSaxDriver */