Frameworks/Adium Framework/Source/AIXMLElement.m
author Stephen Holt <sholt@adium.im>
Wed Aug 26 13:17:35 2009 -0400 (2009-08-26)
changeset 2597 07e07f9788a6
parent 2578 c5b0c0b0c141
child 2791 a18df53b0617
permissions -rw-r--r--
Undo the part of [3855f70905bd]: It caused strings to be incorrectly escaped and causing our XML parsing to break. Rather, escape hash-symbols when parsing in XML data as not to confuse AIHTMLDecoder. Refs #8141. Fixes #12856.
     1 /* AIXMLElement.m
     2  *
     3  * Created by Peter Hosey on 2006-06-07.
     4  *
     5  * This class is explicitly released under the BSD license with the following modification:
     6  * It may be used without reproduction of its copyright notice within The Adium Project.
     7  *
     8  * This class was created for use in the Adium project, which is released under the GPL.
     9  * The release of this specific class (AIXMLElement) under BSD in no way changes the licensing of any other portion
    10  * of the Adium project.
    11  *
    12  ****
    13  Copyright © 2006 Peter Hosey, Colin Barrett
    14  All rights reserved.
    15  
    16  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
    17  Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    18  Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    19  Neither the name of Peter Hosey nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission.
    20  
    21  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
    22  */
    23 
    24 #import <Adium/AIXMLElement.h>
    25 
    26 #import <AIUtilities/AIStringAdditions.h>
    27 
    28 @interface AIXMLElement()
    29 @property (readwrite, retain, nonatomic) NSMutableArray *attributeNames;
    30 @property (readwrite, retain, nonatomic) NSMutableArray *attributeValues;
    31 @end
    32 
    33 @implementation AIXMLElement
    34 
    35 + (id) elementWithNamespaceName:(NSString *)namespace elementName:(NSString *)newName
    36 {
    37 	if (namespace)
    38 		newName = [NSString stringWithFormat:@"%@:%@", namespace, newName];
    39 	return [self elementWithName:newName];
    40 }
    41 - (id) initWithNamespaceName:(NSString *)namespace elementName:(NSString *)newName
    42 {
    43 	if (namespace)
    44 		newName = [NSString stringWithFormat:@"%@:%@", namespace, newName];
    45 	return [self initWithName:newName];
    46 }
    47 + (id) elementWithName:(NSString *)newName
    48 {
    49 	return [[[self alloc] initWithName:newName] autorelease];
    50 }
    51 - (id) initWithName:(NSString *)newName
    52 {
    53 	NSParameterAssert(newName != nil);
    54 
    55 	if ((self = [super init])) {
    56 		name = [newName copy];
    57 		self.attributeNames  = [NSMutableArray array];
    58 		self.attributeValues = [NSMutableArray array];
    59 		contents = [[NSMutableArray alloc] init];
    60 
    61 		//If a list of self-closing tags exists, this could change to a lookup into a static NSSet
    62 		selfCloses = (([newName caseInsensitiveCompare:@"br"] == NSOrderedSame) ? YES : NO);
    63 	}
    64 	return self;
    65 }
    66 
    67 @synthesize attributeNames, attributeValues;
    68 
    69 - (id) init
    70 {
    71 	NSException *exc = [NSException exceptionWithName:@"Can't init AIXMLElement"
    72 											   reason:@"AIXMLElement does not support the -init method; use -initWithName: instead."
    73 											 userInfo:nil];
    74 	[exc raise];
    75 	return nil;
    76 }
    77 
    78 - (void) dealloc
    79 {
    80 	[name release];
    81 	[attributeNames  release];
    82 	[attributeValues release];
    83 	[contents release];
    84 
    85 	[super dealloc];
    86 }
    87 
    88 - (id) copyWithZone:(NSZone *)zone {
    89 	AIXMLElement *other = [[AIXMLElement allocWithZone:zone] initWithName:name];
    90 	other.attributeNames  = [NSMutableArray arrayWithArray:attributeNames];
    91 	other.attributeValues = [NSMutableArray arrayWithArray:attributeValues];
    92 	other.selfCloses = selfCloses;
    93 	other.contents = self.contents; //uses setArray, so this copies
    94 
    95 	return other;
    96 }
    97 
    98 #pragma mark -
    99 
   100 - (NSString *) name
   101 {
   102 	return name;
   103 }
   104 
   105 - (unsigned)numberOfAttributes
   106 {
   107 	return [attributeNames count];
   108 }
   109 - (NSDictionary *)attributes
   110 {
   111 	return [NSDictionary dictionaryWithObjects:attributeValues forKeys:attributeNames];
   112 }
   113 - (void) setAttributeNames:(NSArray *)newAttrNames values:(NSArray *)newAttrVals
   114 {
   115 	NSAssert2([newAttrNames count] == [newAttrVals count], @"Attribute names and values have different lengths, %ui and %ui respectively", [newAttrNames count], [newAttrVals count]);
   116 	unsigned numberOfDuplicates = [newAttrNames count] - [[NSSet setWithArray:newAttrNames] count];
   117 	NSAssert1(numberOfDuplicates == 0, @"Duplicate attributes are not allowed; found %ui duplicate(s)",  numberOfDuplicates);
   118 	
   119 	[attributeNames setArray:newAttrNames];
   120 	[attributeValues setArray:newAttrVals];
   121 }
   122 
   123 - (void)setValue:(NSString *)attrVal forAttribute:(NSString *)attrName
   124 {
   125 	NSUInteger index = [attributeNames indexOfObject:attrName];
   126 	if (index != NSNotFound) {
   127 		[attributeValues replaceObjectAtIndex:index withObject:attrVal];
   128 	} else {
   129 		[attributeNames addObject:attrName];
   130 		[attributeValues addObject:attrVal];
   131 	}
   132 }
   133 - (NSString *)valueForAttribute:(NSString *)attrName
   134 {
   135 	NSUInteger index = [attributeNames indexOfObject:attrName];
   136 	if (index != NSNotFound)
   137 		return [attributeValues objectAtIndex:index];
   138 	return nil;
   139 }
   140 
   141 @synthesize selfCloses;
   142 
   143 #pragma mark -
   144 
   145 //NSString: Unescaped string data (will be escaped for XMLification).
   146 //AIXMLElement: Sub-element (e.g. span in a p).
   147 - (void)addEscapedObject:(id)obj
   148 {
   149 	//Warn but don't assert if null is added.  Adding nothing is a no-op, but we may want to investigate where this is happening further.
   150 	if (!obj) NSLog(@"Warning: Attempted to add (null) to %@", obj);
   151 
   152 	NSAssert2(([obj isKindOfClass:[NSString class]] || [obj isKindOfClass:[AIXMLElement class]]), @"%@: addObject: %@ is of incorrect class",self,obj);
   153 	
   154 	[contents addObject:obj];
   155 }
   156 
   157 - (void) addObject:(id)obj
   158 {
   159 	//Warn but don't assert if null is added.  Adding nothing is a no-op, but we may want to investigate where this is happening further.
   160 	if (!obj) NSLog(@"Warning: Attempted to add (null) to %@", obj);
   161 
   162 	BOOL isString = [obj isKindOfClass:[NSString class]];
   163 	NSAssert2((isString || [obj isKindOfClass:[AIXMLElement class]]), @"%@: addObject: %@ is of incorrect class",self,obj);
   164 
   165 	if(isString) {
   166 		obj = [obj stringByEscapingForXMLWithEntities:nil];
   167 	}
   168 
   169 	[contents addObject:obj];
   170 }
   171 - (void) addObjectsFromArray:(NSArray *)array
   172 {
   173 	//We do it this way for the assertion, and to get free escaping of strings.
   174 	id obj;
   175 	for (obj in array) {
   176 		[self addObject:obj];
   177 	}
   178 }
   179 - (void) insertObject:(id)obj atIndex:(unsigned)idx
   180 {
   181 	BOOL isString = [obj isKindOfClass:[NSString class]];
   182 	NSParameterAssert(isString || [obj isKindOfClass:[AIXMLElement class]]);
   183 
   184 	if(isString) {
   185 		obj = [obj stringByEscapingForXMLWithEntities:nil];
   186 	}
   187 
   188 	[contents insertObject:obj atIndex:idx];
   189 }
   190 
   191 - (NSArray *)contents
   192 {
   193 	return contents;
   194 }
   195 - (void)setContents:(NSArray *)newContents
   196 {
   197 	[contents setArray:newContents];
   198 }
   199 
   200 - (NSString *)contentsAsXMLString
   201 {
   202 	NSMutableString *contentString = [NSMutableString string];
   203 	id obj = nil;
   204 	for (obj in contents) {
   205 		if ([obj isKindOfClass:[NSString class]])
   206 			[contentString appendString:obj];
   207 		else if ([obj isKindOfClass:[AIXMLElement class]])
   208 			[contentString appendString:[obj XMLString]];
   209 	}
   210 	return contentString;
   211 }
   212 
   213 #pragma mark -
   214 
   215 - (NSString *) quotedXMLAttributeValueStringForString:(NSString *)str
   216 {
   217 	return [NSString stringWithFormat:@"\"%@\"", [str stringByEscapingForXMLWithEntities:nil]];
   218 }
   219 
   220 - (void) appendXMLStringtoString:(NSMutableString *)string
   221 {
   222 	[string appendFormat:@"<%@", name];
   223 	if ([attributeNames count]) {
   224 		unsigned attributeIdx = 0U;
   225 		NSString *key;
   226 		for (key in attributeNames) {
   227 			NSString *value = [attributeValues objectAtIndex:attributeIdx++];
   228 			if ([value respondsToSelector:@selector(stringValue)]) {
   229 				value = [(NSNumber *)value stringValue];
   230 			} else if ([value respondsToSelector:@selector(absoluteString)]) {
   231 				value = [(NSURL *)value absoluteString];
   232 			}
   233 			[string appendFormat:@" %@=%@", key, [self quotedXMLAttributeValueStringForString:value]];
   234 		}
   235 	}
   236 	if ((![contents count]) && (selfCloses)) {
   237 		[string appendString:@" /"];
   238 	}
   239 	[string appendString:@">"];
   240 
   241 	id obj;
   242 	for (obj in contents) {
   243 		if ([obj isKindOfClass:[NSString class]]) {
   244 			[string appendString:(NSString *)obj];
   245 		} else if([obj isKindOfClass:[AIXMLElement class]]) {
   246 			[(AIXMLElement *)obj appendXMLStringtoString:string];
   247 		}
   248 	}
   249 
   250 	if ([contents count] || !selfCloses) {
   251 		[string appendFormat:@"</%@>", name];
   252 	}
   253 }
   254 - (NSString *) XMLString
   255 {
   256 	NSMutableString *string = [NSMutableString string];
   257 	[self appendXMLStringtoString:string];
   258 	return [NSString stringWithString:string];
   259 }
   260 
   261 - (void) appendUTF8XMLBytesToData:(NSMutableData *)data
   262 {
   263 	NSMutableString *startTag = [NSMutableString stringWithFormat:@"<%@", name];
   264 	if ([self numberOfAttributes]) {
   265 		unsigned attributeIdx = 0U;
   266 		NSString *key;
   267 		for (key in attributeNames) {
   268 			NSString *value = [attributeValues objectAtIndex:attributeIdx++];
   269 			if ([value respondsToSelector:@selector(stringValue)]) {
   270 				value = [(NSNumber *)value stringValue];
   271 			} else if ([value respondsToSelector:@selector(absoluteString)]) {
   272 				value = [(NSURL *)value absoluteString];
   273 			}
   274 			[startTag appendFormat:@" %@=%@", key, [self quotedXMLAttributeValueStringForString:value]];
   275 		}
   276 	}
   277 	if ((![contents count]) && (selfCloses)) {
   278 		[startTag appendString:@" /"];
   279 	}
   280 	[startTag appendString:@">"];
   281 	[data appendData:[startTag dataUsingEncoding:NSUTF8StringEncoding]];
   282 
   283 	id obj;
   284 	for (obj in contents) {
   285 		if ([obj isKindOfClass:[NSString class]]) {
   286 			[data appendData:[(NSString *)obj dataUsingEncoding:NSUTF8StringEncoding]];
   287 		} else if([obj isKindOfClass:[AIXMLElement class]]) {
   288 			[(AIXMLElement *)obj appendUTF8XMLBytesToData:data];
   289 		}
   290 	}
   291 
   292 	if ([contents count] || !selfCloses) {
   293 		[data appendData:[[NSString stringWithFormat:@"</%@>", name] dataUsingEncoding:NSUTF8StringEncoding]];
   294 	}
   295 }
   296 - (NSData *)UTF8XMLData
   297 {
   298 	NSMutableData *data = [NSMutableData data];
   299 	[self appendUTF8XMLBytesToData:data];
   300 	return [NSData dataWithData:data];
   301 }
   302 
   303 - (NSString *)description
   304 {
   305 	NSMutableString *string = [NSMutableString stringWithFormat:@"<%@ AIXMLElement:id=\"%p\"", name, self];
   306 	if ([attributeNames count] && [attributeValues count]) { //there's no way these could be different values, but whatever
   307 		unsigned attributeIdx = 0U;
   308 		NSString *key;
   309 		for (key in attributeNames) {
   310 			NSString *value = [attributeValues objectAtIndex:attributeIdx++];
   311 			if ([value respondsToSelector:@selector(stringValue)]) {
   312 				value = [(NSNumber *)value stringValue];
   313 			} else if ([value respondsToSelector:@selector(absoluteString)]) {
   314 				value = [(NSURL *)value absoluteString];
   315 			}
   316 			[string appendFormat:@" %@=%@", key, [self quotedXMLAttributeValueStringForString:value]];
   317 		}
   318 	}
   319 	[string appendString:@" />"];
   320 
   321 	return [NSString stringWithString:string];
   322 }
   323 
   324 
   325 
   326 #pragma mark KVC
   327 
   328 /*
   329 These aren't working. I recommend calling -objectForKey on the return value of -attributes.
   330 
   331 Adium[302:117] The following unhandled exception was ignored: NSUnknownKeyException ([<AIXMLElement 0xce582b0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key auto.)
   332 
   333 */
   334 /*
   335 - (id) valueForKey:(NSString *)key {
   336 	unsigned idx = [attributeNames indexOfObject:key];	
   337 	return (idx != NSNotFound) ? [attributeValues objectAtIndex:idx] : [super valueForKey:key];
   338 }
   339 //FIXME: this shouldn't clobber setObject:forKey: on NSObject.
   340 - (void) setValue:(id)obj forKey:(NSString *)key {
   341 	unsigned idx = [attributeNames indexOfObject:key];
   342 	if(idx == NSNotFound) {
   343 		[attributeNames addObject:key];
   344 		[attributeValues addObject:obj];
   345 	} else {
   346 		[attributeValues replaceObjectAtIndex:idx withObject:obj];
   347 	}
   348 }
   349 
   350 */
   351 
   352 @end