code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
//
// ASIInputStream.m
// Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
// Created by Ben Copsey on 10/08/2009.
// Copyright 2009 All-Seeing Interactive. All rights reserved.
//
#import "ASIInputStream.h"
#import "ASIHTTPRequest.h"
// Used to ensure only one request can read data at once
static NSLock *readLock = nil;
@implementation ASIInputStream
+ (void)initialize
{
if (self == [ASIInputStream class]) {
readLock = [[NSLock alloc] init];
}
}
+ (id)inputStreamWithFileAtPath:(NSString *)path request:(ASIHTTPRequest *)theRequest
{
ASIInputStream *theStream = [[[self alloc] init] autorelease];
[theStream setRequest:theRequest];
[theStream setStream:[NSInputStream inputStreamWithFileAtPath:path]];
return theStream;
}
+ (id)inputStreamWithData:(NSData *)data request:(ASIHTTPRequest *)theRequest
{
ASIInputStream *theStream = [[[self alloc] init] autorelease];
[theStream setRequest:theRequest];
[theStream setStream:[NSInputStream inputStreamWithData:data]];
return theStream;
}
- (void)dealloc
{
[stream release];
[super dealloc];
}
// Called when CFNetwork wants to read more of our request body
// When throttling is on, we ask ASIHTTPRequest for the maximum amount of data we can read
- (NSInteger)read:(uint8_t *)buffer maxLength:(NSUInteger)len
{
[readLock lock];
unsigned long toRead = len;
if ([ASIHTTPRequest isBandwidthThrottled]) {
toRead = [ASIHTTPRequest maxUploadReadLength];
if (toRead > len) {
toRead = len;
} else if (toRead == 0) {
toRead = 1;
}
[request performThrottling];
}
[readLock unlock];
NSInteger rv = [stream read:buffer maxLength:toRead];
if (rv > 0)
[ASIHTTPRequest incrementBandwidthUsedInLastSecond:rv];
return rv;
}
/*
* Implement NSInputStream mandatory methods to make sure they are implemented
* (necessary for MacRuby for example) and avoid the overhead of method
* forwarding for these common methods.
*/
- (void)open
{
[stream open];
}
- (void)close
{
[stream close];
}
- (id)delegate
{
return [stream delegate];
}
- (void)setDelegate:(id)delegate
{
[stream setDelegate:delegate];
}
- (void)scheduleInRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode
{
[stream scheduleInRunLoop:aRunLoop forMode:mode];
}
- (void)removeFromRunLoop:(NSRunLoop *)aRunLoop forMode:(NSString *)mode
{
[stream removeFromRunLoop:aRunLoop forMode:mode];
}
- (id)propertyForKey:(NSString *)key
{
return [stream propertyForKey:key];
}
- (BOOL)setProperty:(id)property forKey:(NSString *)key
{
return [stream setProperty:property forKey:key];
}
- (NSStreamStatus)streamStatus
{
return [stream streamStatus];
}
- (NSError *)streamError
{
return [stream streamError];
}
// If we get asked to perform a method we don't have (probably internal ones),
// we'll just forward the message to our stream
- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector
{
return [stream methodSignatureForSelector:aSelector];
}
- (void)forwardInvocation:(NSInvocation *)anInvocation
{
[anInvocation invokeWithTarget:stream];
}
@synthesize stream;
@synthesize request;
@end
| 009-20120511-zi | trunk/Zinipad/ASI/ASIInputStream.m | Objective-C | gpl3 | 3,122 |
//
// ASIAuthenticationDialog.h
// Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
// Created by Ben Copsey on 21/08/2009.
// Copyright 2009 All-Seeing Interactive. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
@class ASIHTTPRequest;
typedef enum _ASIAuthenticationType {
ASIStandardAuthenticationType = 0,
ASIProxyAuthenticationType = 1
} ASIAuthenticationType;
@interface ASIAutorotatingViewController : UIViewController
@end
@interface ASIAuthenticationDialog : ASIAutorotatingViewController <UIActionSheetDelegate, UITableViewDelegate, UITableViewDataSource> {
ASIHTTPRequest *request;
ASIAuthenticationType type;
UITableView *tableView;
UIViewController *presentingController;
BOOL didEnableRotationNotifications;
}
+ (void)presentAuthenticationDialogForRequest:(ASIHTTPRequest *)request;
+ (void)dismiss;
@property (retain) ASIHTTPRequest *request;
@property (assign) ASIAuthenticationType type;
@property (assign) BOOL didEnableRotationNotifications;
@property (retain, nonatomic) UIViewController *presentingController;
@end
| 009-20120511-zi | trunk/Zinipad/ASI/ASIAuthenticationDialog.h | Objective-C | gpl3 | 1,107 |
//
// ASIDownloadCache.m
// Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
// Created by Ben Copsey on 01/05/2010.
// Copyright 2010 All-Seeing Interactive. All rights reserved.
//
#import "ASIDownloadCache.h"
#import "ASIHTTPRequest.h"
#import <CommonCrypto/CommonHMAC.h>
static ASIDownloadCache *sharedCache = nil;
static NSString *sessionCacheFolder = @"SessionStore";
static NSString *permanentCacheFolder = @"PermanentStore";
static NSArray *fileExtensionsToHandleAsHTML = nil;
@interface ASIDownloadCache ()
+ (NSString *)keyForURL:(NSURL *)url;
- (NSString *)pathToFile:(NSString *)file;
@end
@implementation ASIDownloadCache
+ (void)initialize
{
if (self == [ASIDownloadCache class]) {
// Obviously this is not an exhaustive list, but hopefully these are the most commonly used and this will 'just work' for the widest range of people
// I imagine many web developers probably use url rewriting anyway
fileExtensionsToHandleAsHTML = [[NSArray alloc] initWithObjects:@"asp",@"aspx",@"jsp",@"php",@"rb",@"py",@"pl",@"cgi", nil];
}
}
- (id)init
{
self = [super init];
[self setShouldRespectCacheControlHeaders:YES];
[self setDefaultCachePolicy:ASIUseDefaultCachePolicy];
[self setAccessLock:[[[NSRecursiveLock alloc] init] autorelease]];
return self;
}
+ (id)sharedCache
{
if (!sharedCache) {
@synchronized(self) {
if (!sharedCache) {
sharedCache = [[self alloc] init];
[sharedCache setStoragePath:[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"ASIHTTPRequestCache"]];
}
}
}
return sharedCache;
}
- (void)dealloc
{
[storagePath release];
[accessLock release];
[super dealloc];
}
- (NSString *)storagePath
{
[[self accessLock] lock];
NSString *p = [[storagePath retain] autorelease];
[[self accessLock] unlock];
return p;
}
- (void)setStoragePath:(NSString *)path
{
[[self accessLock] lock];
[self clearCachedResponsesForStoragePolicy:ASICacheForSessionDurationCacheStoragePolicy];
[storagePath release];
storagePath = [path retain];
NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
BOOL isDirectory = NO;
NSArray *directories = [NSArray arrayWithObjects:path,[path stringByAppendingPathComponent:sessionCacheFolder],[path stringByAppendingPathComponent:permanentCacheFolder],nil];
for (NSString *directory in directories) {
BOOL exists = [fileManager fileExistsAtPath:directory isDirectory:&isDirectory];
if (exists && !isDirectory) {
[[self accessLock] unlock];
[NSException raise:@"FileExistsAtCachePath" format:@"Cannot create a directory for the cache at '%@', because a file already exists",directory];
} else if (!exists) {
[fileManager createDirectoryAtPath:directory withIntermediateDirectories:NO attributes:nil error:nil];
if (![fileManager fileExistsAtPath:directory]) {
[[self accessLock] unlock];
[NSException raise:@"FailedToCreateCacheDirectory" format:@"Failed to create a directory for the cache at '%@'",directory];
}
}
}
[self clearCachedResponsesForStoragePolicy:ASICacheForSessionDurationCacheStoragePolicy];
[[self accessLock] unlock];
}
- (void)updateExpiryForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge
{
NSString *headerPath = [self pathToStoreCachedResponseHeadersForRequest:request];
NSMutableDictionary *cachedHeaders = [NSMutableDictionary dictionaryWithContentsOfFile:headerPath];
if (!cachedHeaders) {
return;
}
NSDate *expires = [self expiryDateForRequest:request maxAge:maxAge];
if (!expires) {
return;
}
[cachedHeaders setObject:[NSNumber numberWithDouble:[expires timeIntervalSince1970]] forKey:@"X-ASIHTTPRequest-Expires"];
[cachedHeaders writeToFile:headerPath atomically:NO];
}
- (NSDate *)expiryDateForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge
{
return [ASIHTTPRequest expiryDateForRequest:request maxAge:maxAge];
}
- (void)storeResponseForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge
{
[[self accessLock] lock];
if ([request error] || ![request responseHeaders] || ([request cachePolicy] & ASIDoNotWriteToCacheCachePolicy)) {
[[self accessLock] unlock];
return;
}
// We only cache 200/OK or redirect reponses (redirect responses are cached so the cache works better with no internet connection)
int responseCode = [request responseStatusCode];
if (responseCode != 200 && responseCode != 301 && responseCode != 302 && responseCode != 303 && responseCode != 307) {
[[self accessLock] unlock];
return;
}
if ([self shouldRespectCacheControlHeaders] && ![[self class] serverAllowsResponseCachingForRequest:request]) {
[[self accessLock] unlock];
return;
}
NSString *headerPath = [self pathToStoreCachedResponseHeadersForRequest:request];
NSString *dataPath = [self pathToStoreCachedResponseDataForRequest:request];
NSMutableDictionary *responseHeaders = [NSMutableDictionary dictionaryWithDictionary:[request responseHeaders]];
if ([request isResponseCompressed]) {
[responseHeaders removeObjectForKey:@"Content-Encoding"];
}
// Create a special 'X-ASIHTTPRequest-Expires' header
// This is what we use for deciding if cached data is current, rather than parsing the expires / max-age headers individually each time
// We store this as a timestamp to make reading it easier as NSDateFormatter is quite expensive
NSDate *expires = [self expiryDateForRequest:request maxAge:maxAge];
if (expires) {
[responseHeaders setObject:[NSNumber numberWithDouble:[expires timeIntervalSince1970]] forKey:@"X-ASIHTTPRequest-Expires"];
}
// Store the response code in a custom header so we can reuse it later
// We'll change 304/Not Modified to 200/OK because this is likely to be us updating the cached headers with a conditional GET
int statusCode = [request responseStatusCode];
if (statusCode == 304) {
statusCode = 200;
}
[responseHeaders setObject:[NSNumber numberWithInt:statusCode] forKey:@"X-ASIHTTPRequest-Response-Status-Code"];
[responseHeaders writeToFile:headerPath atomically:NO];
if ([request responseData]) {
[[request responseData] writeToFile:dataPath atomically:NO];
} else if ([request downloadDestinationPath] && ![[request downloadDestinationPath] isEqualToString:dataPath]) {
NSError *error = nil;
NSFileManager* manager = [[NSFileManager alloc] init];
if ([manager fileExistsAtPath:dataPath]) {
[manager removeItemAtPath:dataPath error:&error];
}
[manager copyItemAtPath:[request downloadDestinationPath] toPath:dataPath error:&error];
[manager release];
}
[[self accessLock] unlock];
}
- (NSDictionary *)cachedResponseHeadersForURL:(NSURL *)url
{
NSString *path = [self pathToCachedResponseHeadersForURL:url];
if (path) {
return [NSDictionary dictionaryWithContentsOfFile:path];
}
return nil;
}
- (NSData *)cachedResponseDataForURL:(NSURL *)url
{
NSString *path = [self pathToCachedResponseDataForURL:url];
if (path) {
return [NSData dataWithContentsOfFile:path];
}
return nil;
}
- (NSString *)pathToCachedResponseDataForURL:(NSURL *)url
{
// Grab the file extension, if there is one. We do this so we can save the cached response with the same file extension - this is important if you want to display locally cached data in a web view
NSString *extension = [[url path] pathExtension];
// If the url doesn't have an extension, we'll add one so a webview can read it when locally cached
// If the url has the extension of a common web scripting language, we'll change the extension on the cached path to html for the same reason
if (![extension length] || [[[self class] fileExtensionsToHandleAsHTML] containsObject:[extension lowercaseString]]) {
extension = @"html";
}
return [self pathToFile:[[[self class] keyForURL:url] stringByAppendingPathExtension:extension]];
}
+ (NSArray *)fileExtensionsToHandleAsHTML
{
return fileExtensionsToHandleAsHTML;
}
- (NSString *)pathToCachedResponseHeadersForURL:(NSURL *)url
{
return [self pathToFile:[[[self class] keyForURL:url] stringByAppendingPathExtension:@"cachedheaders"]];
}
- (NSString *)pathToFile:(NSString *)file
{
[[self accessLock] lock];
if (![self storagePath]) {
[[self accessLock] unlock];
return nil;
}
NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
// Look in the session store
NSString *dataPath = [[[self storagePath] stringByAppendingPathComponent:sessionCacheFolder] stringByAppendingPathComponent:file];
if ([fileManager fileExistsAtPath:dataPath]) {
[[self accessLock] unlock];
return dataPath;
}
// Look in the permanent store
dataPath = [[[self storagePath] stringByAppendingPathComponent:permanentCacheFolder] stringByAppendingPathComponent:file];
if ([fileManager fileExistsAtPath:dataPath]) {
[[self accessLock] unlock];
return dataPath;
}
[[self accessLock] unlock];
return nil;
}
- (NSString *)pathToStoreCachedResponseDataForRequest:(ASIHTTPRequest *)request
{
[[self accessLock] lock];
if (![self storagePath]) {
[[self accessLock] unlock];
return nil;
}
NSString *path = [[self storagePath] stringByAppendingPathComponent:([request cacheStoragePolicy] == ASICacheForSessionDurationCacheStoragePolicy ? sessionCacheFolder : permanentCacheFolder)];
// Grab the file extension, if there is one. We do this so we can save the cached response with the same file extension - this is important if you want to display locally cached data in a web view
NSString *extension = [[[request url] path] pathExtension];
// If the url doesn't have an extension, we'll add one so a webview can read it when locally cached
// If the url has the extension of a common web scripting language, we'll change the extension on the cached path to html for the same reason
if (![extension length] || [[[self class] fileExtensionsToHandleAsHTML] containsObject:[extension lowercaseString]]) {
extension = @"html";
}
path = [path stringByAppendingPathComponent:[[[self class] keyForURL:[request url]] stringByAppendingPathExtension:extension]];
[[self accessLock] unlock];
return path;
}
- (NSString *)pathToStoreCachedResponseHeadersForRequest:(ASIHTTPRequest *)request
{
[[self accessLock] lock];
if (![self storagePath]) {
[[self accessLock] unlock];
return nil;
}
NSString *path = [[self storagePath] stringByAppendingPathComponent:([request cacheStoragePolicy] == ASICacheForSessionDurationCacheStoragePolicy ? sessionCacheFolder : permanentCacheFolder)];
path = [path stringByAppendingPathComponent:[[[self class] keyForURL:[request url]] stringByAppendingPathExtension:@"cachedheaders"]];
[[self accessLock] unlock];
return path;
}
- (void)removeCachedDataForURL:(NSURL *)url
{
[[self accessLock] lock];
if (![self storagePath]) {
[[self accessLock] unlock];
return;
}
NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
NSString *path = [self pathToCachedResponseHeadersForURL:url];
if (path) {
[fileManager removeItemAtPath:path error:NULL];
}
path = [self pathToCachedResponseDataForURL:url];
if (path) {
[fileManager removeItemAtPath:path error:NULL];
}
[[self accessLock] unlock];
}
- (void)removeCachedDataForRequest:(ASIHTTPRequest *)request
{
[self removeCachedDataForURL:[request url]];
}
- (BOOL)isCachedDataCurrentForRequest:(ASIHTTPRequest *)request
{
[[self accessLock] lock];
if (![self storagePath]) {
[[self accessLock] unlock];
return NO;
}
NSDictionary *cachedHeaders = [self cachedResponseHeadersForURL:[request url]];
if (!cachedHeaders) {
[[self accessLock] unlock];
return NO;
}
NSString *dataPath = [self pathToCachedResponseDataForURL:[request url]];
if (!dataPath) {
[[self accessLock] unlock];
return NO;
}
// New content is not different
if ([request responseStatusCode] == 304) {
[[self accessLock] unlock];
return YES;
}
// If we already have response headers for this request, check to see if the new content is different
// We check [request complete] so that we don't end up comparing response headers from a redirection with these
if ([request responseHeaders] && [request complete]) {
// If the Etag or Last-Modified date are different from the one we have, we'll have to fetch this resource again
NSArray *headersToCompare = [NSArray arrayWithObjects:@"Etag",@"Last-Modified",nil];
for (NSString *header in headersToCompare) {
if (![[[request responseHeaders] objectForKey:header] isEqualToString:[cachedHeaders objectForKey:header]]) {
[[self accessLock] unlock];
return NO;
}
}
}
if ([self shouldRespectCacheControlHeaders]) {
// Look for X-ASIHTTPRequest-Expires header to see if the content is out of date
NSNumber *expires = [cachedHeaders objectForKey:@"X-ASIHTTPRequest-Expires"];
if (expires) {
if ([[NSDate dateWithTimeIntervalSince1970:[expires doubleValue]] timeIntervalSinceNow] >= 0) {
[[self accessLock] unlock];
return YES;
}
}
// No explicit expiration time sent by the server
[[self accessLock] unlock];
return NO;
}
[[self accessLock] unlock];
return YES;
}
- (ASICachePolicy)defaultCachePolicy
{
[[self accessLock] lock];
ASICachePolicy cp = defaultCachePolicy;
[[self accessLock] unlock];
return cp;
}
- (void)setDefaultCachePolicy:(ASICachePolicy)cachePolicy
{
[[self accessLock] lock];
if (!cachePolicy) {
defaultCachePolicy = ASIAskServerIfModifiedWhenStaleCachePolicy;
} else {
defaultCachePolicy = cachePolicy;
}
[[self accessLock] unlock];
}
- (void)clearCachedResponsesForStoragePolicy:(ASICacheStoragePolicy)storagePolicy
{
[[self accessLock] lock];
if (![self storagePath]) {
[[self accessLock] unlock];
return;
}
NSString *path = [[self storagePath] stringByAppendingPathComponent:(storagePolicy == ASICacheForSessionDurationCacheStoragePolicy ? sessionCacheFolder : permanentCacheFolder)];
NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
BOOL isDirectory = NO;
BOOL exists = [fileManager fileExistsAtPath:path isDirectory:&isDirectory];
if (!exists || !isDirectory) {
[[self accessLock] unlock];
return;
}
NSError *error = nil;
NSArray *cacheFiles = [fileManager contentsOfDirectoryAtPath:path error:&error];
if (error) {
[[self accessLock] unlock];
[NSException raise:@"FailedToTraverseCacheDirectory" format:@"Listing cache directory failed at path '%@'",path];
}
for (NSString *file in cacheFiles) {
[fileManager removeItemAtPath:[path stringByAppendingPathComponent:file] error:&error];
if (error) {
[[self accessLock] unlock];
[NSException raise:@"FailedToRemoveCacheFile" format:@"Failed to remove cached data at path '%@'",path];
}
}
[[self accessLock] unlock];
}
+ (BOOL)serverAllowsResponseCachingForRequest:(ASIHTTPRequest *)request
{
NSString *cacheControl = [[[request responseHeaders] objectForKey:@"Cache-Control"] lowercaseString];
if (cacheControl) {
if ([cacheControl isEqualToString:@"no-cache"] || [cacheControl isEqualToString:@"no-store"]) {
return NO;
}
}
NSString *pragma = [[[request responseHeaders] objectForKey:@"Pragma"] lowercaseString];
if (pragma) {
if ([pragma isEqualToString:@"no-cache"]) {
return NO;
}
}
return YES;
}
+ (NSString *)keyForURL:(NSURL *)url
{
NSString *urlString = [url absoluteString];
if ([urlString length] == 0) {
return nil;
}
// Strip trailing slashes so http://allseeing-i.com/ASIHTTPRequest/ is cached the same as http://allseeing-i.com/ASIHTTPRequest
if ([[urlString substringFromIndex:[urlString length]-1] isEqualToString:@"/"]) {
urlString = [urlString substringToIndex:[urlString length]-1];
}
// Borrowed from: http://stackoverflow.com/questions/652300/using-md5-hash-on-a-string-in-cocoa
const char *cStr = [urlString UTF8String];
unsigned char result[16];
CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],result[8], result[9], result[10], result[11],result[12], result[13], result[14], result[15]];
}
- (BOOL)canUseCachedDataForRequest:(ASIHTTPRequest *)request
{
// Ensure the request is allowed to read from the cache
if ([request cachePolicy] & ASIDoNotReadFromCacheCachePolicy) {
return NO;
// If we don't want to load the request whatever happens, always pretend we have cached data even if we don't
} else if ([request cachePolicy] & ASIDontLoadCachePolicy) {
return YES;
}
NSDictionary *headers = [self cachedResponseHeadersForURL:[request url]];
if (!headers) {
return NO;
}
NSString *dataPath = [self pathToCachedResponseDataForURL:[request url]];
if (!dataPath) {
return NO;
}
// If we get here, we have cached data
// If we have cached data, we can use it
if ([request cachePolicy] & ASIOnlyLoadIfNotCachedCachePolicy) {
return YES;
// If we want to fallback to the cache after an error
} else if ([request complete] && [request cachePolicy] & ASIFallbackToCacheIfLoadFailsCachePolicy) {
return YES;
// If we have cached data that is current, we can use it
} else if ([request cachePolicy] & ASIAskServerIfModifiedWhenStaleCachePolicy) {
if ([self isCachedDataCurrentForRequest:request]) {
return YES;
}
// If we've got headers from a conditional GET and the cached data is still current, we can use it
} else if ([request cachePolicy] & ASIAskServerIfModifiedCachePolicy) {
if (![request responseHeaders]) {
return NO;
} else if ([self isCachedDataCurrentForRequest:request]) {
return YES;
}
}
return NO;
}
@synthesize storagePath;
@synthesize defaultCachePolicy;
@synthesize accessLock;
@synthesize shouldRespectCacheControlHeaders;
@end
| 009-20120511-zi | trunk/Zinipad/ASI/ASIDownloadCache.m | Objective-C | gpl3 | 17,761 |
//
// ASIInputStream.h
// Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
// Created by Ben Copsey on 10/08/2009.
// Copyright 2009 All-Seeing Interactive. All rights reserved.
//
#import <Foundation/Foundation.h>
@class ASIHTTPRequest;
// This is a wrapper for NSInputStream that pretends to be an NSInputStream itself
// Subclassing NSInputStream seems to be tricky, and may involve overriding undocumented methods, so we'll cheat instead.
// It is used by ASIHTTPRequest whenever we have a request body, and handles measuring and throttling the bandwidth used for uploading
@interface ASIInputStream : NSObject {
NSInputStream *stream;
ASIHTTPRequest *request;
}
+ (id)inputStreamWithFileAtPath:(NSString *)path request:(ASIHTTPRequest *)request;
+ (id)inputStreamWithData:(NSData *)data request:(ASIHTTPRequest *)request;
@property (retain, nonatomic) NSInputStream *stream;
@property (assign, nonatomic) ASIHTTPRequest *request;
@end
| 009-20120511-zi | trunk/Zinipad/ASI/ASIInputStream.h | Objective-C | gpl3 | 969 |
//
// ASIDataDecompressor.m
// Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
// Created by Ben Copsey on 17/08/2010.
// Copyright 2010 All-Seeing Interactive. All rights reserved.
//
#import "ASIDataDecompressor.h"
#import "ASIHTTPRequest.h"
#define DATA_CHUNK_SIZE 262144 // Deal with gzipped data in 256KB chunks
@interface ASIDataDecompressor ()
+ (NSError *)inflateErrorWithCode:(int)code;
@end;
@implementation ASIDataDecompressor
+ (id)decompressor
{
ASIDataDecompressor *decompressor = [[[self alloc] init] autorelease];
[decompressor setupStream];
return decompressor;
}
- (void)dealloc
{
if (streamReady) {
[self closeStream];
}
[super dealloc];
}
- (NSError *)setupStream
{
if (streamReady) {
return nil;
}
// Setup the inflate stream
zStream.zalloc = Z_NULL;
zStream.zfree = Z_NULL;
zStream.opaque = Z_NULL;
zStream.avail_in = 0;
zStream.next_in = 0;
int status = inflateInit2(&zStream, (15+32));
if (status != Z_OK) {
return [[self class] inflateErrorWithCode:status];
}
streamReady = YES;
return nil;
}
- (NSError *)closeStream
{
if (!streamReady) {
return nil;
}
// Close the inflate stream
streamReady = NO;
int status = inflateEnd(&zStream);
if (status != Z_OK) {
return [[self class] inflateErrorWithCode:status];
}
return nil;
}
- (NSData *)uncompressBytes:(Bytef *)bytes length:(NSUInteger)length error:(NSError **)err
{
if (length == 0) return nil;
NSUInteger halfLength = length/2;
NSMutableData *outputData = [NSMutableData dataWithLength:length+halfLength];
int status;
zStream.next_in = bytes;
zStream.avail_in = (unsigned int)length;
zStream.avail_out = 0;
NSInteger bytesProcessedAlready = zStream.total_out;
while (zStream.avail_in != 0) {
if (zStream.total_out-bytesProcessedAlready >= [outputData length]) {
[outputData increaseLengthBy:halfLength];
}
zStream.next_out = (Bytef*)[outputData mutableBytes] + zStream.total_out-bytesProcessedAlready;
zStream.avail_out = (unsigned int)([outputData length] - (zStream.total_out-bytesProcessedAlready));
status = inflate(&zStream, Z_NO_FLUSH);
if (status == Z_STREAM_END) {
break;
} else if (status != Z_OK) {
if (err) {
*err = [[self class] inflateErrorWithCode:status];
}
return nil;
}
}
// Set real length
[outputData setLength: zStream.total_out-bytesProcessedAlready];
return outputData;
}
+ (NSData *)uncompressData:(NSData*)compressedData error:(NSError **)err
{
NSError *theError = nil;
NSData *outputData = [[ASIDataDecompressor decompressor] uncompressBytes:(Bytef *)[compressedData bytes] length:[compressedData length] error:&theError];
if (theError) {
if (err) {
*err = theError;
}
return nil;
}
return outputData;
}
+ (BOOL)uncompressDataFromFile:(NSString *)sourcePath toFile:(NSString *)destinationPath error:(NSError **)err
{
NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
// Create an empty file at the destination path
if (![fileManager createFileAtPath:destinationPath contents:[NSData data] attributes:nil]) {
if (err) {
*err = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Decompression of %@ failed because we were to create a file at %@",sourcePath,destinationPath],NSLocalizedDescriptionKey,nil]];
}
return NO;
}
// Ensure the source file exists
if (![fileManager fileExistsAtPath:sourcePath]) {
if (err) {
*err = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Decompression of %@ failed the file does not exist",sourcePath],NSLocalizedDescriptionKey,nil]];
}
return NO;
}
UInt8 inputData[DATA_CHUNK_SIZE];
NSData *outputData;
NSInteger readLength;
NSError *theError = nil;
ASIDataDecompressor *decompressor = [ASIDataDecompressor decompressor];
NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath:sourcePath];
[inputStream open];
NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:destinationPath append:NO];
[outputStream open];
while ([decompressor streamReady]) {
// Read some data from the file
readLength = [inputStream read:inputData maxLength:DATA_CHUNK_SIZE];
// Make sure nothing went wrong
if ([inputStream streamStatus] == NSStreamEventErrorOccurred) {
if (err) {
*err = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Decompression of %@ failed because we were unable to read from the source data file",sourcePath],NSLocalizedDescriptionKey,[inputStream streamError],NSUnderlyingErrorKey,nil]];
}
[decompressor closeStream];
return NO;
}
// Have we reached the end of the input data?
if (!readLength) {
break;
}
// Attempt to inflate the chunk of data
outputData = [decompressor uncompressBytes:inputData length:readLength error:&theError];
if (theError) {
if (err) {
*err = theError;
}
[decompressor closeStream];
return NO;
}
// Write the inflated data out to the destination file
[outputStream write:(Bytef*)[outputData bytes] maxLength:[outputData length]];
// Make sure nothing went wrong
if ([inputStream streamStatus] == NSStreamEventErrorOccurred) {
if (err) {
*err = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Decompression of %@ failed because we were unable to write to the destination data file at %@",sourcePath,destinationPath],NSLocalizedDescriptionKey,[outputStream streamError],NSUnderlyingErrorKey,nil]];
}
[decompressor closeStream];
return NO;
}
}
[inputStream close];
[outputStream close];
NSError *error = [decompressor closeStream];
if (error) {
if (err) {
*err = error;
}
return NO;
}
return YES;
}
+ (NSError *)inflateErrorWithCode:(int)code
{
return [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Decompression of data failed with code %hi",code],NSLocalizedDescriptionKey,nil]];
}
@synthesize streamReady;
@end
| 009-20120511-zi | trunk/Zinipad/ASI/ASIDataDecompressor.m | Objective-C | gpl3 | 6,422 |
//
// ASINetworkQueue.h
// Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
// Created by Ben Copsey on 07/11/2008.
// Copyright 2008-2009 All-Seeing Interactive. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "ASIHTTPRequestDelegate.h"
#import "ASIProgressDelegate.h"
@interface ASINetworkQueue : NSOperationQueue <ASIProgressDelegate, ASIHTTPRequestDelegate, NSCopying> {
// Delegate will get didFail + didFinish messages (if set)
id delegate;
// Will be called when a request starts with the request as the argument
SEL requestDidStartSelector;
// Will be called when a request receives response headers
// Should take the form request:didRecieveResponseHeaders:, where the first argument is the request, and the second the headers dictionary
SEL requestDidReceiveResponseHeadersSelector;
// Will be called when a request is about to redirect
// Should take the form request:willRedirectToURL:, where the first argument is the request, and the second the new url
SEL requestWillRedirectSelector;
// Will be called when a request completes with the request as the argument
SEL requestDidFinishSelector;
// Will be called when a request fails with the request as the argument
SEL requestDidFailSelector;
// Will be called when the queue finishes with the queue as the argument
SEL queueDidFinishSelector;
// Upload progress indicator, probably an NSProgressIndicator or UIProgressView
id uploadProgressDelegate;
// Total amount uploaded so far for all requests in this queue
unsigned long long bytesUploadedSoFar;
// Total amount to be uploaded for all requests in this queue - requests add to this figure as they work out how much data they have to transmit
unsigned long long totalBytesToUpload;
// Download progress indicator, probably an NSProgressIndicator or UIProgressView
id downloadProgressDelegate;
// Total amount downloaded so far for all requests in this queue
unsigned long long bytesDownloadedSoFar;
// Total amount to be downloaded for all requests in this queue - requests add to this figure as they receive Content-Length headers
unsigned long long totalBytesToDownload;
// When YES, the queue will cancel all requests when a request fails. Default is YES
BOOL shouldCancelAllRequestsOnFailure;
//Number of real requests (excludes HEAD requests created to manage showAccurateProgress)
int requestsCount;
// When NO, this request will only update the progress indicator when it completes
// When YES, this request will update the progress indicator according to how much data it has received so far
// When YES, the queue will first perform HEAD requests for all GET requests in the queue, so it can calculate the total download size before it starts
// NO means better performance, because it skips this step for GET requests, and it won't waste time updating the progress indicator until a request completes
// Set to YES if the size of a requests in the queue varies greatly for much more accurate results
// Default for requests in the queue is NO
BOOL showAccurateProgress;
// Storage container for additional queue information.
NSDictionary *userInfo;
}
// Convenience constructor
+ (id)queue;
// Call this to reset a queue - it will cancel all operations, clear delegates, and suspend operation
- (void)reset;
// Used internally to manage HEAD requests when showAccurateProgress is YES, do not use!
- (void)addHEADOperation:(NSOperation *)operation;
// All ASINetworkQueues are paused when created so that total size can be calculated before the queue starts
// This method will start the queue
- (void)go;
@property (assign, nonatomic, setter=setUploadProgressDelegate:) id uploadProgressDelegate;
@property (assign, nonatomic, setter=setDownloadProgressDelegate:) id downloadProgressDelegate;
@property (assign) SEL requestDidStartSelector;
@property (assign) SEL requestDidReceiveResponseHeadersSelector;
@property (assign) SEL requestWillRedirectSelector;
@property (assign) SEL requestDidFinishSelector;
@property (assign) SEL requestDidFailSelector;
@property (assign) SEL queueDidFinishSelector;
@property (assign) BOOL shouldCancelAllRequestsOnFailure;
@property (assign) id delegate;
@property (assign) BOOL showAccurateProgress;
@property (assign, readonly) int requestsCount;
@property (retain) NSDictionary *userInfo;
@property (assign) unsigned long long bytesUploadedSoFar;
@property (assign) unsigned long long totalBytesToUpload;
@property (assign) unsigned long long bytesDownloadedSoFar;
@property (assign) unsigned long long totalBytesToDownload;
@end
| 009-20120511-zi | trunk/Zinipad/ASI/ASINetworkQueue.h | Objective-C | gpl3 | 4,621 |
//
// ASIDataCompressor.h
// Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
// Created by Ben Copsey on 17/08/2010.
// Copyright 2010 All-Seeing Interactive. All rights reserved.
//
// This is a helper class used by ASIHTTPRequest to handle deflating (compressing) data in memory and on disk
// You may also find it helpful if you need to deflate data and files yourself - see the class methods below
// Most of the zlib stuff is based on the sample code by Mark Adler available at http://zlib.net
#import <Foundation/Foundation.h>
#import <zlib.h>
@interface ASIDataCompressor : NSObject {
BOOL streamReady;
z_stream zStream;
}
// Convenience constructor will call setupStream for you
+ (id)compressor;
// Compress the passed chunk of data
// Passing YES for shouldFinish will finalize the deflated data - you must pass YES when you are on the last chunk of data
- (NSData *)compressBytes:(Bytef *)bytes length:(NSUInteger)length error:(NSError **)err shouldFinish:(BOOL)shouldFinish;
// Convenience method - pass it some data, and you'll get deflated data back
+ (NSData *)compressData:(NSData*)uncompressedData error:(NSError **)err;
// Convenience method - pass it a file containing the data to compress in sourcePath, and it will write deflated data to destinationPath
+ (BOOL)compressDataFromFile:(NSString *)sourcePath toFile:(NSString *)destinationPath error:(NSError **)err;
// Sets up zlib to handle the inflating. You only need to call this yourself if you aren't using the convenience constructor 'compressor'
- (NSError *)setupStream;
// Tells zlib to clean up. You need to call this if you need to cancel deflating part way through
// If deflating finishes or fails, this method will be called automatically
- (NSError *)closeStream;
@property (assign, readonly) BOOL streamReady;
@end
| 009-20120511-zi | trunk/Zinipad/ASI/ASIDataCompressor.h | Objective-C | gpl3 | 1,836 |
//
// ASINetworkQueue.m
// Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
// Created by Ben Copsey on 07/11/2008.
// Copyright 2008-2009 All-Seeing Interactive. All rights reserved.
//
#import "ASINetworkQueue.h"
#import "ASIHTTPRequest.h"
// Private stuff
@interface ASINetworkQueue ()
- (void)resetProgressDelegate:(id *)progressDelegate;
@property (assign) int requestsCount;
@end
@implementation ASINetworkQueue
- (id)init
{
self = [super init];
[self setShouldCancelAllRequestsOnFailure:YES];
[self setMaxConcurrentOperationCount:4];
[self setSuspended:YES];
return self;
}
+ (id)queue
{
return [[[self alloc] init] autorelease];
}
- (void)dealloc
{
//We need to clear the queue on any requests that haven't got around to cleaning up yet, as otherwise they'll try to let us know if something goes wrong, and we'll be long gone by then
for (ASIHTTPRequest *request in [self operations]) {
[request setQueue:nil];
}
[userInfo release];
[super dealloc];
}
- (void)setSuspended:(BOOL)suspend
{
[super setSuspended:suspend];
}
- (void)reset
{
[self cancelAllOperations];
[self setDelegate:nil];
[self setDownloadProgressDelegate:nil];
[self setUploadProgressDelegate:nil];
[self setRequestDidStartSelector:NULL];
[self setRequestDidReceiveResponseHeadersSelector:NULL];
[self setRequestDidFailSelector:NULL];
[self setRequestDidFinishSelector:NULL];
[self setQueueDidFinishSelector:NULL];
[self setSuspended:YES];
}
- (void)go
{
[self setSuspended:NO];
}
- (void)cancelAllOperations
{
[self setBytesUploadedSoFar:0];
[self setTotalBytesToUpload:0];
[self setBytesDownloadedSoFar:0];
[self setTotalBytesToDownload:0];
[super cancelAllOperations];
}
- (void)setUploadProgressDelegate:(id)newDelegate
{
uploadProgressDelegate = newDelegate;
[self resetProgressDelegate:&uploadProgressDelegate];
}
- (void)setDownloadProgressDelegate:(id)newDelegate
{
downloadProgressDelegate = newDelegate;
[self resetProgressDelegate:&downloadProgressDelegate];
}
- (void)resetProgressDelegate:(id *)progressDelegate
{
#if !TARGET_OS_IPHONE
// If the uploadProgressDelegate is an NSProgressIndicator, we set its MaxValue to 1.0 so we can treat it similarly to UIProgressViews
SEL selector = @selector(setMaxValue:);
if ([*progressDelegate respondsToSelector:selector]) {
double max = 1.0;
[ASIHTTPRequest performSelector:selector onTarget:progressDelegate withObject:nil amount:&max callerToRetain:nil];
}
selector = @selector(setDoubleValue:);
if ([*progressDelegate respondsToSelector:selector]) {
double value = 0.0;
[ASIHTTPRequest performSelector:selector onTarget:progressDelegate withObject:nil amount:&value callerToRetain:nil];
}
#else
SEL selector = @selector(setProgress:);
if ([*progressDelegate respondsToSelector:selector]) {
float value = 0.0f;
[ASIHTTPRequest performSelector:selector onTarget:progressDelegate withObject:nil amount:&value callerToRetain:nil];
}
#endif
}
- (void)addHEADOperation:(NSOperation *)operation
{
if ([operation isKindOfClass:[ASIHTTPRequest class]]) {
ASIHTTPRequest *request = (ASIHTTPRequest *)operation;
[request setRequestMethod:@"HEAD"];
[request setQueuePriority:10];
[request setShowAccurateProgress:YES];
[request setQueue:self];
// Important - we are calling NSOperation's add method - we don't want to add this as a normal request!
[super addOperation:request];
}
}
// Only add ASIHTTPRequests to this queue!!
- (void)addOperation:(NSOperation *)operation
{
if (![operation isKindOfClass:[ASIHTTPRequest class]]) {
[NSException raise:@"AttemptToAddInvalidRequest" format:@"Attempted to add an object that was not an ASIHTTPRequest to an ASINetworkQueue"];
}
[self setRequestsCount:[self requestsCount]+1];
ASIHTTPRequest *request = (ASIHTTPRequest *)operation;
if ([self showAccurateProgress]) {
// Force the request to build its body (this may change requestMethod)
[request buildPostBody];
// If this is a GET request and we want accurate progress, perform a HEAD request first to get the content-length
// We'll only do this before the queue is started
// If requests are added after the queue is started they will probably move the overall progress backwards anyway, so there's no value performing the HEAD requests first
// Instead, they'll update the total progress if and when they receive a content-length header
if ([[request requestMethod] isEqualToString:@"GET"]) {
if ([self isSuspended]) {
ASIHTTPRequest *HEADRequest = [request HEADRequest];
[self addHEADOperation:HEADRequest];
[request addDependency:HEADRequest];
if ([request shouldResetDownloadProgress]) {
[self resetProgressDelegate:&downloadProgressDelegate];
[request setShouldResetDownloadProgress:NO];
}
}
}
[request buildPostBody];
[self request:nil incrementUploadSizeBy:[request postLength]];
} else {
[self request:nil incrementDownloadSizeBy:1];
[self request:nil incrementUploadSizeBy:1];
}
// Tell the request not to increment the upload size when it starts, as we've already added its length
if ([request shouldResetUploadProgress]) {
[self resetProgressDelegate:&uploadProgressDelegate];
[request setShouldResetUploadProgress:NO];
}
[request setShowAccurateProgress:[self showAccurateProgress]];
[request setQueue:self];
[super addOperation:request];
}
- (void)requestStarted:(ASIHTTPRequest *)request
{
if ([self requestDidStartSelector]) {
[[self delegate] performSelector:[self requestDidStartSelector] withObject:request];
}
}
- (void)request:(ASIHTTPRequest *)request didReceiveResponseHeaders:(NSDictionary *)responseHeaders
{
if ([self requestDidReceiveResponseHeadersSelector]) {
[[self delegate] performSelector:[self requestDidReceiveResponseHeadersSelector] withObject:request withObject:responseHeaders];
}
}
- (void)request:(ASIHTTPRequest *)request willRedirectToURL:(NSURL *)newURL
{
if ([self requestWillRedirectSelector]) {
[[self delegate] performSelector:[self requestWillRedirectSelector] withObject:request withObject:newURL];
}
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
[self setRequestsCount:[self requestsCount]-1];
if ([self requestDidFinishSelector]) {
[[self delegate] performSelector:[self requestDidFinishSelector] withObject:request];
}
if ([self requestsCount] == 0) {
if ([self queueDidFinishSelector]) {
[[self delegate] performSelector:[self queueDidFinishSelector] withObject:self];
}
}
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
[self setRequestsCount:[self requestsCount]-1];
if ([self requestDidFailSelector]) {
[[self delegate] performSelector:[self requestDidFailSelector] withObject:request];
}
if ([self requestsCount] == 0) {
if ([self queueDidFinishSelector]) {
[[self delegate] performSelector:[self queueDidFinishSelector] withObject:self];
}
}
if ([self shouldCancelAllRequestsOnFailure] && [self requestsCount] > 0) {
[self cancelAllOperations];
}
}
- (void)request:(ASIHTTPRequest *)request didReceiveBytes:(long long)bytes
{
[self setBytesDownloadedSoFar:[self bytesDownloadedSoFar]+bytes];
if ([self downloadProgressDelegate]) {
[ASIHTTPRequest updateProgressIndicator:&downloadProgressDelegate withProgress:[self bytesDownloadedSoFar] ofTotal:[self totalBytesToDownload]];
}
}
- (void)request:(ASIHTTPRequest *)request didSendBytes:(long long)bytes
{
[self setBytesUploadedSoFar:[self bytesUploadedSoFar]+bytes];
if ([self uploadProgressDelegate]) {
[ASIHTTPRequest updateProgressIndicator:&uploadProgressDelegate withProgress:[self bytesUploadedSoFar] ofTotal:[self totalBytesToUpload]];
}
}
- (void)request:(ASIHTTPRequest *)request incrementDownloadSizeBy:(long long)newLength
{
[self setTotalBytesToDownload:[self totalBytesToDownload]+newLength];
}
- (void)request:(ASIHTTPRequest *)request incrementUploadSizeBy:(long long)newLength
{
[self setTotalBytesToUpload:[self totalBytesToUpload]+newLength];
}
// Since this queue takes over as the delegate for all requests it contains, it should forward authorisation requests to its own delegate
- (void)authenticationNeededForRequest:(ASIHTTPRequest *)request
{
if ([[self delegate] respondsToSelector:@selector(authenticationNeededForRequest:)]) {
[[self delegate] performSelector:@selector(authenticationNeededForRequest:) withObject:request];
}
}
- (void)proxyAuthenticationNeededForRequest:(ASIHTTPRequest *)request
{
if ([[self delegate] respondsToSelector:@selector(proxyAuthenticationNeededForRequest:)]) {
[[self delegate] performSelector:@selector(proxyAuthenticationNeededForRequest:) withObject:request];
}
}
- (BOOL)respondsToSelector:(SEL)selector
{
// We handle certain methods differently because whether our delegate implements them or not can affect how the request should behave
// If the delegate implements this, the request will stop to wait for credentials
if (selector == @selector(authenticationNeededForRequest:)) {
if ([[self delegate] respondsToSelector:@selector(authenticationNeededForRequest:)]) {
return YES;
}
return NO;
// If the delegate implements this, the request will to wait for credentials
} else if (selector == @selector(proxyAuthenticationNeededForRequest:)) {
if ([[self delegate] respondsToSelector:@selector(proxyAuthenticationNeededForRequest:)]) {
return YES;
}
return NO;
// If the delegate implements requestWillRedirectSelector, the request will stop to allow the delegate to change the url
} else if (selector == @selector(request:willRedirectToURL:)) {
if ([self requestWillRedirectSelector] && [[self delegate] respondsToSelector:[self requestWillRedirectSelector]]) {
return YES;
}
return NO;
}
return [super respondsToSelector:selector];
}
#pragma mark NSCopying
- (id)copyWithZone:(NSZone *)zone
{
ASINetworkQueue *newQueue = [[[self class] alloc] init];
[newQueue setDelegate:[self delegate]];
[newQueue setRequestDidStartSelector:[self requestDidStartSelector]];
[newQueue setRequestWillRedirectSelector:[self requestWillRedirectSelector]];
[newQueue setRequestDidReceiveResponseHeadersSelector:[self requestDidReceiveResponseHeadersSelector]];
[newQueue setRequestDidFinishSelector:[self requestDidFinishSelector]];
[newQueue setRequestDidFailSelector:[self requestDidFailSelector]];
[newQueue setQueueDidFinishSelector:[self queueDidFinishSelector]];
[newQueue setUploadProgressDelegate:[self uploadProgressDelegate]];
[newQueue setDownloadProgressDelegate:[self downloadProgressDelegate]];
[newQueue setShouldCancelAllRequestsOnFailure:[self shouldCancelAllRequestsOnFailure]];
[newQueue setShowAccurateProgress:[self showAccurateProgress]];
[newQueue setUserInfo:[[[self userInfo] copyWithZone:zone] autorelease]];
return newQueue;
}
@synthesize requestsCount;
@synthesize bytesUploadedSoFar;
@synthesize totalBytesToUpload;
@synthesize bytesDownloadedSoFar;
@synthesize totalBytesToDownload;
@synthesize shouldCancelAllRequestsOnFailure;
@synthesize uploadProgressDelegate;
@synthesize downloadProgressDelegate;
@synthesize requestDidStartSelector;
@synthesize requestDidReceiveResponseHeadersSelector;
@synthesize requestWillRedirectSelector;
@synthesize requestDidFinishSelector;
@synthesize requestDidFailSelector;
@synthesize queueDidFinishSelector;
@synthesize delegate;
@synthesize showAccurateProgress;
@synthesize userInfo;
@end
| 009-20120511-zi | trunk/Zinipad/ASI/ASINetworkQueue.m | Objective-C | gpl3 | 11,405 |
//
// ASIAuthenticationDialog.m
// Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
// Created by Ben Copsey on 21/08/2009.
// Copyright 2009 All-Seeing Interactive. All rights reserved.
//
#import "ASIAuthenticationDialog.h"
#import "ASIHTTPRequest.h"
#import <QuartzCore/QuartzCore.h>
static ASIAuthenticationDialog *sharedDialog = nil;
BOOL isDismissing = NO;
static NSMutableArray *requestsNeedingAuthentication = nil;
static const NSUInteger kUsernameRow = 0;
static const NSUInteger kUsernameSection = 0;
static const NSUInteger kPasswordRow = 1;
static const NSUInteger kPasswordSection = 0;
static const NSUInteger kDomainRow = 0;
static const NSUInteger kDomainSection = 1;
@implementation ASIAutorotatingViewController
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
return YES;
}
@end
@interface ASIAuthenticationDialog ()
- (void)showTitle;
- (void)show;
- (NSArray *)requestsRequiringTheseCredentials;
- (void)presentNextDialog;
- (void)keyboardWillShow:(NSNotification *)notification;
- (void)orientationChanged:(NSNotification *)notification;
- (void)cancelAuthenticationFromDialog:(id)sender;
- (void)loginWithCredentialsFromDialog:(id)sender;
@property (retain) UITableView *tableView;
@end
@implementation ASIAuthenticationDialog
#pragma mark init / dealloc
+ (void)initialize
{
if (self == [ASIAuthenticationDialog class]) {
requestsNeedingAuthentication = [[NSMutableArray array] retain];
}
}
+ (void)presentAuthenticationDialogForRequest:(ASIHTTPRequest *)theRequest
{
// No need for a lock here, this will always be called on the main thread
if (!sharedDialog) {
sharedDialog = [[self alloc] init];
[sharedDialog setRequest:theRequest];
if ([theRequest authenticationNeeded] == ASIProxyAuthenticationNeeded) {
[sharedDialog setType:ASIProxyAuthenticationType];
} else {
[sharedDialog setType:ASIStandardAuthenticationType];
}
[sharedDialog show];
} else {
[requestsNeedingAuthentication addObject:theRequest];
}
}
- (id)init
{
if ((self = [self initWithNibName:nil bundle:nil])) {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
#endif
if (![UIDevice currentDevice].generatesDeviceOrientationNotifications) {
[[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
[self setDidEnableRotationNotifications:YES];
}
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationChanged:) name:UIDeviceOrientationDidChangeNotification object:nil];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2
}
#endif
}
return self;
}
- (void)dealloc
{
if ([self didEnableRotationNotifications]) {
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIDeviceOrientationDidChangeNotification object:nil];
}
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
[request release];
[tableView release];
[presentingController.view removeFromSuperview];
[presentingController release];
[super dealloc];
}
#pragma mark keyboard notifications
- (void)keyboardWillShow:(NSNotification *)notification
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
#endif
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_3_2
NSValue *keyboardBoundsValue = [[notification userInfo] objectForKey:UIKeyboardFrameEndUserInfoKey];
#else
NSValue *keyboardBoundsValue = [[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey];
#endif
CGRect keyboardBounds;
[keyboardBoundsValue getValue:&keyboardBounds];
UIEdgeInsets e = UIEdgeInsetsMake(0, 0, keyboardBounds.size.height, 0);
[[self tableView] setScrollIndicatorInsets:e];
[[self tableView] setContentInset:e];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2
}
#endif
}
// Manually handles orientation changes on iPhone
- (void)orientationChanged:(NSNotification *)notification
{
[self showTitle];
UIInterfaceOrientation o = (UIInterfaceOrientation)[[UIApplication sharedApplication] statusBarOrientation];
CGFloat angle = 0;
switch (o) {
case UIDeviceOrientationLandscapeLeft: angle = 90; break;
case UIDeviceOrientationLandscapeRight: angle = -90; break;
case UIDeviceOrientationPortraitUpsideDown: angle = 180; break;
default: break;
}
CGRect f = [[UIScreen mainScreen] applicationFrame];
// Swap the frame height and width if necessary
if (UIDeviceOrientationIsLandscape(o)) {
CGFloat t;
t = f.size.width;
f.size.width = f.size.height;
f.size.height = t;
}
CGAffineTransform previousTransform = self.view.layer.affineTransform;
CGAffineTransform newTransform = CGAffineTransformMakeRotation((CGFloat)(angle * M_PI / 180.0));
// Reset the transform so we can set the size
self.view.layer.affineTransform = CGAffineTransformIdentity;
self.view.frame = (CGRect){ { 0, 0 }, f.size};
// Revert to the previous transform for correct animation
self.view.layer.affineTransform = previousTransform;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3];
// Set the new transform
self.view.layer.affineTransform = newTransform;
// Fix the view origin
self.view.frame = (CGRect){ { f.origin.x, f.origin.y },self.view.frame.size};
[UIView commitAnimations];
}
#pragma mark utilities
- (UIViewController *)presentingController
{
if (!presentingController) {
presentingController = [[ASIAutorotatingViewController alloc] initWithNibName:nil bundle:nil];
// Attach to the window, but don't interfere.
UIWindow *window = [[[UIApplication sharedApplication] windows] objectAtIndex:0];
[window addSubview:[presentingController view]];
[[presentingController view] setFrame:CGRectZero];
[[presentingController view] setUserInteractionEnabled:NO];
}
return presentingController;
}
- (UITextField *)textFieldInRow:(NSUInteger)row section:(NSUInteger)section
{
return [[[[[self tableView] cellForRowAtIndexPath:
[NSIndexPath indexPathForRow:row inSection:section]]
contentView] subviews] objectAtIndex:0];
}
- (UITextField *)usernameField
{
return [self textFieldInRow:kUsernameRow section:kUsernameSection];
}
- (UITextField *)passwordField
{
return [self textFieldInRow:kPasswordRow section:kPasswordSection];
}
- (UITextField *)domainField
{
return [self textFieldInRow:kDomainRow section:kDomainSection];
}
#pragma mark show / dismiss
+ (void)dismiss
{
if ([sharedDialog respondsToSelector:@selector(presentingViewController)])
[[sharedDialog presentingViewController] dismissModalViewControllerAnimated:YES];
else
[[sharedDialog parentViewController] dismissModalViewControllerAnimated:YES];
}
- (void)viewDidDisappear:(BOOL)animated
{
[self retain];
[sharedDialog release];
sharedDialog = nil;
[self performSelector:@selector(presentNextDialog) withObject:nil afterDelay:0];
[self release];
}
- (void)dismiss
{
if (self == sharedDialog) {
[[self class] dismiss];
} else {
if ([self respondsToSelector:@selector(presentingViewController)])
[[self presentingViewController] dismissModalViewControllerAnimated:YES];
else
[[self parentViewController] dismissModalViewControllerAnimated:YES];
}
}
- (void)showTitle
{
UINavigationBar *navigationBar = [[[self view] subviews] objectAtIndex:0];
UINavigationItem *navItem = [[navigationBar items] objectAtIndex:0];
if (UIInterfaceOrientationIsPortrait([[UIDevice currentDevice] orientation])) {
// Setup the title
if ([self type] == ASIProxyAuthenticationType) {
[navItem setPrompt:@"Login to this secure proxy server."];
} else {
[navItem setPrompt:@"Login to this secure server."];
}
} else {
[navItem setPrompt:nil];
}
[navigationBar sizeToFit];
CGRect f = [[self view] bounds];
f.origin.y = [navigationBar frame].size.height;
f.size.height -= f.origin.y;
[[self tableView] setFrame:f];
}
- (void)show
{
// Remove all subviews
UIView *v;
while ((v = [[[self view] subviews] lastObject])) {
[v removeFromSuperview];
}
// Setup toolbar
UINavigationBar *bar = [[[UINavigationBar alloc] init] autorelease];
[bar setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
UINavigationItem *navItem = [[[UINavigationItem alloc] init] autorelease];
bar.items = [NSArray arrayWithObject:navItem];
[[self view] addSubview:bar];
[self showTitle];
// Setup toolbar buttons
if ([self type] == ASIProxyAuthenticationType) {
[navItem setTitle:[[self request] proxyHost]];
} else {
[navItem setTitle:[[[self request] url] host]];
}
[navItem setLeftBarButtonItem:[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelAuthenticationFromDialog:)] autorelease]];
[navItem setRightBarButtonItem:[[[UIBarButtonItem alloc] initWithTitle:@"Login" style:UIBarButtonItemStyleDone target:self action:@selector(loginWithCredentialsFromDialog:)] autorelease]];
// We show the login form in a table view, similar to Safari's authentication dialog
[bar sizeToFit];
CGRect f = [[self view] bounds];
f.origin.y = [bar frame].size.height;
f.size.height -= f.origin.y;
[self setTableView:[[[UITableView alloc] initWithFrame:f style:UITableViewStyleGrouped] autorelease]];
[[self tableView] setDelegate:self];
[[self tableView] setDataSource:self];
[[self tableView] setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
[[self view] addSubview:[self tableView]];
// Force reload the table content, and focus the first field to show the keyboard
[[self tableView] reloadData];
[[[[[self tableView] cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]].contentView subviews] objectAtIndex:0] becomeFirstResponder];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
[self setModalPresentationStyle:UIModalPresentationFormSheet];
}
#endif
[[self presentingController] presentModalViewController:self animated:YES];
}
#pragma mark button callbacks
- (void)cancelAuthenticationFromDialog:(id)sender
{
for (ASIHTTPRequest *theRequest in [self requestsRequiringTheseCredentials]) {
[theRequest cancelAuthentication];
[requestsNeedingAuthentication removeObject:theRequest];
}
[self dismiss];
}
- (NSArray *)requestsRequiringTheseCredentials
{
NSMutableArray *requestsRequiringTheseCredentials = [NSMutableArray array];
NSURL *requestURL = [[self request] url];
for (ASIHTTPRequest *otherRequest in requestsNeedingAuthentication) {
NSURL *theURL = [otherRequest url];
if (([otherRequest authenticationNeeded] == [[self request] authenticationNeeded]) && [[theURL host] isEqualToString:[requestURL host]] && ([theURL port] == [requestURL port] || ([requestURL port] && [[theURL port] isEqualToNumber:[requestURL port]])) && [[theURL scheme] isEqualToString:[requestURL scheme]] && ((![otherRequest authenticationRealm] && ![[self request] authenticationRealm]) || ([otherRequest authenticationRealm] && [[self request] authenticationRealm] && [[[self request] authenticationRealm] isEqualToString:[otherRequest authenticationRealm]]))) {
[requestsRequiringTheseCredentials addObject:otherRequest];
}
}
[requestsRequiringTheseCredentials addObject:[self request]];
return requestsRequiringTheseCredentials;
}
- (void)presentNextDialog
{
if ([requestsNeedingAuthentication count]) {
ASIHTTPRequest *nextRequest = [requestsNeedingAuthentication objectAtIndex:0];
[requestsNeedingAuthentication removeObjectAtIndex:0];
[[self class] presentAuthenticationDialogForRequest:nextRequest];
}
}
- (void)loginWithCredentialsFromDialog:(id)sender
{
for (ASIHTTPRequest *theRequest in [self requestsRequiringTheseCredentials]) {
NSString *username = [[self usernameField] text];
NSString *password = [[self passwordField] text];
if (username == nil) { username = @""; }
if (password == nil) { password = @""; }
if ([self type] == ASIProxyAuthenticationType) {
[theRequest setProxyUsername:username];
[theRequest setProxyPassword:password];
} else {
[theRequest setUsername:username];
[theRequest setPassword:password];
}
// Handle NTLM domains
NSString *scheme = ([self type] == ASIStandardAuthenticationType) ? [[self request] authenticationScheme] : [[self request] proxyAuthenticationScheme];
if ([scheme isEqualToString:(NSString *)kCFHTTPAuthenticationSchemeNTLM]) {
NSString *domain = [[self domainField] text];
if ([self type] == ASIProxyAuthenticationType) {
[theRequest setProxyDomain:domain];
} else {
[theRequest setDomain:domain];
}
}
[theRequest retryUsingSuppliedCredentials];
[requestsNeedingAuthentication removeObject:theRequest];
}
[self dismiss];
}
#pragma mark table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)aTableView
{
NSString *scheme = ([self type] == ASIStandardAuthenticationType) ? [[self request] authenticationScheme] : [[self request] proxyAuthenticationScheme];
if ([scheme isEqualToString:(NSString *)kCFHTTPAuthenticationSchemeNTLM]) {
return 2;
}
return 1;
}
- (CGFloat)tableView:(UITableView *)aTableView heightForFooterInSection:(NSInteger)section
{
if (section == [self numberOfSectionsInTableView:aTableView]-1) {
return 30;
}
return 0;
}
- (CGFloat)tableView:(UITableView *)aTableView heightForHeaderInSection:(NSInteger)section
{
if (section == 0) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_3_2
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
return 54;
}
#endif
return 30;
}
return 0;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if (section == 0) {
return [[self request] authenticationRealm];
}
return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
#if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_3_0
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil] autorelease];
#else
UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:CGRectMake(0,0,0,0) reuseIdentifier:nil] autorelease];
#endif
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
CGRect f = CGRectInset([cell bounds], 10, 10);
UITextField *textField = [[[UITextField alloc] initWithFrame:f] autorelease];
[textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
[textField setAutocapitalizationType:UITextAutocapitalizationTypeNone];
[textField setAutocorrectionType:UITextAutocorrectionTypeNo];
NSUInteger s = [indexPath section];
NSUInteger r = [indexPath row];
if (s == kUsernameSection && r == kUsernameRow) {
[textField setPlaceholder:@"User"];
} else if (s == kPasswordSection && r == kPasswordRow) {
[textField setPlaceholder:@"Password"];
[textField setSecureTextEntry:YES];
} else if (s == kDomainSection && r == kDomainRow) {
[textField setPlaceholder:@"Domain"];
}
[cell.contentView addSubview:textField];
return cell;
}
- (NSInteger)tableView:(UITableView *)aTableView numberOfRowsInSection:(NSInteger)section
{
if (section == 0) {
return 2;
} else {
return 1;
}
}
- (NSString *)tableView:(UITableView *)aTableView titleForFooterInSection:(NSInteger)section
{
if (section == [self numberOfSectionsInTableView:aTableView]-1) {
// If we're using Basic authentication and the connection is not using SSL, we'll show the plain text message
if ([[[self request] authenticationScheme] isEqualToString:(NSString *)kCFHTTPAuthenticationSchemeBasic] && ![[[[self request] url] scheme] isEqualToString:@"https"]) {
return @"Password will be sent in the clear.";
// We are using Digest, NTLM, or any scheme over SSL
} else {
return @"Password will be sent securely.";
}
}
return nil;
}
#pragma mark -
@synthesize request;
@synthesize type;
@synthesize tableView;
@synthesize didEnableRotationNotifications;
@synthesize presentingController;
@end
| 009-20120511-zi | trunk/Zinipad/ASI/ASIAuthenticationDialog.m | Objective-C | gpl3 | 16,202 |
//
// ASIHTTPRequest.h
//
// Created by Ben Copsey on 04/10/2007.
// Copyright 2007-2011 All-Seeing Interactive. All rights reserved.
//
// A guide to the main features is available at:
// http://allseeing-i.com/ASIHTTPRequest
//
// Portions are based on the ImageClient example from Apple:
// See: http://developer.apple.com/samplecode/ImageClient/listing37.html
#import <Foundation/Foundation.h>
#if TARGET_OS_IPHONE
#import <CFNetwork/CFNetwork.h>
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
#import <UIKit/UIKit.h> // Necessary for background task support
#endif
#endif
#import <stdio.h>
#import "ASIHTTPRequestConfig.h"
#import "ASIHTTPRequestDelegate.h"
#import "ASIProgressDelegate.h"
#import "ASICacheDelegate.h"
@class ASIDataDecompressor;
extern NSString *ASIHTTPRequestVersion;
// Make targeting different platforms more reliable
// See: http://www.blumtnwerx.com/blog/2009/06/cross-sdk-code-hygiene-in-xcode/
#ifndef __IPHONE_3_2
#define __IPHONE_3_2 30200
#endif
#ifndef __IPHONE_4_0
#define __IPHONE_4_0 40000
#endif
#ifndef __MAC_10_5
#define __MAC_10_5 1050
#endif
#ifndef __MAC_10_6
#define __MAC_10_6 1060
#endif
typedef enum _ASIAuthenticationState {
ASINoAuthenticationNeededYet = 0,
ASIHTTPAuthenticationNeeded = 1,
ASIProxyAuthenticationNeeded = 2
} ASIAuthenticationState;
typedef enum _ASINetworkErrorType {
ASIConnectionFailureErrorType = 1,
ASIRequestTimedOutErrorType = 2,
ASIAuthenticationErrorType = 3,
ASIRequestCancelledErrorType = 4,
ASIUnableToCreateRequestErrorType = 5,
ASIInternalErrorWhileBuildingRequestType = 6,
ASIInternalErrorWhileApplyingCredentialsType = 7,
ASIFileManagementError = 8,
ASITooMuchRedirectionErrorType = 9,
ASIUnhandledExceptionError = 10,
ASICompressionError = 11
} ASINetworkErrorType;
// The error domain that all errors generated by ASIHTTPRequest use
extern NSString* const NetworkRequestErrorDomain;
// You can use this number to throttle upload and download bandwidth in iPhone OS apps send or receive a large amount of data
// This may help apps that might otherwise be rejected for inclusion into the app store for using excessive bandwidth
// This number is not official, as far as I know there is no officially documented bandwidth limit
extern unsigned long const ASIWWANBandwidthThrottleAmount;
#if NS_BLOCKS_AVAILABLE
typedef void (^ASIBasicBlock)(void);
typedef void (^ASIHeadersBlock)(NSDictionary *responseHeaders);
typedef void (^ASISizeBlock)(long long size);
typedef void (^ASIProgressBlock)(unsigned long long size, unsigned long long total);
typedef void (^ASIDataBlock)(NSData *data);
#endif
@interface ASIHTTPRequest : NSOperation <NSCopying> {
// The url for this operation, should include GET params in the query string where appropriate
NSURL *url;
// Will always contain the original url used for making the request (the value of url can change when a request is redirected)
NSURL *originalURL;
// Temporarily stores the url we are about to redirect to. Will be nil again when we do redirect
NSURL *redirectURL;
// The delegate - will be notified of various changes in state via the ASIHTTPRequestDelegate protocol
id <ASIHTTPRequestDelegate> delegate;
// Another delegate that is also notified of request status changes and progress updates
// Generally, you won't use this directly, but ASINetworkQueue sets itself as the queue so it can proxy updates to its own delegates
// NOTE: WILL BE RETAINED BY THE REQUEST
id <ASIHTTPRequestDelegate, ASIProgressDelegate> queue;
// HTTP method to use (eg: GET / POST / PUT / DELETE / HEAD etc). Defaults to GET
NSString *requestMethod;
// Request body - only used when the whole body is stored in memory (shouldStreamPostDataFromDisk is false)
NSMutableData *postBody;
// gzipped request body used when shouldCompressRequestBody is YES
NSData *compressedPostBody;
// When true, post body will be streamed from a file on disk, rather than loaded into memory at once (useful for large uploads)
// Automatically set to true in ASIFormDataRequests when using setFile:forKey:
BOOL shouldStreamPostDataFromDisk;
// Path to file used to store post body (when shouldStreamPostDataFromDisk is true)
// You can set this yourself - useful if you want to PUT a file from local disk
NSString *postBodyFilePath;
// Path to a temporary file used to store a deflated post body (when shouldCompressPostBody is YES)
NSString *compressedPostBodyFilePath;
// Set to true when ASIHTTPRequest automatically created a temporary file containing the request body (when true, the file at postBodyFilePath will be deleted at the end of the request)
BOOL didCreateTemporaryPostDataFile;
// Used when writing to the post body when shouldStreamPostDataFromDisk is true (via appendPostData: or appendPostDataFromFile:)
NSOutputStream *postBodyWriteStream;
// Used for reading from the post body when sending the request
NSInputStream *postBodyReadStream;
// Dictionary for custom HTTP request headers
NSMutableDictionary *requestHeaders;
// Set to YES when the request header dictionary has been populated, used to prevent this happening more than once
BOOL haveBuiltRequestHeaders;
// Will be populated with HTTP response headers from the server
NSDictionary *responseHeaders;
// Can be used to manually insert cookie headers to a request, but it's more likely that sessionCookies will do this for you
NSMutableArray *requestCookies;
// Will be populated with cookies
NSArray *responseCookies;
// If use useCookiePersistence is true, network requests will present valid cookies from previous requests
BOOL useCookiePersistence;
// If useKeychainPersistence is true, network requests will attempt to read credentials from the keychain, and will save them in the keychain when they are successfully presented
BOOL useKeychainPersistence;
// If useSessionPersistence is true, network requests will save credentials and reuse for the duration of the session (until clearSession is called)
BOOL useSessionPersistence;
// If allowCompressedResponse is true, requests will inform the server they can accept compressed data, and will automatically decompress gzipped responses. Default is true.
BOOL allowCompressedResponse;
// If shouldCompressRequestBody is true, the request body will be gzipped. Default is false.
// You will probably need to enable this feature on your webserver to make this work. Tested with apache only.
BOOL shouldCompressRequestBody;
// When downloadDestinationPath is set, the result of this request will be downloaded to the file at this location
// If downloadDestinationPath is not set, download data will be stored in memory
NSString *downloadDestinationPath;
// The location that files will be downloaded to. Once a download is complete, files will be decompressed (if necessary) and moved to downloadDestinationPath
NSString *temporaryFileDownloadPath;
// If the response is gzipped and shouldWaitToInflateCompressedResponses is NO, a file will be created at this path containing the inflated response as it comes in
NSString *temporaryUncompressedDataDownloadPath;
// Used for writing data to a file when downloadDestinationPath is set
NSOutputStream *fileDownloadOutputStream;
NSOutputStream *inflatedFileDownloadOutputStream;
// When the request fails or completes successfully, complete will be true
BOOL complete;
// external "finished" indicator, subject of KVO notifications; updates after 'complete'
BOOL finished;
// True if our 'cancel' selector has been called
BOOL cancelled;
// If an error occurs, error will contain an NSError
// If error code is = ASIConnectionFailureErrorType (1, Connection failure occurred) - inspect [[error userInfo] objectForKey:NSUnderlyingErrorKey] for more information
NSError *error;
// Username and password used for authentication
NSString *username;
NSString *password;
// User-Agent for this request
NSString *userAgentString;
// Domain used for NTLM authentication
NSString *domain;
// Username and password used for proxy authentication
NSString *proxyUsername;
NSString *proxyPassword;
// Domain used for NTLM proxy authentication
NSString *proxyDomain;
// Delegate for displaying upload progress (usually an NSProgressIndicator, but you can supply a different object and handle this yourself)
id <ASIProgressDelegate> uploadProgressDelegate;
// Delegate for displaying download progress (usually an NSProgressIndicator, but you can supply a different object and handle this yourself)
id <ASIProgressDelegate> downloadProgressDelegate;
// Whether we've seen the headers of the response yet
BOOL haveExaminedHeaders;
// Data we receive will be stored here. Data may be compressed unless allowCompressedResponse is false - you should use [request responseData] instead in most cases
NSMutableData *rawResponseData;
// Used for sending and receiving data
CFHTTPMessageRef request;
NSInputStream *readStream;
// Used for authentication
CFHTTPAuthenticationRef requestAuthentication;
NSDictionary *requestCredentials;
// Used during NTLM authentication
int authenticationRetryCount;
// Authentication scheme (Basic, Digest, NTLM)
// If you are using Basic authentication and want to force ASIHTTPRequest to send an authorization header without waiting for a 401, you must set this to (NSString *)kCFHTTPAuthenticationSchemeBasic
NSString *authenticationScheme;
// Realm for authentication when credentials are required
NSString *authenticationRealm;
// When YES, ASIHTTPRequest will present a dialog allowing users to enter credentials when no-matching credentials were found for a server that requires authentication
// The dialog will not be shown if your delegate responds to authenticationNeededForRequest:
// Default is NO.
BOOL shouldPresentAuthenticationDialog;
// When YES, ASIHTTPRequest will present a dialog allowing users to enter credentials when no-matching credentials were found for a proxy server that requires authentication
// The dialog will not be shown if your delegate responds to proxyAuthenticationNeededForRequest:
// Default is YES (basically, because most people won't want the hassle of adding support for authenticating proxies to their apps)
BOOL shouldPresentProxyAuthenticationDialog;
// Used for proxy authentication
CFHTTPAuthenticationRef proxyAuthentication;
NSDictionary *proxyCredentials;
// Used during authentication with an NTLM proxy
int proxyAuthenticationRetryCount;
// Authentication scheme for the proxy (Basic, Digest, NTLM)
NSString *proxyAuthenticationScheme;
// Realm for proxy authentication when credentials are required
NSString *proxyAuthenticationRealm;
// HTTP status code, eg: 200 = OK, 404 = Not found etc
int responseStatusCode;
// Description of the HTTP status code
NSString *responseStatusMessage;
// Size of the response
unsigned long long contentLength;
// Size of the partially downloaded content
unsigned long long partialDownloadSize;
// Size of the POST payload
unsigned long long postLength;
// The total amount of downloaded data
unsigned long long totalBytesRead;
// The total amount of uploaded data
unsigned long long totalBytesSent;
// Last amount of data read (used for incrementing progress)
unsigned long long lastBytesRead;
// Last amount of data sent (used for incrementing progress)
unsigned long long lastBytesSent;
// This lock prevents the operation from being cancelled at an inopportune moment
NSRecursiveLock *cancelledLock;
// Called on the delegate (if implemented) when the request starts. Default is requestStarted:
SEL didStartSelector;
// Called on the delegate (if implemented) when the request receives response headers. Default is request:didReceiveResponseHeaders:
SEL didReceiveResponseHeadersSelector;
// Called on the delegate (if implemented) when the request receives a Location header and shouldRedirect is YES
// The delegate can then change the url if needed, and can restart the request by calling [request redirectToURL:], or simply cancel it
SEL willRedirectSelector;
// Called on the delegate (if implemented) when the request completes successfully. Default is requestFinished:
SEL didFinishSelector;
// Called on the delegate (if implemented) when the request fails. Default is requestFailed:
SEL didFailSelector;
// Called on the delegate (if implemented) when the request receives data. Default is request:didReceiveData:
// If you set this and implement the method in your delegate, you must handle the data yourself - ASIHTTPRequest will not populate responseData or write the data to downloadDestinationPath
SEL didReceiveDataSelector;
// Used for recording when something last happened during the request, we will compare this value with the current date to time out requests when appropriate
NSDate *lastActivityTime;
// Number of seconds to wait before timing out - default is 10
NSTimeInterval timeOutSeconds;
// Will be YES when a HEAD request will handle the content-length before this request starts
BOOL shouldResetUploadProgress;
BOOL shouldResetDownloadProgress;
// Used by HEAD requests when showAccurateProgress is YES to preset the content-length for this request
ASIHTTPRequest *mainRequest;
// When NO, this request will only update the progress indicator when it completes
// When YES, this request will update the progress indicator according to how much data it has received so far
// The default for requests is YES
// Also see the comments in ASINetworkQueue.h
BOOL showAccurateProgress;
// Used to ensure the progress indicator is only incremented once when showAccurateProgress = NO
BOOL updatedProgress;
// Prevents the body of the post being built more than once (largely for subclasses)
BOOL haveBuiltPostBody;
// Used internally, may reflect the size of the internal buffer used by CFNetwork
// POST / PUT operations with body sizes greater than uploadBufferSize will not timeout unless more than uploadBufferSize bytes have been sent
// Likely to be 32KB on iPhone 3.0, 128KB on Mac OS X Leopard and iPhone 2.2.x
unsigned long long uploadBufferSize;
// Text encoding for responses that do not send a Content-Type with a charset value. Defaults to NSISOLatin1StringEncoding
NSStringEncoding defaultResponseEncoding;
// The text encoding of the response, will be defaultResponseEncoding if the server didn't specify. Can't be set.
NSStringEncoding responseEncoding;
// Tells ASIHTTPRequest not to delete partial downloads, and allows it to use an existing file to resume a download. Defaults to NO.
BOOL allowResumeForFileDownloads;
// Custom user information associated with the request (not sent to the server)
NSDictionary *userInfo;
NSInteger tag;
// Use HTTP 1.0 rather than 1.1 (defaults to false)
BOOL useHTTPVersionOne;
// When YES, requests will automatically redirect when they get a HTTP 30x header (defaults to YES)
BOOL shouldRedirect;
// Used internally to tell the main loop we need to stop and retry with a new url
BOOL needsRedirect;
// Incremented every time this request redirects. When it reaches 5, we give up
int redirectCount;
// When NO, requests will not check the secure certificate is valid (use for self-signed certificates during development, DO NOT USE IN PRODUCTION) Default is YES
BOOL validatesSecureCertificate;
// If not nil and the URL scheme is https, CFNetwork configured to supply a client certificate
SecIdentityRef clientCertificateIdentity;
NSArray *clientCertificates;
// Details on the proxy to use - you could set these yourself, but it's probably best to let ASIHTTPRequest detect the system proxy settings
NSString *proxyHost;
int proxyPort;
// ASIHTTPRequest will assume kCFProxyTypeHTTP if the proxy type could not be automatically determined
// Set to kCFProxyTypeSOCKS if you are manually configuring a SOCKS proxy
NSString *proxyType;
// URL for a PAC (Proxy Auto Configuration) file. If you want to set this yourself, it's probably best if you use a local file
NSURL *PACurl;
// See ASIAuthenticationState values above. 0 == default == No authentication needed yet
ASIAuthenticationState authenticationNeeded;
// When YES, ASIHTTPRequests will present credentials from the session store for requests to the same server before being asked for them
// This avoids an extra round trip for requests after authentication has succeeded, which is much for efficient for authenticated requests with large bodies, or on slower connections
// Set to NO to only present credentials when explicitly asked for them
// This only affects credentials stored in the session cache when useSessionPersistence is YES. Credentials from the keychain are never presented unless the server asks for them
// Default is YES
// For requests using Basic authentication, set authenticationScheme to (NSString *)kCFHTTPAuthenticationSchemeBasic, and credentials can be sent on the very first request when shouldPresentCredentialsBeforeChallenge is YES
BOOL shouldPresentCredentialsBeforeChallenge;
// YES when the request hasn't finished yet. Will still be YES even if the request isn't doing anything (eg it's waiting for delegate authentication). READ-ONLY
BOOL inProgress;
// Used internally to track whether the stream is scheduled on the run loop or not
// Bandwidth throttling can unschedule the stream to slow things down while a request is in progress
BOOL readStreamIsScheduled;
// Set to allow a request to automatically retry itself on timeout
// Default is zero - timeout will stop the request
int numberOfTimesToRetryOnTimeout;
// The number of times this request has retried (when numberOfTimesToRetryOnTimeout > 0)
int retryCount;
// Temporarily set to YES when a closed connection forces a retry (internally, this stops ASIHTTPRequest cleaning up a temporary post body)
BOOL willRetryRequest;
// When YES, requests will keep the connection to the server alive for a while to allow subsequent requests to re-use it for a substantial speed-boost
// Persistent connections will not be used if the server explicitly closes the connection
// Default is YES
BOOL shouldAttemptPersistentConnection;
// Number of seconds to keep an inactive persistent connection open on the client side
// Default is 60
// If we get a keep-alive header, this is this value is replaced with how long the server told us to keep the connection around
// A future date is created from this and used for expiring the connection, this is stored in connectionInfo's expires value
NSTimeInterval persistentConnectionTimeoutSeconds;
// Set to yes when an appropriate keep-alive header is found
BOOL connectionCanBeReused;
// Stores information about the persistent connection that is currently in use.
// It may contain:
// * The id we set for a particular connection, incremented every time we want to specify that we need a new connection
// * The date that connection should expire
// * A host, port and scheme for the connection. These are used to determine whether that connection can be reused by a subsequent request (all must match the new request)
// * An id for the request that is currently using the connection. This is used for determining if a connection is available or not (we store a number rather than a reference to the request so we don't need to hang onto a request until the connection expires)
// * A reference to the stream that is currently using the connection. This is necessary because we need to keep the old stream open until we've opened a new one.
// The stream will be closed + released either when another request comes to use the connection, or when the timer fires to tell the connection to expire
NSMutableDictionary *connectionInfo;
// When set to YES, 301 and 302 automatic redirects will use the original method and and body, according to the HTTP 1.1 standard
// Default is NO (to follow the behaviour of most browsers)
BOOL shouldUseRFC2616RedirectBehaviour;
// Used internally to record when a request has finished downloading data
BOOL downloadComplete;
// An ID that uniquely identifies this request - primarily used for debugging persistent connections
NSNumber *requestID;
// Will be ASIHTTPRequestRunLoopMode for synchronous requests, NSDefaultRunLoopMode for all other requests
NSString *runLoopMode;
// This timer checks up on the request every 0.25 seconds, and updates progress
NSTimer *statusTimer;
// The download cache that will be used for this request (use [ASIHTTPRequest setDefaultCache:cache] to configure a default cache
id <ASICacheDelegate> downloadCache;
// The cache policy that will be used for this request - See ASICacheDelegate.h for possible values
ASICachePolicy cachePolicy;
// The cache storage policy that will be used for this request - See ASICacheDelegate.h for possible values
ASICacheStoragePolicy cacheStoragePolicy;
// Will be true when the response was pulled from the cache rather than downloaded
BOOL didUseCachedResponse;
// Set secondsToCache to use a custom time interval for expiring the response when it is stored in a cache
NSTimeInterval secondsToCache;
#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
BOOL shouldContinueWhenAppEntersBackground;
UIBackgroundTaskIdentifier backgroundTask;
#endif
// When downloading a gzipped response, the request will use this helper object to inflate the response
ASIDataDecompressor *dataDecompressor;
// Controls how responses with a gzipped encoding are inflated (decompressed)
// When set to YES (This is the default):
// * gzipped responses for requests without a downloadDestinationPath will be inflated only when [request responseData] / [request responseString] is called
// * gzipped responses for requests with a downloadDestinationPath set will be inflated only when the request completes
//
// When set to NO
// All requests will inflate the response as it comes in
// * If the request has no downloadDestinationPath set, the raw (compressed) response is discarded and rawResponseData will contain the decompressed response
// * If the request has a downloadDestinationPath, the raw response will be stored in temporaryFileDownloadPath as normal, the inflated response will be stored in temporaryUncompressedDataDownloadPath
// Once the request completes successfully, the contents of temporaryUncompressedDataDownloadPath are moved into downloadDestinationPath
//
// Setting this to NO may be especially useful for users using ASIHTTPRequest in conjunction with a streaming parser, as it will allow partial gzipped responses to be inflated and passed on to the parser while the request is still running
BOOL shouldWaitToInflateCompressedResponses;
// Will be YES if this is a request created behind the scenes to download a PAC file - these requests do not attempt to configure their own proxies
BOOL isPACFileRequest;
// Used for downloading PAC files from http / https webservers
ASIHTTPRequest *PACFileRequest;
// Used for asynchronously reading PAC files from file:// URLs
NSInputStream *PACFileReadStream;
// Used for storing PAC data from file URLs as it is downloaded
NSMutableData *PACFileData;
// Set to YES in startSynchronous. Currently used by proxy detection to download PAC files synchronously when appropriate
BOOL isSynchronous;
#if NS_BLOCKS_AVAILABLE
//block to execute when request starts
ASIBasicBlock startedBlock;
//block to execute when headers are received
ASIHeadersBlock headersReceivedBlock;
//block to execute when request completes successfully
ASIBasicBlock completionBlock;
//block to execute when request fails
ASIBasicBlock failureBlock;
//block for when bytes are received
ASIProgressBlock bytesReceivedBlock;
//block for when bytes are sent
ASIProgressBlock bytesSentBlock;
//block for when download size is incremented
ASISizeBlock downloadSizeIncrementedBlock;
//block for when upload size is incremented
ASISizeBlock uploadSizeIncrementedBlock;
//block for handling raw bytes received
ASIDataBlock dataReceivedBlock;
//block for handling authentication
ASIBasicBlock authenticationNeededBlock;
//block for handling proxy authentication
ASIBasicBlock proxyAuthenticationNeededBlock;
//block for handling redirections, if you want to
ASIBasicBlock requestRedirectedBlock;
#endif
}
#pragma mark init / dealloc
// Should be an HTTP or HTTPS url, may include username and password if appropriate
- (id)initWithURL:(NSURL *)newURL;
// Convenience constructor
+ (id)requestWithURL:(NSURL *)newURL;
+ (id)requestWithURL:(NSURL *)newURL usingCache:(id <ASICacheDelegate>)cache;
+ (id)requestWithURL:(NSURL *)newURL usingCache:(id <ASICacheDelegate>)cache andCachePolicy:(ASICachePolicy)policy;
#if NS_BLOCKS_AVAILABLE
- (void)setStartedBlock:(ASIBasicBlock)aStartedBlock;
- (void)setHeadersReceivedBlock:(ASIHeadersBlock)aReceivedBlock;
- (void)setCompletionBlock:(ASIBasicBlock)aCompletionBlock;
- (void)setFailedBlock:(ASIBasicBlock)aFailedBlock;
- (void)setBytesReceivedBlock:(ASIProgressBlock)aBytesReceivedBlock;
- (void)setBytesSentBlock:(ASIProgressBlock)aBytesSentBlock;
- (void)setDownloadSizeIncrementedBlock:(ASISizeBlock) aDownloadSizeIncrementedBlock;
- (void)setUploadSizeIncrementedBlock:(ASISizeBlock) anUploadSizeIncrementedBlock;
- (void)setDataReceivedBlock:(ASIDataBlock)aReceivedBlock;
- (void)setAuthenticationNeededBlock:(ASIBasicBlock)anAuthenticationBlock;
- (void)setProxyAuthenticationNeededBlock:(ASIBasicBlock)aProxyAuthenticationBlock;
- (void)setRequestRedirectedBlock:(ASIBasicBlock)aRedirectBlock;
#endif
#pragma mark setup request
// Add a custom header to the request
- (void)addRequestHeader:(NSString *)header value:(NSString *)value;
// Called during buildRequestHeaders and after a redirect to create a cookie header from request cookies and the global store
- (void)applyCookieHeader;
// Populate the request headers dictionary. Called before a request is started, or by a HEAD request that needs to borrow them
- (void)buildRequestHeaders;
// Used to apply authorization header to a request before it is sent (when shouldPresentCredentialsBeforeChallenge is YES)
- (void)applyAuthorizationHeader;
// Create the post body
- (void)buildPostBody;
// Called to add data to the post body. Will append to postBody when shouldStreamPostDataFromDisk is false, or write to postBodyWriteStream when true
- (void)appendPostData:(NSData *)data;
- (void)appendPostDataFromFile:(NSString *)file;
#pragma mark get information about this request
// Returns the contents of the result as an NSString (not appropriate for binary data - used responseData instead)
- (NSString *)responseString;
// Response data, automatically uncompressed where appropriate
- (NSData *)responseData;
// Returns true if the response was gzip compressed
- (BOOL)isResponseCompressed;
#pragma mark running a request
// Run a request synchronously, and return control when the request completes or fails
- (void)startSynchronous;
// Run request in the background
- (void)startAsynchronous;
// Clears all delegates and blocks, then cancels the request
- (void)clearDelegatesAndCancel;
#pragma mark HEAD request
// Used by ASINetworkQueue to create a HEAD request appropriate for this request with the same headers (though you can use it yourself)
- (ASIHTTPRequest *)HEADRequest;
#pragma mark upload/download progress
// Called approximately every 0.25 seconds to update the progress delegates
- (void)updateProgressIndicators;
// Updates upload progress (notifies the queue and/or uploadProgressDelegate of this request)
- (void)updateUploadProgress;
// Updates download progress (notifies the queue and/or uploadProgressDelegate of this request)
- (void)updateDownloadProgress;
// Called when authorisation is needed, as we only find out we don't have permission to something when the upload is complete
- (void)removeUploadProgressSoFar;
// Called when we get a content-length header and shouldResetDownloadProgress is true
- (void)incrementDownloadSizeBy:(long long)length;
// Called when a request starts and shouldResetUploadProgress is true
// Also called (with a negative length) to remove the size of the underlying buffer used for uploading
- (void)incrementUploadSizeBy:(long long)length;
// Helper method for interacting with progress indicators to abstract the details of different APIS (NSProgressIndicator and UIProgressView)
+ (void)updateProgressIndicator:(id *)indicator withProgress:(unsigned long long)progress ofTotal:(unsigned long long)total;
// Helper method used for performing invocations on the main thread (used for progress)
+ (void)performSelector:(SEL)selector onTarget:(id *)target withObject:(id)object amount:(void *)amount callerToRetain:(id)caller;
#pragma mark talking to delegates
// Called when a request starts, lets the delegate know via didStartSelector
- (void)requestStarted;
// Called when a request receives response headers, lets the delegate know via didReceiveResponseHeadersSelector
- (void)requestReceivedResponseHeaders:(NSDictionary *)newHeaders;
// Called when a request completes successfully, lets the delegate know via didFinishSelector
- (void)requestFinished;
// Called when a request fails, and lets the delegate know via didFailSelector
- (void)failWithError:(NSError *)theError;
// Called to retry our request when our persistent connection is closed
// Returns YES if we haven't already retried, and connection will be restarted
// Otherwise, returns NO, and nothing will happen
- (BOOL)retryUsingNewConnection;
// Can be called by delegates from inside their willRedirectSelector implementations to restart the request with a new url
- (void)redirectToURL:(NSURL *)newURL;
#pragma mark parsing HTTP response headers
// Reads the response headers to find the content length, encoding, cookies for the session
// Also initiates request redirection when shouldRedirect is true
// And works out if HTTP auth is required
- (void)readResponseHeaders;
// Attempts to set the correct encoding by looking at the Content-Type header, if this is one
- (void)parseStringEncodingFromHeaders;
+ (void)parseMimeType:(NSString **)mimeType andResponseEncoding:(NSStringEncoding *)stringEncoding fromContentType:(NSString *)contentType;
#pragma mark http authentication stuff
// Apply credentials to this request
- (BOOL)applyCredentials:(NSDictionary *)newCredentials;
- (BOOL)applyProxyCredentials:(NSDictionary *)newCredentials;
// Attempt to obtain credentials for this request from the URL, username and password or keychain
- (NSMutableDictionary *)findCredentials;
- (NSMutableDictionary *)findProxyCredentials;
// Unlock (unpause) the request thread so it can resume the request
// Should be called by delegates when they have populated the authentication information after an authentication challenge
- (void)retryUsingSuppliedCredentials;
// Should be called by delegates when they wish to cancel authentication and stop
- (void)cancelAuthentication;
// Apply authentication information and resume the request after an authentication challenge
- (void)attemptToApplyCredentialsAndResume;
- (void)attemptToApplyProxyCredentialsAndResume;
// Attempt to show the built-in authentication dialog, returns YES if credentials were supplied, NO if user cancelled dialog / dialog is disabled / running on main thread
// Currently only used on iPhone OS
- (BOOL)showProxyAuthenticationDialog;
- (BOOL)showAuthenticationDialog;
// Construct a basic authentication header from the username and password supplied, and add it to the request headers
// Used when shouldPresentCredentialsBeforeChallenge is YES
- (void)addBasicAuthenticationHeaderWithUsername:(NSString *)theUsername andPassword:(NSString *)thePassword;
#pragma mark stream status handlers
// CFnetwork event handlers
- (void)handleNetworkEvent:(CFStreamEventType)type;
- (void)handleBytesAvailable;
- (void)handleStreamComplete;
- (void)handleStreamError;
#pragma mark cleanup
// Cleans up and lets the queue know this operation is finished.
// Appears in this header for subclassing only, do not call this method from outside your request!
- (void)markAsFinished;
// Cleans up temporary files. There's normally no reason to call these yourself, they are called automatically when a request completes or fails
// Clean up the temporary file used to store the downloaded data when it comes in (if downloadDestinationPath is set)
- (BOOL)removeTemporaryDownloadFile;
// Clean up the temporary file used to store data that is inflated (decompressed) as it comes in
- (BOOL)removeTemporaryUncompressedDownloadFile;
// Clean up the temporary file used to store the request body (when shouldStreamPostDataFromDisk is YES)
- (BOOL)removeTemporaryUploadFile;
// Clean up the temporary file used to store a deflated (compressed) request body when shouldStreamPostDataFromDisk is YES
- (BOOL)removeTemporaryCompressedUploadFile;
// Remove a file on disk, returning NO and populating the passed error pointer if it fails
+ (BOOL)removeFileAtPath:(NSString *)path error:(NSError **)err;
#pragma mark persistent connections
// Get the ID of the connection this request used (only really useful in tests and debugging)
- (NSNumber *)connectionID;
// Called automatically when a request is started to clean up any persistent connections that have expired
+ (void)expirePersistentConnections;
#pragma mark default time out
+ (NSTimeInterval)defaultTimeOutSeconds;
+ (void)setDefaultTimeOutSeconds:(NSTimeInterval)newTimeOutSeconds;
#pragma mark client certificate
- (void)setClientCertificateIdentity:(SecIdentityRef)anIdentity;
#pragma mark session credentials
+ (NSMutableArray *)sessionProxyCredentialsStore;
+ (NSMutableArray *)sessionCredentialsStore;
+ (void)storeProxyAuthenticationCredentialsInSessionStore:(NSDictionary *)credentials;
+ (void)storeAuthenticationCredentialsInSessionStore:(NSDictionary *)credentials;
+ (void)removeProxyAuthenticationCredentialsFromSessionStore:(NSDictionary *)credentials;
+ (void)removeAuthenticationCredentialsFromSessionStore:(NSDictionary *)credentials;
- (NSDictionary *)findSessionProxyAuthenticationCredentials;
- (NSDictionary *)findSessionAuthenticationCredentials;
#pragma mark keychain storage
// Save credentials for this request to the keychain
- (void)saveCredentialsToKeychain:(NSDictionary *)newCredentials;
// Save credentials to the keychain
+ (void)saveCredentials:(NSURLCredential *)credentials forHost:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm;
+ (void)saveCredentials:(NSURLCredential *)credentials forProxy:(NSString *)host port:(int)port realm:(NSString *)realm;
// Return credentials from the keychain
+ (NSURLCredential *)savedCredentialsForHost:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm;
+ (NSURLCredential *)savedCredentialsForProxy:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm;
// Remove credentials from the keychain
+ (void)removeCredentialsForHost:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm;
+ (void)removeCredentialsForProxy:(NSString *)host port:(int)port realm:(NSString *)realm;
// We keep track of any cookies we accept, so that we can remove them from the persistent store later
+ (void)setSessionCookies:(NSMutableArray *)newSessionCookies;
+ (NSMutableArray *)sessionCookies;
// Adds a cookie to our list of cookies we've accepted, checking first for an old version of the same cookie and removing that
+ (void)addSessionCookie:(NSHTTPCookie *)newCookie;
// Dump all session data (authentication and cookies)
+ (void)clearSession;
#pragma mark get user agent
// Will be used as a user agent if requests do not specify a custom user agent
// Is only used when you have specified a Bundle Display Name (CFDisplayBundleName) or Bundle Name (CFBundleName) in your plist
+ (NSString *)defaultUserAgentString;
+ (void)setDefaultUserAgentString:(NSString *)agent;
#pragma mark mime-type detection
// Return the mime type for a file
+ (NSString *)mimeTypeForFileAtPath:(NSString *)path;
#pragma mark bandwidth measurement / throttling
// The maximum number of bytes ALL requests can send / receive in a second
// This is a rough figure. The actual amount used will be slightly more, this does not include HTTP headers
+ (unsigned long)maxBandwidthPerSecond;
+ (void)setMaxBandwidthPerSecond:(unsigned long)bytes;
// Get a rough average (for the last 5 seconds) of how much bandwidth is being used, in bytes
+ (unsigned long)averageBandwidthUsedPerSecond;
- (void)performThrottling;
// Will return YES is bandwidth throttling is currently in use
+ (BOOL)isBandwidthThrottled;
// Used internally to record bandwidth use, and by ASIInputStreams when uploading. It's probably best if you don't mess with this.
+ (void)incrementBandwidthUsedInLastSecond:(unsigned long)bytes;
// On iPhone, ASIHTTPRequest can automatically turn throttling on and off as the connection type changes between WWAN and WiFi
#if TARGET_OS_IPHONE
// Set to YES to automatically turn on throttling when WWAN is connected, and automatically turn it off when it isn't
+ (void)setShouldThrottleBandwidthForWWAN:(BOOL)throttle;
// Turns on throttling automatically when WWAN is connected using a custom limit, and turns it off automatically when it isn't
+ (void)throttleBandwidthForWWANUsingLimit:(unsigned long)limit;
#pragma mark reachability
// Returns YES when an iPhone OS device is connected via WWAN, false when connected via WIFI or not connected
+ (BOOL)isNetworkReachableViaWWAN;
#endif
#pragma mark queue
// Returns the shared queue
+ (NSOperationQueue *)sharedQueue;
#pragma mark cache
+ (void)setDefaultCache:(id <ASICacheDelegate>)cache;
+ (id <ASICacheDelegate>)defaultCache;
// Returns the maximum amount of data we can read as part of the current measurement period, and sleeps this thread if our allowance is used up
+ (unsigned long)maxUploadReadLength;
#pragma mark network activity
+ (BOOL)isNetworkInUse;
+ (void)setShouldUpdateNetworkActivityIndicator:(BOOL)shouldUpdate;
// Shows the network activity spinner thing on iOS. You may wish to override this to do something else in Mac projects
+ (void)showNetworkActivityIndicator;
// Hides the network activity spinner thing on iOS
+ (void)hideNetworkActivityIndicator;
#pragma mark miscellany
// Used for generating Authorization header when using basic authentication when shouldPresentCredentialsBeforeChallenge is true
// And also by ASIS3Request
+ (NSString *)base64forData:(NSData *)theData;
// Returns the expiration date for the request.
// Calculated from the Expires response header property, unless maxAge is non-zero or
// there exists a non-zero max-age property in the Cache-Control response header.
+ (NSDate *)expiryDateForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge;
// Returns a date from a string in RFC1123 format
+ (NSDate *)dateFromRFC1123String:(NSString *)string;
// Used for detecting multitasking support at runtime (for backgrounding requests)
#if TARGET_OS_IPHONE
+ (BOOL)isMultitaskingSupported;
#endif
#pragma mark threading behaviour
// In the default implementation, all requests run in a single background thread
// Advanced users only: Override this method in a subclass for a different threading behaviour
// Eg: return [NSThread mainThread] to run all requests in the main thread
// Alternatively, you can create a thread on demand, or manage a pool of threads
// Threads returned by this method will need to run the runloop in default mode (eg CFRunLoopRun())
// Requests will stop the runloop when they complete
// If you have multiple requests sharing the thread you'll need to restart the runloop when this happens
+ (NSThread *)threadForRequest:(ASIHTTPRequest *)request;
#pragma mark ===
@property (retain) NSString *username;
@property (retain) NSString *password;
@property (retain) NSString *userAgentString;
@property (retain) NSString *domain;
@property (retain) NSString *proxyUsername;
@property (retain) NSString *proxyPassword;
@property (retain) NSString *proxyDomain;
@property (retain) NSString *proxyHost;
@property (assign) int proxyPort;
@property (retain) NSString *proxyType;
@property (retain,setter=setURL:, nonatomic) NSURL *url;
@property (retain) NSURL *originalURL;
@property (assign, nonatomic) id delegate;
@property (retain, nonatomic) id queue;
@property (assign, nonatomic) id uploadProgressDelegate;
@property (assign, nonatomic) id downloadProgressDelegate;
@property (assign) BOOL useKeychainPersistence;
@property (assign) BOOL useSessionPersistence;
@property (retain) NSString *downloadDestinationPath;
@property (retain) NSString *temporaryFileDownloadPath;
@property (retain) NSString *temporaryUncompressedDataDownloadPath;
@property (assign) SEL didStartSelector;
@property (assign) SEL didReceiveResponseHeadersSelector;
@property (assign) SEL willRedirectSelector;
@property (assign) SEL didFinishSelector;
@property (assign) SEL didFailSelector;
@property (assign) SEL didReceiveDataSelector;
@property (retain,readonly) NSString *authenticationRealm;
@property (retain,readonly) NSString *proxyAuthenticationRealm;
@property (retain) NSError *error;
@property (assign,readonly) BOOL complete;
@property (retain) NSDictionary *responseHeaders;
@property (retain) NSMutableDictionary *requestHeaders;
@property (retain) NSMutableArray *requestCookies;
@property (retain,readonly) NSArray *responseCookies;
@property (assign) BOOL useCookiePersistence;
@property (retain) NSDictionary *requestCredentials;
@property (retain) NSDictionary *proxyCredentials;
@property (assign,readonly) int responseStatusCode;
@property (retain,readonly) NSString *responseStatusMessage;
@property (retain) NSMutableData *rawResponseData;
@property (assign) NSTimeInterval timeOutSeconds;
@property (retain, nonatomic) NSString *requestMethod;
@property (retain) NSMutableData *postBody;
@property (assign) unsigned long long contentLength;
@property (assign) unsigned long long postLength;
@property (assign) BOOL shouldResetDownloadProgress;
@property (assign) BOOL shouldResetUploadProgress;
@property (assign) ASIHTTPRequest *mainRequest;
@property (assign) BOOL showAccurateProgress;
@property (assign) unsigned long long totalBytesRead;
@property (assign) unsigned long long totalBytesSent;
@property (assign) NSStringEncoding defaultResponseEncoding;
@property (assign) NSStringEncoding responseEncoding;
@property (assign) BOOL allowCompressedResponse;
@property (assign) BOOL allowResumeForFileDownloads;
@property (retain) NSDictionary *userInfo;
@property (assign) NSInteger tag;
@property (retain) NSString *postBodyFilePath;
@property (assign) BOOL shouldStreamPostDataFromDisk;
@property (assign) BOOL didCreateTemporaryPostDataFile;
@property (assign) BOOL useHTTPVersionOne;
@property (assign, readonly) unsigned long long partialDownloadSize;
@property (assign) BOOL shouldRedirect;
@property (assign) BOOL validatesSecureCertificate;
@property (assign) BOOL shouldCompressRequestBody;
@property (retain) NSURL *PACurl;
@property (retain) NSString *authenticationScheme;
@property (retain) NSString *proxyAuthenticationScheme;
@property (assign) BOOL shouldPresentAuthenticationDialog;
@property (assign) BOOL shouldPresentProxyAuthenticationDialog;
@property (assign, readonly) ASIAuthenticationState authenticationNeeded;
@property (assign) BOOL shouldPresentCredentialsBeforeChallenge;
@property (assign, readonly) int authenticationRetryCount;
@property (assign, readonly) int proxyAuthenticationRetryCount;
@property (assign) BOOL haveBuiltRequestHeaders;
@property (assign, nonatomic) BOOL haveBuiltPostBody;
@property (assign, readonly) BOOL inProgress;
@property (assign) int numberOfTimesToRetryOnTimeout;
@property (assign, readonly) int retryCount;
@property (assign) BOOL shouldAttemptPersistentConnection;
@property (assign) NSTimeInterval persistentConnectionTimeoutSeconds;
@property (assign) BOOL shouldUseRFC2616RedirectBehaviour;
@property (assign, readonly) BOOL connectionCanBeReused;
@property (retain, readonly) NSNumber *requestID;
@property (assign) id <ASICacheDelegate> downloadCache;
@property (assign) ASICachePolicy cachePolicy;
@property (assign) ASICacheStoragePolicy cacheStoragePolicy;
@property (assign, readonly) BOOL didUseCachedResponse;
@property (assign) NSTimeInterval secondsToCache;
@property (retain) NSArray *clientCertificates;
#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
@property (assign) BOOL shouldContinueWhenAppEntersBackground;
#endif
@property (retain) ASIDataDecompressor *dataDecompressor;
@property (assign) BOOL shouldWaitToInflateCompressedResponses;
@end
| 009-20120511-zi | trunk/Zinipad/ASI/ASIHTTPRequest.h | Objective-C | gpl3 | 45,045 |
//
// ASIProgressDelegate.h
// Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
// Created by Ben Copsey on 13/04/2010.
// Copyright 2010 All-Seeing Interactive. All rights reserved.
//
@class ASIHTTPRequest;
@protocol ASIProgressDelegate <NSObject>
@optional
// These methods are used to update UIProgressViews (iPhone OS) or NSProgressIndicators (Mac OS X)
// If you are using a custom progress delegate, you may find it easier to implement didReceiveBytes / didSendBytes instead
#if TARGET_OS_IPHONE
- (void)setProgress:(float)newProgress;
#else
- (void)setDoubleValue:(double)newProgress;
- (void)setMaxValue:(double)newMax;
#endif
// Called when the request receives some data - bytes is the length of that data
- (void)request:(ASIHTTPRequest *)request didReceiveBytes:(long long)bytes;
// Called when the request sends some data
// The first 32KB (128KB on older platforms) of data sent is not included in this amount because of limitations with the CFNetwork API
// bytes may be less than zero if a request needs to remove upload progress (probably because the request needs to run again)
- (void)request:(ASIHTTPRequest *)request didSendBytes:(long long)bytes;
// Called when a request needs to change the length of the content to download
- (void)request:(ASIHTTPRequest *)request incrementDownloadSizeBy:(long long)newLength;
// Called when a request needs to change the length of the content to upload
// newLength may be less than zero when a request needs to remove the size of the internal buffer from progress tracking
- (void)request:(ASIHTTPRequest *)request incrementUploadSizeBy:(long long)newLength;
@end
| 009-20120511-zi | trunk/Zinipad/ASI/ASIProgressDelegate.h | Objective-C | gpl3 | 1,656 |
//
// ASICacheDelegate.h
// Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
// Created by Ben Copsey on 01/05/2010.
// Copyright 2010 All-Seeing Interactive. All rights reserved.
//
#import <Foundation/Foundation.h>
@class ASIHTTPRequest;
// Cache policies control the behaviour of a cache and how requests use the cache
// When setting a cache policy, you can use a combination of these values as a bitmask
// For example: [request setCachePolicy:ASIAskServerIfModifiedCachePolicy|ASIFallbackToCacheIfLoadFailsCachePolicy|ASIDoNotWriteToCacheCachePolicy];
// Note that some of the behaviours below are mutally exclusive - you cannot combine ASIAskServerIfModifiedWhenStaleCachePolicy and ASIAskServerIfModifiedCachePolicy, for example.
typedef enum _ASICachePolicy {
// The default cache policy. When you set a request to use this, it will use the cache's defaultCachePolicy
// ASIDownloadCache's default cache policy is 'ASIAskServerIfModifiedWhenStaleCachePolicy'
ASIUseDefaultCachePolicy = 0,
// Tell the request not to read from the cache
ASIDoNotReadFromCacheCachePolicy = 1,
// The the request not to write to the cache
ASIDoNotWriteToCacheCachePolicy = 2,
// Ask the server if there is an updated version of this resource (using a conditional GET) ONLY when the cached data is stale
ASIAskServerIfModifiedWhenStaleCachePolicy = 4,
// Always ask the server if there is an updated version of this resource (using a conditional GET)
ASIAskServerIfModifiedCachePolicy = 8,
// If cached data exists, use it even if it is stale. This means requests will not talk to the server unless the resource they are requesting is not in the cache
ASIOnlyLoadIfNotCachedCachePolicy = 16,
// If cached data exists, use it even if it is stale. If cached data does not exist, stop (will not set an error on the request)
ASIDontLoadCachePolicy = 32,
// Specifies that cached data may be used if the request fails. If cached data is used, the request will succeed without error. Usually used in combination with other options above.
ASIFallbackToCacheIfLoadFailsCachePolicy = 64
} ASICachePolicy;
// Cache storage policies control whether cached data persists between application launches (ASICachePermanentlyCacheStoragePolicy) or not (ASICacheForSessionDurationCacheStoragePolicy)
// Calling [ASIHTTPRequest clearSession] will remove any data stored using ASICacheForSessionDurationCacheStoragePolicy
typedef enum _ASICacheStoragePolicy {
ASICacheForSessionDurationCacheStoragePolicy = 0,
ASICachePermanentlyCacheStoragePolicy = 1
} ASICacheStoragePolicy;
@protocol ASICacheDelegate <NSObject>
@required
// Should return the cache policy that will be used when requests have their cache policy set to ASIUseDefaultCachePolicy
- (ASICachePolicy)defaultCachePolicy;
// Returns the date a cached response should expire on. Pass a non-zero max age to specify a custom date.
- (NSDate *)expiryDateForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge;
// Updates cached response headers with a new expiry date. Pass a non-zero max age to specify a custom date.
- (void)updateExpiryForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge;
// Looks at the request's cache policy and any cached headers to determine if the cache data is still valid
- (BOOL)canUseCachedDataForRequest:(ASIHTTPRequest *)request;
// Removes cached data for a particular request
- (void)removeCachedDataForRequest:(ASIHTTPRequest *)request;
// Should return YES if the cache considers its cached response current for the request
// Should return NO is the data is not cached, or (for example) if the cached headers state the request should have expired
- (BOOL)isCachedDataCurrentForRequest:(ASIHTTPRequest *)request;
// Should store the response for the passed request in the cache
// When a non-zero maxAge is passed, it should be used as the expiry time for the cached response
- (void)storeResponseForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge;
// Removes cached data for a particular url
- (void)removeCachedDataForURL:(NSURL *)url;
// Should return an NSDictionary of cached headers for the passed URL, if it is stored in the cache
- (NSDictionary *)cachedResponseHeadersForURL:(NSURL *)url;
// Should return the cached body of a response for the passed URL, if it is stored in the cache
- (NSData *)cachedResponseDataForURL:(NSURL *)url;
// Returns a path to the cached response data, if it exists
- (NSString *)pathToCachedResponseDataForURL:(NSURL *)url;
// Returns a path to the cached response headers, if they url
- (NSString *)pathToCachedResponseHeadersForURL:(NSURL *)url;
// Returns the location to use to store cached response headers for a particular request
- (NSString *)pathToStoreCachedResponseHeadersForRequest:(ASIHTTPRequest *)request;
// Returns the location to use to store a cached response body for a particular request
- (NSString *)pathToStoreCachedResponseDataForRequest:(ASIHTTPRequest *)request;
// Clear cached data stored for the passed storage policy
- (void)clearCachedResponsesForStoragePolicy:(ASICacheStoragePolicy)cachePolicy;
@end
| 009-20120511-zi | trunk/Zinipad/ASI/ASICacheDelegate.h | Objective-C | gpl3 | 5,151 |
//
// ASIFormDataRequest.m
// Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
// Created by Ben Copsey on 07/11/2008.
// Copyright 2008-2009 All-Seeing Interactive. All rights reserved.
//
#import "ASIFormDataRequest.h"
// Private stuff
@interface ASIFormDataRequest ()
- (void)buildMultipartFormDataPostBody;
- (void)buildURLEncodedPostBody;
- (void)appendPostString:(NSString *)string;
@property (retain) NSMutableArray *postData;
@property (retain) NSMutableArray *fileData;
#if DEBUG_FORM_DATA_REQUEST
- (void)addToDebugBody:(NSString *)string;
@property (retain, nonatomic) NSString *debugBodyString;
#endif
@end
@implementation ASIFormDataRequest
#pragma mark utilities
- (NSString*)encodeURL:(NSString *)string
{
NSString *newString = [NSMakeCollectable(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL, CFSTR(":/?#[]@!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding([self stringEncoding]))) autorelease];
if (newString) {
return newString;
}
return @"";
}
#pragma mark init / dealloc
+ (id)requestWithURL:(NSURL *)newURL
{
return [[[self alloc] initWithURL:newURL] autorelease];
}
- (id)initWithURL:(NSURL *)newURL
{
self = [super initWithURL:newURL];
[self setPostFormat:ASIURLEncodedPostFormat];
[self setStringEncoding:NSUTF8StringEncoding];
[self setRequestMethod:@"POST"];
return self;
}
- (void)dealloc
{
#if DEBUG_FORM_DATA_REQUEST
[debugBodyString release];
#endif
[postData release];
[fileData release];
[super dealloc];
}
#pragma mark setup request
- (void)addPostValue:(id <NSObject>)value forKey:(NSString *)key
{
if (!key) {
return;
}
if (![self postData]) {
[self setPostData:[NSMutableArray array]];
}
NSMutableDictionary *keyValuePair = [NSMutableDictionary dictionaryWithCapacity:2];
[keyValuePair setValue:key forKey:@"key"];
[keyValuePair setValue:[value description] forKey:@"value"];
[[self postData] addObject:keyValuePair];
}
- (void)setPostValue:(id <NSObject>)value forKey:(NSString *)key
{
// Remove any existing value
NSUInteger i;
for (i=0; i<[[self postData] count]; i++) {
NSDictionary *val = [[self postData] objectAtIndex:i];
if ([[val objectForKey:@"key"] isEqualToString:key]) {
[[self postData] removeObjectAtIndex:i];
i--;
}
}
[self addPostValue:value forKey:key];
}
- (void)addFile:(NSString *)filePath forKey:(NSString *)key
{
[self addFile:filePath withFileName:nil andContentType:nil forKey:key];
}
- (void)addFile:(NSString *)filePath withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key
{
BOOL isDirectory = NO;
BOOL fileExists = [[[[NSFileManager alloc] init] autorelease] fileExistsAtPath:filePath isDirectory:&isDirectory];
if (!fileExists || isDirectory) {
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileBuildingRequestType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"No file exists at %@",filePath],NSLocalizedDescriptionKey,nil]]];
}
// If the caller didn't specify a custom file name, we'll use the file name of the file we were passed
if (!fileName) {
fileName = [filePath lastPathComponent];
}
// If we were given the path to a file, and the user didn't specify a mime type, we can detect it from the file extension
if (!contentType) {
contentType = [ASIHTTPRequest mimeTypeForFileAtPath:filePath];
}
[self addData:filePath withFileName:fileName andContentType:contentType forKey:key];
}
- (void)setFile:(NSString *)filePath forKey:(NSString *)key
{
[self setFile:filePath withFileName:nil andContentType:nil forKey:key];
}
- (void)setFile:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key
{
// Remove any existing value
NSUInteger i;
for (i=0; i<[[self fileData] count]; i++) {
NSDictionary *val = [[self fileData] objectAtIndex:i];
if ([[val objectForKey:@"key"] isEqualToString:key]) {
[[self fileData] removeObjectAtIndex:i];
i--;
}
}
[self addFile:data withFileName:fileName andContentType:contentType forKey:key];
}
- (void)addData:(NSData *)data forKey:(NSString *)key
{
[self addData:data withFileName:@"file" andContentType:nil forKey:key];
}
- (void)addData:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key
{
if (![self fileData]) {
[self setFileData:[NSMutableArray array]];
}
if (!contentType) {
contentType = @"application/octet-stream";
}
NSMutableDictionary *fileInfo = [NSMutableDictionary dictionaryWithCapacity:4];
[fileInfo setValue:key forKey:@"key"];
[fileInfo setValue:fileName forKey:@"fileName"];
[fileInfo setValue:contentType forKey:@"contentType"];
[fileInfo setValue:data forKey:@"data"];
[[self fileData] addObject:fileInfo];
}
- (void)setData:(NSData *)data forKey:(NSString *)key
{
[self setData:data withFileName:@"file" andContentType:nil forKey:key];
}
- (void)setData:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key
{
// Remove any existing value
NSUInteger i;
for (i=0; i<[[self fileData] count]; i++) {
NSDictionary *val = [[self fileData] objectAtIndex:i];
if ([[val objectForKey:@"key"] isEqualToString:key]) {
[[self fileData] removeObjectAtIndex:i];
i--;
}
}
[self addData:data withFileName:fileName andContentType:contentType forKey:key];
}
- (void)buildPostBody
{
if ([self haveBuiltPostBody]) {
return;
}
#if DEBUG_FORM_DATA_REQUEST
[self setDebugBodyString:@""];
#endif
if (![self postData] && ![self fileData]) {
[super buildPostBody];
return;
}
if ([[self fileData] count] > 0) {
[self setShouldStreamPostDataFromDisk:YES];
}
if ([self postFormat] == ASIURLEncodedPostFormat) {
[self buildURLEncodedPostBody];
} else {
[self buildMultipartFormDataPostBody];
}
[super buildPostBody];
#if DEBUG_FORM_DATA_REQUEST
ASI_DEBUG_LOG(@"%@",[self debugBodyString]);
[self setDebugBodyString:nil];
#endif
}
- (void)buildMultipartFormDataPostBody
{
#if DEBUG_FORM_DATA_REQUEST
[self addToDebugBody:@"\r\n==== Building a multipart/form-data body ====\r\n"];
#endif
NSString *charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding([self stringEncoding]));
// We don't bother to check if post data contains the boundary, since it's pretty unlikely that it does.
CFUUIDRef uuid = CFUUIDCreate(nil);
NSString *uuidString = [(NSString*)CFUUIDCreateString(nil, uuid) autorelease];
CFRelease(uuid);
NSString *stringBoundary = [NSString stringWithFormat:@"0xKhTmLbOuNdArY-%@",uuidString];
[self addRequestHeader:@"Content-Type" value:[NSString stringWithFormat:@"multipart/form-data; charset=%@; boundary=%@", charset, stringBoundary]];
[self appendPostString:[NSString stringWithFormat:@"--%@\r\n",stringBoundary]];
// Adds post data
NSString *endItemBoundary = [NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary];
NSUInteger i=0;
for (NSDictionary *val in [self postData]) {
[self appendPostString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",[val objectForKey:@"key"]]];
[self appendPostString:[val objectForKey:@"value"]];
i++;
if (i != [[self postData] count] || [[self fileData] count] > 0) { //Only add the boundary if this is not the last item in the post body
[self appendPostString:endItemBoundary];
}
}
// Adds files to upload
i=0;
for (NSDictionary *val in [self fileData]) {
[self appendPostString:[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", [val objectForKey:@"key"], [val objectForKey:@"fileName"]]];
[self appendPostString:[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", [val objectForKey:@"contentType"]]];
id data = [val objectForKey:@"data"];
if ([data isKindOfClass:[NSString class]]) {
[self appendPostDataFromFile:data];
} else {
[self appendPostData:data];
}
i++;
// Only add the boundary if this is not the last item in the post body
if (i != [[self fileData] count]) {
[self appendPostString:endItemBoundary];
}
}
[self appendPostString:[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary]];
#if DEBUG_FORM_DATA_REQUEST
[self addToDebugBody:@"==== End of multipart/form-data body ====\r\n"];
#endif
}
- (void)buildURLEncodedPostBody
{
// We can't post binary data using application/x-www-form-urlencoded
if ([[self fileData] count] > 0) {
[self setPostFormat:ASIMultipartFormDataPostFormat];
[self buildMultipartFormDataPostBody];
return;
}
#if DEBUG_FORM_DATA_REQUEST
[self addToDebugBody:@"\r\n==== Building an application/x-www-form-urlencoded body ====\r\n"];
#endif
NSString *charset = (NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding([self stringEncoding]));
[self addRequestHeader:@"Content-Type" value:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@",charset]];
NSUInteger i=0;
NSUInteger count = [[self postData] count]-1;
for (NSDictionary *val in [self postData]) {
NSString *data = [NSString stringWithFormat:@"%@=%@%@", [self encodeURL:[val objectForKey:@"key"]], [self encodeURL:[val objectForKey:@"value"]],(i<count ? @"&" : @"")];
[self appendPostString:data];
i++;
}
#if DEBUG_FORM_DATA_REQUEST
[self addToDebugBody:@"\r\n==== End of application/x-www-form-urlencoded body ====\r\n"];
#endif
}
- (void)appendPostString:(NSString *)string
{
#if DEBUG_FORM_DATA_REQUEST
[self addToDebugBody:string];
#endif
[super appendPostData:[string dataUsingEncoding:[self stringEncoding]]];
}
#if DEBUG_FORM_DATA_REQUEST
- (void)appendPostData:(NSData *)data
{
[self addToDebugBody:[NSString stringWithFormat:@"[%lu bytes of data]",(unsigned long)[data length]]];
[super appendPostData:data];
}
- (void)appendPostDataFromFile:(NSString *)file
{
NSError *err = nil;
unsigned long long fileSize = [[[[[[NSFileManager alloc] init] autorelease] attributesOfItemAtPath:file error:&err] objectForKey:NSFileSize] unsignedLongLongValue];
if (err) {
[self addToDebugBody:[NSString stringWithFormat:@"[Error: Failed to obtain the size of the file at '%@']",file]];
} else {
[self addToDebugBody:[NSString stringWithFormat:@"[%llu bytes of data from file '%@']",fileSize,file]];
}
[super appendPostDataFromFile:file];
}
- (void)addToDebugBody:(NSString *)string
{
if (string) {
[self setDebugBodyString:[[self debugBodyString] stringByAppendingString:string]];
}
}
#endif
#pragma mark NSCopying
- (id)copyWithZone:(NSZone *)zone
{
ASIFormDataRequest *newRequest = [super copyWithZone:zone];
[newRequest setPostData:[[[self postData] mutableCopyWithZone:zone] autorelease]];
[newRequest setFileData:[[[self fileData] mutableCopyWithZone:zone] autorelease]];
[newRequest setPostFormat:[self postFormat]];
[newRequest setStringEncoding:[self stringEncoding]];
[newRequest setRequestMethod:[self requestMethod]];
return newRequest;
}
@synthesize postData;
@synthesize fileData;
@synthesize postFormat;
@synthesize stringEncoding;
#if DEBUG_FORM_DATA_REQUEST
@synthesize debugBodyString;
#endif
@end
| 009-20120511-zi | trunk/Zinipad/ASI/ASIFormDataRequest.m | Objective-C | gpl3 | 11,266 |
//
// ASIHTTPRequest.m
//
// Created by Ben Copsey on 04/10/2007.
// Copyright 2007-2011 All-Seeing Interactive. All rights reserved.
//
// A guide to the main features is available at:
// http://allseeing-i.com/ASIHTTPRequest
//
// Portions are based on the ImageClient example from Apple:
// See: http://developer.apple.com/samplecode/ImageClient/listing37.html
#import "ASIHTTPRequest.h"
#if TARGET_OS_IPHONE
#import "Reachability.h"
#import "ASIAuthenticationDialog.h"
#import <MobileCoreServices/MobileCoreServices.h>
#else
#import <SystemConfiguration/SystemConfiguration.h>
#endif
#import "ASIInputStream.h"
#import "ASIDataDecompressor.h"
#import "ASIDataCompressor.h"
// Automatically set on build
NSString *ASIHTTPRequestVersion = @"v1.8.1-61 2011-09-19";
static NSString *defaultUserAgent = nil;
NSString* const NetworkRequestErrorDomain = @"ASIHTTPRequestErrorDomain";
static NSString *ASIHTTPRequestRunLoopMode = @"ASIHTTPRequestRunLoopMode";
static const CFOptionFlags kNetworkEvents = kCFStreamEventHasBytesAvailable | kCFStreamEventEndEncountered | kCFStreamEventErrorOccurred;
// In memory caches of credentials, used on when useSessionPersistence is YES
static NSMutableArray *sessionCredentialsStore = nil;
static NSMutableArray *sessionProxyCredentialsStore = nil;
// This lock mediates access to session credentials
static NSRecursiveLock *sessionCredentialsLock = nil;
// We keep track of cookies we have received here so we can remove them from the sharedHTTPCookieStorage later
static NSMutableArray *sessionCookies = nil;
// The number of times we will allow requests to redirect before we fail with a redirection error
const int RedirectionLimit = 5;
// The default number of seconds to use for a timeout
static NSTimeInterval defaultTimeOutSeconds = 10;
static void ReadStreamClientCallBack(CFReadStreamRef readStream, CFStreamEventType type, void *clientCallBackInfo) {
[((ASIHTTPRequest*)clientCallBackInfo) handleNetworkEvent: type];
}
// This lock prevents the operation from being cancelled while it is trying to update the progress, and vice versa
static NSRecursiveLock *progressLock;
static NSError *ASIRequestCancelledError;
static NSError *ASIRequestTimedOutError;
static NSError *ASIAuthenticationError;
static NSError *ASIUnableToCreateRequestError;
static NSError *ASITooMuchRedirectionError;
static NSMutableArray *bandwidthUsageTracker = nil;
static unsigned long averageBandwidthUsedPerSecond = 0;
// These are used for queuing persistent connections on the same connection
// Incremented every time we specify we want a new connection
static unsigned int nextConnectionNumberToCreate = 0;
// An array of connectionInfo dictionaries.
// When attempting a persistent connection, we look here to try to find an existing connection to the same server that is currently not in use
static NSMutableArray *persistentConnectionsPool = nil;
// Mediates access to the persistent connections pool
static NSRecursiveLock *connectionsLock = nil;
// Each request gets a new id, we store this rather than a ref to the request itself in the connectionInfo dictionary.
// We do this so we don't have to keep the request around while we wait for the connection to expire
static unsigned int nextRequestID = 0;
// Records how much bandwidth all requests combined have used in the last second
static unsigned long bandwidthUsedInLastSecond = 0;
// A date one second in the future from the time it was created
static NSDate *bandwidthMeasurementDate = nil;
// Since throttling variables are shared among all requests, we'll use a lock to mediate access
static NSLock *bandwidthThrottlingLock = nil;
// the maximum number of bytes that can be transmitted in one second
static unsigned long maxBandwidthPerSecond = 0;
// A default figure for throttling bandwidth on mobile devices
unsigned long const ASIWWANBandwidthThrottleAmount = 14800;
#if TARGET_OS_IPHONE
// YES when bandwidth throttling is active
// This flag does not denote whether throttling is turned on - rather whether it is currently in use
// It will be set to NO when throttling was turned on with setShouldThrottleBandwidthForWWAN, but a WI-FI connection is active
static BOOL isBandwidthThrottled = NO;
// When YES, bandwidth will be automatically throttled when using WWAN (3G/Edge/GPRS)
// Wifi will not be throttled
static BOOL shouldThrottleBandwidthForWWANOnly = NO;
#endif
// Mediates access to the session cookies so requests
static NSRecursiveLock *sessionCookiesLock = nil;
// This lock ensures delegates only receive one notification that authentication is required at once
// When using ASIAuthenticationDialogs, it also ensures only one dialog is shown at once
// If a request can't acquire the lock immediately, it means a dialog is being shown or a delegate is handling the authentication challenge
// Once it gets the lock, it will try to look for existing credentials again rather than showing the dialog / notifying the delegate
// This is so it can make use of any credentials supplied for the other request, if they are appropriate
static NSRecursiveLock *delegateAuthenticationLock = nil;
// When throttling bandwidth, Set to a date in future that we will allow all requests to wake up and reschedule their streams
static NSDate *throttleWakeUpTime = nil;
static id <ASICacheDelegate> defaultCache = nil;
// Used for tracking when requests are using the network
static unsigned int runningRequestCount = 0;
// You can use [ASIHTTPRequest setShouldUpdateNetworkActivityIndicator:NO] if you want to manage it yourself
// Alternatively, override showNetworkActivityIndicator / hideNetworkActivityIndicator
// By default this does nothing on Mac OS X, but again override the above methods for a different behaviour
static BOOL shouldUpdateNetworkActivityIndicator = YES;
// The thread all requests will run on
// Hangs around forever, but will be blocked unless there are requests underway
static NSThread *networkThread = nil;
static NSOperationQueue *sharedQueue = nil;
// Private stuff
@interface ASIHTTPRequest ()
- (void)cancelLoad;
- (void)destroyReadStream;
- (void)scheduleReadStream;
- (void)unscheduleReadStream;
- (BOOL)willAskDelegateForCredentials;
- (BOOL)willAskDelegateForProxyCredentials;
- (void)askDelegateForProxyCredentials;
- (void)askDelegateForCredentials;
- (void)failAuthentication;
+ (void)measureBandwidthUsage;
+ (void)recordBandwidthUsage;
- (void)startRequest;
- (void)updateStatus:(NSTimer *)timer;
- (void)checkRequestStatus;
- (void)reportFailure;
- (void)reportFinished;
- (void)markAsFinished;
- (void)performRedirect;
- (BOOL)shouldTimeOut;
- (BOOL)willRedirect;
- (BOOL)willAskDelegateToConfirmRedirect;
+ (void)performInvocation:(NSInvocation *)invocation onTarget:(id *)target releasingObject:(id)objectToRelease;
+ (void)hideNetworkActivityIndicatorAfterDelay;
+ (void)hideNetworkActivityIndicatorIfNeeeded;
+ (void)runRequests;
// Handling Proxy autodetection and PAC file downloads
- (BOOL)configureProxies;
- (void)fetchPACFile;
- (void)finishedDownloadingPACFile:(ASIHTTPRequest *)theRequest;
- (void)runPACScript:(NSString *)script;
- (void)timeOutPACRead;
- (void)useDataFromCache;
// Called to update the size of a partial download when starting a request, or retrying after a timeout
- (void)updatePartialDownloadSize;
#if TARGET_OS_IPHONE
+ (void)registerForNetworkReachabilityNotifications;
+ (void)unsubscribeFromNetworkReachabilityNotifications;
// Called when the status of the network changes
+ (void)reachabilityChanged:(NSNotification *)note;
#endif
#if NS_BLOCKS_AVAILABLE
- (void)performBlockOnMainThread:(ASIBasicBlock)block;
- (void)releaseBlocksOnMainThread;
+ (void)releaseBlocks:(NSArray *)blocks;
- (void)callBlock:(ASIBasicBlock)block;
#endif
@property (assign) BOOL complete;
@property (retain) NSArray *responseCookies;
@property (assign) int responseStatusCode;
@property (retain, nonatomic) NSDate *lastActivityTime;
@property (assign) unsigned long long partialDownloadSize;
@property (assign, nonatomic) unsigned long long uploadBufferSize;
@property (retain, nonatomic) NSOutputStream *postBodyWriteStream;
@property (retain, nonatomic) NSInputStream *postBodyReadStream;
@property (assign, nonatomic) unsigned long long lastBytesRead;
@property (assign, nonatomic) unsigned long long lastBytesSent;
@property (retain) NSRecursiveLock *cancelledLock;
@property (retain, nonatomic) NSOutputStream *fileDownloadOutputStream;
@property (retain, nonatomic) NSOutputStream *inflatedFileDownloadOutputStream;
@property (assign) int authenticationRetryCount;
@property (assign) int proxyAuthenticationRetryCount;
@property (assign, nonatomic) BOOL updatedProgress;
@property (assign, nonatomic) BOOL needsRedirect;
@property (assign, nonatomic) int redirectCount;
@property (retain, nonatomic) NSData *compressedPostBody;
@property (retain, nonatomic) NSString *compressedPostBodyFilePath;
@property (retain) NSString *authenticationRealm;
@property (retain) NSString *proxyAuthenticationRealm;
@property (retain) NSString *responseStatusMessage;
@property (assign) BOOL inProgress;
@property (assign) int retryCount;
@property (assign) BOOL willRetryRequest;
@property (assign) BOOL connectionCanBeReused;
@property (retain, nonatomic) NSMutableDictionary *connectionInfo;
@property (retain, nonatomic) NSInputStream *readStream;
@property (assign) ASIAuthenticationState authenticationNeeded;
@property (assign, nonatomic) BOOL readStreamIsScheduled;
@property (assign, nonatomic) BOOL downloadComplete;
@property (retain) NSNumber *requestID;
@property (assign, nonatomic) NSString *runLoopMode;
@property (retain, nonatomic) NSTimer *statusTimer;
@property (assign) BOOL didUseCachedResponse;
@property (retain, nonatomic) NSURL *redirectURL;
@property (assign, nonatomic) BOOL isPACFileRequest;
@property (retain, nonatomic) ASIHTTPRequest *PACFileRequest;
@property (retain, nonatomic) NSInputStream *PACFileReadStream;
@property (retain, nonatomic) NSMutableData *PACFileData;
@property (assign, nonatomic, setter=setSynchronous:) BOOL isSynchronous;
@end
@implementation ASIHTTPRequest
#pragma mark init / dealloc
+ (void)initialize
{
if (self == [ASIHTTPRequest class]) {
persistentConnectionsPool = [[NSMutableArray alloc] init];
connectionsLock = [[NSRecursiveLock alloc] init];
progressLock = [[NSRecursiveLock alloc] init];
bandwidthThrottlingLock = [[NSLock alloc] init];
sessionCookiesLock = [[NSRecursiveLock alloc] init];
sessionCredentialsLock = [[NSRecursiveLock alloc] init];
delegateAuthenticationLock = [[NSRecursiveLock alloc] init];
bandwidthUsageTracker = [[NSMutableArray alloc] initWithCapacity:5];
ASIRequestTimedOutError = [[NSError alloc] initWithDomain:NetworkRequestErrorDomain code:ASIRequestTimedOutErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"The request timed out",NSLocalizedDescriptionKey,nil]];
ASIAuthenticationError = [[NSError alloc] initWithDomain:NetworkRequestErrorDomain code:ASIAuthenticationErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Authentication needed",NSLocalizedDescriptionKey,nil]];
ASIRequestCancelledError = [[NSError alloc] initWithDomain:NetworkRequestErrorDomain code:ASIRequestCancelledErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"The request was cancelled",NSLocalizedDescriptionKey,nil]];
ASIUnableToCreateRequestError = [[NSError alloc] initWithDomain:NetworkRequestErrorDomain code:ASIUnableToCreateRequestErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Unable to create request (bad url?)",NSLocalizedDescriptionKey,nil]];
ASITooMuchRedirectionError = [[NSError alloc] initWithDomain:NetworkRequestErrorDomain code:ASITooMuchRedirectionErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"The request failed because it redirected too many times",NSLocalizedDescriptionKey,nil]];
sharedQueue = [[NSOperationQueue alloc] init];
[sharedQueue setMaxConcurrentOperationCount:4];
}
}
- (id)initWithURL:(NSURL *)newURL
{
self = [self init];
[self setRequestMethod:@"GET"];
[self setRunLoopMode:NSDefaultRunLoopMode];
[self setShouldAttemptPersistentConnection:YES];
[self setPersistentConnectionTimeoutSeconds:60.0];
[self setShouldPresentCredentialsBeforeChallenge:YES];
[self setShouldRedirect:YES];
[self setShowAccurateProgress:YES];
[self setShouldResetDownloadProgress:YES];
[self setShouldResetUploadProgress:YES];
[self setAllowCompressedResponse:YES];
[self setShouldWaitToInflateCompressedResponses:YES];
[self setDefaultResponseEncoding:NSISOLatin1StringEncoding];
[self setShouldPresentProxyAuthenticationDialog:YES];
[self setTimeOutSeconds:[ASIHTTPRequest defaultTimeOutSeconds]];
[self setUseSessionPersistence:YES];
[self setUseCookiePersistence:YES];
[self setValidatesSecureCertificate:YES];
[self setRequestCookies:[[[NSMutableArray alloc] init] autorelease]];
[self setDidStartSelector:@selector(requestStarted:)];
[self setDidReceiveResponseHeadersSelector:@selector(request:didReceiveResponseHeaders:)];
[self setWillRedirectSelector:@selector(request:willRedirectToURL:)];
[self setDidFinishSelector:@selector(requestFinished:)];
[self setDidFailSelector:@selector(requestFailed:)];
[self setDidReceiveDataSelector:@selector(request:didReceiveData:)];
[self setURL:newURL];
[self setCancelledLock:[[[NSRecursiveLock alloc] init] autorelease]];
[self setDownloadCache:[[self class] defaultCache]];
return self;
}
+ (id)requestWithURL:(NSURL *)newURL
{
return [[[self alloc] initWithURL:newURL] autorelease];
}
+ (id)requestWithURL:(NSURL *)newURL usingCache:(id <ASICacheDelegate>)cache
{
return [self requestWithURL:newURL usingCache:cache andCachePolicy:ASIUseDefaultCachePolicy];
}
+ (id)requestWithURL:(NSURL *)newURL usingCache:(id <ASICacheDelegate>)cache andCachePolicy:(ASICachePolicy)policy
{
ASIHTTPRequest *request = [[[self alloc] initWithURL:newURL] autorelease];
[request setDownloadCache:cache];
[request setCachePolicy:policy];
return request;
}
- (void)dealloc
{
[self setAuthenticationNeeded:ASINoAuthenticationNeededYet];
if (requestAuthentication) {
CFRelease(requestAuthentication);
}
if (proxyAuthentication) {
CFRelease(proxyAuthentication);
}
if (request) {
CFRelease(request);
}
if (clientCertificateIdentity) {
CFRelease(clientCertificateIdentity);
}
[self cancelLoad];
[redirectURL release];
[statusTimer invalidate];
[statusTimer release];
[queue release];
[userInfo release];
[postBody release];
[compressedPostBody release];
[error release];
[requestHeaders release];
[requestCookies release];
[downloadDestinationPath release];
[temporaryFileDownloadPath release];
[temporaryUncompressedDataDownloadPath release];
[fileDownloadOutputStream release];
[inflatedFileDownloadOutputStream release];
[username release];
[password release];
[domain release];
[authenticationRealm release];
[authenticationScheme release];
[requestCredentials release];
[proxyHost release];
[proxyType release];
[proxyUsername release];
[proxyPassword release];
[proxyDomain release];
[proxyAuthenticationRealm release];
[proxyAuthenticationScheme release];
[proxyCredentials release];
[url release];
[originalURL release];
[lastActivityTime release];
[responseCookies release];
[rawResponseData release];
[responseHeaders release];
[requestMethod release];
[cancelledLock release];
[postBodyFilePath release];
[compressedPostBodyFilePath release];
[postBodyWriteStream release];
[postBodyReadStream release];
[PACurl release];
[clientCertificates release];
[responseStatusMessage release];
[connectionInfo release];
[requestID release];
[dataDecompressor release];
[userAgentString release];
#if NS_BLOCKS_AVAILABLE
[self releaseBlocksOnMainThread];
#endif
[super dealloc];
}
#if NS_BLOCKS_AVAILABLE
- (void)releaseBlocksOnMainThread
{
NSMutableArray *blocks = [NSMutableArray array];
if (completionBlock) {
[blocks addObject:completionBlock];
[completionBlock release];
completionBlock = nil;
}
if (failureBlock) {
[blocks addObject:failureBlock];
[failureBlock release];
failureBlock = nil;
}
if (startedBlock) {
[blocks addObject:startedBlock];
[startedBlock release];
startedBlock = nil;
}
if (headersReceivedBlock) {
[blocks addObject:headersReceivedBlock];
[headersReceivedBlock release];
headersReceivedBlock = nil;
}
if (bytesReceivedBlock) {
[blocks addObject:bytesReceivedBlock];
[bytesReceivedBlock release];
bytesReceivedBlock = nil;
}
if (bytesSentBlock) {
[blocks addObject:bytesSentBlock];
[bytesSentBlock release];
bytesSentBlock = nil;
}
if (downloadSizeIncrementedBlock) {
[blocks addObject:downloadSizeIncrementedBlock];
[downloadSizeIncrementedBlock release];
downloadSizeIncrementedBlock = nil;
}
if (uploadSizeIncrementedBlock) {
[blocks addObject:uploadSizeIncrementedBlock];
[uploadSizeIncrementedBlock release];
uploadSizeIncrementedBlock = nil;
}
if (dataReceivedBlock) {
[blocks addObject:dataReceivedBlock];
[dataReceivedBlock release];
dataReceivedBlock = nil;
}
if (proxyAuthenticationNeededBlock) {
[blocks addObject:proxyAuthenticationNeededBlock];
[proxyAuthenticationNeededBlock release];
proxyAuthenticationNeededBlock = nil;
}
if (authenticationNeededBlock) {
[blocks addObject:authenticationNeededBlock];
[authenticationNeededBlock release];
authenticationNeededBlock = nil;
}
if (requestRedirectedBlock) {
[blocks addObject:requestRedirectedBlock];
[requestRedirectedBlock release];
requestRedirectedBlock = nil;
}
[[self class] performSelectorOnMainThread:@selector(releaseBlocks:) withObject:blocks waitUntilDone:[NSThread isMainThread]];
}
// Always called on main thread
+ (void)releaseBlocks:(NSArray *)blocks
{
// Blocks will be released when this method exits
}
#endif
#pragma mark setup request
- (void)addRequestHeader:(NSString *)header value:(NSString *)value
{
if (!requestHeaders) {
[self setRequestHeaders:[NSMutableDictionary dictionaryWithCapacity:1]];
}
[requestHeaders setObject:value forKey:header];
}
// This function will be called either just before a request starts, or when postLength is needed, whichever comes first
// postLength must be set by the time this function is complete
- (void)buildPostBody
{
if ([self haveBuiltPostBody]) {
return;
}
// Are we submitting the request body from a file on disk
if ([self postBodyFilePath]) {
// If we were writing to the post body via appendPostData or appendPostDataFromFile, close the write stream
if ([self postBodyWriteStream]) {
[[self postBodyWriteStream] close];
[self setPostBodyWriteStream:nil];
}
NSString *path;
if ([self shouldCompressRequestBody]) {
if (![self compressedPostBodyFilePath]) {
[self setCompressedPostBodyFilePath:[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]];
NSError *err = nil;
if (![ASIDataCompressor compressDataFromFile:[self postBodyFilePath] toFile:[self compressedPostBodyFilePath] error:&err]) {
[self failWithError:err];
return;
}
}
path = [self compressedPostBodyFilePath];
} else {
path = [self postBodyFilePath];
}
NSError *err = nil;
[self setPostLength:[[[[[NSFileManager alloc] init] autorelease] attributesOfItemAtPath:path error:&err] fileSize]];
if (err) {
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIFileManagementError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Failed to get attributes for file at path '%@'",path],NSLocalizedDescriptionKey,error,NSUnderlyingErrorKey,nil]]];
return;
}
// Otherwise, we have an in-memory request body
} else {
if ([self shouldCompressRequestBody]) {
NSError *err = nil;
NSData *compressedBody = [ASIDataCompressor compressData:[self postBody] error:&err];
if (err) {
[self failWithError:err];
return;
}
[self setCompressedPostBody:compressedBody];
[self setPostLength:[[self compressedPostBody] length]];
} else {
[self setPostLength:[[self postBody] length]];
}
}
if ([self postLength] > 0) {
if ([requestMethod isEqualToString:@"GET"] || [requestMethod isEqualToString:@"DELETE"] || [requestMethod isEqualToString:@"HEAD"]) {
[self setRequestMethod:@"POST"];
}
[self addRequestHeader:@"Content-Length" value:[NSString stringWithFormat:@"%llu",[self postLength]]];
}
[self setHaveBuiltPostBody:YES];
}
// Sets up storage for the post body
- (void)setupPostBody
{
if ([self shouldStreamPostDataFromDisk]) {
if (![self postBodyFilePath]) {
[self setPostBodyFilePath:[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]];
[self setDidCreateTemporaryPostDataFile:YES];
}
if (![self postBodyWriteStream]) {
[self setPostBodyWriteStream:[[[NSOutputStream alloc] initToFileAtPath:[self postBodyFilePath] append:NO] autorelease]];
[[self postBodyWriteStream] open];
}
} else {
if (![self postBody]) {
[self setPostBody:[[[NSMutableData alloc] init] autorelease]];
}
}
}
- (void)appendPostData:(NSData *)data
{
[self setupPostBody];
if ([data length] == 0) {
return;
}
if ([self shouldStreamPostDataFromDisk]) {
[[self postBodyWriteStream] write:[data bytes] maxLength:[data length]];
} else {
[[self postBody] appendData:data];
}
}
- (void)appendPostDataFromFile:(NSString *)file
{
[self setupPostBody];
NSInputStream *stream = [[[NSInputStream alloc] initWithFileAtPath:file] autorelease];
[stream open];
NSUInteger bytesRead;
while ([stream hasBytesAvailable]) {
unsigned char buffer[1024*256];
bytesRead = [stream read:buffer maxLength:sizeof(buffer)];
if (bytesRead == 0) {
break;
}
if ([self shouldStreamPostDataFromDisk]) {
[[self postBodyWriteStream] write:buffer maxLength:bytesRead];
} else {
[[self postBody] appendData:[NSData dataWithBytes:buffer length:bytesRead]];
}
}
[stream close];
}
- (NSString *)requestMethod
{
[[self cancelledLock] lock];
NSString *m = requestMethod;
[[self cancelledLock] unlock];
return m;
}
- (void)setRequestMethod:(NSString *)newRequestMethod
{
[[self cancelledLock] lock];
if (requestMethod != newRequestMethod) {
[requestMethod release];
requestMethod = [newRequestMethod retain];
if ([requestMethod isEqualToString:@"POST"] || [requestMethod isEqualToString:@"PUT"] || [postBody length] || postBodyFilePath) {
[self setShouldAttemptPersistentConnection:NO];
}
}
[[self cancelledLock] unlock];
}
- (NSURL *)url
{
[[self cancelledLock] lock];
NSURL *u = url;
[[self cancelledLock] unlock];
return u;
}
- (void)setURL:(NSURL *)newURL
{
[[self cancelledLock] lock];
if ([newURL isEqual:[self url]]) {
[[self cancelledLock] unlock];
return;
}
[url release];
url = [newURL retain];
if (requestAuthentication) {
CFRelease(requestAuthentication);
requestAuthentication = NULL;
}
if (proxyAuthentication) {
CFRelease(proxyAuthentication);
proxyAuthentication = NULL;
}
if (request) {
CFRelease(request);
request = NULL;
}
[self setRedirectURL:nil];
[[self cancelledLock] unlock];
}
- (id)delegate
{
[[self cancelledLock] lock];
id d = delegate;
[[self cancelledLock] unlock];
return d;
}
- (void)setDelegate:(id)newDelegate
{
[[self cancelledLock] lock];
delegate = newDelegate;
[[self cancelledLock] unlock];
}
- (id)queue
{
[[self cancelledLock] lock];
id q = queue;
[[self cancelledLock] unlock];
return q;
}
- (void)setQueue:(id)newQueue
{
[[self cancelledLock] lock];
if (newQueue != queue) {
[queue release];
queue = [newQueue retain];
}
[[self cancelledLock] unlock];
}
#pragma mark get information about this request
// cancel the request - this must be run on the same thread as the request is running on
- (void)cancelOnRequestThread
{
#if DEBUG_REQUEST_STATUS
ASI_DEBUG_LOG(@"[STATUS] Request cancelled: %@",self);
#endif
[[self cancelledLock] lock];
if ([self isCancelled] || [self complete]) {
[[self cancelledLock] unlock];
return;
}
[self failWithError:ASIRequestCancelledError];
[self setComplete:YES];
[self cancelLoad];
CFRetain(self);
[self willChangeValueForKey:@"isCancelled"];
cancelled = YES;
[self didChangeValueForKey:@"isCancelled"];
[[self cancelledLock] unlock];
CFRelease(self);
}
- (void)cancel
{
[self performSelector:@selector(cancelOnRequestThread) onThread:[[self class] threadForRequest:self] withObject:nil waitUntilDone:NO];
}
- (void)clearDelegatesAndCancel
{
[[self cancelledLock] lock];
// Clear delegates
[self setDelegate:nil];
[self setQueue:nil];
[self setDownloadProgressDelegate:nil];
[self setUploadProgressDelegate:nil];
#if NS_BLOCKS_AVAILABLE
// Clear blocks
[self releaseBlocksOnMainThread];
#endif
[[self cancelledLock] unlock];
[self cancel];
}
- (BOOL)isCancelled
{
BOOL result;
[[self cancelledLock] lock];
result = cancelled;
[[self cancelledLock] unlock];
return result;
}
// Call this method to get the received data as an NSString. Don't use for binary data!
- (NSString *)responseString
{
NSData *data = [self responseData];
if (!data) {
return nil;
}
return [[[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:[self responseEncoding]] autorelease];
}
- (BOOL)isResponseCompressed
{
NSString *encoding = [[self responseHeaders] objectForKey:@"Content-Encoding"];
return encoding && [encoding rangeOfString:@"gzip"].location != NSNotFound;
}
- (NSData *)responseData
{
if ([self isResponseCompressed] && [self shouldWaitToInflateCompressedResponses]) {
return [ASIDataDecompressor uncompressData:[self rawResponseData] error:NULL];
} else {
return [self rawResponseData];
}
return nil;
}
#pragma mark running a request
- (void)startSynchronous
{
#if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
ASI_DEBUG_LOG(@"[STATUS] Starting synchronous request %@",self);
#endif
[self setSynchronous:YES];
[self setRunLoopMode:ASIHTTPRequestRunLoopMode];
[self setInProgress:YES];
if (![self isCancelled] && ![self complete]) {
[self main];
while (!complete) {
[[NSRunLoop currentRunLoop] runMode:[self runLoopMode] beforeDate:[NSDate distantFuture]];
}
}
[self setInProgress:NO];
}
- (void)start
{
[self setInProgress:YES];
[self performSelector:@selector(main) onThread:[[self class] threadForRequest:self] withObject:nil waitUntilDone:NO];
}
- (void)startAsynchronous
{
#if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
ASI_DEBUG_LOG(@"[STATUS] Starting asynchronous request %@",self);
#endif
[sharedQueue addOperation:self];
}
#pragma mark concurrency
- (BOOL)isConcurrent
{
return YES;
}
- (BOOL)isFinished
{
return finished;
}
- (BOOL)isExecuting {
return [self inProgress];
}
#pragma mark request logic
// Create the request
- (void)main
{
@try {
[[self cancelledLock] lock];
#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
if ([ASIHTTPRequest isMultitaskingSupported] && [self shouldContinueWhenAppEntersBackground]) {
if (!backgroundTask || backgroundTask == UIBackgroundTaskInvalid) {
backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
// Synchronize the cleanup call on the main thread in case
// the task actually finishes at around the same time.
dispatch_async(dispatch_get_main_queue(), ^{
if (backgroundTask != UIBackgroundTaskInvalid)
{
[[UIApplication sharedApplication] endBackgroundTask:backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
[self cancel];
}
});
}];
}
}
#endif
// A HEAD request generated by an ASINetworkQueue may have set the error already. If so, we should not proceed.
if ([self error]) {
[self setComplete:YES];
[self markAsFinished];
return;
}
[self setComplete:NO];
[self setDidUseCachedResponse:NO];
if (![self url]) {
[self failWithError:ASIUnableToCreateRequestError];
return;
}
// Must call before we create the request so that the request method can be set if needs be
if (![self mainRequest]) {
[self buildPostBody];
}
if (![[self requestMethod] isEqualToString:@"GET"]) {
[self setDownloadCache:nil];
}
// If we're redirecting, we'll already have a CFHTTPMessageRef
if (request) {
CFRelease(request);
}
// Create a new HTTP request.
request = CFHTTPMessageCreateRequest(kCFAllocatorDefault, (CFStringRef)[self requestMethod], (CFURLRef)[self url], [self useHTTPVersionOne] ? kCFHTTPVersion1_0 : kCFHTTPVersion1_1);
if (!request) {
[self failWithError:ASIUnableToCreateRequestError];
return;
}
//If this is a HEAD request generated by an ASINetworkQueue, we need to let the main request generate its headers first so we can use them
if ([self mainRequest]) {
[[self mainRequest] buildRequestHeaders];
}
// Even if this is a HEAD request with a mainRequest, we still need to call to give subclasses a chance to add their own to HEAD requests (ASIS3Request does this)
[self buildRequestHeaders];
if ([self downloadCache]) {
// If this request should use the default policy, set its policy to the download cache's default policy
if (![self cachePolicy]) {
[self setCachePolicy:[[self downloadCache] defaultCachePolicy]];
}
// If have have cached data that is valid for this request, use that and stop
if ([[self downloadCache] canUseCachedDataForRequest:self]) {
[self useDataFromCache];
return;
}
// If cached data is stale, or we have been told to ask the server if it has been modified anyway, we need to add headers for a conditional GET
if ([self cachePolicy] & (ASIAskServerIfModifiedWhenStaleCachePolicy|ASIAskServerIfModifiedCachePolicy)) {
NSDictionary *cachedHeaders = [[self downloadCache] cachedResponseHeadersForURL:[self url]];
if (cachedHeaders) {
NSString *etag = [cachedHeaders objectForKey:@"Etag"];
if (etag) {
[[self requestHeaders] setObject:etag forKey:@"If-None-Match"];
}
NSString *lastModified = [cachedHeaders objectForKey:@"Last-Modified"];
if (lastModified) {
[[self requestHeaders] setObject:lastModified forKey:@"If-Modified-Since"];
}
}
}
}
[self applyAuthorizationHeader];
NSString *header;
for (header in [self requestHeaders]) {
CFHTTPMessageSetHeaderFieldValue(request, (CFStringRef)header, (CFStringRef)[[self requestHeaders] objectForKey:header]);
}
// If we immediately have access to proxy settings, start the request
// Otherwise, we'll start downloading the proxy PAC file, and call startRequest once that process is complete
if ([self configureProxies]) {
[self startRequest];
}
} @catch (NSException *exception) {
NSError *underlyingError = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASIUnhandledExceptionError userInfo:[exception userInfo]];
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIUnhandledExceptionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[exception name],NSLocalizedDescriptionKey,[exception reason],NSLocalizedFailureReasonErrorKey,underlyingError,NSUnderlyingErrorKey,nil]]];
} @finally {
[[self cancelledLock] unlock];
}
}
- (void)applyAuthorizationHeader
{
// Do we want to send credentials before we are asked for them?
if (![self shouldPresentCredentialsBeforeChallenge]) {
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ will not send credentials to the server until it asks for them",self);
#endif
return;
}
NSDictionary *credentials = nil;
// Do we already have an auth header?
if (![[self requestHeaders] objectForKey:@"Authorization"]) {
// If we have basic authentication explicitly set and a username and password set on the request, add a basic auth header
if ([self username] && [self password] && [[self authenticationScheme] isEqualToString:(NSString *)kCFHTTPAuthenticationSchemeBasic]) {
[self addBasicAuthenticationHeaderWithUsername:[self username] andPassword:[self password]];
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ has a username and password set, and was manually configured to use BASIC. Will send credentials without waiting for an authentication challenge",self);
#endif
} else {
// See if we have any cached credentials we can use in the session store
if ([self useSessionPersistence]) {
credentials = [self findSessionAuthenticationCredentials];
if (credentials) {
// When the Authentication key is set, the credentials were stored after an authentication challenge, so we can let CFNetwork apply them
// (credentials for Digest and NTLM will always be stored like this)
if ([credentials objectForKey:@"Authentication"]) {
// If we've already talked to this server and have valid credentials, let's apply them to the request
if (CFHTTPMessageApplyCredentialDictionary(request, (CFHTTPAuthenticationRef)[credentials objectForKey:@"Authentication"], (CFDictionaryRef)[credentials objectForKey:@"Credentials"], NULL)) {
[self setAuthenticationScheme:[credentials objectForKey:@"AuthenticationScheme"]];
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ found cached credentials (%@), will reuse without waiting for an authentication challenge",self,[credentials objectForKey:@"AuthenticationScheme"]);
#endif
} else {
[[self class] removeAuthenticationCredentialsFromSessionStore:[credentials objectForKey:@"Credentials"]];
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Failed to apply cached credentials to request %@. These will be removed from the session store, and this request will wait for an authentication challenge",self);
#endif
}
// If the Authentication key is not set, these credentials were stored after a username and password set on a previous request passed basic authentication
// When this happens, we'll need to create the Authorization header ourselves
} else {
NSDictionary *usernameAndPassword = [credentials objectForKey:@"Credentials"];
[self addBasicAuthenticationHeaderWithUsername:[usernameAndPassword objectForKey:(NSString *)kCFHTTPAuthenticationUsername] andPassword:[usernameAndPassword objectForKey:(NSString *)kCFHTTPAuthenticationPassword]];
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ found cached BASIC credentials from a previous request. Will send credentials without waiting for an authentication challenge",self);
#endif
}
}
}
}
}
// Apply proxy authentication credentials
if ([self useSessionPersistence]) {
credentials = [self findSessionProxyAuthenticationCredentials];
if (credentials) {
if (!CFHTTPMessageApplyCredentialDictionary(request, (CFHTTPAuthenticationRef)[credentials objectForKey:@"Authentication"], (CFDictionaryRef)[credentials objectForKey:@"Credentials"], NULL)) {
[[self class] removeProxyAuthenticationCredentialsFromSessionStore:[credentials objectForKey:@"Credentials"]];
}
}
}
}
- (void)applyCookieHeader
{
// Add cookies from the persistent (mac os global) store
if ([self useCookiePersistence]) {
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[[self url] absoluteURL]];
if (cookies) {
[[self requestCookies] addObjectsFromArray:cookies];
}
}
// Apply request cookies
NSArray *cookies;
if ([self mainRequest]) {
cookies = [[self mainRequest] requestCookies];
} else {
cookies = [self requestCookies];
}
if ([cookies count] > 0) {
NSHTTPCookie *cookie;
NSString *cookieHeader = nil;
for (cookie in cookies) {
if (!cookieHeader) {
cookieHeader = [NSString stringWithFormat: @"%@=%@",[cookie name],[cookie value]];
} else {
cookieHeader = [NSString stringWithFormat: @"%@; %@=%@",cookieHeader,[cookie name],[cookie value]];
}
}
if (cookieHeader) {
[self addRequestHeader:@"Cookie" value:cookieHeader];
}
}
}
- (void)buildRequestHeaders
{
if ([self haveBuiltRequestHeaders]) {
return;
}
[self setHaveBuiltRequestHeaders:YES];
if ([self mainRequest]) {
for (NSString *header in [[self mainRequest] requestHeaders]) {
[self addRequestHeader:header value:[[[self mainRequest] requestHeaders] valueForKey:header]];
}
return;
}
[self applyCookieHeader];
// Build and set the user agent string if the request does not already have a custom user agent specified
if (![[self requestHeaders] objectForKey:@"User-Agent"]) {
NSString *tempUserAgentString = [self userAgentString];
if (!tempUserAgentString) {
tempUserAgentString = [ASIHTTPRequest defaultUserAgentString];
}
if (tempUserAgentString) {
[self addRequestHeader:@"User-Agent" value:tempUserAgentString];
}
}
// Accept a compressed response
if ([self allowCompressedResponse]) {
[self addRequestHeader:@"Accept-Encoding" value:@"gzip"];
}
// Configure a compressed request body
if ([self shouldCompressRequestBody]) {
[self addRequestHeader:@"Content-Encoding" value:@"gzip"];
}
// Should this request resume an existing download?
[self updatePartialDownloadSize];
if ([self partialDownloadSize]) {
[self addRequestHeader:@"Range" value:[NSString stringWithFormat:@"bytes=%llu-",[self partialDownloadSize]]];
}
}
- (void)updatePartialDownloadSize
{
NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
if ([self allowResumeForFileDownloads] && [self downloadDestinationPath] && [self temporaryFileDownloadPath] && [fileManager fileExistsAtPath:[self temporaryFileDownloadPath]]) {
NSError *err = nil;
[self setPartialDownloadSize:[[fileManager attributesOfItemAtPath:[self temporaryFileDownloadPath] error:&err] fileSize]];
if (err) {
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIFileManagementError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Failed to get attributes for file at path '%@'",[self temporaryFileDownloadPath]],NSLocalizedDescriptionKey,error,NSUnderlyingErrorKey,nil]]];
return;
}
}
}
- (void)startRequest
{
if ([self isCancelled]) {
return;
}
[self performSelectorOnMainThread:@selector(requestStarted) withObject:nil waitUntilDone:[NSThread isMainThread]];
[self setDownloadComplete:NO];
[self setComplete:NO];
[self setTotalBytesRead:0];
[self setLastBytesRead:0];
if ([self redirectCount] == 0) {
[self setOriginalURL:[self url]];
}
// If we're retrying a request, let's remove any progress we made
if ([self lastBytesSent] > 0) {
[self removeUploadProgressSoFar];
}
[self setLastBytesSent:0];
[self setContentLength:0];
[self setResponseHeaders:nil];
if (![self downloadDestinationPath]) {
[self setRawResponseData:[[[NSMutableData alloc] init] autorelease]];
}
//
// Create the stream for the request
//
NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
[self setReadStreamIsScheduled:NO];
// Do we need to stream the request body from disk
if ([self shouldStreamPostDataFromDisk] && [self postBodyFilePath] && [fileManager fileExistsAtPath:[self postBodyFilePath]]) {
// Are we gzipping the request body?
if ([self compressedPostBodyFilePath] && [fileManager fileExistsAtPath:[self compressedPostBodyFilePath]]) {
[self setPostBodyReadStream:[ASIInputStream inputStreamWithFileAtPath:[self compressedPostBodyFilePath] request:self]];
} else {
[self setPostBodyReadStream:[ASIInputStream inputStreamWithFileAtPath:[self postBodyFilePath] request:self]];
}
[self setReadStream:[NSMakeCollectable(CFReadStreamCreateForStreamedHTTPRequest(kCFAllocatorDefault, request,(CFReadStreamRef)[self postBodyReadStream])) autorelease]];
} else {
// If we have a request body, we'll stream it from memory using our custom stream, so that we can measure bandwidth use and it can be bandwidth-throttled if necessary
if ([self postBody] && [[self postBody] length] > 0) {
if ([self shouldCompressRequestBody] && [self compressedPostBody]) {
[self setPostBodyReadStream:[ASIInputStream inputStreamWithData:[self compressedPostBody] request:self]];
} else if ([self postBody]) {
[self setPostBodyReadStream:[ASIInputStream inputStreamWithData:[self postBody] request:self]];
}
[self setReadStream:[NSMakeCollectable(CFReadStreamCreateForStreamedHTTPRequest(kCFAllocatorDefault, request,(CFReadStreamRef)[self postBodyReadStream])) autorelease]];
} else {
[self setReadStream:[NSMakeCollectable(CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, request)) autorelease]];
}
}
if (![self readStream]) {
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileBuildingRequestType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Unable to create read stream",NSLocalizedDescriptionKey,nil]]];
return;
}
//
// Handle SSL certificate settings
//
if([[[[self url] scheme] lowercaseString] isEqualToString:@"https"]) {
// Tell CFNetwork not to validate SSL certificates
if (![self validatesSecureCertificate]) {
// see: http://iphonedevelopment.blogspot.com/2010/05/nsstream-tcp-and-ssl.html
NSDictionary *sslProperties = [[NSDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithBool:YES], kCFStreamSSLAllowsExpiredCertificates,
[NSNumber numberWithBool:YES], kCFStreamSSLAllowsAnyRoot,
[NSNumber numberWithBool:NO], kCFStreamSSLValidatesCertificateChain,
kCFNull,kCFStreamSSLPeerName,
nil];
CFReadStreamSetProperty((CFReadStreamRef)[self readStream],
kCFStreamPropertySSLSettings,
(CFTypeRef)sslProperties);
[sslProperties release];
}
// Tell CFNetwork to use a client certificate
if (clientCertificateIdentity) {
NSMutableDictionary *sslProperties = [NSMutableDictionary dictionaryWithCapacity:1];
NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[clientCertificates count]+1];
// The first object in the array is our SecIdentityRef
[certificates addObject:(id)clientCertificateIdentity];
// If we've added any additional certificates, add them too
for (id cert in clientCertificates) {
[certificates addObject:cert];
}
[sslProperties setObject:certificates forKey:(NSString *)kCFStreamSSLCertificates];
CFReadStreamSetProperty((CFReadStreamRef)[self readStream], kCFStreamPropertySSLSettings, sslProperties);
}
}
//
// Handle proxy settings
//
if ([self proxyHost] && [self proxyPort]) {
NSString *hostKey;
NSString *portKey;
if (![self proxyType]) {
[self setProxyType:(NSString *)kCFProxyTypeHTTP];
}
if ([[self proxyType] isEqualToString:(NSString *)kCFProxyTypeSOCKS]) {
hostKey = (NSString *)kCFStreamPropertySOCKSProxyHost;
portKey = (NSString *)kCFStreamPropertySOCKSProxyPort;
} else {
hostKey = (NSString *)kCFStreamPropertyHTTPProxyHost;
portKey = (NSString *)kCFStreamPropertyHTTPProxyPort;
if ([[[[self url] scheme] lowercaseString] isEqualToString:@"https"]) {
hostKey = (NSString *)kCFStreamPropertyHTTPSProxyHost;
portKey = (NSString *)kCFStreamPropertyHTTPSProxyPort;
}
}
NSMutableDictionary *proxyToUse = [NSMutableDictionary dictionaryWithObjectsAndKeys:[self proxyHost],hostKey,[NSNumber numberWithInt:[self proxyPort]],portKey,nil];
if ([[self proxyType] isEqualToString:(NSString *)kCFProxyTypeSOCKS]) {
CFReadStreamSetProperty((CFReadStreamRef)[self readStream], kCFStreamPropertySOCKSProxy, proxyToUse);
} else {
CFReadStreamSetProperty((CFReadStreamRef)[self readStream], kCFStreamPropertyHTTPProxy, proxyToUse);
}
}
//
// Handle persistent connections
//
[ASIHTTPRequest expirePersistentConnections];
[connectionsLock lock];
if (![[self url] host] || ![[self url] scheme]) {
[self setConnectionInfo:nil];
[self setShouldAttemptPersistentConnection:NO];
}
// Will store the old stream that was using this connection (if there was one) so we can clean it up once we've opened our own stream
NSInputStream *oldStream = nil;
// Use a persistent connection if possible
if ([self shouldAttemptPersistentConnection]) {
// If we are redirecting, we will re-use the current connection only if we are connecting to the same server
if ([self connectionInfo]) {
if (![[[self connectionInfo] objectForKey:@"host"] isEqualToString:[[self url] host]] || ![[[self connectionInfo] objectForKey:@"scheme"] isEqualToString:[[self url] scheme]] || [(NSNumber *)[[self connectionInfo] objectForKey:@"port"] intValue] != [[[self url] port] intValue]) {
[self setConnectionInfo:nil];
// Check if we should have expired this connection
} else if ([[[self connectionInfo] objectForKey:@"expires"] timeIntervalSinceNow] < 0) {
#if DEBUG_PERSISTENT_CONNECTIONS
ASI_DEBUG_LOG(@"[CONNECTION] Not re-using connection #%i because it has expired",[[[self connectionInfo] objectForKey:@"id"] intValue]);
#endif
[persistentConnectionsPool removeObject:[self connectionInfo]];
[self setConnectionInfo:nil];
} else if ([[self connectionInfo] objectForKey:@"request"] != nil) {
//Some other request reused this connection already - we'll have to create a new one
#if DEBUG_PERSISTENT_CONNECTIONS
ASI_DEBUG_LOG(@"%@ - Not re-using connection #%i for request #%i because it is already used by request #%i",self,[[[self connectionInfo] objectForKey:@"id"] intValue],[[self requestID] intValue],[[[self connectionInfo] objectForKey:@"request"] intValue]);
#endif
[self setConnectionInfo:nil];
}
}
if (![self connectionInfo] && [[self url] host] && [[self url] scheme]) { // We must have a proper url with a host and scheme, or this will explode
// Look for a connection to the same server in the pool
for (NSMutableDictionary *existingConnection in persistentConnectionsPool) {
if (![existingConnection objectForKey:@"request"] && [[existingConnection objectForKey:@"host"] isEqualToString:[[self url] host]] && [[existingConnection objectForKey:@"scheme"] isEqualToString:[[self url] scheme]] && [(NSNumber *)[existingConnection objectForKey:@"port"] intValue] == [[[self url] port] intValue]) {
[self setConnectionInfo:existingConnection];
}
}
}
if ([[self connectionInfo] objectForKey:@"stream"]) {
oldStream = [[[self connectionInfo] objectForKey:@"stream"] retain];
}
// No free connection was found in the pool matching the server/scheme/port we're connecting to, we'll need to create a new one
if (![self connectionInfo]) {
[self setConnectionInfo:[NSMutableDictionary dictionary]];
nextConnectionNumberToCreate++;
[[self connectionInfo] setObject:[NSNumber numberWithInt:nextConnectionNumberToCreate] forKey:@"id"];
[[self connectionInfo] setObject:[[self url] host] forKey:@"host"];
[[self connectionInfo] setObject:[NSNumber numberWithInt:[[[self url] port] intValue]] forKey:@"port"];
[[self connectionInfo] setObject:[[self url] scheme] forKey:@"scheme"];
[persistentConnectionsPool addObject:[self connectionInfo]];
}
// If we are retrying this request, it will already have a requestID
if (![self requestID]) {
nextRequestID++;
[self setRequestID:[NSNumber numberWithUnsignedInt:nextRequestID]];
}
[[self connectionInfo] setObject:[self requestID] forKey:@"request"];
[[self connectionInfo] setObject:[self readStream] forKey:@"stream"];
CFReadStreamSetProperty((CFReadStreamRef)[self readStream], kCFStreamPropertyHTTPAttemptPersistentConnection, kCFBooleanTrue);
#if DEBUG_PERSISTENT_CONNECTIONS
ASI_DEBUG_LOG(@"[CONNECTION] Request #%@ will use connection #%i",[self requestID],[[[self connectionInfo] objectForKey:@"id"] intValue]);
#endif
// Tag the stream with an id that tells it which connection to use behind the scenes
// See http://lists.apple.com/archives/macnetworkprog/2008/Dec/msg00001.html for details on this approach
CFReadStreamSetProperty((CFReadStreamRef)[self readStream], CFSTR("ASIStreamID"), [[self connectionInfo] objectForKey:@"id"]);
} else {
#if DEBUG_PERSISTENT_CONNECTIONS
ASI_DEBUG_LOG(@"[CONNECTION] Request %@ will not use a persistent connection",self);
#endif
}
[connectionsLock unlock];
// Schedule the stream
if (![self readStreamIsScheduled] && (!throttleWakeUpTime || [throttleWakeUpTime timeIntervalSinceDate:[NSDate date]] < 0)) {
[self scheduleReadStream];
}
BOOL streamSuccessfullyOpened = NO;
// Start the HTTP connection
CFStreamClientContext ctxt = {0, self, NULL, NULL, NULL};
if (CFReadStreamSetClient((CFReadStreamRef)[self readStream], kNetworkEvents, ReadStreamClientCallBack, &ctxt)) {
if (CFReadStreamOpen((CFReadStreamRef)[self readStream])) {
streamSuccessfullyOpened = YES;
}
}
// Here, we'll close the stream that was previously using this connection, if there was one
// We've kept it open until now (when we've just opened a new stream) so that the new stream can make use of the old connection
// http://lists.apple.com/archives/Macnetworkprog/2006/Mar/msg00119.html
if (oldStream) {
[oldStream close];
[oldStream release];
oldStream = nil;
}
if (!streamSuccessfullyOpened) {
[self setConnectionCanBeReused:NO];
[self destroyReadStream];
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileBuildingRequestType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Unable to start HTTP connection",NSLocalizedDescriptionKey,nil]]];
return;
}
if (![self mainRequest]) {
if ([self shouldResetUploadProgress]) {
if ([self showAccurateProgress]) {
[self incrementUploadSizeBy:[self postLength]];
} else {
[self incrementUploadSizeBy:1];
}
[ASIHTTPRequest updateProgressIndicator:&uploadProgressDelegate withProgress:0 ofTotal:1];
}
if ([self shouldResetDownloadProgress] && ![self partialDownloadSize]) {
[ASIHTTPRequest updateProgressIndicator:&downloadProgressDelegate withProgress:0 ofTotal:1];
}
}
// Record when the request started, so we can timeout if nothing happens
[self setLastActivityTime:[NSDate date]];
[self setStatusTimer:[NSTimer timerWithTimeInterval:0.25 target:self selector:@selector(updateStatus:) userInfo:nil repeats:YES]];
[[NSRunLoop currentRunLoop] addTimer:[self statusTimer] forMode:[self runLoopMode]];
}
- (void)setStatusTimer:(NSTimer *)timer
{
CFRetain(self);
// We must invalidate the old timer here, not before we've created and scheduled a new timer
// This is because the timer may be the only thing retaining an asynchronous request
if (statusTimer && timer != statusTimer) {
[statusTimer invalidate];
[statusTimer release];
}
statusTimer = [timer retain];
CFRelease(self);
}
// This gets fired every 1/4 of a second to update the progress and work out if we need to timeout
- (void)updateStatus:(NSTimer*)timer
{
[self checkRequestStatus];
if (![self inProgress]) {
[self setStatusTimer:nil];
}
}
- (void)performRedirect
{
[self setURL:[self redirectURL]];
[self setComplete:YES];
[self setNeedsRedirect:NO];
[self setRedirectCount:[self redirectCount]+1];
if ([self redirectCount] > RedirectionLimit) {
// Some naughty / badly coded website is trying to force us into a redirection loop. This is not cool.
[self failWithError:ASITooMuchRedirectionError];
[self setComplete:YES];
} else {
// Go all the way back to the beginning and build the request again, so that we can apply any new cookies
[self main];
}
}
// Called by delegate to resume loading with a new url after the delegate received request:willRedirectToURL:
- (void)redirectToURL:(NSURL *)newURL
{
[self setRedirectURL:newURL];
[self performSelector:@selector(performRedirect) onThread:[[self class] threadForRequest:self] withObject:nil waitUntilDone:NO];
}
- (BOOL)shouldTimeOut
{
NSTimeInterval secondsSinceLastActivity = [[NSDate date] timeIntervalSinceDate:lastActivityTime];
// See if we need to timeout
if ([self readStream] && [self readStreamIsScheduled] && [self lastActivityTime] && [self timeOutSeconds] > 0 && secondsSinceLastActivity > [self timeOutSeconds]) {
// We have no body, or we've sent more than the upload buffer size,so we can safely time out here
if ([self postLength] == 0 || ([self uploadBufferSize] > 0 && [self totalBytesSent] > [self uploadBufferSize])) {
return YES;
// ***Black magic warning***
// We have a body, but we've taken longer than timeOutSeconds to upload the first small chunk of data
// Since there's no reliable way to track upload progress for the first 32KB (iPhone) or 128KB (Mac) with CFNetwork, we'll be slightly more forgiving on the timeout, as there's a strong chance our connection is just very slow.
} else if (secondsSinceLastActivity > [self timeOutSeconds]*1.5) {
return YES;
}
}
return NO;
}
- (void)checkRequestStatus
{
// We won't let the request cancel while we're updating progress / checking for a timeout
[[self cancelledLock] lock];
// See if our NSOperationQueue told us to cancel
if ([self isCancelled] || [self complete]) {
[[self cancelledLock] unlock];
return;
}
[self performThrottling];
if ([self shouldTimeOut]) {
// Do we need to auto-retry this request?
if ([self numberOfTimesToRetryOnTimeout] > [self retryCount]) {
// If we are resuming a download, we may need to update the Range header to take account of data we've just downloaded
[self updatePartialDownloadSize];
if ([self partialDownloadSize]) {
CFHTTPMessageSetHeaderFieldValue(request, (CFStringRef)@"Range", (CFStringRef)[NSString stringWithFormat:@"bytes=%llu-",[self partialDownloadSize]]);
}
[self setRetryCount:[self retryCount]+1];
[self unscheduleReadStream];
[[self cancelledLock] unlock];
[self startRequest];
return;
}
[self failWithError:ASIRequestTimedOutError];
[self cancelLoad];
[self setComplete:YES];
[[self cancelledLock] unlock];
return;
}
// readStream will be null if we aren't currently running (perhaps we're waiting for a delegate to supply credentials)
if ([self readStream]) {
// If we have a post body
if ([self postLength]) {
[self setLastBytesSent:totalBytesSent];
// Find out how much data we've uploaded so far
[self setTotalBytesSent:[[NSMakeCollectable(CFReadStreamCopyProperty((CFReadStreamRef)[self readStream], kCFStreamPropertyHTTPRequestBytesWrittenCount)) autorelease] unsignedLongLongValue]];
if (totalBytesSent > lastBytesSent) {
// We've uploaded more data, reset the timeout
[self setLastActivityTime:[NSDate date]];
[ASIHTTPRequest incrementBandwidthUsedInLastSecond:(unsigned long)(totalBytesSent-lastBytesSent)];
#if DEBUG_REQUEST_STATUS
if ([self totalBytesSent] == [self postLength]) {
ASI_DEBUG_LOG(@"[STATUS] Request %@ finished uploading data",self);
}
#endif
}
}
[self updateProgressIndicators];
}
[[self cancelledLock] unlock];
}
// Cancel loading and clean up. DO NOT USE THIS TO CANCEL REQUESTS - use [request cancel] instead
- (void)cancelLoad
{
// If we're in the middle of downloading a PAC file, let's stop that first
if (PACFileReadStream) {
[PACFileReadStream setDelegate:nil];
[PACFileReadStream close];
[self setPACFileReadStream:nil];
[self setPACFileData:nil];
} else if (PACFileRequest) {
[PACFileRequest setDelegate:nil];
[PACFileRequest cancel];
[self setPACFileRequest:nil];
}
[self destroyReadStream];
[[self postBodyReadStream] close];
[self setPostBodyReadStream:nil];
if ([self rawResponseData]) {
if (![self complete]) {
[self setRawResponseData:nil];
}
// If we were downloading to a file
} else if ([self temporaryFileDownloadPath]) {
[[self fileDownloadOutputStream] close];
[self setFileDownloadOutputStream:nil];
[[self inflatedFileDownloadOutputStream] close];
[self setInflatedFileDownloadOutputStream:nil];
// If we haven't said we might want to resume, let's remove the temporary file too
if (![self complete]) {
if (![self allowResumeForFileDownloads]) {
[self removeTemporaryDownloadFile];
}
[self removeTemporaryUncompressedDownloadFile];
}
}
// Clean up any temporary file used to store request body for streaming
if (![self authenticationNeeded] && ![self willRetryRequest] && [self didCreateTemporaryPostDataFile]) {
[self removeTemporaryUploadFile];
[self removeTemporaryCompressedUploadFile];
[self setDidCreateTemporaryPostDataFile:NO];
}
}
#pragma mark HEAD request
// Used by ASINetworkQueue to create a HEAD request appropriate for this request with the same headers (though you can use it yourself)
- (ASIHTTPRequest *)HEADRequest
{
ASIHTTPRequest *headRequest = [[self class] requestWithURL:[self url]];
// Copy the properties that make sense for a HEAD request
[headRequest setRequestHeaders:[[[self requestHeaders] mutableCopy] autorelease]];
[headRequest setRequestCookies:[[[self requestCookies] mutableCopy] autorelease]];
[headRequest setUseCookiePersistence:[self useCookiePersistence]];
[headRequest setUseKeychainPersistence:[self useKeychainPersistence]];
[headRequest setUseSessionPersistence:[self useSessionPersistence]];
[headRequest setAllowCompressedResponse:[self allowCompressedResponse]];
[headRequest setUsername:[self username]];
[headRequest setPassword:[self password]];
[headRequest setDomain:[self domain]];
[headRequest setProxyUsername:[self proxyUsername]];
[headRequest setProxyPassword:[self proxyPassword]];
[headRequest setProxyDomain:[self proxyDomain]];
[headRequest setProxyHost:[self proxyHost]];
[headRequest setProxyPort:[self proxyPort]];
[headRequest setProxyType:[self proxyType]];
[headRequest setShouldPresentAuthenticationDialog:[self shouldPresentAuthenticationDialog]];
[headRequest setShouldPresentProxyAuthenticationDialog:[self shouldPresentProxyAuthenticationDialog]];
[headRequest setTimeOutSeconds:[self timeOutSeconds]];
[headRequest setUseHTTPVersionOne:[self useHTTPVersionOne]];
[headRequest setValidatesSecureCertificate:[self validatesSecureCertificate]];
[headRequest setClientCertificateIdentity:clientCertificateIdentity];
[headRequest setClientCertificates:[[clientCertificates copy] autorelease]];
[headRequest setPACurl:[self PACurl]];
[headRequest setShouldPresentCredentialsBeforeChallenge:[self shouldPresentCredentialsBeforeChallenge]];
[headRequest setNumberOfTimesToRetryOnTimeout:[self numberOfTimesToRetryOnTimeout]];
[headRequest setShouldUseRFC2616RedirectBehaviour:[self shouldUseRFC2616RedirectBehaviour]];
[headRequest setShouldAttemptPersistentConnection:[self shouldAttemptPersistentConnection]];
[headRequest setPersistentConnectionTimeoutSeconds:[self persistentConnectionTimeoutSeconds]];
[headRequest setMainRequest:self];
[headRequest setRequestMethod:@"HEAD"];
return headRequest;
}
#pragma mark upload/download progress
- (void)updateProgressIndicators
{
//Only update progress if this isn't a HEAD request used to preset the content-length
if (![self mainRequest]) {
if ([self showAccurateProgress] || ([self complete] && ![self updatedProgress])) {
[self updateUploadProgress];
[self updateDownloadProgress];
}
}
}
- (id)uploadProgressDelegate
{
[[self cancelledLock] lock];
id d = [[uploadProgressDelegate retain] autorelease];
[[self cancelledLock] unlock];
return d;
}
- (void)setUploadProgressDelegate:(id)newDelegate
{
[[self cancelledLock] lock];
uploadProgressDelegate = newDelegate;
#if !TARGET_OS_IPHONE
// If the uploadProgressDelegate is an NSProgressIndicator, we set its MaxValue to 1.0 so we can update it as if it were a UIProgressView
double max = 1.0;
[ASIHTTPRequest performSelector:@selector(setMaxValue:) onTarget:&uploadProgressDelegate withObject:nil amount:&max callerToRetain:nil];
#endif
[[self cancelledLock] unlock];
}
- (id)downloadProgressDelegate
{
[[self cancelledLock] lock];
id d = [[downloadProgressDelegate retain] autorelease];
[[self cancelledLock] unlock];
return d;
}
- (void)setDownloadProgressDelegate:(id)newDelegate
{
[[self cancelledLock] lock];
downloadProgressDelegate = newDelegate;
#if !TARGET_OS_IPHONE
// If the downloadProgressDelegate is an NSProgressIndicator, we set its MaxValue to 1.0 so we can update it as if it were a UIProgressView
double max = 1.0;
[ASIHTTPRequest performSelector:@selector(setMaxValue:) onTarget:&downloadProgressDelegate withObject:nil amount:&max callerToRetain:nil];
#endif
[[self cancelledLock] unlock];
}
- (void)updateDownloadProgress
{
// We won't update download progress until we've examined the headers, since we might need to authenticate
if (![self responseHeaders] || [self needsRedirect] || !([self contentLength] || [self complete])) {
return;
}
unsigned long long bytesReadSoFar = [self totalBytesRead]+[self partialDownloadSize];
unsigned long long value = 0;
if ([self showAccurateProgress] && [self contentLength]) {
value = bytesReadSoFar-[self lastBytesRead];
if (value == 0) {
return;
}
} else {
value = 1;
[self setUpdatedProgress:YES];
}
if (!value) {
return;
}
[ASIHTTPRequest performSelector:@selector(request:didReceiveBytes:) onTarget:&queue withObject:self amount:&value callerToRetain:self];
[ASIHTTPRequest performSelector:@selector(request:didReceiveBytes:) onTarget:&downloadProgressDelegate withObject:self amount:&value callerToRetain:self];
[ASIHTTPRequest updateProgressIndicator:&downloadProgressDelegate withProgress:[self totalBytesRead]+[self partialDownloadSize] ofTotal:[self contentLength]+[self partialDownloadSize]];
#if NS_BLOCKS_AVAILABLE
if (bytesReceivedBlock) {
unsigned long long totalSize = [self contentLength] + [self partialDownloadSize];
[self performBlockOnMainThread:^{ if (bytesReceivedBlock) { bytesReceivedBlock(value, totalSize); }}];
}
#endif
[self setLastBytesRead:bytesReadSoFar];
}
- (void)updateUploadProgress
{
if ([self isCancelled] || [self totalBytesSent] == 0) {
return;
}
// If this is the first time we've written to the buffer, totalBytesSent will be the size of the buffer (currently seems to be 128KB on both Leopard and iPhone 2.2.1, 32KB on iPhone 3.0)
// If request body is less than the buffer size, totalBytesSent will be the total size of the request body
// We will remove this from any progress display, as kCFStreamPropertyHTTPRequestBytesWrittenCount does not tell us how much data has actually be written
if ([self uploadBufferSize] == 0 && [self totalBytesSent] != [self postLength]) {
[self setUploadBufferSize:[self totalBytesSent]];
[self incrementUploadSizeBy:-[self uploadBufferSize]];
}
unsigned long long value = 0;
if ([self showAccurateProgress]) {
if ([self totalBytesSent] == [self postLength] || [self lastBytesSent] > 0) {
value = [self totalBytesSent]-[self lastBytesSent];
} else {
return;
}
} else {
value = 1;
[self setUpdatedProgress:YES];
}
if (!value) {
return;
}
[ASIHTTPRequest performSelector:@selector(request:didSendBytes:) onTarget:&queue withObject:self amount:&value callerToRetain:self];
[ASIHTTPRequest performSelector:@selector(request:didSendBytes:) onTarget:&uploadProgressDelegate withObject:self amount:&value callerToRetain:self];
[ASIHTTPRequest updateProgressIndicator:&uploadProgressDelegate withProgress:[self totalBytesSent]-[self uploadBufferSize] ofTotal:[self postLength]-[self uploadBufferSize]];
#if NS_BLOCKS_AVAILABLE
if(bytesSentBlock){
unsigned long long totalSize = [self postLength];
[self performBlockOnMainThread:^{ if (bytesSentBlock) { bytesSentBlock(value, totalSize); }}];
}
#endif
}
- (void)incrementDownloadSizeBy:(long long)length
{
[ASIHTTPRequest performSelector:@selector(request:incrementDownloadSizeBy:) onTarget:&queue withObject:self amount:&length callerToRetain:self];
[ASIHTTPRequest performSelector:@selector(request:incrementDownloadSizeBy:) onTarget:&downloadProgressDelegate withObject:self amount:&length callerToRetain:self];
#if NS_BLOCKS_AVAILABLE
if(downloadSizeIncrementedBlock){
[self performBlockOnMainThread:^{ if (downloadSizeIncrementedBlock) { downloadSizeIncrementedBlock(length); }}];
}
#endif
}
- (void)incrementUploadSizeBy:(long long)length
{
[ASIHTTPRequest performSelector:@selector(request:incrementUploadSizeBy:) onTarget:&queue withObject:self amount:&length callerToRetain:self];
[ASIHTTPRequest performSelector:@selector(request:incrementUploadSizeBy:) onTarget:&uploadProgressDelegate withObject:self amount:&length callerToRetain:self];
#if NS_BLOCKS_AVAILABLE
if(uploadSizeIncrementedBlock) {
[self performBlockOnMainThread:^{ if (uploadSizeIncrementedBlock) { uploadSizeIncrementedBlock(length); }}];
}
#endif
}
-(void)removeUploadProgressSoFar
{
long long progressToRemove = -[self totalBytesSent];
[ASIHTTPRequest performSelector:@selector(request:didSendBytes:) onTarget:&queue withObject:self amount:&progressToRemove callerToRetain:self];
[ASIHTTPRequest performSelector:@selector(request:didSendBytes:) onTarget:&uploadProgressDelegate withObject:self amount:&progressToRemove callerToRetain:self];
[ASIHTTPRequest updateProgressIndicator:&uploadProgressDelegate withProgress:0 ofTotal:[self postLength]];
#if NS_BLOCKS_AVAILABLE
if(bytesSentBlock){
unsigned long long totalSize = [self postLength];
[self performBlockOnMainThread:^{ if (bytesSentBlock) { bytesSentBlock(progressToRemove, totalSize); }}];
}
#endif
}
#if NS_BLOCKS_AVAILABLE
- (void)performBlockOnMainThread:(ASIBasicBlock)block
{
[self performSelectorOnMainThread:@selector(callBlock:) withObject:[[block copy] autorelease] waitUntilDone:[NSThread isMainThread]];
}
- (void)callBlock:(ASIBasicBlock)block
{
block();
}
#endif
+ (void)performSelector:(SEL)selector onTarget:(id *)target withObject:(id)object amount:(void *)amount callerToRetain:(id)callerToRetain
{
if ([*target respondsToSelector:selector]) {
NSMethodSignature *signature = nil;
signature = [*target methodSignatureForSelector:selector];
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
[invocation setSelector:selector];
int argumentNumber = 2;
// If we got an object parameter, we pass a pointer to the object pointer
if (object) {
[invocation setArgument:&object atIndex:argumentNumber];
argumentNumber++;
}
// For the amount we'll just pass the pointer directly so NSInvocation will call the method using the number itself rather than a pointer to it
if (amount) {
[invocation setArgument:amount atIndex:argumentNumber];
}
SEL callback = @selector(performInvocation:onTarget:releasingObject:);
NSMethodSignature *cbSignature = [ASIHTTPRequest methodSignatureForSelector:callback];
NSInvocation *cbInvocation = [NSInvocation invocationWithMethodSignature:cbSignature];
[cbInvocation setSelector:callback];
[cbInvocation setTarget:self];
[cbInvocation setArgument:&invocation atIndex:2];
[cbInvocation setArgument:&target atIndex:3];
if (callerToRetain) {
[cbInvocation setArgument:&callerToRetain atIndex:4];
}
CFRetain(invocation);
// Used to pass in a request that we must retain until after the call
// We're using CFRetain rather than [callerToRetain retain] so things to avoid earthquakes when using garbage collection
if (callerToRetain) {
CFRetain(callerToRetain);
}
[cbInvocation performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:[NSThread isMainThread]];
}
}
+ (void)performInvocation:(NSInvocation *)invocation onTarget:(id *)target releasingObject:(id)objectToRelease
{
if (*target && [*target respondsToSelector:[invocation selector]]) {
[invocation invokeWithTarget:*target];
}
CFRelease(invocation);
if (objectToRelease) {
CFRelease(objectToRelease);
}
}
+ (void)updateProgressIndicator:(id *)indicator withProgress:(unsigned long long)progress ofTotal:(unsigned long long)total
{
#if TARGET_OS_IPHONE
// Cocoa Touch: UIProgressView
SEL selector = @selector(setProgress:);
float progressAmount = (float)((progress*1.0)/(total*1.0));
#else
// Cocoa: NSProgressIndicator
double progressAmount = progressAmount = (progress*1.0)/(total*1.0);
SEL selector = @selector(setDoubleValue:);
#endif
if (![*indicator respondsToSelector:selector]) {
return;
}
[progressLock lock];
[ASIHTTPRequest performSelector:selector onTarget:indicator withObject:nil amount:&progressAmount callerToRetain:nil];
[progressLock unlock];
}
#pragma mark talking to delegates / calling blocks
/* ALWAYS CALLED ON MAIN THREAD! */
- (void)requestStarted
{
if ([self error] || [self mainRequest]) {
return;
}
if (delegate && [delegate respondsToSelector:didStartSelector]) {
[delegate performSelector:didStartSelector withObject:self];
}
#if NS_BLOCKS_AVAILABLE
if(startedBlock){
startedBlock();
}
#endif
if (queue && [queue respondsToSelector:@selector(requestStarted:)]) {
[queue performSelector:@selector(requestStarted:) withObject:self];
}
}
/* ALWAYS CALLED ON MAIN THREAD! */
- (void)requestRedirected
{
if ([self error] || [self mainRequest]) {
return;
}
if([[self delegate] respondsToSelector:@selector(requestRedirected:)]){
[[self delegate] performSelector:@selector(requestRedirected:) withObject:self];
}
#if NS_BLOCKS_AVAILABLE
if(requestRedirectedBlock){
requestRedirectedBlock();
}
#endif
}
/* ALWAYS CALLED ON MAIN THREAD! */
- (void)requestReceivedResponseHeaders:(NSMutableDictionary *)newResponseHeaders
{
if ([self error] || [self mainRequest]) {
return;
}
if (delegate && [delegate respondsToSelector:didReceiveResponseHeadersSelector]) {
[delegate performSelector:didReceiveResponseHeadersSelector withObject:self withObject:newResponseHeaders];
}
#if NS_BLOCKS_AVAILABLE
if(headersReceivedBlock){
headersReceivedBlock(newResponseHeaders);
}
#endif
if (queue && [queue respondsToSelector:@selector(request:didReceiveResponseHeaders:)]) {
[queue performSelector:@selector(request:didReceiveResponseHeaders:) withObject:self withObject:newResponseHeaders];
}
}
/* ALWAYS CALLED ON MAIN THREAD! */
- (void)requestWillRedirectToURL:(NSURL *)newURL
{
if ([self error] || [self mainRequest]) {
return;
}
if (delegate && [delegate respondsToSelector:willRedirectSelector]) {
[delegate performSelector:willRedirectSelector withObject:self withObject:newURL];
}
if (queue && [queue respondsToSelector:@selector(request:willRedirectToURL:)]) {
[queue performSelector:@selector(request:willRedirectToURL:) withObject:self withObject:newURL];
}
}
// Subclasses might override this method to process the result in the same thread
// If you do this, don't forget to call [super requestFinished] to let the queue / delegate know we're done
- (void)requestFinished
{
#if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
ASI_DEBUG_LOG(@"[STATUS] Request finished: %@",self);
#endif
if ([self error] || [self mainRequest]) {
return;
}
if ([self isPACFileRequest]) {
[self reportFinished];
} else {
[self performSelectorOnMainThread:@selector(reportFinished) withObject:nil waitUntilDone:[NSThread isMainThread]];
}
}
/* ALWAYS CALLED ON MAIN THREAD! */
- (void)reportFinished
{
if (delegate && [delegate respondsToSelector:didFinishSelector]) {
[delegate performSelector:didFinishSelector withObject:self];
}
#if NS_BLOCKS_AVAILABLE
if(completionBlock){
completionBlock();
}
#endif
if (queue && [queue respondsToSelector:@selector(requestFinished:)]) {
[queue performSelector:@selector(requestFinished:) withObject:self];
}
}
/* ALWAYS CALLED ON MAIN THREAD! */
- (void)reportFailure
{
if (delegate && [delegate respondsToSelector:didFailSelector]) {
[delegate performSelector:didFailSelector withObject:self];
}
#if NS_BLOCKS_AVAILABLE
if(failureBlock){
failureBlock();
}
#endif
if (queue && [queue respondsToSelector:@selector(requestFailed:)]) {
[queue performSelector:@selector(requestFailed:) withObject:self];
}
}
/* ALWAYS CALLED ON MAIN THREAD! */
- (void)passOnReceivedData:(NSData *)data
{
if (delegate && [delegate respondsToSelector:didReceiveDataSelector]) {
[delegate performSelector:didReceiveDataSelector withObject:self withObject:data];
}
#if NS_BLOCKS_AVAILABLE
if (dataReceivedBlock) {
dataReceivedBlock(data);
}
#endif
}
// Subclasses might override this method to perform error handling in the same thread
// If you do this, don't forget to call [super failWithError:] to let the queue / delegate know we're done
- (void)failWithError:(NSError *)theError
{
#if DEBUG_REQUEST_STATUS || DEBUG_THROTTLING
ASI_DEBUG_LOG(@"[STATUS] Request %@: %@",self,(theError == ASIRequestCancelledError ? @"Cancelled" : @"Failed"));
#endif
[self setComplete:YES];
// Invalidate the current connection so subsequent requests don't attempt to reuse it
if (theError && [theError code] != ASIAuthenticationErrorType && [theError code] != ASITooMuchRedirectionErrorType) {
[connectionsLock lock];
#if DEBUG_PERSISTENT_CONNECTIONS
ASI_DEBUG_LOG(@"[CONNECTION] Request #%@ failed and will invalidate connection #%@",[self requestID],[[self connectionInfo] objectForKey:@"id"]);
#endif
[[self connectionInfo] removeObjectForKey:@"request"];
[persistentConnectionsPool removeObject:[self connectionInfo]];
[connectionsLock unlock];
[self destroyReadStream];
}
if ([self connectionCanBeReused]) {
[[self connectionInfo] setObject:[NSDate dateWithTimeIntervalSinceNow:[self persistentConnectionTimeoutSeconds]] forKey:@"expires"];
}
if ([self isCancelled] || [self error]) {
return;
}
// If we have cached data, use it and ignore the error when using ASIFallbackToCacheIfLoadFailsCachePolicy
if ([self downloadCache] && ([self cachePolicy] & ASIFallbackToCacheIfLoadFailsCachePolicy)) {
if ([[self downloadCache] canUseCachedDataForRequest:self]) {
[self useDataFromCache];
return;
}
}
[self setError:theError];
ASIHTTPRequest *failedRequest = self;
// If this is a HEAD request created by an ASINetworkQueue or compatible queue delegate, make the main request fail
if ([self mainRequest]) {
failedRequest = [self mainRequest];
[failedRequest setError:theError];
}
if ([self isPACFileRequest]) {
[failedRequest reportFailure];
} else {
[failedRequest performSelectorOnMainThread:@selector(reportFailure) withObject:nil waitUntilDone:[NSThread isMainThread]];
}
if (!inProgress)
{
// if we're not in progress, we can't notify the queue we've finished (doing so can cause a crash later on)
// "markAsFinished" will be at the start of main() when we are started
return;
}
[self markAsFinished];
}
#pragma mark parsing HTTP response headers
- (void)readResponseHeaders
{
[self setAuthenticationNeeded:ASINoAuthenticationNeededYet];
CFHTTPMessageRef message = (CFHTTPMessageRef)CFReadStreamCopyProperty((CFReadStreamRef)[self readStream], kCFStreamPropertyHTTPResponseHeader);
if (!message) {
return;
}
// Make sure we've received all the headers
if (!CFHTTPMessageIsHeaderComplete(message)) {
CFRelease(message);
return;
}
#if DEBUG_REQUEST_STATUS
if ([self totalBytesSent] == [self postLength]) {
ASI_DEBUG_LOG(@"[STATUS] Request %@ received response headers",self);
}
#endif
[self setResponseHeaders:[NSMakeCollectable(CFHTTPMessageCopyAllHeaderFields(message)) autorelease]];
[self setResponseStatusCode:(int)CFHTTPMessageGetResponseStatusCode(message)];
[self setResponseStatusMessage:[NSMakeCollectable(CFHTTPMessageCopyResponseStatusLine(message)) autorelease]];
if ([self downloadCache] && ([[self downloadCache] canUseCachedDataForRequest:self])) {
// Update the expiry date
[[self downloadCache] updateExpiryForRequest:self maxAge:[self secondsToCache]];
// Read the response from the cache
[self useDataFromCache];
CFRelease(message);
return;
}
// Is the server response a challenge for credentials?
if ([self responseStatusCode] == 401) {
[self setAuthenticationNeeded:ASIHTTPAuthenticationNeeded];
} else if ([self responseStatusCode] == 407) {
[self setAuthenticationNeeded:ASIProxyAuthenticationNeeded];
} else {
#if DEBUG_HTTP_AUTHENTICATION
if ([self authenticationScheme]) {
ASI_DEBUG_LOG(@"[AUTH] Request %@ has passed %@ authentication",self,[self authenticationScheme]);
}
#endif
}
// Authentication succeeded, or no authentication was required
if (![self authenticationNeeded]) {
// Did we get here without an authentication challenge? (which can happen when shouldPresentCredentialsBeforeChallenge is YES and basic auth was successful)
if (!requestAuthentication && [[self authenticationScheme] isEqualToString:(NSString *)kCFHTTPAuthenticationSchemeBasic] && [self username] && [self password] && [self useSessionPersistence]) {
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ passed BASIC authentication, and will save credentials in the session store for future use",self);
#endif
NSMutableDictionary *newCredentials = [NSMutableDictionary dictionaryWithCapacity:2];
[newCredentials setObject:[self username] forKey:(NSString *)kCFHTTPAuthenticationUsername];
[newCredentials setObject:[self password] forKey:(NSString *)kCFHTTPAuthenticationPassword];
// Store the credentials in the session
NSMutableDictionary *sessionCredentials = [NSMutableDictionary dictionary];
[sessionCredentials setObject:newCredentials forKey:@"Credentials"];
[sessionCredentials setObject:[self url] forKey:@"URL"];
[sessionCredentials setObject:(NSString *)kCFHTTPAuthenticationSchemeBasic forKey:@"AuthenticationScheme"];
[[self class] storeAuthenticationCredentialsInSessionStore:sessionCredentials];
}
}
// Read response textEncoding
[self parseStringEncodingFromHeaders];
// Handle cookies
NSArray *newCookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[self responseHeaders] forURL:[self url]];
[self setResponseCookies:newCookies];
if ([self useCookiePersistence]) {
// Store cookies in global persistent store
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:newCookies forURL:[self url] mainDocumentURL:nil];
// We also keep any cookies in the sessionCookies array, so that we have a reference to them if we need to remove them later
NSHTTPCookie *cookie;
for (cookie in newCookies) {
[ASIHTTPRequest addSessionCookie:cookie];
}
}
// Do we need to redirect?
if (![self willRedirect]) {
// See if we got a Content-length header
NSString *cLength = [responseHeaders valueForKey:@"Content-Length"];
ASIHTTPRequest *theRequest = self;
if ([self mainRequest]) {
theRequest = [self mainRequest];
}
if (cLength) {
unsigned long long length = strtoull([cLength UTF8String], NULL, 0);
// Workaround for Apache HEAD requests for dynamically generated content returning the wrong Content-Length when using gzip
if ([self mainRequest] && [self allowCompressedResponse] && length == 20 && [self showAccurateProgress] && [self shouldResetDownloadProgress]) {
[[self mainRequest] setShowAccurateProgress:NO];
[[self mainRequest] incrementDownloadSizeBy:1];
} else {
[theRequest setContentLength:length];
if ([self showAccurateProgress] && [self shouldResetDownloadProgress]) {
[theRequest incrementDownloadSizeBy:[theRequest contentLength]+[theRequest partialDownloadSize]];
}
}
} else if ([self showAccurateProgress] && [self shouldResetDownloadProgress]) {
[theRequest setShowAccurateProgress:NO];
[theRequest incrementDownloadSizeBy:1];
}
}
// Handle connection persistence
if ([self shouldAttemptPersistentConnection]) {
NSString *connectionHeader = [[[self responseHeaders] objectForKey:@"Connection"] lowercaseString];
NSString *httpVersion = [NSMakeCollectable(CFHTTPMessageCopyVersion(message)) autorelease];
// Don't re-use the connection if the server is HTTP 1.0 and didn't send Connection: Keep-Alive
if (![httpVersion isEqualToString:(NSString *)kCFHTTPVersion1_0] || [connectionHeader isEqualToString:@"keep-alive"]) {
// See if server explicitly told us to close the connection
if (![connectionHeader isEqualToString:@"close"]) {
NSString *keepAliveHeader = [[self responseHeaders] objectForKey:@"Keep-Alive"];
// If we got a keep alive header, we'll reuse the connection for as long as the server tells us
if (keepAliveHeader) {
int timeout = 0;
int max = 0;
NSScanner *scanner = [NSScanner scannerWithString:keepAliveHeader];
[scanner scanString:@"timeout=" intoString:NULL];
[scanner scanInt:&timeout];
[scanner scanUpToString:@"max=" intoString:NULL];
[scanner scanString:@"max=" intoString:NULL];
[scanner scanInt:&max];
if (max > 5) {
[self setConnectionCanBeReused:YES];
[self setPersistentConnectionTimeoutSeconds:timeout];
#if DEBUG_PERSISTENT_CONNECTIONS
ASI_DEBUG_LOG(@"[CONNECTION] Got a keep-alive header, will keep this connection open for %f seconds", [self persistentConnectionTimeoutSeconds]);
#endif
}
// Otherwise, we'll assume we can keep this connection open
} else {
[self setConnectionCanBeReused:YES];
#if DEBUG_PERSISTENT_CONNECTIONS
ASI_DEBUG_LOG(@"[CONNECTION] Got no keep-alive header, will keep this connection open for %f seconds", [self persistentConnectionTimeoutSeconds]);
#endif
}
}
}
}
CFRelease(message);
[self performSelectorOnMainThread:@selector(requestReceivedResponseHeaders:) withObject:[[[self responseHeaders] copy] autorelease] waitUntilDone:[NSThread isMainThread]];
}
- (BOOL)willRedirect
{
// Do we need to redirect?
if (![self shouldRedirect] || ![responseHeaders valueForKey:@"Location"]) {
return NO;
}
// Note that ASIHTTPRequest does not currently support 305 Use Proxy
int responseCode = [self responseStatusCode];
if (responseCode != 301 && responseCode != 302 && responseCode != 303 && responseCode != 307) {
return NO;
}
[self performSelectorOnMainThread:@selector(requestRedirected) withObject:nil waitUntilDone:[NSThread isMainThread]];
// By default, we redirect 301 and 302 response codes as GET requests
// According to RFC 2616 this is wrong, but this is what most browsers do, so it's probably what you're expecting to happen
// See also:
// http://allseeing-i.lighthouseapp.com/projects/27881/tickets/27-302-redirection-issue
if (responseCode != 307 && (![self shouldUseRFC2616RedirectBehaviour] || responseCode == 303)) {
[self setRequestMethod:@"GET"];
[self setPostBody:nil];
[self setPostLength:0];
// Perhaps there are other headers we should be preserving, but it's hard to know what we need to keep and what to throw away.
NSString *userAgentHeader = [[self requestHeaders] objectForKey:@"User-Agent"];
NSString *acceptHeader = [[self requestHeaders] objectForKey:@"Accept"];
[self setRequestHeaders:nil];
if (userAgentHeader) {
[self addRequestHeader:@"User-Agent" value:userAgentHeader];
}
if (acceptHeader) {
[self addRequestHeader:@"Accept" value:acceptHeader];
}
[self setHaveBuiltRequestHeaders:NO];
} else {
// Force rebuild the cookie header incase we got some new cookies from this request
// All other request headers will remain as they are for 301 / 302 redirects
[self applyCookieHeader];
}
// Force the redirected request to rebuild the request headers (if not a 303, it will re-use old ones, and add any new ones)
[self setRedirectURL:[[NSURL URLWithString:[responseHeaders valueForKey:@"Location"] relativeToURL:[self url]] absoluteURL]];
[self setNeedsRedirect:YES];
// Clear the request cookies
// This means manually added cookies will not be added to the redirect request - only those stored in the global persistent store
// But, this is probably the safest option - we might be redirecting to a different domain
[self setRequestCookies:[NSMutableArray array]];
#if DEBUG_REQUEST_STATUS
ASI_DEBUG_LOG(@"[STATUS] Request will redirect (code: %i): %@",responseCode,self);
#endif
return YES;
}
- (void)parseStringEncodingFromHeaders
{
// Handle response text encoding
NSStringEncoding charset = 0;
NSString *mimeType = nil;
[[self class] parseMimeType:&mimeType andResponseEncoding:&charset fromContentType:[[self responseHeaders] valueForKey:@"Content-Type"]];
if (charset != 0) {
[self setResponseEncoding:charset];
} else {
[self setResponseEncoding:[self defaultResponseEncoding]];
}
}
#pragma mark http authentication
- (void)saveProxyCredentialsToKeychain:(NSDictionary *)newCredentials
{
NSURLCredential *authenticationCredentials = [NSURLCredential credentialWithUser:[newCredentials objectForKey:(NSString *)kCFHTTPAuthenticationUsername] password:[newCredentials objectForKey:(NSString *)kCFHTTPAuthenticationPassword] persistence:NSURLCredentialPersistencePermanent];
if (authenticationCredentials) {
[ASIHTTPRequest saveCredentials:authenticationCredentials forProxy:[self proxyHost] port:[self proxyPort] realm:[self proxyAuthenticationRealm]];
}
}
- (void)saveCredentialsToKeychain:(NSDictionary *)newCredentials
{
NSURLCredential *authenticationCredentials = [NSURLCredential credentialWithUser:[newCredentials objectForKey:(NSString *)kCFHTTPAuthenticationUsername] password:[newCredentials objectForKey:(NSString *)kCFHTTPAuthenticationPassword] persistence:NSURLCredentialPersistencePermanent];
if (authenticationCredentials) {
[ASIHTTPRequest saveCredentials:authenticationCredentials forHost:[[self url] host] port:[[[self url] port] intValue] protocol:[[self url] scheme] realm:[self authenticationRealm]];
}
}
- (BOOL)applyProxyCredentials:(NSDictionary *)newCredentials
{
[self setProxyAuthenticationRetryCount:[self proxyAuthenticationRetryCount]+1];
if (newCredentials && proxyAuthentication && request) {
// Apply whatever credentials we've built up to the old request
if (CFHTTPMessageApplyCredentialDictionary(request, proxyAuthentication, (CFMutableDictionaryRef)newCredentials, NULL)) {
//If we have credentials and they're ok, let's save them to the keychain
if (useKeychainPersistence) {
[self saveProxyCredentialsToKeychain:newCredentials];
}
if (useSessionPersistence) {
NSMutableDictionary *sessionProxyCredentials = [NSMutableDictionary dictionary];
[sessionProxyCredentials setObject:(id)proxyAuthentication forKey:@"Authentication"];
[sessionProxyCredentials setObject:newCredentials forKey:@"Credentials"];
[sessionProxyCredentials setObject:[self proxyHost] forKey:@"Host"];
[sessionProxyCredentials setObject:[NSNumber numberWithInt:[self proxyPort]] forKey:@"Port"];
[sessionProxyCredentials setObject:[self proxyAuthenticationScheme] forKey:@"AuthenticationScheme"];
[[self class] storeProxyAuthenticationCredentialsInSessionStore:sessionProxyCredentials];
}
[self setProxyCredentials:newCredentials];
return YES;
} else {
[[self class] removeProxyAuthenticationCredentialsFromSessionStore:newCredentials];
}
}
return NO;
}
- (BOOL)applyCredentials:(NSDictionary *)newCredentials
{
[self setAuthenticationRetryCount:[self authenticationRetryCount]+1];
if (newCredentials && requestAuthentication && request) {
// Apply whatever credentials we've built up to the old request
if (CFHTTPMessageApplyCredentialDictionary(request, requestAuthentication, (CFMutableDictionaryRef)newCredentials, NULL)) {
//If we have credentials and they're ok, let's save them to the keychain
if (useKeychainPersistence) {
[self saveCredentialsToKeychain:newCredentials];
}
if (useSessionPersistence) {
NSMutableDictionary *sessionCredentials = [NSMutableDictionary dictionary];
[sessionCredentials setObject:(id)requestAuthentication forKey:@"Authentication"];
[sessionCredentials setObject:newCredentials forKey:@"Credentials"];
[sessionCredentials setObject:[self url] forKey:@"URL"];
[sessionCredentials setObject:[self authenticationScheme] forKey:@"AuthenticationScheme"];
if ([self authenticationRealm]) {
[sessionCredentials setObject:[self authenticationRealm] forKey:@"AuthenticationRealm"];
}
[[self class] storeAuthenticationCredentialsInSessionStore:sessionCredentials];
}
[self setRequestCredentials:newCredentials];
return YES;
} else {
[[self class] removeAuthenticationCredentialsFromSessionStore:newCredentials];
}
}
return NO;
}
- (NSMutableDictionary *)findProxyCredentials
{
NSMutableDictionary *newCredentials = [[[NSMutableDictionary alloc] init] autorelease];
NSString *user = nil;
NSString *pass = nil;
ASIHTTPRequest *theRequest = [self mainRequest];
// If this is a HEAD request generated by an ASINetworkQueue, we'll try to use the details from the main request
if ([theRequest proxyUsername] && [theRequest proxyPassword]) {
user = [theRequest proxyUsername];
pass = [theRequest proxyPassword];
// Let's try to use the ones set in this object
} else if ([self proxyUsername] && [self proxyPassword]) {
user = [self proxyUsername];
pass = [self proxyPassword];
}
// When we connect to a website using NTLM via a proxy, we will use the main credentials
if ((!user || !pass) && [self proxyAuthenticationScheme] == (NSString *)kCFHTTPAuthenticationSchemeNTLM) {
user = [self username];
pass = [self password];
}
// Ok, that didn't work, let's try the keychain
// For authenticating proxies, we'll look in the keychain regardless of the value of useKeychainPersistence
if ((!user || !pass)) {
NSURLCredential *authenticationCredentials = [ASIHTTPRequest savedCredentialsForProxy:[self proxyHost] port:[self proxyPort] protocol:[[self url] scheme] realm:[self proxyAuthenticationRealm]];
if (authenticationCredentials) {
user = [authenticationCredentials user];
pass = [authenticationCredentials password];
}
}
// Handle NTLM, which requires a domain to be set too
if (CFHTTPAuthenticationRequiresAccountDomain(proxyAuthentication)) {
NSString *ntlmDomain = [self proxyDomain];
// If we have no domain yet
if (!ntlmDomain || [ntlmDomain length] == 0) {
// Let's try to extract it from the username
NSArray* ntlmComponents = [user componentsSeparatedByString:@"\\"];
if ([ntlmComponents count] == 2) {
ntlmDomain = [ntlmComponents objectAtIndex:0];
user = [ntlmComponents objectAtIndex:1];
// If we are connecting to a website using NTLM, but we are connecting via a proxy, the string we need may be in the domain property
} else {
ntlmDomain = [self domain];
}
if (!ntlmDomain) {
ntlmDomain = @"";
}
}
[newCredentials setObject:ntlmDomain forKey:(NSString *)kCFHTTPAuthenticationAccountDomain];
}
// If we have a username and password, let's apply them to the request and continue
if (user && pass) {
[newCredentials setObject:user forKey:(NSString *)kCFHTTPAuthenticationUsername];
[newCredentials setObject:pass forKey:(NSString *)kCFHTTPAuthenticationPassword];
return newCredentials;
}
return nil;
}
- (NSMutableDictionary *)findCredentials
{
NSMutableDictionary *newCredentials = [[[NSMutableDictionary alloc] init] autorelease];
// First, let's look at the url to see if the username and password were included
NSString *user = [[self url] user];
NSString *pass = [[self url] password];
if (user && pass) {
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ will use credentials set on its url",self);
#endif
} else {
// If this is a HEAD request generated by an ASINetworkQueue, we'll try to use the details from the main request
if ([self mainRequest] && [[self mainRequest] username] && [[self mainRequest] password]) {
user = [[self mainRequest] username];
pass = [[self mainRequest] password];
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ will use credentials from its parent request",self);
#endif
// Let's try to use the ones set in this object
} else if ([self username] && [self password]) {
user = [self username];
pass = [self password];
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ will use username and password properties as credentials",self);
#endif
}
}
// Ok, that didn't work, let's try the keychain
if ((!user || !pass) && useKeychainPersistence) {
NSURLCredential *authenticationCredentials = [ASIHTTPRequest savedCredentialsForHost:[[self url] host] port:[[[self url] port] intValue] protocol:[[self url] scheme] realm:[self authenticationRealm]];
if (authenticationCredentials) {
user = [authenticationCredentials user];
pass = [authenticationCredentials password];
#if DEBUG_HTTP_AUTHENTICATION
if (user && pass) {
ASI_DEBUG_LOG(@"[AUTH] Request %@ will use credentials from the keychain",self);
}
#endif
}
}
// Handle NTLM, which requires a domain to be set too
if (CFHTTPAuthenticationRequiresAccountDomain(requestAuthentication)) {
NSString *ntlmDomain = [self domain];
// If we have no domain yet, let's try to extract it from the username
if (!ntlmDomain || [ntlmDomain length] == 0) {
ntlmDomain = @"";
NSArray* ntlmComponents = [user componentsSeparatedByString:@"\\"];
if ([ntlmComponents count] == 2) {
ntlmDomain = [ntlmComponents objectAtIndex:0];
user = [ntlmComponents objectAtIndex:1];
}
}
[newCredentials setObject:ntlmDomain forKey:(NSString *)kCFHTTPAuthenticationAccountDomain];
}
// If we have a username and password, let's apply them to the request and continue
if (user && pass) {
[newCredentials setObject:user forKey:(NSString *)kCFHTTPAuthenticationUsername];
[newCredentials setObject:pass forKey:(NSString *)kCFHTTPAuthenticationPassword];
return newCredentials;
}
return nil;
}
// Called by delegate or authentication dialog to resume loading once authentication info has been populated
- (void)retryUsingSuppliedCredentials
{
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ received credentials from its delegate or an ASIAuthenticationDialog, will retry",self);
#endif
//If the url was changed by the delegate, our CFHTTPMessageRef will be NULL and we'll go back to the start
if (!request) {
[self performSelector:@selector(main) onThread:[[self class] threadForRequest:self] withObject:nil waitUntilDone:NO];
return;
}
[self performSelector:@selector(attemptToApplyCredentialsAndResume) onThread:[[self class] threadForRequest:self] withObject:nil waitUntilDone:NO];
}
// Called by delegate or authentication dialog to cancel authentication
- (void)cancelAuthentication
{
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ had authentication cancelled by its delegate or an ASIAuthenticationDialog",self);
#endif
[self performSelector:@selector(failAuthentication) onThread:[[self class] threadForRequest:self] withObject:nil waitUntilDone:NO];
}
- (void)failAuthentication
{
[self failWithError:ASIAuthenticationError];
}
- (BOOL)showProxyAuthenticationDialog
{
if ([self isSynchronous]) {
return NO;
}
// Mac authentication dialog coming soon!
#if TARGET_OS_IPHONE
if ([self shouldPresentProxyAuthenticationDialog]) {
[ASIAuthenticationDialog performSelectorOnMainThread:@selector(presentAuthenticationDialogForRequest:) withObject:self waitUntilDone:[NSThread isMainThread]];
return YES;
}
return NO;
#else
return NO;
#endif
}
- (BOOL)willAskDelegateForProxyCredentials
{
if ([self isSynchronous]) {
return NO;
}
// If we have a delegate, we'll see if it can handle proxyAuthenticationNeededForRequest:.
// Otherwise, we'll try the queue (if this request is part of one) and it will pass the message on to its own delegate
id authenticationDelegate = [self delegate];
if (!authenticationDelegate) {
authenticationDelegate = [self queue];
}
BOOL delegateOrBlockWillHandleAuthentication = NO;
if ([authenticationDelegate respondsToSelector:@selector(proxyAuthenticationNeededForRequest:)]) {
delegateOrBlockWillHandleAuthentication = YES;
}
#if NS_BLOCKS_AVAILABLE
if(proxyAuthenticationNeededBlock){
delegateOrBlockWillHandleAuthentication = YES;
}
#endif
if (delegateOrBlockWillHandleAuthentication) {
[self performSelectorOnMainThread:@selector(askDelegateForProxyCredentials) withObject:nil waitUntilDone:NO];
}
return delegateOrBlockWillHandleAuthentication;
}
/* ALWAYS CALLED ON MAIN THREAD! */
- (void)askDelegateForProxyCredentials
{
id authenticationDelegate = [self delegate];
if (!authenticationDelegate) {
authenticationDelegate = [self queue];
}
if ([authenticationDelegate respondsToSelector:@selector(proxyAuthenticationNeededForRequest:)]) {
[authenticationDelegate performSelector:@selector(proxyAuthenticationNeededForRequest:) withObject:self];
return;
}
#if NS_BLOCKS_AVAILABLE
if(proxyAuthenticationNeededBlock){
proxyAuthenticationNeededBlock();
}
#endif
}
- (BOOL)willAskDelegateForCredentials
{
if ([self isSynchronous]) {
return NO;
}
// If we have a delegate, we'll see if it can handle proxyAuthenticationNeededForRequest:.
// Otherwise, we'll try the queue (if this request is part of one) and it will pass the message on to its own delegate
id authenticationDelegate = [self delegate];
if (!authenticationDelegate) {
authenticationDelegate = [self queue];
}
BOOL delegateOrBlockWillHandleAuthentication = NO;
if ([authenticationDelegate respondsToSelector:@selector(authenticationNeededForRequest:)]) {
delegateOrBlockWillHandleAuthentication = YES;
}
#if NS_BLOCKS_AVAILABLE
if (authenticationNeededBlock) {
delegateOrBlockWillHandleAuthentication = YES;
}
#endif
if (delegateOrBlockWillHandleAuthentication) {
[self performSelectorOnMainThread:@selector(askDelegateForCredentials) withObject:nil waitUntilDone:NO];
}
return delegateOrBlockWillHandleAuthentication;
}
/* ALWAYS CALLED ON MAIN THREAD! */
- (void)askDelegateForCredentials
{
id authenticationDelegate = [self delegate];
if (!authenticationDelegate) {
authenticationDelegate = [self queue];
}
if ([authenticationDelegate respondsToSelector:@selector(authenticationNeededForRequest:)]) {
[authenticationDelegate performSelector:@selector(authenticationNeededForRequest:) withObject:self];
return;
}
#if NS_BLOCKS_AVAILABLE
if (authenticationNeededBlock) {
authenticationNeededBlock();
}
#endif
}
- (void)attemptToApplyProxyCredentialsAndResume
{
if ([self error] || [self isCancelled]) {
return;
}
// Read authentication data
if (!proxyAuthentication) {
CFHTTPMessageRef responseHeader = (CFHTTPMessageRef) CFReadStreamCopyProperty((CFReadStreamRef)[self readStream],kCFStreamPropertyHTTPResponseHeader);
proxyAuthentication = CFHTTPAuthenticationCreateFromResponse(NULL, responseHeader);
CFRelease(responseHeader);
[self setProxyAuthenticationScheme:[NSMakeCollectable(CFHTTPAuthenticationCopyMethod(proxyAuthentication)) autorelease]];
}
// If we haven't got a CFHTTPAuthenticationRef by now, something is badly wrong, so we'll have to give up
if (!proxyAuthentication) {
[self cancelLoad];
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileApplyingCredentialsType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Failed to get authentication object from response headers",NSLocalizedDescriptionKey,nil]]];
return;
}
// Get the authentication realm
[self setProxyAuthenticationRealm:nil];
if (!CFHTTPAuthenticationRequiresAccountDomain(proxyAuthentication)) {
[self setProxyAuthenticationRealm:[NSMakeCollectable(CFHTTPAuthenticationCopyRealm(proxyAuthentication)) autorelease]];
}
// See if authentication is valid
CFStreamError err;
if (!CFHTTPAuthenticationIsValid(proxyAuthentication, &err)) {
CFRelease(proxyAuthentication);
proxyAuthentication = NULL;
// check for bad credentials, so we can give the delegate a chance to replace them
if (err.domain == kCFStreamErrorDomainHTTP && (err.error == kCFStreamErrorHTTPAuthenticationBadUserName || err.error == kCFStreamErrorHTTPAuthenticationBadPassword)) {
// Prevent more than one request from asking for credentials at once
[delegateAuthenticationLock lock];
// We know the credentials we just presented are bad, we should remove them from the session store too
[[self class] removeProxyAuthenticationCredentialsFromSessionStore:proxyCredentials];
[self setProxyCredentials:nil];
// If the user cancelled authentication via a dialog presented by another request, our queue may have cancelled us
if ([self error] || [self isCancelled]) {
[delegateAuthenticationLock unlock];
return;
}
// Now we've acquired the lock, it may be that the session contains credentials we can re-use for this request
if ([self useSessionPersistence]) {
NSDictionary *credentials = [self findSessionProxyAuthenticationCredentials];
if (credentials && [self applyProxyCredentials:[credentials objectForKey:@"Credentials"]]) {
[delegateAuthenticationLock unlock];
[self startRequest];
return;
}
}
[self setLastActivityTime:nil];
if ([self willAskDelegateForProxyCredentials]) {
[self attemptToApplyProxyCredentialsAndResume];
[delegateAuthenticationLock unlock];
return;
}
if ([self showProxyAuthenticationDialog]) {
[self attemptToApplyProxyCredentialsAndResume];
[delegateAuthenticationLock unlock];
return;
}
[delegateAuthenticationLock unlock];
}
[self cancelLoad];
[self failWithError:ASIAuthenticationError];
return;
}
[self cancelLoad];
if (proxyCredentials) {
// We use startRequest rather than starting all over again in load request because NTLM requires we reuse the request
if ((([self proxyAuthenticationScheme] != (NSString *)kCFHTTPAuthenticationSchemeNTLM) || [self proxyAuthenticationRetryCount] < 2) && [self applyProxyCredentials:proxyCredentials]) {
[self startRequest];
// We've failed NTLM authentication twice, we should assume our credentials are wrong
} else if ([self proxyAuthenticationScheme] == (NSString *)kCFHTTPAuthenticationSchemeNTLM && [self proxyAuthenticationRetryCount] == 2) {
[self failWithError:ASIAuthenticationError];
// Something went wrong, we'll have to give up
} else {
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileApplyingCredentialsType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Failed to apply proxy credentials to request",NSLocalizedDescriptionKey,nil]]];
}
// Are a user name & password needed?
} else if (CFHTTPAuthenticationRequiresUserNameAndPassword(proxyAuthentication)) {
// Prevent more than one request from asking for credentials at once
[delegateAuthenticationLock lock];
// If the user cancelled authentication via a dialog presented by another request, our queue may have cancelled us
if ([self error] || [self isCancelled]) {
[delegateAuthenticationLock unlock];
return;
}
// Now we've acquired the lock, it may be that the session contains credentials we can re-use for this request
if ([self useSessionPersistence]) {
NSDictionary *credentials = [self findSessionProxyAuthenticationCredentials];
if (credentials && [self applyProxyCredentials:[credentials objectForKey:@"Credentials"]]) {
[delegateAuthenticationLock unlock];
[self startRequest];
return;
}
}
NSMutableDictionary *newCredentials = [self findProxyCredentials];
//If we have some credentials to use let's apply them to the request and continue
if (newCredentials) {
if ([self applyProxyCredentials:newCredentials]) {
[delegateAuthenticationLock unlock];
[self startRequest];
} else {
[delegateAuthenticationLock unlock];
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileApplyingCredentialsType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Failed to apply proxy credentials to request",NSLocalizedDescriptionKey,nil]]];
}
return;
}
if ([self willAskDelegateForProxyCredentials]) {
[delegateAuthenticationLock unlock];
return;
}
if ([self showProxyAuthenticationDialog]) {
[delegateAuthenticationLock unlock];
return;
}
[delegateAuthenticationLock unlock];
// The delegate isn't interested and we aren't showing the authentication dialog, we'll have to give up
[self failWithError:ASIAuthenticationError];
return;
}
}
- (BOOL)showAuthenticationDialog
{
if ([self isSynchronous]) {
return NO;
}
// Mac authentication dialog coming soon!
#if TARGET_OS_IPHONE
if ([self shouldPresentAuthenticationDialog]) {
[ASIAuthenticationDialog performSelectorOnMainThread:@selector(presentAuthenticationDialogForRequest:) withObject:self waitUntilDone:[NSThread isMainThread]];
return YES;
}
return NO;
#else
return NO;
#endif
}
- (void)attemptToApplyCredentialsAndResume
{
if ([self error] || [self isCancelled]) {
return;
}
// Do we actually need to authenticate with a proxy?
if ([self authenticationNeeded] == ASIProxyAuthenticationNeeded) {
[self attemptToApplyProxyCredentialsAndResume];
return;
}
// Read authentication data
if (!requestAuthentication) {
CFHTTPMessageRef responseHeader = (CFHTTPMessageRef) CFReadStreamCopyProperty((CFReadStreamRef)[self readStream],kCFStreamPropertyHTTPResponseHeader);
requestAuthentication = CFHTTPAuthenticationCreateFromResponse(NULL, responseHeader);
CFRelease(responseHeader);
[self setAuthenticationScheme:[NSMakeCollectable(CFHTTPAuthenticationCopyMethod(requestAuthentication)) autorelease]];
}
if (!requestAuthentication) {
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ failed to read authentication information from response headers",self);
#endif
[self cancelLoad];
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileApplyingCredentialsType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Failed to get authentication object from response headers",NSLocalizedDescriptionKey,nil]]];
return;
}
// Get the authentication realm
[self setAuthenticationRealm:nil];
if (!CFHTTPAuthenticationRequiresAccountDomain(requestAuthentication)) {
[self setAuthenticationRealm:[NSMakeCollectable(CFHTTPAuthenticationCopyRealm(requestAuthentication)) autorelease]];
}
#if DEBUG_HTTP_AUTHENTICATION
NSString *realm = [self authenticationRealm];
if (realm) {
realm = [NSString stringWithFormat:@" (Realm: %@)",realm];
} else {
realm = @"";
}
if ([self authenticationScheme] != (NSString *)kCFHTTPAuthenticationSchemeNTLM || [self authenticationRetryCount] == 0) {
ASI_DEBUG_LOG(@"[AUTH] Request %@ received 401 challenge and must authenticate using %@%@",self,[self authenticationScheme],realm);
} else {
ASI_DEBUG_LOG(@"[AUTH] Request %@ NTLM handshake step %i",self,[self authenticationRetryCount]+1);
}
#endif
// See if authentication is valid
CFStreamError err;
if (!CFHTTPAuthenticationIsValid(requestAuthentication, &err)) {
CFRelease(requestAuthentication);
requestAuthentication = NULL;
// check for bad credentials, so we can give the delegate a chance to replace them
if (err.domain == kCFStreamErrorDomainHTTP && (err.error == kCFStreamErrorHTTPAuthenticationBadUserName || err.error == kCFStreamErrorHTTPAuthenticationBadPassword)) {
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ had bad credentials, will remove them from the session store if they are cached",self);
#endif
// Prevent more than one request from asking for credentials at once
[delegateAuthenticationLock lock];
// We know the credentials we just presented are bad, we should remove them from the session store too
[[self class] removeAuthenticationCredentialsFromSessionStore:requestCredentials];
[self setRequestCredentials:nil];
// If the user cancelled authentication via a dialog presented by another request, our queue may have cancelled us
if ([self error] || [self isCancelled]) {
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ failed or was cancelled while waiting to access credentials",self);
#endif
[delegateAuthenticationLock unlock];
return;
}
// Now we've acquired the lock, it may be that the session contains credentials we can re-use for this request
if ([self useSessionPersistence]) {
NSDictionary *credentials = [self findSessionAuthenticationCredentials];
if (credentials && [self applyCredentials:[credentials objectForKey:@"Credentials"]]) {
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ will reuse cached credentials from the session (%@)",self,[credentials objectForKey:@"AuthenticationScheme"]);
#endif
[delegateAuthenticationLock unlock];
[self startRequest];
return;
}
}
[self setLastActivityTime:nil];
if ([self willAskDelegateForCredentials]) {
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ will ask its delegate for credentials to use",self);
#endif
[delegateAuthenticationLock unlock];
return;
}
if ([self showAuthenticationDialog]) {
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ will ask ASIAuthenticationDialog for credentials",self);
#endif
[delegateAuthenticationLock unlock];
return;
}
[delegateAuthenticationLock unlock];
}
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ has no credentials to present and must give up",self);
#endif
[self cancelLoad];
[self failWithError:ASIAuthenticationError];
return;
}
[self cancelLoad];
if (requestCredentials) {
if ((([self authenticationScheme] != (NSString *)kCFHTTPAuthenticationSchemeNTLM) || [self authenticationRetryCount] < 2) && [self applyCredentials:requestCredentials]) {
[self startRequest];
// We've failed NTLM authentication twice, we should assume our credentials are wrong
} else if ([self authenticationScheme] == (NSString *)kCFHTTPAuthenticationSchemeNTLM && [self authenticationRetryCount ] == 2) {
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ has failed NTLM authentication",self);
#endif
[self failWithError:ASIAuthenticationError];
} else {
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ had credentials and they were not marked as bad, but we got a 401 all the same.",self);
#endif
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileApplyingCredentialsType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Failed to apply credentials to request",NSLocalizedDescriptionKey,nil]]];
}
// Are a user name & password needed?
} else if (CFHTTPAuthenticationRequiresUserNameAndPassword(requestAuthentication)) {
// Prevent more than one request from asking for credentials at once
[delegateAuthenticationLock lock];
// If the user cancelled authentication via a dialog presented by another request, our queue may have cancelled us
if ([self error] || [self isCancelled]) {
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ failed or was cancelled while waiting to access credentials",self);
#endif
[delegateAuthenticationLock unlock];
return;
}
// Now we've acquired the lock, it may be that the session contains credentials we can re-use for this request
if ([self useSessionPersistence]) {
NSDictionary *credentials = [self findSessionAuthenticationCredentials];
if (credentials && [self applyCredentials:[credentials objectForKey:@"Credentials"]]) {
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ will reuse cached credentials from the session (%@)",self,[credentials objectForKey:@"AuthenticationScheme"]);
#endif
[delegateAuthenticationLock unlock];
[self startRequest];
return;
}
}
NSMutableDictionary *newCredentials = [self findCredentials];
//If we have some credentials to use let's apply them to the request and continue
if (newCredentials) {
if ([self applyCredentials:newCredentials]) {
[delegateAuthenticationLock unlock];
[self startRequest];
} else {
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ failed to apply credentials",self);
#endif
[delegateAuthenticationLock unlock];
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileApplyingCredentialsType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Failed to apply credentials to request",NSLocalizedDescriptionKey,nil]]];
}
return;
}
if ([self willAskDelegateForCredentials]) {
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ will ask its delegate for credentials to use",self);
#endif
[delegateAuthenticationLock unlock];
return;
}
if ([self showAuthenticationDialog]) {
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ will ask ASIAuthenticationDialog for credentials",self);
#endif
[delegateAuthenticationLock unlock];
return;
}
#if DEBUG_HTTP_AUTHENTICATION
ASI_DEBUG_LOG(@"[AUTH] Request %@ has no credentials to present and must give up",self);
#endif
[delegateAuthenticationLock unlock];
[self failWithError:ASIAuthenticationError];
return;
}
}
- (void)addBasicAuthenticationHeaderWithUsername:(NSString *)theUsername andPassword:(NSString *)thePassword
{
[self addRequestHeader:@"Authorization" value:[NSString stringWithFormat:@"Basic %@",[ASIHTTPRequest base64forData:[[NSString stringWithFormat:@"%@:%@",theUsername,thePassword] dataUsingEncoding:NSUTF8StringEncoding]]]];
[self setAuthenticationScheme:(NSString *)kCFHTTPAuthenticationSchemeBasic];
}
#pragma mark stream status handlers
- (void)handleNetworkEvent:(CFStreamEventType)type
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[[self cancelledLock] lock];
if ([self complete] || [self isCancelled]) {
[[self cancelledLock] unlock];
[pool drain];
return;
}
CFRetain(self);
// Dispatch the stream events.
switch (type) {
case kCFStreamEventHasBytesAvailable:
[self handleBytesAvailable];
break;
case kCFStreamEventEndEncountered:
[self handleStreamComplete];
break;
case kCFStreamEventErrorOccurred:
[self handleStreamError];
break;
default:
break;
}
[self performThrottling];
[[self cancelledLock] unlock];
if ([self downloadComplete] && [self needsRedirect]) {
if (![self willAskDelegateToConfirmRedirect]) {
[self performRedirect];
}
} else if ([self downloadComplete] && [self authenticationNeeded]) {
[self attemptToApplyCredentialsAndResume];
}
CFRelease(self);
[pool drain];
}
- (BOOL)willAskDelegateToConfirmRedirect
{
// We must lock to ensure delegate / queue aren't changed while we check them
[[self cancelledLock] lock];
// Here we perform an initial check to see if either the delegate or the queue wants to be asked about the redirect, because if not we should redirect straight away
// We will check again on the main thread later
BOOL needToAskDelegateAboutRedirect = (([self delegate] && [[self delegate] respondsToSelector:[self willRedirectSelector]]) || ([self queue] && [[self queue] respondsToSelector:@selector(request:willRedirectToURL:)]));
[[self cancelledLock] unlock];
// Either the delegate or the queue's delegate is interested in being told when we are about to redirect
if (needToAskDelegateAboutRedirect) {
NSURL *newURL = [[[self redirectURL] copy] autorelease];
[self setRedirectURL:nil];
[self performSelectorOnMainThread:@selector(requestWillRedirectToURL:) withObject:newURL waitUntilDone:[NSThread isMainThread]];
return true;
}
return false;
}
- (void)handleBytesAvailable
{
if (![self responseHeaders]) {
[self readResponseHeaders];
}
// If we've cancelled the load part way through (for example, after deciding to use a cached version)
if ([self complete]) {
return;
}
// In certain (presumably very rare) circumstances, handleBytesAvailable seems to be called when there isn't actually any data available
// We'll check that there is actually data available to prevent blocking on CFReadStreamRead()
// So far, I've only seen this in the stress tests, so it might never happen in real-world situations.
if (!CFReadStreamHasBytesAvailable((CFReadStreamRef)[self readStream])) {
return;
}
long long bufferSize = 16384;
if (contentLength > 262144) {
bufferSize = 262144;
} else if (contentLength > 65536) {
bufferSize = 65536;
}
// Reduce the buffer size if we're receiving data too quickly when bandwidth throttling is active
// This just augments the throttling done in measureBandwidthUsage to reduce the amount we go over the limit
if ([[self class] isBandwidthThrottled]) {
[bandwidthThrottlingLock lock];
if (maxBandwidthPerSecond > 0) {
long long maxiumumSize = (long long)maxBandwidthPerSecond-(long long)bandwidthUsedInLastSecond;
if (maxiumumSize < 0) {
// We aren't supposed to read any more data right now, but we'll read a single byte anyway so the CFNetwork's buffer isn't full
bufferSize = 1;
} else if (maxiumumSize/4 < bufferSize) {
// We were going to fetch more data that we should be allowed, so we'll reduce the size of our read
bufferSize = maxiumumSize/4;
}
}
if (bufferSize < 1) {
bufferSize = 1;
}
[bandwidthThrottlingLock unlock];
}
UInt8 buffer[bufferSize];
NSInteger bytesRead = [[self readStream] read:buffer maxLength:sizeof(buffer)];
// Less than zero is an error
if (bytesRead < 0) {
[self handleStreamError];
// If zero bytes were read, wait for the EOF to come.
} else if (bytesRead) {
// If we are inflating the response on the fly
NSData *inflatedData = nil;
if ([self isResponseCompressed] && ![self shouldWaitToInflateCompressedResponses]) {
if (![self dataDecompressor]) {
[self setDataDecompressor:[ASIDataDecompressor decompressor]];
}
NSError *err = nil;
inflatedData = [[self dataDecompressor] uncompressBytes:buffer length:bytesRead error:&err];
if (err) {
[self failWithError:err];
return;
}
}
[self setTotalBytesRead:[self totalBytesRead]+bytesRead];
[self setLastActivityTime:[NSDate date]];
// For bandwidth measurement / throttling
[ASIHTTPRequest incrementBandwidthUsedInLastSecond:bytesRead];
// If we need to redirect, and have automatic redirect on, and might be resuming a download, let's do nothing with the content
if ([self needsRedirect] && [self shouldRedirect] && [self allowResumeForFileDownloads]) {
return;
}
BOOL dataWillBeHandledExternally = NO;
if ([[self delegate] respondsToSelector:[self didReceiveDataSelector]]) {
dataWillBeHandledExternally = YES;
}
#if NS_BLOCKS_AVAILABLE
if (dataReceivedBlock) {
dataWillBeHandledExternally = YES;
}
#endif
// Does the delegate want to handle the data manually?
if (dataWillBeHandledExternally) {
NSData *data = nil;
if ([self isResponseCompressed] && ![self shouldWaitToInflateCompressedResponses]) {
data = inflatedData;
} else {
data = [NSData dataWithBytes:buffer length:bytesRead];
}
[self performSelectorOnMainThread:@selector(passOnReceivedData:) withObject:data waitUntilDone:[NSThread isMainThread]];
// Are we downloading to a file?
} else if ([self downloadDestinationPath]) {
BOOL append = NO;
if (![self fileDownloadOutputStream]) {
if (![self temporaryFileDownloadPath]) {
[self setTemporaryFileDownloadPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]];
} else if ([self allowResumeForFileDownloads] && [[self requestHeaders] objectForKey:@"Range"]) {
if ([[self responseHeaders] objectForKey:@"Content-Range"]) {
append = YES;
} else {
[self incrementDownloadSizeBy:-[self partialDownloadSize]];
[self setPartialDownloadSize:0];
}
}
[self setFileDownloadOutputStream:[[[NSOutputStream alloc] initToFileAtPath:[self temporaryFileDownloadPath] append:append] autorelease]];
[[self fileDownloadOutputStream] open];
}
[[self fileDownloadOutputStream] write:buffer maxLength:bytesRead];
if ([self isResponseCompressed] && ![self shouldWaitToInflateCompressedResponses]) {
if (![self inflatedFileDownloadOutputStream]) {
if (![self temporaryUncompressedDataDownloadPath]) {
[self setTemporaryUncompressedDataDownloadPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[[NSProcessInfo processInfo] globallyUniqueString]]];
}
[self setInflatedFileDownloadOutputStream:[[[NSOutputStream alloc] initToFileAtPath:[self temporaryUncompressedDataDownloadPath] append:append] autorelease]];
[[self inflatedFileDownloadOutputStream] open];
}
[[self inflatedFileDownloadOutputStream] write:[inflatedData bytes] maxLength:[inflatedData length]];
}
//Otherwise, let's add the data to our in-memory store
} else {
if ([self isResponseCompressed] && ![self shouldWaitToInflateCompressedResponses]) {
[rawResponseData appendData:inflatedData];
} else {
[rawResponseData appendBytes:buffer length:bytesRead];
}
}
}
}
- (void)handleStreamComplete
{
#if DEBUG_REQUEST_STATUS
ASI_DEBUG_LOG(@"[STATUS] Request %@ finished downloading data (%qu bytes)",self, [self totalBytesRead]);
#endif
[self setStatusTimer:nil];
[self setDownloadComplete:YES];
if (![self responseHeaders]) {
[self readResponseHeaders];
}
[progressLock lock];
// Find out how much data we've uploaded so far
[self setLastBytesSent:totalBytesSent];
[self setTotalBytesSent:[[NSMakeCollectable(CFReadStreamCopyProperty((CFReadStreamRef)[self readStream], kCFStreamPropertyHTTPRequestBytesWrittenCount)) autorelease] unsignedLongLongValue]];
[self setComplete:YES];
if (![self contentLength]) {
[self setContentLength:[self totalBytesRead]];
}
[self updateProgressIndicators];
[[self postBodyReadStream] close];
[self setPostBodyReadStream:nil];
[self setDataDecompressor:nil];
NSError *fileError = nil;
// Delete up the request body temporary file, if it exists
if ([self didCreateTemporaryPostDataFile] && ![self authenticationNeeded]) {
[self removeTemporaryUploadFile];
[self removeTemporaryCompressedUploadFile];
}
// Close the output stream as we're done writing to the file
if ([self temporaryFileDownloadPath]) {
[[self fileDownloadOutputStream] close];
[self setFileDownloadOutputStream:nil];
[[self inflatedFileDownloadOutputStream] close];
[self setInflatedFileDownloadOutputStream:nil];
// If we are going to redirect and we are resuming, let's ignore this download
if ([self shouldRedirect] && [self needsRedirect] && [self allowResumeForFileDownloads]) {
} else if ([self isResponseCompressed]) {
// Decompress the file directly to the destination path
if ([self shouldWaitToInflateCompressedResponses]) {
[ASIDataDecompressor uncompressDataFromFile:[self temporaryFileDownloadPath] toFile:[self downloadDestinationPath] error:&fileError];
// Response should already have been inflated, move the temporary file to the destination path
} else {
NSError *moveError = nil;
[[[[NSFileManager alloc] init] autorelease] moveItemAtPath:[self temporaryUncompressedDataDownloadPath] toPath:[self downloadDestinationPath] error:&moveError];
if (moveError) {
fileError = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASIFileManagementError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Failed to move file from '%@' to '%@'",[self temporaryFileDownloadPath],[self downloadDestinationPath]],NSLocalizedDescriptionKey,moveError,NSUnderlyingErrorKey,nil]];
}
[self setTemporaryUncompressedDataDownloadPath:nil];
}
[self removeTemporaryDownloadFile];
} else {
//Remove any file at the destination path
NSError *moveError = nil;
if (![[self class] removeFileAtPath:[self downloadDestinationPath] error:&moveError]) {
fileError = moveError;
}
//Move the temporary file to the destination path
if (!fileError) {
[[[[NSFileManager alloc] init] autorelease] moveItemAtPath:[self temporaryFileDownloadPath] toPath:[self downloadDestinationPath] error:&moveError];
if (moveError) {
fileError = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASIFileManagementError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Failed to move file from '%@' to '%@'",[self temporaryFileDownloadPath],[self downloadDestinationPath]],NSLocalizedDescriptionKey,moveError,NSUnderlyingErrorKey,nil]];
}
[self setTemporaryFileDownloadPath:nil];
}
}
}
// Save to the cache
if ([self downloadCache] && ![self didUseCachedResponse]) {
[[self downloadCache] storeResponseForRequest:self maxAge:[self secondsToCache]];
}
[progressLock unlock];
[connectionsLock lock];
if (![self connectionCanBeReused]) {
[self unscheduleReadStream];
}
#if DEBUG_PERSISTENT_CONNECTIONS
if ([self requestID]) {
ASI_DEBUG_LOG(@"[CONNECTION] Request #%@ finished using connection #%@",[self requestID], [[self connectionInfo] objectForKey:@"id"]);
}
#endif
[[self connectionInfo] removeObjectForKey:@"request"];
[[self connectionInfo] setObject:[NSDate dateWithTimeIntervalSinceNow:[self persistentConnectionTimeoutSeconds]] forKey:@"expires"];
[connectionsLock unlock];
if (![self authenticationNeeded]) {
[self destroyReadStream];
}
if (![self needsRedirect] && ![self authenticationNeeded] && ![self didUseCachedResponse]) {
if (fileError) {
[self failWithError:fileError];
} else {
[self requestFinished];
}
[self markAsFinished];
// If request has asked delegate or ASIAuthenticationDialog for credentials
} else if ([self authenticationNeeded]) {
// Do nothing.
}
}
- (void)markAsFinished
{
// Autoreleased requests may well be dealloced here otherwise
CFRetain(self);
// dealloc won't be called when running with GC, so we'll clean these up now
if (request) {
CFRelease(request);
request = nil;
}
if (requestAuthentication) {
CFRelease(requestAuthentication);
requestAuthentication = nil;
}
if (proxyAuthentication) {
CFRelease(proxyAuthentication);
proxyAuthentication = nil;
}
BOOL wasInProgress = inProgress;
BOOL wasFinished = finished;
if (!wasFinished)
[self willChangeValueForKey:@"isFinished"];
if (wasInProgress)
[self willChangeValueForKey:@"isExecuting"];
[self setInProgress:NO];
finished = YES;
if (wasInProgress)
[self didChangeValueForKey:@"isExecuting"];
if (!wasFinished)
[self didChangeValueForKey:@"isFinished"];
#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
if ([ASIHTTPRequest isMultitaskingSupported] && [self shouldContinueWhenAppEntersBackground]) {
dispatch_async(dispatch_get_main_queue(), ^{
if (backgroundTask != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:backgroundTask];
backgroundTask = UIBackgroundTaskInvalid;
}
});
}
#endif
CFRelease(self);
}
- (void)useDataFromCache
{
NSDictionary *headers = [[self downloadCache] cachedResponseHeadersForURL:[self url]];
NSString *dataPath = [[self downloadCache] pathToCachedResponseDataForURL:[self url]];
ASIHTTPRequest *theRequest = self;
if ([self mainRequest]) {
theRequest = [self mainRequest];
}
if (headers && dataPath) {
[self setResponseStatusCode:[[headers objectForKey:@"X-ASIHTTPRequest-Response-Status-Code"] intValue]];
[self setDidUseCachedResponse:YES];
[theRequest setResponseHeaders:headers];
if ([theRequest downloadDestinationPath]) {
[theRequest setDownloadDestinationPath:dataPath];
} else {
[theRequest setRawResponseData:[NSMutableData dataWithData:[[self downloadCache] cachedResponseDataForURL:[self url]]]];
}
[theRequest setContentLength:[[[self responseHeaders] objectForKey:@"Content-Length"] longLongValue]];
[theRequest setTotalBytesRead:[self contentLength]];
[theRequest parseStringEncodingFromHeaders];
[theRequest setResponseCookies:[NSHTTPCookie cookiesWithResponseHeaderFields:headers forURL:[self url]]];
// See if we need to redirect
if ([self willRedirect]) {
if (![self willAskDelegateToConfirmRedirect]) {
[self performRedirect];
}
return;
}
}
[theRequest setComplete:YES];
[theRequest setDownloadComplete:YES];
// If we're pulling data from the cache without contacting the server at all, we won't have set originalURL yet
if ([self redirectCount] == 0) {
[theRequest setOriginalURL:[theRequest url]];
}
[theRequest updateProgressIndicators];
[theRequest requestFinished];
[theRequest markAsFinished];
if ([self mainRequest]) {
[self markAsFinished];
}
}
- (BOOL)retryUsingNewConnection
{
if ([self retryCount] == 0) {
[self setWillRetryRequest:YES];
[self cancelLoad];
[self setWillRetryRequest:NO];
#if DEBUG_PERSISTENT_CONNECTIONS
ASI_DEBUG_LOG(@"[CONNECTION] Request attempted to use connection #%@, but it has been closed - will retry with a new connection", [[self connectionInfo] objectForKey:@"id"]);
#endif
[connectionsLock lock];
[[self connectionInfo] removeObjectForKey:@"request"];
[persistentConnectionsPool removeObject:[self connectionInfo]];
[self setConnectionInfo:nil];
[connectionsLock unlock];
[self setRetryCount:[self retryCount]+1];
[self startRequest];
return YES;
}
#if DEBUG_PERSISTENT_CONNECTIONS
ASI_DEBUG_LOG(@"[CONNECTION] Request attempted to use connection #%@, but it has been closed - we have already retried with a new connection, so we must give up", [[self connectionInfo] objectForKey:@"id"]);
#endif
return NO;
}
- (void)handleStreamError
{
NSError *underlyingError = [NSMakeCollectable(CFReadStreamCopyError((CFReadStreamRef)[self readStream])) autorelease];
if (![self error]) { // We may already have handled this error
// First, check for a 'socket not connected', 'broken pipe' or 'connection lost' error
// This may occur when we've attempted to reuse a connection that should have been closed
// If we get this, we need to retry the request
// We'll only do this once - if it happens again on retry, we'll give up
// -1005 = kCFURLErrorNetworkConnectionLost - this doesn't seem to be declared on Mac OS 10.5
if (([[underlyingError domain] isEqualToString:NSPOSIXErrorDomain] && ([underlyingError code] == ENOTCONN || [underlyingError code] == EPIPE))
|| ([[underlyingError domain] isEqualToString:(NSString *)kCFErrorDomainCFNetwork] && [underlyingError code] == -1005)) {
if ([self retryUsingNewConnection]) {
return;
}
}
NSString *reason = @"A connection failure occurred";
// We'll use a custom error message for SSL errors, but you should always check underlying error if you want more details
// For some reason SecureTransport.h doesn't seem to be available on iphone, so error codes hard-coded
// Also, iPhone seems to handle errors differently from Mac OS X - a self-signed certificate returns a different error code on each platform, so we'll just provide a general error
if ([[underlyingError domain] isEqualToString:NSOSStatusErrorDomain]) {
if ([underlyingError code] <= -9800 && [underlyingError code] >= -9818) {
reason = [NSString stringWithFormat:@"%@: SSL problem (Possible causes may include a bad/expired/self-signed certificate, clock set to wrong date)",reason];
}
}
[self cancelLoad];
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIConnectionFailureErrorType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:reason,NSLocalizedDescriptionKey,underlyingError,NSUnderlyingErrorKey,nil]]];
} else {
[self cancelLoad];
}
[self checkRequestStatus];
}
#pragma mark managing the read stream
- (void)destroyReadStream
{
if ([self readStream]) {
[self unscheduleReadStream];
if (![self connectionCanBeReused]) {
[[self readStream] removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:[self runLoopMode]];
[[self readStream] close];
}
[self setReadStream:nil];
}
}
- (void)scheduleReadStream
{
if ([self readStream] && ![self readStreamIsScheduled]) {
[connectionsLock lock];
runningRequestCount++;
if (shouldUpdateNetworkActivityIndicator) {
[[self class] showNetworkActivityIndicator];
}
[connectionsLock unlock];
// Reset the timeout
[self setLastActivityTime:[NSDate date]];
CFStreamClientContext ctxt = {0, self, NULL, NULL, NULL};
CFReadStreamSetClient((CFReadStreamRef)[self readStream], kNetworkEvents, ReadStreamClientCallBack, &ctxt);
[[self readStream] scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:[self runLoopMode]];
[self setReadStreamIsScheduled:YES];
}
}
- (void)unscheduleReadStream
{
if ([self readStream] && [self readStreamIsScheduled]) {
[connectionsLock lock];
runningRequestCount--;
if (shouldUpdateNetworkActivityIndicator && runningRequestCount == 0) {
// This call will wait half a second before turning off the indicator
// This can prevent flicker when you have a single request finish and then immediately start another request
// We run this on the main thread because we have no guarantee this thread will have a runloop in 0.5 seconds time
// We don't bother the cancel this call if we start a new request, because we'll check if requests are running before we hide it
[[self class] performSelectorOnMainThread:@selector(hideNetworkActivityIndicatorAfterDelay) withObject:nil waitUntilDone:[NSThread isMainThread]];
}
[connectionsLock unlock];
CFReadStreamSetClient((CFReadStreamRef)[self readStream], kCFStreamEventNone, NULL, NULL);
[[self readStream] removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:[self runLoopMode]];
[self setReadStreamIsScheduled:NO];
}
}
#pragma mark cleanup
- (BOOL)removeTemporaryDownloadFile
{
NSError *err = nil;
if ([self temporaryFileDownloadPath]) {
if (![[self class] removeFileAtPath:[self temporaryFileDownloadPath] error:&err]) {
[self failWithError:err];
}
[self setTemporaryFileDownloadPath:nil];
}
return (!err);
}
- (BOOL)removeTemporaryUncompressedDownloadFile
{
NSError *err = nil;
if ([self temporaryUncompressedDataDownloadPath]) {
if (![[self class] removeFileAtPath:[self temporaryUncompressedDataDownloadPath] error:&err]) {
[self failWithError:err];
}
[self setTemporaryUncompressedDataDownloadPath:nil];
}
return (!err);
}
- (BOOL)removeTemporaryUploadFile
{
NSError *err = nil;
if ([self postBodyFilePath]) {
if (![[self class] removeFileAtPath:[self postBodyFilePath] error:&err]) {
[self failWithError:err];
}
[self setPostBodyFilePath:nil];
}
return (!err);
}
- (BOOL)removeTemporaryCompressedUploadFile
{
NSError *err = nil;
if ([self compressedPostBodyFilePath]) {
if (![[self class] removeFileAtPath:[self compressedPostBodyFilePath] error:&err]) {
[self failWithError:err];
}
[self setCompressedPostBodyFilePath:nil];
}
return (!err);
}
+ (BOOL)removeFileAtPath:(NSString *)path error:(NSError **)err
{
NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
if ([fileManager fileExistsAtPath:path]) {
NSError *removeError = nil;
[fileManager removeItemAtPath:path error:&removeError];
if (removeError) {
if (err) {
*err = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASIFileManagementError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Failed to delete file at path '%@'",path],NSLocalizedDescriptionKey,removeError,NSUnderlyingErrorKey,nil]];
}
return NO;
}
}
return YES;
}
#pragma mark Proxies
- (BOOL)configureProxies
{
// Have details of the proxy been set on this request
if (![self isPACFileRequest] && (![self proxyHost] && ![self proxyPort])) {
// If not, we need to figure out what they'll be
NSArray *proxies = nil;
// Have we been given a proxy auto config file?
if ([self PACurl]) {
// If yes, we'll need to fetch the PAC file asynchronously, so we stop this request to wait until we have the proxy details.
[self fetchPACFile];
return NO;
// Detect proxy settings and apply them
} else {
#if TARGET_OS_IPHONE
NSDictionary *proxySettings = [NSMakeCollectable(CFNetworkCopySystemProxySettings()) autorelease];
#else
NSDictionary *proxySettings = [NSMakeCollectable(SCDynamicStoreCopyProxies(NULL)) autorelease];
#endif
proxies = [NSMakeCollectable(CFNetworkCopyProxiesForURL((CFURLRef)[self url], (CFDictionaryRef)proxySettings)) autorelease];
// Now check to see if the proxy settings contained a PAC url, we need to run the script to get the real list of proxies if so
NSDictionary *settings = [proxies objectAtIndex:0];
if ([settings objectForKey:(NSString *)kCFProxyAutoConfigurationURLKey]) {
[self setPACurl:[settings objectForKey:(NSString *)kCFProxyAutoConfigurationURLKey]];
[self fetchPACFile];
return NO;
}
}
if (!proxies) {
[self setReadStream:nil];
[self failWithError:[NSError errorWithDomain:NetworkRequestErrorDomain code:ASIInternalErrorWhileBuildingRequestType userInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"Unable to obtain information on proxy servers needed for request",NSLocalizedDescriptionKey,nil]]];
return NO;
}
// I don't really understand why the dictionary returned by CFNetworkCopyProxiesForURL uses different key names from CFNetworkCopySystemProxySettings/SCDynamicStoreCopyProxies
// and why its key names are documented while those we actually need to use don't seem to be (passing the kCF* keys doesn't seem to work)
if ([proxies count] > 0) {
NSDictionary *settings = [proxies objectAtIndex:0];
[self setProxyHost:[settings objectForKey:(NSString *)kCFProxyHostNameKey]];
[self setProxyPort:[[settings objectForKey:(NSString *)kCFProxyPortNumberKey] intValue]];
[self setProxyType:[settings objectForKey:(NSString *)kCFProxyTypeKey]];
}
}
return YES;
}
// Attempts to download a PAC (Proxy Auto-Configuration) file
// PAC files at file://, http:// and https:// addresses are supported
- (void)fetchPACFile
{
// For file:// urls, we'll use an async NSInputStream (ASIHTTPRequest does not support file:// urls)
if ([[self PACurl] isFileURL]) {
NSInputStream *stream = [[[NSInputStream alloc] initWithFileAtPath:[[self PACurl] path]] autorelease];
[self setPACFileReadStream:stream];
[stream setDelegate:(id)self];
[stream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:[self runLoopMode]];
[stream open];
// If it takes more than timeOutSeconds to read the PAC, we'll just give up and assume no proxies
// We won't bother to handle cases where the first part of the PAC is read within timeOutSeconds, but the whole thing takes longer
// Either our PAC file is in easy reach, or it's going to slow things down to the point that it's probably better requests fail
[self performSelector:@selector(timeOutPACRead) withObject:nil afterDelay:[self timeOutSeconds]];
return;
}
NSString *scheme = [[[self PACurl] scheme] lowercaseString];
if (![scheme isEqualToString:@"http"] && ![scheme isEqualToString:@"https"]) {
// Don't know how to read data from this URL, we'll have to give up
// We'll simply assume no proxies, and start the request as normal
[self startRequest];
return;
}
// Create an ASIHTTPRequest to fetch the PAC file
ASIHTTPRequest *PACRequest = [ASIHTTPRequest requestWithURL:[self PACurl]];
// Will prevent this request attempting to configure proxy settings for itself
[PACRequest setIsPACFileRequest:YES];
[PACRequest setTimeOutSeconds:[self timeOutSeconds]];
// If we're a synchronous request, we'll download the PAC file synchronously
if ([self isSynchronous]) {
[PACRequest startSynchronous];
if (![PACRequest error] && [PACRequest responseString]) {
[self runPACScript:[PACRequest responseString]];
}
[self startRequest];
return;
}
[self setPACFileRequest:PACRequest];
// Force this request to run before others in the shared queue
[PACRequest setQueuePriority:NSOperationQueuePriorityHigh];
// We'll treat failure to download the PAC file the same as success - if we were unable to fetch a PAC file, we proceed as if we have no proxy server and let this request fail itself if necessary
[PACRequest setDelegate:self];
[PACRequest setDidFinishSelector:@selector(finishedDownloadingPACFile:)];
[PACRequest setDidFailSelector:@selector(finishedDownloadingPACFile:)];
[PACRequest startAsynchronous];
// Temporarily increase the number of operations in the shared queue to give our request a chance to run
[connectionsLock lock];
[sharedQueue setMaxConcurrentOperationCount:[sharedQueue maxConcurrentOperationCount]+1];
[connectionsLock unlock];
}
// Called as we read the PAC file from a file:// url
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode
{
if (![self PACFileReadStream]) {
return;
}
if (eventCode == NSStreamEventHasBytesAvailable) {
if (![self PACFileData]) {
[self setPACFileData:[NSMutableData data]];
}
// If your PAC file is larger than 16KB, you're just being cruel.
uint8_t buf[16384];
NSInteger len = [(NSInputStream *)stream read:buf maxLength:16384];
if (len) {
[[self PACFileData] appendBytes:(const void *)buf length:len];
}
} else if (eventCode == NSStreamEventErrorOccurred || eventCode == NSStreamEventEndEncountered) {
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(timeOutPACRead) object:nil];
[stream close];
[stream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:[self runLoopMode]];
[self setPACFileReadStream:nil];
if (eventCode == NSStreamEventEndEncountered) {
// It sounds as though we have no idea what encoding a PAC file will use
static NSStringEncoding encodingsToTry[2] = {NSUTF8StringEncoding,NSISOLatin1StringEncoding};
NSUInteger i;
for (i=0; i<2; i++) {
NSString *pacScript = [[[NSString alloc] initWithBytes:[[self PACFileData] bytes] length:[[self PACFileData] length] encoding:encodingsToTry[i]] autorelease];
if (pacScript) {
[self runPACScript:pacScript];
break;
}
}
}
[self setPACFileData:nil];
[self startRequest];
}
}
// Called if it takes longer than timeOutSeconds to read the whole PAC file (when reading from a file:// url)
- (void)timeOutPACRead
{
[self stream:[self PACFileReadStream] handleEvent:NSStreamEventErrorOccurred];
}
// Runs the downloaded PAC script
- (void)runPACScript:(NSString *)script
{
if (script) {
// From: http://developer.apple.com/samplecode/CFProxySupportTool/listing1.html
// Work around <rdar://problem/5530166>. This dummy call to
// CFNetworkCopyProxiesForURL initialise some state within CFNetwork
// that is required by CFNetworkCopyProxiesForAutoConfigurationScript.
CFRelease(CFNetworkCopyProxiesForURL((CFURLRef)[self url], NULL));
// Obtain the list of proxies by running the autoconfiguration script
CFErrorRef err = NULL;
NSArray *proxies = [NSMakeCollectable(CFNetworkCopyProxiesForAutoConfigurationScript((CFStringRef)script,(CFURLRef)[self url], &err)) autorelease];
if (!err && [proxies count] > 0) {
NSDictionary *settings = [proxies objectAtIndex:0];
[self setProxyHost:[settings objectForKey:(NSString *)kCFProxyHostNameKey]];
[self setProxyPort:[[settings objectForKey:(NSString *)kCFProxyPortNumberKey] intValue]];
[self setProxyType:[settings objectForKey:(NSString *)kCFProxyTypeKey]];
}
}
}
// Called if we successfully downloaded a PAC file from a webserver
- (void)finishedDownloadingPACFile:(ASIHTTPRequest *)theRequest
{
if (![theRequest error] && [theRequest responseString]) {
[self runPACScript:[theRequest responseString]];
}
// Set the shared queue's maxConcurrentOperationCount back to normal
[connectionsLock lock];
[sharedQueue setMaxConcurrentOperationCount:[sharedQueue maxConcurrentOperationCount]-1];
[connectionsLock unlock];
// We no longer need our PAC file request
[self setPACFileRequest:nil];
// Start the request
[self startRequest];
}
#pragma mark persistent connections
- (NSNumber *)connectionID
{
return [[self connectionInfo] objectForKey:@"id"];
}
+ (void)expirePersistentConnections
{
[connectionsLock lock];
NSUInteger i;
for (i=0; i<[persistentConnectionsPool count]; i++) {
NSDictionary *existingConnection = [persistentConnectionsPool objectAtIndex:i];
if (![existingConnection objectForKey:@"request"] && [[existingConnection objectForKey:@"expires"] timeIntervalSinceNow] <= 0) {
#if DEBUG_PERSISTENT_CONNECTIONS
ASI_DEBUG_LOG(@"[CONNECTION] Closing connection #%i because it has expired",[[existingConnection objectForKey:@"id"] intValue]);
#endif
NSInputStream *stream = [existingConnection objectForKey:@"stream"];
if (stream) {
[stream close];
}
[persistentConnectionsPool removeObject:existingConnection];
i--;
}
}
[connectionsLock unlock];
}
#pragma mark NSCopying
- (id)copyWithZone:(NSZone *)zone
{
// Don't forget - this will return a retained copy!
ASIHTTPRequest *newRequest = [[[self class] alloc] initWithURL:[self url]];
[newRequest setDelegate:[self delegate]];
[newRequest setRequestMethod:[self requestMethod]];
[newRequest setPostBody:[self postBody]];
[newRequest setShouldStreamPostDataFromDisk:[self shouldStreamPostDataFromDisk]];
[newRequest setPostBodyFilePath:[self postBodyFilePath]];
[newRequest setRequestHeaders:[[[self requestHeaders] mutableCopyWithZone:zone] autorelease]];
[newRequest setRequestCookies:[[[self requestCookies] mutableCopyWithZone:zone] autorelease]];
[newRequest setUseCookiePersistence:[self useCookiePersistence]];
[newRequest setUseKeychainPersistence:[self useKeychainPersistence]];
[newRequest setUseSessionPersistence:[self useSessionPersistence]];
[newRequest setAllowCompressedResponse:[self allowCompressedResponse]];
[newRequest setDownloadDestinationPath:[self downloadDestinationPath]];
[newRequest setTemporaryFileDownloadPath:[self temporaryFileDownloadPath]];
[newRequest setUsername:[self username]];
[newRequest setPassword:[self password]];
[newRequest setDomain:[self domain]];
[newRequest setProxyUsername:[self proxyUsername]];
[newRequest setProxyPassword:[self proxyPassword]];
[newRequest setProxyDomain:[self proxyDomain]];
[newRequest setProxyHost:[self proxyHost]];
[newRequest setProxyPort:[self proxyPort]];
[newRequest setProxyType:[self proxyType]];
[newRequest setUploadProgressDelegate:[self uploadProgressDelegate]];
[newRequest setDownloadProgressDelegate:[self downloadProgressDelegate]];
[newRequest setShouldPresentAuthenticationDialog:[self shouldPresentAuthenticationDialog]];
[newRequest setShouldPresentProxyAuthenticationDialog:[self shouldPresentProxyAuthenticationDialog]];
[newRequest setPostLength:[self postLength]];
[newRequest setHaveBuiltPostBody:[self haveBuiltPostBody]];
[newRequest setDidStartSelector:[self didStartSelector]];
[newRequest setDidFinishSelector:[self didFinishSelector]];
[newRequest setDidFailSelector:[self didFailSelector]];
[newRequest setTimeOutSeconds:[self timeOutSeconds]];
[newRequest setShouldResetDownloadProgress:[self shouldResetDownloadProgress]];
[newRequest setShouldResetUploadProgress:[self shouldResetUploadProgress]];
[newRequest setShowAccurateProgress:[self showAccurateProgress]];
[newRequest setDefaultResponseEncoding:[self defaultResponseEncoding]];
[newRequest setAllowResumeForFileDownloads:[self allowResumeForFileDownloads]];
[newRequest setUserInfo:[[[self userInfo] copyWithZone:zone] autorelease]];
[newRequest setTag:[self tag]];
[newRequest setUseHTTPVersionOne:[self useHTTPVersionOne]];
[newRequest setShouldRedirect:[self shouldRedirect]];
[newRequest setValidatesSecureCertificate:[self validatesSecureCertificate]];
[newRequest setClientCertificateIdentity:clientCertificateIdentity];
[newRequest setClientCertificates:[[clientCertificates copy] autorelease]];
[newRequest setPACurl:[self PACurl]];
[newRequest setShouldPresentCredentialsBeforeChallenge:[self shouldPresentCredentialsBeforeChallenge]];
[newRequest setNumberOfTimesToRetryOnTimeout:[self numberOfTimesToRetryOnTimeout]];
[newRequest setShouldUseRFC2616RedirectBehaviour:[self shouldUseRFC2616RedirectBehaviour]];
[newRequest setShouldAttemptPersistentConnection:[self shouldAttemptPersistentConnection]];
[newRequest setPersistentConnectionTimeoutSeconds:[self persistentConnectionTimeoutSeconds]];
[newRequest setAuthenticationScheme:[self authenticationScheme]];
return newRequest;
}
#pragma mark default time out
+ (NSTimeInterval)defaultTimeOutSeconds
{
return defaultTimeOutSeconds;
}
+ (void)setDefaultTimeOutSeconds:(NSTimeInterval)newTimeOutSeconds
{
defaultTimeOutSeconds = newTimeOutSeconds;
}
#pragma mark client certificate
- (void)setClientCertificateIdentity:(SecIdentityRef)anIdentity {
if(clientCertificateIdentity) {
CFRelease(clientCertificateIdentity);
}
clientCertificateIdentity = anIdentity;
if (clientCertificateIdentity) {
CFRetain(clientCertificateIdentity);
}
}
#pragma mark session credentials
+ (NSMutableArray *)sessionProxyCredentialsStore
{
[sessionCredentialsLock lock];
if (!sessionProxyCredentialsStore) {
sessionProxyCredentialsStore = [[NSMutableArray alloc] init];
}
[sessionCredentialsLock unlock];
return sessionProxyCredentialsStore;
}
+ (NSMutableArray *)sessionCredentialsStore
{
[sessionCredentialsLock lock];
if (!sessionCredentialsStore) {
sessionCredentialsStore = [[NSMutableArray alloc] init];
}
[sessionCredentialsLock unlock];
return sessionCredentialsStore;
}
+ (void)storeProxyAuthenticationCredentialsInSessionStore:(NSDictionary *)credentials
{
[sessionCredentialsLock lock];
[self removeProxyAuthenticationCredentialsFromSessionStore:[credentials objectForKey:@"Credentials"]];
[[[self class] sessionProxyCredentialsStore] addObject:credentials];
[sessionCredentialsLock unlock];
}
+ (void)storeAuthenticationCredentialsInSessionStore:(NSDictionary *)credentials
{
[sessionCredentialsLock lock];
[self removeAuthenticationCredentialsFromSessionStore:[credentials objectForKey:@"Credentials"]];
[[[self class] sessionCredentialsStore] addObject:credentials];
[sessionCredentialsLock unlock];
}
+ (void)removeProxyAuthenticationCredentialsFromSessionStore:(NSDictionary *)credentials
{
[sessionCredentialsLock lock];
NSMutableArray *sessionCredentialsList = [[self class] sessionProxyCredentialsStore];
NSUInteger i;
for (i=0; i<[sessionCredentialsList count]; i++) {
NSDictionary *theCredentials = [sessionCredentialsList objectAtIndex:i];
if ([theCredentials objectForKey:@"Credentials"] == credentials) {
[sessionCredentialsList removeObjectAtIndex:i];
[sessionCredentialsLock unlock];
return;
}
}
[sessionCredentialsLock unlock];
}
+ (void)removeAuthenticationCredentialsFromSessionStore:(NSDictionary *)credentials
{
[sessionCredentialsLock lock];
NSMutableArray *sessionCredentialsList = [[self class] sessionCredentialsStore];
NSUInteger i;
for (i=0; i<[sessionCredentialsList count]; i++) {
NSDictionary *theCredentials = [sessionCredentialsList objectAtIndex:i];
if ([theCredentials objectForKey:@"Credentials"] == credentials) {
[sessionCredentialsList removeObjectAtIndex:i];
[sessionCredentialsLock unlock];
return;
}
}
[sessionCredentialsLock unlock];
}
- (NSDictionary *)findSessionProxyAuthenticationCredentials
{
[sessionCredentialsLock lock];
NSMutableArray *sessionCredentialsList = [[self class] sessionProxyCredentialsStore];
for (NSDictionary *theCredentials in sessionCredentialsList) {
if ([[theCredentials objectForKey:@"Host"] isEqualToString:[self proxyHost]] && [[theCredentials objectForKey:@"Port"] intValue] == [self proxyPort]) {
[sessionCredentialsLock unlock];
return theCredentials;
}
}
[sessionCredentialsLock unlock];
return nil;
}
- (NSDictionary *)findSessionAuthenticationCredentials
{
[sessionCredentialsLock lock];
NSMutableArray *sessionCredentialsList = [[self class] sessionCredentialsStore];
NSURL *requestURL = [self url];
BOOL haveFoundExactMatch;
NSDictionary *closeMatch = nil;
// Loop through all the cached credentials we have, looking for the best match for this request
for (NSDictionary *theCredentials in sessionCredentialsList) {
haveFoundExactMatch = NO;
NSURL *cachedCredentialsURL = [theCredentials objectForKey:@"URL"];
// Find an exact match (same url)
if ([cachedCredentialsURL isEqual:[self url]]) {
haveFoundExactMatch = YES;
// This is not an exact match for the url, and we already have a close match we can use
} else if (closeMatch) {
continue;
// Find a close match (same host, scheme and port)
} else if ([[cachedCredentialsURL host] isEqualToString:[requestURL host]] && ([cachedCredentialsURL port] == [requestURL port] || ([requestURL port] && [[cachedCredentialsURL port] isEqualToNumber:[requestURL port]])) && [[cachedCredentialsURL scheme] isEqualToString:[requestURL scheme]]) {
} else {
continue;
}
// Just a sanity check to ensure we never choose credentials from a different realm. Can't really do more than that, as either this request or the stored credentials may not have a realm when the other does
if ([self authenticationRealm] && ([theCredentials objectForKey:@"AuthenticationRealm"] && ![[theCredentials objectForKey:@"AuthenticationRealm"] isEqualToString:[self authenticationRealm]])) {
continue;
}
// If we have a username and password set on the request, check that they are the same as the cached ones
if ([self username] && [self password]) {
NSDictionary *usernameAndPassword = [theCredentials objectForKey:@"Credentials"];
NSString *storedUsername = [usernameAndPassword objectForKey:(NSString *)kCFHTTPAuthenticationUsername];
NSString *storedPassword = [usernameAndPassword objectForKey:(NSString *)kCFHTTPAuthenticationPassword];
if (![storedUsername isEqualToString:[self username]] || ![storedPassword isEqualToString:[self password]]) {
continue;
}
}
// If we have an exact match for the url, use those credentials
if (haveFoundExactMatch) {
[sessionCredentialsLock unlock];
return theCredentials;
}
// We have no exact match, let's remember that we have a good match for this server, and we'll use it at the end if we don't find an exact match
closeMatch = theCredentials;
}
[sessionCredentialsLock unlock];
// Return credentials that matched on host, port and scheme, or nil if we didn't find any
return closeMatch;
}
#pragma mark keychain storage
+ (void)saveCredentials:(NSURLCredential *)credentials forHost:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm
{
NSURLProtectionSpace *protectionSpace = [[[NSURLProtectionSpace alloc] initWithHost:host port:port protocol:protocol realm:realm authenticationMethod:NSURLAuthenticationMethodDefault] autorelease];
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credentials forProtectionSpace:protectionSpace];
}
+ (void)saveCredentials:(NSURLCredential *)credentials forProxy:(NSString *)host port:(int)port realm:(NSString *)realm
{
NSURLProtectionSpace *protectionSpace = [[[NSURLProtectionSpace alloc] initWithProxyHost:host port:port type:NSURLProtectionSpaceHTTPProxy realm:realm authenticationMethod:NSURLAuthenticationMethodDefault] autorelease];
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credentials forProtectionSpace:protectionSpace];
}
+ (NSURLCredential *)savedCredentialsForHost:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm
{
NSURLProtectionSpace *protectionSpace = [[[NSURLProtectionSpace alloc] initWithHost:host port:port protocol:protocol realm:realm authenticationMethod:NSURLAuthenticationMethodDefault] autorelease];
return [[NSURLCredentialStorage sharedCredentialStorage] defaultCredentialForProtectionSpace:protectionSpace];
}
+ (NSURLCredential *)savedCredentialsForProxy:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm
{
NSURLProtectionSpace *protectionSpace = [[[NSURLProtectionSpace alloc] initWithProxyHost:host port:port type:NSURLProtectionSpaceHTTPProxy realm:realm authenticationMethod:NSURLAuthenticationMethodDefault] autorelease];
return [[NSURLCredentialStorage sharedCredentialStorage] defaultCredentialForProtectionSpace:protectionSpace];
}
+ (void)removeCredentialsForHost:(NSString *)host port:(int)port protocol:(NSString *)protocol realm:(NSString *)realm
{
NSURLProtectionSpace *protectionSpace = [[[NSURLProtectionSpace alloc] initWithHost:host port:port protocol:protocol realm:realm authenticationMethod:NSURLAuthenticationMethodDefault] autorelease];
NSURLCredential *credential = [[NSURLCredentialStorage sharedCredentialStorage] defaultCredentialForProtectionSpace:protectionSpace];
if (credential) {
[[NSURLCredentialStorage sharedCredentialStorage] removeCredential:credential forProtectionSpace:protectionSpace];
}
}
+ (void)removeCredentialsForProxy:(NSString *)host port:(int)port realm:(NSString *)realm
{
NSURLProtectionSpace *protectionSpace = [[[NSURLProtectionSpace alloc] initWithProxyHost:host port:port type:NSURLProtectionSpaceHTTPProxy realm:realm authenticationMethod:NSURLAuthenticationMethodDefault] autorelease];
NSURLCredential *credential = [[NSURLCredentialStorage sharedCredentialStorage] defaultCredentialForProtectionSpace:protectionSpace];
if (credential) {
[[NSURLCredentialStorage sharedCredentialStorage] removeCredential:credential forProtectionSpace:protectionSpace];
}
}
+ (NSMutableArray *)sessionCookies
{
[sessionCookiesLock lock];
if (!sessionCookies) {
[ASIHTTPRequest setSessionCookies:[NSMutableArray array]];
}
NSMutableArray *cookies = [[sessionCookies retain] autorelease];
[sessionCookiesLock unlock];
return cookies;
}
+ (void)setSessionCookies:(NSMutableArray *)newSessionCookies
{
[sessionCookiesLock lock];
// Remove existing cookies from the persistent store
for (NSHTTPCookie *cookie in sessionCookies) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
[sessionCookies release];
sessionCookies = [newSessionCookies retain];
[sessionCookiesLock unlock];
}
+ (void)addSessionCookie:(NSHTTPCookie *)newCookie
{
[sessionCookiesLock lock];
NSHTTPCookie *cookie;
NSUInteger i;
NSUInteger max = [[ASIHTTPRequest sessionCookies] count];
for (i=0; i<max; i++) {
cookie = [[ASIHTTPRequest sessionCookies] objectAtIndex:i];
if ([[cookie domain] isEqualToString:[newCookie domain]] && [[cookie path] isEqualToString:[newCookie path]] && [[cookie name] isEqualToString:[newCookie name]]) {
[[ASIHTTPRequest sessionCookies] removeObjectAtIndex:i];
break;
}
}
[[ASIHTTPRequest sessionCookies] addObject:newCookie];
[sessionCookiesLock unlock];
}
// Dump all session data (authentication and cookies)
+ (void)clearSession
{
[sessionCredentialsLock lock];
[[[self class] sessionCredentialsStore] removeAllObjects];
[sessionCredentialsLock unlock];
[[self class] setSessionCookies:nil];
[[[self class] defaultCache] clearCachedResponsesForStoragePolicy:ASICacheForSessionDurationCacheStoragePolicy];
}
#pragma mark get user agent
+ (NSString *)defaultUserAgentString
{
@synchronized (self) {
if (!defaultUserAgent) {
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
// Attempt to find a name for this application
NSString *appName = [bundle objectForInfoDictionaryKey:@"CFBundleDisplayName"];
if (!appName) {
appName = [bundle objectForInfoDictionaryKey:@"CFBundleName"];
}
NSData *latin1Data = [appName dataUsingEncoding:NSUTF8StringEncoding];
appName = [[[NSString alloc] initWithData:latin1Data encoding:NSISOLatin1StringEncoding] autorelease];
// If we couldn't find one, we'll give up (and ASIHTTPRequest will use the standard CFNetwork user agent)
if (!appName) {
return nil;
}
NSString *appVersion = nil;
NSString *marketingVersionNumber = [bundle objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
NSString *developmentVersionNumber = [bundle objectForInfoDictionaryKey:@"CFBundleVersion"];
if (marketingVersionNumber && developmentVersionNumber) {
if ([marketingVersionNumber isEqualToString:developmentVersionNumber]) {
appVersion = marketingVersionNumber;
} else {
appVersion = [NSString stringWithFormat:@"%@ rv:%@",marketingVersionNumber,developmentVersionNumber];
}
} else {
appVersion = (marketingVersionNumber ? marketingVersionNumber : developmentVersionNumber);
}
NSString *deviceName;
NSString *OSName;
NSString *OSVersion;
NSString *locale = [[NSLocale currentLocale] localeIdentifier];
#if TARGET_OS_IPHONE
UIDevice *device = [UIDevice currentDevice];
deviceName = [device model];
OSName = [device systemName];
OSVersion = [device systemVersion];
#else
deviceName = @"Macintosh";
OSName = @"Mac OS X";
// From http://www.cocoadev.com/index.pl?DeterminingOSVersion
// We won't bother to check for systems prior to 10.4, since ASIHTTPRequest only works on 10.5+
OSErr err;
SInt32 versionMajor, versionMinor, versionBugFix;
err = Gestalt(gestaltSystemVersionMajor, &versionMajor);
if (err != noErr) return nil;
err = Gestalt(gestaltSystemVersionMinor, &versionMinor);
if (err != noErr) return nil;
err = Gestalt(gestaltSystemVersionBugFix, &versionBugFix);
if (err != noErr) return nil;
OSVersion = [NSString stringWithFormat:@"%u.%u.%u", versionMajor, versionMinor, versionBugFix];
#endif
// Takes the form "My Application 1.0 (Macintosh; Mac OS X 10.5.7; en_GB)"
[self setDefaultUserAgentString:[NSString stringWithFormat:@"%@ %@ (%@; %@ %@; %@)", appName, appVersion, deviceName, OSName, OSVersion, locale]];
}
return [[defaultUserAgent retain] autorelease];
}
return nil;
}
+ (void)setDefaultUserAgentString:(NSString *)agent
{
@synchronized (self) {
if (defaultUserAgent == agent) {
return;
}
[defaultUserAgent release];
defaultUserAgent = [agent copy];
}
}
#pragma mark mime-type detection
+ (NSString *)mimeTypeForFileAtPath:(NSString *)path
{
if (![[[[NSFileManager alloc] init] autorelease] fileExistsAtPath:path]) {
return nil;
}
// Borrowed from http://stackoverflow.com/questions/2439020/wheres-the-iphone-mime-type-database
CFStringRef UTI = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (CFStringRef)[path pathExtension], NULL);
CFStringRef MIMEType = UTTypeCopyPreferredTagWithClass (UTI, kUTTagClassMIMEType);
CFRelease(UTI);
if (!MIMEType) {
return @"application/octet-stream";
}
return [NSMakeCollectable(MIMEType) autorelease];
}
#pragma mark bandwidth measurement / throttling
- (void)performThrottling
{
if (![self readStream]) {
return;
}
[ASIHTTPRequest measureBandwidthUsage];
if ([ASIHTTPRequest isBandwidthThrottled]) {
[bandwidthThrottlingLock lock];
// Handle throttling
if (throttleWakeUpTime) {
if ([throttleWakeUpTime timeIntervalSinceDate:[NSDate date]] > 0) {
if ([self readStreamIsScheduled]) {
[self unscheduleReadStream];
#if DEBUG_THROTTLING
ASI_DEBUG_LOG(@"[THROTTLING] Sleeping request %@ until after %@",self,throttleWakeUpTime);
#endif
}
} else {
if (![self readStreamIsScheduled]) {
[self scheduleReadStream];
#if DEBUG_THROTTLING
ASI_DEBUG_LOG(@"[THROTTLING] Waking up request %@",self);
#endif
}
}
}
[bandwidthThrottlingLock unlock];
// Bandwidth throttling must have been turned off since we last looked, let's re-schedule the stream
} else if (![self readStreamIsScheduled]) {
[self scheduleReadStream];
}
}
+ (BOOL)isBandwidthThrottled
{
#if TARGET_OS_IPHONE
[bandwidthThrottlingLock lock];
BOOL throttle = isBandwidthThrottled || (!shouldThrottleBandwidthForWWANOnly && (maxBandwidthPerSecond > 0));
[bandwidthThrottlingLock unlock];
return throttle;
#else
[bandwidthThrottlingLock lock];
BOOL throttle = (maxBandwidthPerSecond > 0);
[bandwidthThrottlingLock unlock];
return throttle;
#endif
}
+ (unsigned long)maxBandwidthPerSecond
{
[bandwidthThrottlingLock lock];
unsigned long amount = maxBandwidthPerSecond;
[bandwidthThrottlingLock unlock];
return amount;
}
+ (void)setMaxBandwidthPerSecond:(unsigned long)bytes
{
[bandwidthThrottlingLock lock];
maxBandwidthPerSecond = bytes;
[bandwidthThrottlingLock unlock];
}
+ (void)incrementBandwidthUsedInLastSecond:(unsigned long)bytes
{
[bandwidthThrottlingLock lock];
bandwidthUsedInLastSecond += bytes;
[bandwidthThrottlingLock unlock];
}
+ (void)recordBandwidthUsage
{
if (bandwidthUsedInLastSecond == 0) {
[bandwidthUsageTracker removeAllObjects];
} else {
NSTimeInterval interval = [bandwidthMeasurementDate timeIntervalSinceNow];
while ((interval < 0 || [bandwidthUsageTracker count] > 5) && [bandwidthUsageTracker count] > 0) {
[bandwidthUsageTracker removeObjectAtIndex:0];
interval++;
}
}
#if DEBUG_THROTTLING
ASI_DEBUG_LOG(@"[THROTTLING] ===Used: %u bytes of bandwidth in last measurement period===",bandwidthUsedInLastSecond);
#endif
[bandwidthUsageTracker addObject:[NSNumber numberWithUnsignedLong:bandwidthUsedInLastSecond]];
[bandwidthMeasurementDate release];
bandwidthMeasurementDate = [[NSDate dateWithTimeIntervalSinceNow:1] retain];
bandwidthUsedInLastSecond = 0;
NSUInteger measurements = [bandwidthUsageTracker count];
unsigned long totalBytes = 0;
for (NSNumber *bytes in bandwidthUsageTracker) {
totalBytes += [bytes unsignedLongValue];
}
averageBandwidthUsedPerSecond = totalBytes/measurements;
}
+ (unsigned long)averageBandwidthUsedPerSecond
{
[bandwidthThrottlingLock lock];
unsigned long amount = averageBandwidthUsedPerSecond;
[bandwidthThrottlingLock unlock];
return amount;
}
+ (void)measureBandwidthUsage
{
// Other requests may have to wait for this lock if we're sleeping, but this is fine, since in that case we already know they shouldn't be sending or receiving data
[bandwidthThrottlingLock lock];
if (!bandwidthMeasurementDate || [bandwidthMeasurementDate timeIntervalSinceNow] < -0) {
[ASIHTTPRequest recordBandwidthUsage];
}
// Are we performing bandwidth throttling?
if (
#if TARGET_OS_IPHONE
isBandwidthThrottled || (!shouldThrottleBandwidthForWWANOnly && (maxBandwidthPerSecond))
#else
maxBandwidthPerSecond
#endif
) {
// How much data can we still send or receive this second?
long long bytesRemaining = (long long)maxBandwidthPerSecond - (long long)bandwidthUsedInLastSecond;
// Have we used up our allowance?
if (bytesRemaining < 0) {
// Yes, put this request to sleep until a second is up, with extra added punishment sleeping time for being very naughty (we have used more bandwidth than we were allowed)
double extraSleepyTime = (-bytesRemaining/(maxBandwidthPerSecond*1.0));
[throttleWakeUpTime release];
throttleWakeUpTime = [[NSDate alloc] initWithTimeInterval:extraSleepyTime sinceDate:bandwidthMeasurementDate];
}
}
[bandwidthThrottlingLock unlock];
}
+ (unsigned long)maxUploadReadLength
{
[bandwidthThrottlingLock lock];
// We'll split our bandwidth allowance into 4 (which is the default for an ASINetworkQueue's max concurrent operations count) to give all running requests a fighting chance of reading data this cycle
long long toRead = maxBandwidthPerSecond/4;
if (maxBandwidthPerSecond > 0 && (bandwidthUsedInLastSecond + toRead > maxBandwidthPerSecond)) {
toRead = (long long)maxBandwidthPerSecond-(long long)bandwidthUsedInLastSecond;
if (toRead < 0) {
toRead = 0;
}
}
if (toRead == 0 || !bandwidthMeasurementDate || [bandwidthMeasurementDate timeIntervalSinceNow] < -0) {
[throttleWakeUpTime release];
throttleWakeUpTime = [bandwidthMeasurementDate retain];
}
[bandwidthThrottlingLock unlock];
return (unsigned long)toRead;
}
#if TARGET_OS_IPHONE
+ (void)setShouldThrottleBandwidthForWWAN:(BOOL)throttle
{
if (throttle) {
[ASIHTTPRequest throttleBandwidthForWWANUsingLimit:ASIWWANBandwidthThrottleAmount];
} else {
[ASIHTTPRequest unsubscribeFromNetworkReachabilityNotifications];
[ASIHTTPRequest setMaxBandwidthPerSecond:0];
[bandwidthThrottlingLock lock];
isBandwidthThrottled = NO;
shouldThrottleBandwidthForWWANOnly = NO;
[bandwidthThrottlingLock unlock];
}
}
+ (void)throttleBandwidthForWWANUsingLimit:(unsigned long)limit
{
[bandwidthThrottlingLock lock];
shouldThrottleBandwidthForWWANOnly = YES;
maxBandwidthPerSecond = limit;
[ASIHTTPRequest registerForNetworkReachabilityNotifications];
[bandwidthThrottlingLock unlock];
[ASIHTTPRequest reachabilityChanged:nil];
}
#pragma mark reachability
+ (void)registerForNetworkReachabilityNotifications
{
[[Reachability reachabilityForInternetConnection] startNotifier];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
}
+ (void)unsubscribeFromNetworkReachabilityNotifications
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];
}
+ (BOOL)isNetworkReachableViaWWAN
{
return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] == ReachableViaWWAN);
}
+ (void)reachabilityChanged:(NSNotification *)note
{
[bandwidthThrottlingLock lock];
isBandwidthThrottled = [ASIHTTPRequest isNetworkReachableViaWWAN];
[bandwidthThrottlingLock unlock];
}
#endif
#pragma mark queue
// Returns the shared queue
+ (NSOperationQueue *)sharedQueue
{
return [[sharedQueue retain] autorelease];
}
#pragma mark cache
+ (void)setDefaultCache:(id <ASICacheDelegate>)cache
{
@synchronized (self) {
[cache retain];
[defaultCache release];
defaultCache = cache;
}
}
+ (id <ASICacheDelegate>)defaultCache
{
@synchronized(self) {
return [[defaultCache retain] autorelease];
}
return nil;
}
#pragma mark network activity
+ (BOOL)isNetworkInUse
{
[connectionsLock lock];
BOOL inUse = (runningRequestCount > 0);
[connectionsLock unlock];
return inUse;
}
+ (void)setShouldUpdateNetworkActivityIndicator:(BOOL)shouldUpdate
{
[connectionsLock lock];
shouldUpdateNetworkActivityIndicator = shouldUpdate;
[connectionsLock unlock];
}
+ (void)showNetworkActivityIndicator
{
#if TARGET_OS_IPHONE
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
#endif
}
+ (void)hideNetworkActivityIndicator
{
#if TARGET_OS_IPHONE
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
#endif
}
/* Always called on main thread */
+ (void)hideNetworkActivityIndicatorAfterDelay
{
[self performSelector:@selector(hideNetworkActivityIndicatorIfNeeeded) withObject:nil afterDelay:0.5];
}
+ (void)hideNetworkActivityIndicatorIfNeeeded
{
[connectionsLock lock];
if (runningRequestCount == 0) {
[self hideNetworkActivityIndicator];
}
[connectionsLock unlock];
}
#pragma mark threading behaviour
// In the default implementation, all requests run in a single background thread
// Advanced users only: Override this method in a subclass for a different threading behaviour
// Eg: return [NSThread mainThread] to run all requests in the main thread
// Alternatively, you can create a thread on demand, or manage a pool of threads
// Threads returned by this method will need to run the runloop in default mode (eg CFRunLoopRun())
// Requests will stop the runloop when they complete
// If you have multiple requests sharing the thread or you want to re-use the thread, you'll need to restart the runloop
+ (NSThread *)threadForRequest:(ASIHTTPRequest *)request
{
if (networkThread == nil) {
@synchronized(self) {
if (networkThread == nil) {
networkThread = [[NSThread alloc] initWithTarget:self selector:@selector(runRequests) object:nil];
[networkThread start];
}
}
}
return networkThread;
}
+ (void)runRequests
{
// Should keep the runloop from exiting
CFRunLoopSourceContext context = {0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL};
CFRunLoopSourceRef source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context);
CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
BOOL runAlways = YES; // Introduced to cheat Static Analyzer
while (runAlways) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1.0e10, true);
[pool drain];
}
// Should never be called, but anyway
CFRunLoopRemoveSource(CFRunLoopGetCurrent(), source, kCFRunLoopDefaultMode);
CFRelease(source);
}
#pragma mark miscellany
#if TARGET_OS_IPHONE
+ (BOOL)isMultitaskingSupported
{
BOOL multiTaskingSupported = NO;
if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) {
multiTaskingSupported = [(id)[UIDevice currentDevice] isMultitaskingSupported];
}
return multiTaskingSupported;
}
#endif
// From: http://www.cocoadev.com/index.pl?BaseSixtyFour
+ (NSString*)base64forData:(NSData*)theData {
const uint8_t* input = (const uint8_t*)[theData bytes];
NSInteger length = [theData length];
static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t* output = (uint8_t*)data.mutableBytes;
NSInteger i,i2;
for (i=0; i < length; i += 3) {
NSInteger value = 0;
for (i2=0; i2<3; i2++) {
value <<= 8;
if (i+i2 < length) {
value |= (0xFF & input[i+i2]);
}
}
NSInteger theIndex = (i / 3) * 4;
output[theIndex + 0] = table[(value >> 18) & 0x3F];
output[theIndex + 1] = table[(value >> 12) & 0x3F];
output[theIndex + 2] = (i + 1) < length ? table[(value >> 6) & 0x3F] : '=';
output[theIndex + 3] = (i + 2) < length ? table[(value >> 0) & 0x3F] : '=';
}
return [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] autorelease];
}
+ (NSDate *)expiryDateForRequest:(ASIHTTPRequest *)request maxAge:(NSTimeInterval)maxAge
{
NSDictionary *responseHeaders = [request responseHeaders];
// If we weren't given a custom max-age, lets look for one in the response headers
if (!maxAge) {
NSString *cacheControl = [[responseHeaders objectForKey:@"Cache-Control"] lowercaseString];
if (cacheControl) {
NSScanner *scanner = [NSScanner scannerWithString:cacheControl];
[scanner scanUpToString:@"max-age" intoString:NULL];
if ([scanner scanString:@"max-age" intoString:NULL]) {
[scanner scanString:@"=" intoString:NULL];
[scanner scanDouble:&maxAge];
}
}
}
// RFC 2612 says max-age must override any Expires header
if (maxAge) {
return [[NSDate date] addTimeInterval:maxAge];
} else {
NSString *expires = [responseHeaders objectForKey:@"Expires"];
if (expires) {
return [ASIHTTPRequest dateFromRFC1123String:expires];
}
}
return nil;
}
// Based on hints from http://stackoverflow.com/questions/1850824/parsing-a-rfc-822-date-with-nsdateformatter
+ (NSDate *)dateFromRFC1123String:(NSString *)string
{
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];
// Does the string include a week day?
NSString *day = @"";
if ([string rangeOfString:@","].location != NSNotFound) {
day = @"EEE, ";
}
// Does the string include seconds?
NSString *seconds = @"";
if ([[string componentsSeparatedByString:@":"] count] == 3) {
seconds = @":ss";
}
[formatter setDateFormat:[NSString stringWithFormat:@"%@dd MMM yyyy HH:mm%@ z",day,seconds]];
return [formatter dateFromString:string];
}
+ (void)parseMimeType:(NSString **)mimeType andResponseEncoding:(NSStringEncoding *)stringEncoding fromContentType:(NSString *)contentType
{
if (!contentType) {
return;
}
NSScanner *charsetScanner = [NSScanner scannerWithString: contentType];
if (![charsetScanner scanUpToString:@";" intoString:mimeType] || [charsetScanner scanLocation] == [contentType length]) {
*mimeType = [contentType stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
return;
}
*mimeType = [*mimeType stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *charsetSeparator = @"charset=";
NSString *IANAEncoding = nil;
if ([charsetScanner scanUpToString: charsetSeparator intoString: NULL] && [charsetScanner scanLocation] < [contentType length]) {
[charsetScanner setScanLocation: [charsetScanner scanLocation] + [charsetSeparator length]];
[charsetScanner scanUpToString: @";" intoString: &IANAEncoding];
}
if (IANAEncoding) {
CFStringEncoding cfEncoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)IANAEncoding);
if (cfEncoding != kCFStringEncodingInvalidId) {
*stringEncoding = CFStringConvertEncodingToNSStringEncoding(cfEncoding);
}
}
}
#pragma mark -
#pragma mark blocks
#if NS_BLOCKS_AVAILABLE
- (void)setStartedBlock:(ASIBasicBlock)aStartedBlock
{
[startedBlock release];
startedBlock = [aStartedBlock copy];
}
- (void)setHeadersReceivedBlock:(ASIHeadersBlock)aReceivedBlock
{
[headersReceivedBlock release];
headersReceivedBlock = [aReceivedBlock copy];
}
- (void)setCompletionBlock:(ASIBasicBlock)aCompletionBlock
{
[completionBlock release];
completionBlock = [aCompletionBlock copy];
}
- (void)setFailedBlock:(ASIBasicBlock)aFailedBlock
{
[failureBlock release];
failureBlock = [aFailedBlock copy];
}
- (void)setBytesReceivedBlock:(ASIProgressBlock)aBytesReceivedBlock
{
[bytesReceivedBlock release];
bytesReceivedBlock = [aBytesReceivedBlock copy];
}
- (void)setBytesSentBlock:(ASIProgressBlock)aBytesSentBlock
{
[bytesSentBlock release];
bytesSentBlock = [aBytesSentBlock copy];
}
- (void)setDownloadSizeIncrementedBlock:(ASISizeBlock)aDownloadSizeIncrementedBlock{
[downloadSizeIncrementedBlock release];
downloadSizeIncrementedBlock = [aDownloadSizeIncrementedBlock copy];
}
- (void)setUploadSizeIncrementedBlock:(ASISizeBlock)anUploadSizeIncrementedBlock
{
[uploadSizeIncrementedBlock release];
uploadSizeIncrementedBlock = [anUploadSizeIncrementedBlock copy];
}
- (void)setDataReceivedBlock:(ASIDataBlock)aReceivedBlock
{
[dataReceivedBlock release];
dataReceivedBlock = [aReceivedBlock copy];
}
- (void)setAuthenticationNeededBlock:(ASIBasicBlock)anAuthenticationBlock
{
[authenticationNeededBlock release];
authenticationNeededBlock = [anAuthenticationBlock copy];
}
- (void)setProxyAuthenticationNeededBlock:(ASIBasicBlock)aProxyAuthenticationBlock
{
[proxyAuthenticationNeededBlock release];
proxyAuthenticationNeededBlock = [aProxyAuthenticationBlock copy];
}
- (void)setRequestRedirectedBlock:(ASIBasicBlock)aRedirectBlock
{
[requestRedirectedBlock release];
requestRedirectedBlock = [aRedirectBlock copy];
}
#endif
#pragma mark ===
@synthesize username;
@synthesize password;
@synthesize userAgentString;
@synthesize domain;
@synthesize proxyUsername;
@synthesize proxyPassword;
@synthesize proxyDomain;
@synthesize url;
@synthesize originalURL;
@synthesize delegate;
@synthesize queue;
@synthesize uploadProgressDelegate;
@synthesize downloadProgressDelegate;
@synthesize useKeychainPersistence;
@synthesize useSessionPersistence;
@synthesize useCookiePersistence;
@synthesize downloadDestinationPath;
@synthesize temporaryFileDownloadPath;
@synthesize temporaryUncompressedDataDownloadPath;
@synthesize didStartSelector;
@synthesize didReceiveResponseHeadersSelector;
@synthesize willRedirectSelector;
@synthesize didFinishSelector;
@synthesize didFailSelector;
@synthesize didReceiveDataSelector;
@synthesize authenticationRealm;
@synthesize proxyAuthenticationRealm;
@synthesize error;
@synthesize complete;
@synthesize requestHeaders;
@synthesize responseHeaders;
@synthesize responseCookies;
@synthesize requestCookies;
@synthesize requestCredentials;
@synthesize responseStatusCode;
@synthesize rawResponseData;
@synthesize lastActivityTime;
@synthesize timeOutSeconds;
@synthesize requestMethod;
@synthesize postBody;
@synthesize compressedPostBody;
@synthesize contentLength;
@synthesize partialDownloadSize;
@synthesize postLength;
@synthesize shouldResetDownloadProgress;
@synthesize shouldResetUploadProgress;
@synthesize mainRequest;
@synthesize totalBytesRead;
@synthesize totalBytesSent;
@synthesize showAccurateProgress;
@synthesize uploadBufferSize;
@synthesize defaultResponseEncoding;
@synthesize responseEncoding;
@synthesize allowCompressedResponse;
@synthesize allowResumeForFileDownloads;
@synthesize userInfo;
@synthesize tag;
@synthesize postBodyFilePath;
@synthesize compressedPostBodyFilePath;
@synthesize postBodyWriteStream;
@synthesize postBodyReadStream;
@synthesize shouldStreamPostDataFromDisk;
@synthesize didCreateTemporaryPostDataFile;
@synthesize useHTTPVersionOne;
@synthesize lastBytesRead;
@synthesize lastBytesSent;
@synthesize cancelledLock;
@synthesize haveBuiltPostBody;
@synthesize fileDownloadOutputStream;
@synthesize inflatedFileDownloadOutputStream;
@synthesize authenticationRetryCount;
@synthesize proxyAuthenticationRetryCount;
@synthesize updatedProgress;
@synthesize shouldRedirect;
@synthesize validatesSecureCertificate;
@synthesize needsRedirect;
@synthesize redirectCount;
@synthesize shouldCompressRequestBody;
@synthesize proxyCredentials;
@synthesize proxyHost;
@synthesize proxyPort;
@synthesize proxyType;
@synthesize PACurl;
@synthesize authenticationScheme;
@synthesize proxyAuthenticationScheme;
@synthesize shouldPresentAuthenticationDialog;
@synthesize shouldPresentProxyAuthenticationDialog;
@synthesize authenticationNeeded;
@synthesize responseStatusMessage;
@synthesize shouldPresentCredentialsBeforeChallenge;
@synthesize haveBuiltRequestHeaders;
@synthesize inProgress;
@synthesize numberOfTimesToRetryOnTimeout;
@synthesize retryCount;
@synthesize willRetryRequest;
@synthesize shouldAttemptPersistentConnection;
@synthesize persistentConnectionTimeoutSeconds;
@synthesize connectionCanBeReused;
@synthesize connectionInfo;
@synthesize readStream;
@synthesize readStreamIsScheduled;
@synthesize shouldUseRFC2616RedirectBehaviour;
@synthesize downloadComplete;
@synthesize requestID;
@synthesize runLoopMode;
@synthesize statusTimer;
@synthesize downloadCache;
@synthesize cachePolicy;
@synthesize cacheStoragePolicy;
@synthesize didUseCachedResponse;
@synthesize secondsToCache;
@synthesize clientCertificates;
@synthesize redirectURL;
#if TARGET_OS_IPHONE && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_4_0
@synthesize shouldContinueWhenAppEntersBackground;
#endif
@synthesize dataDecompressor;
@synthesize shouldWaitToInflateCompressedResponses;
@synthesize isPACFileRequest;
@synthesize PACFileRequest;
@synthesize PACFileReadStream;
@synthesize PACFileData;
@synthesize isSynchronous;
@end
| 009-20120511-zi | trunk/Zinipad/ASI/ASIHTTPRequest.m | Objective-C | gpl3 | 184,635 |
//
// ASIDataCompressor.m
// Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
// Created by Ben Copsey on 17/08/2010.
// Copyright 2010 All-Seeing Interactive. All rights reserved.
//
#import "ASIDataCompressor.h"
#import "ASIHTTPRequest.h"
#define DATA_CHUNK_SIZE 262144 // Deal with gzipped data in 256KB chunks
#define COMPRESSION_AMOUNT Z_DEFAULT_COMPRESSION
@interface ASIDataCompressor ()
+ (NSError *)deflateErrorWithCode:(int)code;
@end
@implementation ASIDataCompressor
+ (id)compressor
{
ASIDataCompressor *compressor = [[[self alloc] init] autorelease];
[compressor setupStream];
return compressor;
}
- (void)dealloc
{
if (streamReady) {
[self closeStream];
}
[super dealloc];
}
- (NSError *)setupStream
{
if (streamReady) {
return nil;
}
// Setup the inflate stream
zStream.zalloc = Z_NULL;
zStream.zfree = Z_NULL;
zStream.opaque = Z_NULL;
zStream.avail_in = 0;
zStream.next_in = 0;
int status = deflateInit2(&zStream, COMPRESSION_AMOUNT, Z_DEFLATED, (15+16), 8, Z_DEFAULT_STRATEGY);
if (status != Z_OK) {
return [[self class] deflateErrorWithCode:status];
}
streamReady = YES;
return nil;
}
- (NSError *)closeStream
{
if (!streamReady) {
return nil;
}
// Close the deflate stream
streamReady = NO;
int status = deflateEnd(&zStream);
if (status != Z_OK) {
return [[self class] deflateErrorWithCode:status];
}
return nil;
}
- (NSData *)compressBytes:(Bytef *)bytes length:(NSUInteger)length error:(NSError **)err shouldFinish:(BOOL)shouldFinish
{
if (length == 0) return nil;
NSUInteger halfLength = length/2;
// We'll take a guess that the compressed data will fit in half the size of the original (ie the max to compress at once is half DATA_CHUNK_SIZE), if not, we'll increase it below
NSMutableData *outputData = [NSMutableData dataWithLength:length/2];
int status;
zStream.next_in = bytes;
zStream.avail_in = (unsigned int)length;
zStream.avail_out = 0;
NSInteger bytesProcessedAlready = zStream.total_out;
while (zStream.avail_out == 0) {
if (zStream.total_out-bytesProcessedAlready >= [outputData length]) {
[outputData increaseLengthBy:halfLength];
}
zStream.next_out = (Bytef*)[outputData mutableBytes] + zStream.total_out-bytesProcessedAlready;
zStream.avail_out = (unsigned int)([outputData length] - (zStream.total_out-bytesProcessedAlready));
status = deflate(&zStream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
if (status == Z_STREAM_END) {
break;
} else if (status != Z_OK) {
if (err) {
*err = [[self class] deflateErrorWithCode:status];
}
return NO;
}
}
// Set real length
[outputData setLength: zStream.total_out-bytesProcessedAlready];
return outputData;
}
+ (NSData *)compressData:(NSData*)uncompressedData error:(NSError **)err
{
NSError *theError = nil;
NSData *outputData = [[ASIDataCompressor compressor] compressBytes:(Bytef *)[uncompressedData bytes] length:[uncompressedData length] error:&theError shouldFinish:YES];
if (theError) {
if (err) {
*err = theError;
}
return nil;
}
return outputData;
}
+ (BOOL)compressDataFromFile:(NSString *)sourcePath toFile:(NSString *)destinationPath error:(NSError **)err
{
NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
// Create an empty file at the destination path
if (![fileManager createFileAtPath:destinationPath contents:[NSData data] attributes:nil]) {
if (err) {
*err = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Compression of %@ failed because we were to create a file at %@",sourcePath,destinationPath],NSLocalizedDescriptionKey,nil]];
}
return NO;
}
// Ensure the source file exists
if (![fileManager fileExistsAtPath:sourcePath]) {
if (err) {
*err = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Compression of %@ failed the file does not exist",sourcePath],NSLocalizedDescriptionKey,nil]];
}
return NO;
}
UInt8 inputData[DATA_CHUNK_SIZE];
NSData *outputData;
NSInteger readLength;
NSError *theError = nil;
ASIDataCompressor *compressor = [ASIDataCompressor compressor];
NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath:sourcePath];
[inputStream open];
NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:destinationPath append:NO];
[outputStream open];
while ([compressor streamReady]) {
// Read some data from the file
readLength = [inputStream read:inputData maxLength:DATA_CHUNK_SIZE];
// Make sure nothing went wrong
if ([inputStream streamStatus] == NSStreamEventErrorOccurred) {
if (err) {
*err = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Compression of %@ failed because we were unable to read from the source data file",sourcePath],NSLocalizedDescriptionKey,[inputStream streamError],NSUnderlyingErrorKey,nil]];
}
[compressor closeStream];
return NO;
}
// Have we reached the end of the input data?
if (!readLength) {
break;
}
// Attempt to deflate the chunk of data
outputData = [compressor compressBytes:inputData length:readLength error:&theError shouldFinish:readLength < DATA_CHUNK_SIZE ];
if (theError) {
if (err) {
*err = theError;
}
[compressor closeStream];
return NO;
}
// Write the deflated data out to the destination file
[outputStream write:(const uint8_t *)[outputData bytes] maxLength:[outputData length]];
// Make sure nothing went wrong
if ([inputStream streamStatus] == NSStreamEventErrorOccurred) {
if (err) {
*err = [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Compression of %@ failed because we were unable to write to the destination data file at %@",sourcePath,destinationPath],NSLocalizedDescriptionKey,[outputStream streamError],NSUnderlyingErrorKey,nil]];
}
[compressor closeStream];
return NO;
}
}
[inputStream close];
[outputStream close];
NSError *error = [compressor closeStream];
if (error) {
if (err) {
*err = error;
}
return NO;
}
return YES;
}
+ (NSError *)deflateErrorWithCode:(int)code
{
return [NSError errorWithDomain:NetworkRequestErrorDomain code:ASICompressionError userInfo:[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Compression of data failed with code %hi",code],NSLocalizedDescriptionKey,nil]];
}
@synthesize streamReady;
@end
| 009-20120511-zi | trunk/Zinipad/ASI/ASIDataCompressor.m | Objective-C | gpl3 | 6,755 |
//
// ASIFormDataRequest.h
// Part of ASIHTTPRequest -> http://allseeing-i.com/ASIHTTPRequest
//
// Created by Ben Copsey on 07/11/2008.
// Copyright 2008-2009 All-Seeing Interactive. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "ASIHTTPRequest.h"
#import "ASIHTTPRequestConfig.h"
typedef enum _ASIPostFormat {
ASIMultipartFormDataPostFormat = 0,
ASIURLEncodedPostFormat = 1
} ASIPostFormat;
@interface ASIFormDataRequest : ASIHTTPRequest <NSCopying> {
// Parameters that will be POSTed to the url
NSMutableArray *postData;
// Files that will be POSTed to the url
NSMutableArray *fileData;
ASIPostFormat postFormat;
NSStringEncoding stringEncoding;
#if DEBUG_FORM_DATA_REQUEST
// Will store a string version of the request body that will be printed to the console when ASIHTTPREQUEST_DEBUG is set in GCC_PREPROCESSOR_DEFINITIONS
NSString *debugBodyString;
#endif
}
#pragma mark utilities
- (NSString*)encodeURL:(NSString *)string;
#pragma mark setup request
// Add a POST variable to the request
- (void)addPostValue:(id <NSObject>)value forKey:(NSString *)key;
// Set a POST variable for this request, clearing any others with the same key
- (void)setPostValue:(id <NSObject>)value forKey:(NSString *)key;
// Add the contents of a local file to the request
- (void)addFile:(NSString *)filePath forKey:(NSString *)key;
// Same as above, but you can specify the content-type and file name
- (void)addFile:(NSString *)filePath withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key;
// Add the contents of a local file to the request, clearing any others with the same key
- (void)setFile:(NSString *)filePath forKey:(NSString *)key;
// Same as above, but you can specify the content-type and file name
- (void)setFile:(NSString *)filePath withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key;
// Add the contents of an NSData object to the request
- (void)addData:(NSData *)data forKey:(NSString *)key;
// Same as above, but you can specify the content-type and file name
- (void)addData:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key;
// Add the contents of an NSData object to the request, clearing any others with the same key
- (void)setData:(NSData *)data forKey:(NSString *)key;
// Same as above, but you can specify the content-type and file name
- (void)setData:(id)data withFileName:(NSString *)fileName andContentType:(NSString *)contentType forKey:(NSString *)key;
@property (assign) ASIPostFormat postFormat;
@property (assign) NSStringEncoding stringEncoding;
@end
| 009-20120511-zi | trunk/Zinipad/ASI/ASIFormDataRequest.h | Objective-C | gpl3 | 2,693 |
//
// RootViewController.h
// ViewAnimationTest
//
// Created by 성주 이 on 5/17/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "TreeView.h"
#import "LeftTreeView.h"
#import "SampleBookViewWallpaper.h"
#import "SampleBookViewFlooring.h"
@interface ZinMainViewController : UIViewController<TreeViewSelectDelegate,LeftTreeViewSelectDelegate>
{
BOOL _isExpanded;
UIView* _leftMenuBar;
UIView* _mainStage;
UIView* _rightMenuBar;
int treeSelectIndex;
UIView* CurrentView;
int CurrentViewIndex;
SampleBookViewWallpaper *sampleBookView ;
SampleBookViewFlooring *sampleBookViewFlooring;
UIView* secDepthView;
UIView* secDepthViewWallpaper;
UIImage* rootButtonImg;
UIImage* subButtonLastImg;
UIImage* rootButtonPressedImg;
//left
UIScrollView* leftMenuScroll;
NSMutableArray* leftMenuButtonList;
//right
UIScrollView* rightMenuScroll;
NSMutableArray* rightMenuButtonList;
int nIndexRoot;
int nIndexSub;
int categoryValue;
int nIndexRootWallpaper;
int nIndexSubWallpaper;
int categoryValueWallpaper;
}
@property (nonatomic, retain) UIView* _leftMenuBar;
@property (nonatomic, retain) UIView* _mainStage;
@property (nonatomic, retain) UIView* _rightMenuBar;
@property (nonatomic, retain) UIView* CurrentView;
@property (nonatomic, retain) UIView* secDepthView;
@property (nonatomic, retain) UIView* secDepthViewWallpaper;
@property (nonatomic, retain) UIScrollView* leftMenuScroll;
@property (nonatomic, retain) UIScrollView* rightMenuScroll;
@property (nonatomic, retain) NSMutableArray* leftMenuButtonList;
@property (nonatomic, retain) NSMutableArray* rightMenuButtonList;
@property (nonatomic, retain) UIImage* rootButtonImg;
@property (nonatomic, retain) UIImage* rootButtonPressedImg;
@property (nonatomic, retain) UIImage* subButtonLastImg;
-(void)buttonPressed:(id)sender;
-(void)SearchButtonPressed:(id)sender;
-(void)mainStageView;
//Top버튼
-(void)zinButtonPressed:(id)sender;
-(void)MatchingButtonPressed:(id)sender;
-(void)CalButtonPressed:(id)sender;
-(void)SetButtonPressed:(id)sender;
-(void)HelpButtonPressed:(id)sender;
@end
| 009-20120511-zi | trunk/Zinipad/ZinMainViewController.h | Objective-C | gpl3 | 2,235 |
//
// MatchingViewController.h
// Zinipad
//
// Created by ZeLkOvA on 12. 6. 25..
// Copyright (c) 2012년 __MyCompanyName__. All rights reserved.
//
#import <UIKit/UIKit.h>
#import <OpenGLES/EAGLDrawable.h>
#import <OpenGLES/EAGL.h>
#import <OpenGLES/ES1/gl.h>
#import <OpenGLES/ES1/glext.h>
#import <QuartzCore/QuartzCore.h>
@interface MatchingViewController : UIViewController
{
}
- (CATransform3D)transformForItemView:(UIView *)view ;
@end
| 009-20120511-zi | trunk/Zinipad/MatchingViewController.h | Objective-C | gpl3 | 452 |
<!DOCTYPE html>
<html lang="en">
<head>
<?php $this->load->view('admin/meta'); ?>
</head>
<body>
<?php $this->load->view('admin/nav'); ?>
<div class="container">
<h1>Bootstrap starter template</h1>
<p>Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
<table class="table table-bordered">
<thead>
<tr>
<th>S.No.</th>
<th>Name</th>
<th>Address</th>
<th>Phone</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>S.Nasdado.</td>
<td>Nameasdad</td>
<td>Addressasdads</td>
<td>Phoneasda sd</td>
<td>Action asd asd</td>
</tr>
</tbody>
</table>
</div> <!-- /container -->
<?php $this->load->view('admin/nav'); ?>
</body>
</html>
| 069h-course-management | trunk/ci/search.php | PHP | mit | 1,081 |
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html> | 069h-course-management | trunk/ci/application/config/index.html | HTML | mit | 114 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| DATABASE CONNECTIVITY SETTINGS
| -------------------------------------------------------------------
| This file will contain the settings needed to access your database.
|
| For complete instructions please consult the 'Database Connection'
| page of the User Guide.
|
| -------------------------------------------------------------------
| EXPLANATION OF VARIABLES
| -------------------------------------------------------------------
|
| ['hostname'] The hostname of your database server.
| ['username'] The username used to connect to the database
| ['password'] The password used to connect to the database
| ['database'] The name of the database you want to connect to
| ['dbdriver'] The database type. ie: mysql. Currently supported:
mysql, mysqli, postgre, odbc, mssql, sqlite, oci8
| ['dbprefix'] You can add an optional prefix, which will be added
| to the table name when using the Active Record class
| ['pconnect'] TRUE/FALSE - Whether to use a persistent connection
| ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.
| ['cache_on'] TRUE/FALSE - Enables/disables query caching
| ['cachedir'] The path to the folder where cache files should be stored
| ['char_set'] The character set used in communicating with the database
| ['dbcollat'] The character collation used in communicating with the database
| NOTE: For MySQL and MySQLi databases, this setting is only used
| as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7
| (and in table creation queries made with DB Forge).
| There is an incompatibility in PHP with mysql_real_escape_string() which
| can make your site vulnerable to SQL injection if you are using a
| multi-byte character set and are running versions lower than these.
| Sites using Latin-1 or UTF-8 database character set and collation are unaffected.
| ['swap_pre'] A default table prefix that should be swapped with the dbprefix
| ['autoinit'] Whether or not to automatically initialize the database.
| ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections
| - good for ensuring strict SQL while developing
|
| The $active_group variable lets you choose which connection group to
| make active. By default there is only one group (the 'default' group).
|
| The $active_record variables lets you determine whether or not to load
| the active record class
*/
$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'onlineexam';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;
/* End of file database.php */
/* Location: ./application/config/database.php */ | 069h-course-management | trunk/ci/application/config/database.php | PHP | mit | 3,225 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
| example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
| http://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There area two reserved routes:
|
| $route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
| $route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router what URI segments to use if those provided
| in the URL cannot be matched to a valid route.
|
*/
$route['default_controller'] = "admin/home";
$route['404_override'] = '';
/* End of file routes.php */
/* Location: ./application/config/routes.php */ | 069h-course-management | trunk/ci/application/config/routes.php | PHP | mit | 1,546 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| File and Directory Modes
|--------------------------------------------------------------------------
|
| These prefs are used when checking and setting modes when working
| with the file system. The defaults are fine on servers with proper
| security, but you may wish (or even need) to change the values in
| certain environments (Apache running a separate process for each
| user, PHP under CGI with Apache suEXEC, etc.). Octal values should
| always be used to set the mode correctly.
|
*/
define('FILE_READ_MODE', 0644);
define('FILE_WRITE_MODE', 0666);
define('DIR_READ_MODE', 0755);
define('DIR_WRITE_MODE', 0777);
/*
|--------------------------------------------------------------------------
| File Stream Modes
|--------------------------------------------------------------------------
|
| These modes are used when working with fopen()/popen()
|
*/
define('FOPEN_READ', 'rb');
define('FOPEN_READ_WRITE', 'r+b');
define('FOPEN_WRITE_CREATE_DESTRUCTIVE', 'wb'); // truncates existing file data, use with care
define('FOPEN_READ_WRITE_CREATE_DESTRUCTIVE', 'w+b'); // truncates existing file data, use with care
define('FOPEN_WRITE_CREATE', 'ab');
define('FOPEN_READ_WRITE_CREATE', 'a+b');
define('FOPEN_WRITE_CREATE_STRICT', 'xb');
define('FOPEN_READ_WRITE_CREATE_STRICT', 'x+b');
/* End of file constants.php */
/* Location: ./application/config/constants.php */ | 069h-course-management | trunk/ci/application/config/constants.php | PHP | mit | 1,558 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| If this is not set then CodeIgniter will guess the protocol, domain and
| path to your installation.
|
*/
$config['base_url'] = '';
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = 'index.php';
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string. The default setting of 'AUTO' works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'AUTO' Default - auto detects
| 'PATH_INFO' Uses the PATH_INFO
| 'QUERY_STRING' Uses the QUERY_STRING
| 'REQUEST_URI' Uses the REQUEST_URI
| 'ORIG_PATH_INFO' Uses the ORIG_PATH_INFO
|
*/
$config['uri_protocol'] = 'AUTO';
/*
|--------------------------------------------------------------------------
| URL suffix
|--------------------------------------------------------------------------
|
| This option allows you to add a suffix to all URLs generated by CodeIgniter.
| For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/urls.html
*/
$config['url_suffix'] = '';
/*
|--------------------------------------------------------------------------
| Default Language
|--------------------------------------------------------------------------
|
| This determines which set of language files should be used. Make sure
| there is an available translation if you intend to use something other
| than english.
|
*/
$config['language'] = 'english';
/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
*/
$config['charset'] = 'UTF-8';
/*
|--------------------------------------------------------------------------
| Enable/Disable System Hooks
|--------------------------------------------------------------------------
|
| If you would like to use the 'hooks' feature you must enable it by
| setting this variable to TRUE (boolean). See the user guide for details.
|
*/
$config['enable_hooks'] = FALSE;
/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries. For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/core_classes.html
| http://codeigniter.com/user_guide/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'MY_';
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify with a regular expression which characters are permitted
| within your URLs. When someone tries to submit a URL with disallowed
| characters they will get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible. By default only these are allowed: a-z 0-9~%.:_-
|
| Leave blank to allow all characters -- but only if you are insane.
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
/*
|--------------------------------------------------------------------------
| Enable Query Strings
|--------------------------------------------------------------------------
|
| By default CodeIgniter uses search-engine friendly segment based URLs:
| example.com/who/what/where/
|
| By default CodeIgniter enables access to the $_GET array. If for some
| reason you would like to disable it, set 'allow_get_array' to FALSE.
|
| You can optionally enable standard query string based URLs:
| example.com?who=me&what=something&where=here
|
| Options are: TRUE or FALSE (boolean)
|
| The other items let you set the query string 'words' that will
| invoke your controllers and its functions:
| example.com/index.php?c=controller&m=function
|
| Please note that some of the helpers won't work as expected when
| this feature is enabled, since CodeIgniter is designed primarily to
| use segment based URLs.
|
*/
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd'; // experimental not currently in use
/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| If you have enabled error logging, you can set an error threshold to
| determine what gets logged. Threshold options are:
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disables logging, Error logging TURNED OFF
| 1 = Error Messages (including PHP errors)
| 2 = Debug Messages
| 3 = Informational Messages
| 4 = All Messages
|
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
/*
|--------------------------------------------------------------------------
| Error Logging Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/logs/ folder. Use a full server path with trailing slash.
|
*/
$config['log_path'] = '';
/*
|--------------------------------------------------------------------------
| Date Format for Logs
|--------------------------------------------------------------------------
|
| Each item that is logged has an associated date. You can use PHP date
| codes to set your own date formatting
|
*/
$config['log_date_format'] = 'Y-m-d H:i:s';
/*
|--------------------------------------------------------------------------
| Cache Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| system/cache/ folder. Use a full server path with trailing slash.
|
*/
$config['cache_path'] = '';
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| If you use the Encryption class or the Session class you
| MUST set an encryption key. See the user guide for info.
|
*/
$config['encryption_key'] = 'g%^kjhg67876fghjjbvdf4567';
/*
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|
| 'sess_cookie_name' = the name you want for the cookie
| 'sess_expiration' = the number of SECONDS you want the session to last.
| by default sessions last 7200 seconds (two hours). Set to zero for no expiration.
| 'sess_expire_on_close' = Whether to cause the session to expire automatically
| when the browser window is closed
| 'sess_encrypt_cookie' = Whether to encrypt the cookie
| 'sess_use_database' = Whether to save the session data to a database
| 'sess_table_name' = The name of the session database table
| 'sess_match_ip' = Whether to match the user's IP address when reading the session data
| 'sess_match_useragent' = Whether to match the User Agent when reading the session data
| 'sess_time_to_update' = how many seconds between CI refreshing Session Information
|
*/
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = FALSE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path' = Typically will be a forward slash
| 'cookie_secure' = Cookies will only be set if a secure HTTPS connection exists.
|
*/
$config['cookie_prefix'] = "";
$config['cookie_domain'] = "";
$config['cookie_path'] = "/";
$config['cookie_secure'] = FALSE;
/*
|--------------------------------------------------------------------------
| Global XSS Filtering
|--------------------------------------------------------------------------
|
| Determines whether the XSS filter is always active when GET, POST or
| COOKIE data is encountered
|
*/
$config['global_xss_filtering'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cross Site Request Forgery
|--------------------------------------------------------------------------
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
|
| 'csrf_token_name' = The token name
| 'csrf_cookie_name' = The cookie name
| 'csrf_expire' = The number in seconds the token should expire.
*/
$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
/*
|--------------------------------------------------------------------------
| Output Compression
|--------------------------------------------------------------------------
|
| Enables Gzip output compression for faster page loads. When enabled,
| the output class will test whether your server supports Gzip.
| Even if it does, however, not all browsers support compression
| so enable only if you are reasonably sure your visitors can handle it.
|
| VERY IMPORTANT: If you are getting a blank page when compression is enabled it
| means you are prematurely outputting something to your browser. It could
| even be a line of whitespace at the end of one of your scripts. For
| compression to work, nothing can be sent before the output buffer is called
| by the output class. Do not 'echo' any values with compression enabled.
|
*/
$config['compress_output'] = FALSE;
/*
|--------------------------------------------------------------------------
| Master Time Reference
|--------------------------------------------------------------------------
|
| Options are 'local' or 'gmt'. This pref tells the system whether to use
| your server's local time as the master 'now' reference, or convert it to
| GMT. See the 'date helper' page of the user guide for information
| regarding date handling.
|
*/
$config['time_reference'] = 'local';
/*
|--------------------------------------------------------------------------
| Rewrite PHP Short Tags
|--------------------------------------------------------------------------
|
| If your PHP installation does not have short tag support enabled CI
| can rewrite the tags on-the-fly, enabling you to utilize that syntax
| in your view files. Options are TRUE or FALSE (boolean)
|
*/
$config['rewrite_short_tags'] = FALSE;
/*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy IP
| addresses from which CodeIgniter should trust the HTTP_X_FORWARDED_FOR
| header in order to properly identify the visitor's IP address.
| Comma-delimited, e.g. '10.0.1.200,10.0.1.201'
|
*/
$config['proxy_ips'] = '';
/* End of file config.php */
/* Location: ./application/config/config.php */
| 069h-course-management | trunk/ci/application/config/config.php | PHP | mit | 12,833 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| AUTO-LOADER
| -------------------------------------------------------------------
| This file specifies which systems should be loaded by default.
|
| In order to keep the framework as light-weight as possible only the
| absolute minimal resources are loaded by default. For example,
| the database is not connected to automatically since no assumption
| is made regarding whether you intend to use it. This file lets
| you globally define which systems you would like loaded with every
| request.
|
| -------------------------------------------------------------------
| Instructions
| -------------------------------------------------------------------
|
| These are the things you can load automatically:
|
| 1. Packages
| 2. Libraries
| 3. Helper files
| 4. Custom config files
| 5. Language files
| 6. Models
|
*/
/*
| -------------------------------------------------------------------
| Auto-load Packges
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared');
|
*/
$autoload['packages'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in the system/libraries folder
| or in your application/libraries folder.
|
| Prototype:
|
| $autoload['libraries'] = array('database', 'session', 'xmlrpc');
*/
//$autoload['libraries'] = array();
$autoload['libraries'] = array('database', 'session');
/*
| -------------------------------------------------------------------
| Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['helper'] = array('url', 'file');
*/
$autoload['helper'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Config files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['config'] = array('config1', 'config2');
|
| NOTE: This item is intended for use ONLY if you have created custom
| config files. Otherwise, leave it blank.
|
*/
$autoload['config'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Language files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['language'] = array('lang1', 'lang2');
|
| NOTE: Do not include the "_lang" part of your file. For example
| "codeigniter_lang.php" would be referenced as array('codeigniter');
|
*/
$autoload['language'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Models
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['model'] = array('model1', 'model2');
|
*/
$autoload['model'] = array();
/* End of file autoload.php */
/* Location: ./application/config/autoload.php */ | 069h-course-management | trunk/ci/application/config/autoload.php | PHP | mit | 3,145 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| MIME TYPES
| -------------------------------------------------------------------
| This file contains an array of mime types. It is used by the
| Upload class to help identify allowed file types.
|
*/
$mimes = array( 'hqx' => 'application/mac-binhex40',
'cpt' => 'application/mac-compactpro',
'csv' => array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel'),
'bin' => 'application/macbinary',
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'exe' => array('application/octet-stream', 'application/x-msdownload'),
'class' => 'application/octet-stream',
'psd' => 'application/x-photoshop',
'so' => 'application/octet-stream',
'sea' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => array('application/pdf', 'application/x-download'),
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => array('application/excel', 'application/vnd.ms-excel', 'application/msexcel'),
'ppt' => array('application/powerpoint', 'application/vnd.ms-powerpoint'),
'wbxml' => 'application/wbxml',
'wmlc' => 'application/wmlc',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'dvi' => 'application/x-dvi',
'gtar' => 'application/x-gtar',
'gz' => 'application/x-gzip',
'php' => 'application/x-httpd-php',
'php4' => 'application/x-httpd-php',
'php3' => 'application/x-httpd-php',
'phtml' => 'application/x-httpd-php',
'phps' => 'application/x-httpd-php-source',
'js' => 'application/x-javascript',
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'tar' => 'application/x-tar',
'tgz' => array('application/x-tar', 'application/x-gzip-compressed'),
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'zip' => array('application/x-zip', 'application/zip', 'application/x-zip-compressed'),
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp3' => array('audio/mpeg', 'audio/mpg', 'audio/mpeg3', 'audio/mp3'),
'aif' => 'audio/x-aiff',
'aiff' => 'audio/x-aiff',
'aifc' => 'audio/x-aiff',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'ra' => 'audio/x-realaudio',
'rv' => 'video/vnd.rn-realvideo',
'wav' => array('audio/x-wav', 'audio/wave', 'audio/wav'),
'bmp' => array('image/bmp', 'image/x-windows-bmp'),
'gif' => 'image/gif',
'jpeg' => array('image/jpeg', 'image/pjpeg'),
'jpg' => array('image/jpeg', 'image/pjpeg'),
'jpe' => array('image/jpeg', 'image/pjpeg'),
'png' => array('image/png', 'image/x-png'),
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'css' => 'text/css',
'html' => 'text/html',
'htm' => 'text/html',
'shtml' => 'text/html',
'txt' => 'text/plain',
'text' => 'text/plain',
'log' => array('text/plain', 'text/x-log'),
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'xml' => 'text/xml',
'xsl' => 'text/xml',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'avi' => 'video/x-msvideo',
'movie' => 'video/x-sgi-movie',
'doc' => 'application/msword',
'docx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip'),
'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip'),
'word' => array('application/msword', 'application/octet-stream'),
'xl' => 'application/excel',
'eml' => 'message/rfc822',
'json' => array('application/json', 'text/json')
);
/* End of file mimes.php */
/* Location: ./application/config/mimes.php */
| 069h-course-management | trunk/ci/application/config/mimes.php | PHP | mit | 4,453 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| Foreign Characters
| -------------------------------------------------------------------
| This file contains an array of foreign characters for transliteration
| conversion used by the Text helper
|
*/
$foreign_characters = array(
'/ä|æ|ǽ/' => 'ae',
'/ö|œ/' => 'oe',
'/ü/' => 'ue',
'/Ä/' => 'Ae',
'/Ü/' => 'Ue',
'/Ö/' => 'Oe',
'/À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ/' => 'A',
'/à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª/' => 'a',
'/Ç|Ć|Ĉ|Ċ|Č/' => 'C',
'/ç|ć|ĉ|ċ|č/' => 'c',
'/Ð|Ď|Đ/' => 'D',
'/ð|ď|đ/' => 'd',
'/È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě/' => 'E',
'/è|é|ê|ë|ē|ĕ|ė|ę|ě/' => 'e',
'/Ĝ|Ğ|Ġ|Ģ/' => 'G',
'/ĝ|ğ|ġ|ģ/' => 'g',
'/Ĥ|Ħ/' => 'H',
'/ĥ|ħ/' => 'h',
'/Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ/' => 'I',
'/ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı/' => 'i',
'/Ĵ/' => 'J',
'/ĵ/' => 'j',
'/Ķ/' => 'K',
'/ķ/' => 'k',
'/Ĺ|Ļ|Ľ|Ŀ|Ł/' => 'L',
'/ĺ|ļ|ľ|ŀ|ł/' => 'l',
'/Ñ|Ń|Ņ|Ň/' => 'N',
'/ñ|ń|ņ|ň|ʼn/' => 'n',
'/Ò|Ó|Ô|Õ|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ/' => 'O',
'/ò|ó|ô|õ|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º/' => 'o',
'/Ŕ|Ŗ|Ř/' => 'R',
'/ŕ|ŗ|ř/' => 'r',
'/Ś|Ŝ|Ş|Š/' => 'S',
'/ś|ŝ|ş|š|ſ/' => 's',
'/Ţ|Ť|Ŧ/' => 'T',
'/ţ|ť|ŧ/' => 't',
'/Ù|Ú|Û|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ/' => 'U',
'/ù|ú|û|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ/' => 'u',
'/Ý|Ÿ|Ŷ/' => 'Y',
'/ý|ÿ|ŷ/' => 'y',
'/Ŵ/' => 'W',
'/ŵ/' => 'w',
'/Ź|Ż|Ž/' => 'Z',
'/ź|ż|ž/' => 'z',
'/Æ|Ǽ/' => 'AE',
'/ß/'=> 'ss',
'/IJ/' => 'IJ',
'/ij/' => 'ij',
'/Œ/' => 'OE',
'/ƒ/' => 'f'
);
/* End of file foreign_chars.php */
/* Location: ./application/config/foreign_chars.php */ | 069h-course-management | trunk/ci/application/config/foreign_chars.php | PHP | mit | 1,781 |
<?php defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Enable/Disable Migrations
|--------------------------------------------------------------------------
|
| Migrations are disabled by default but should be enabled
| whenever you intend to do a schema migration.
|
*/
$config['migration_enabled'] = FALSE;
/*
|--------------------------------------------------------------------------
| Migrations version
|--------------------------------------------------------------------------
|
| This is used to set migration version that the file system should be on.
| If you run $this->migration->latest() this is the version that schema will
| be upgraded / downgraded to.
|
*/
$config['migration_version'] = 0;
/*
|--------------------------------------------------------------------------
| Migrations Path
|--------------------------------------------------------------------------
|
| Path to your migrations folder.
| Typically, it will be within your application path.
| Also, writing permission is required within the migrations path.
|
*/
$config['migration_path'] = APPPATH . 'migrations/';
/* End of file migration.php */
/* Location: ./application/config/migration.php */ | 069h-course-management | trunk/ci/application/config/migration.php | PHP | mit | 1,322 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| USER AGENT TYPES
| -------------------------------------------------------------------
| This file contains four arrays of user agent data. It is used by the
| User Agent Class to help identify browser, platform, robot, and
| mobile device data. The array keys are used to identify the device
| and the array values are used to set the actual name of the item.
|
*/
$platforms = array (
'windows nt 6.0' => 'Windows Longhorn',
'windows nt 5.2' => 'Windows 2003',
'windows nt 5.0' => 'Windows 2000',
'windows nt 5.1' => 'Windows XP',
'windows nt 4.0' => 'Windows NT 4.0',
'winnt4.0' => 'Windows NT 4.0',
'winnt 4.0' => 'Windows NT',
'winnt' => 'Windows NT',
'windows 98' => 'Windows 98',
'win98' => 'Windows 98',
'windows 95' => 'Windows 95',
'win95' => 'Windows 95',
'windows' => 'Unknown Windows OS',
'os x' => 'Mac OS X',
'ppc mac' => 'Power PC Mac',
'freebsd' => 'FreeBSD',
'ppc' => 'Macintosh',
'linux' => 'Linux',
'debian' => 'Debian',
'sunos' => 'Sun Solaris',
'beos' => 'BeOS',
'apachebench' => 'ApacheBench',
'aix' => 'AIX',
'irix' => 'Irix',
'osf' => 'DEC OSF',
'hp-ux' => 'HP-UX',
'netbsd' => 'NetBSD',
'bsdi' => 'BSDi',
'openbsd' => 'OpenBSD',
'gnu' => 'GNU/Linux',
'unix' => 'Unknown Unix OS'
);
// The order of this array should NOT be changed. Many browsers return
// multiple browser types so we want to identify the sub-type first.
$browsers = array(
'Flock' => 'Flock',
'Chrome' => 'Chrome',
'Opera' => 'Opera',
'MSIE' => 'Internet Explorer',
'Internet Explorer' => 'Internet Explorer',
'Shiira' => 'Shiira',
'Firefox' => 'Firefox',
'Chimera' => 'Chimera',
'Phoenix' => 'Phoenix',
'Firebird' => 'Firebird',
'Camino' => 'Camino',
'Netscape' => 'Netscape',
'OmniWeb' => 'OmniWeb',
'Safari' => 'Safari',
'Mozilla' => 'Mozilla',
'Konqueror' => 'Konqueror',
'icab' => 'iCab',
'Lynx' => 'Lynx',
'Links' => 'Links',
'hotjava' => 'HotJava',
'amaya' => 'Amaya',
'IBrowse' => 'IBrowse'
);
$mobiles = array(
// legacy array, old values commented out
'mobileexplorer' => 'Mobile Explorer',
// 'openwave' => 'Open Wave',
// 'opera mini' => 'Opera Mini',
// 'operamini' => 'Opera Mini',
// 'elaine' => 'Palm',
'palmsource' => 'Palm',
// 'digital paths' => 'Palm',
// 'avantgo' => 'Avantgo',
// 'xiino' => 'Xiino',
'palmscape' => 'Palmscape',
// 'nokia' => 'Nokia',
// 'ericsson' => 'Ericsson',
// 'blackberry' => 'BlackBerry',
// 'motorola' => 'Motorola'
// Phones and Manufacturers
'motorola' => "Motorola",
'nokia' => "Nokia",
'palm' => "Palm",
'iphone' => "Apple iPhone",
'ipad' => "iPad",
'ipod' => "Apple iPod Touch",
'sony' => "Sony Ericsson",
'ericsson' => "Sony Ericsson",
'blackberry' => "BlackBerry",
'cocoon' => "O2 Cocoon",
'blazer' => "Treo",
'lg' => "LG",
'amoi' => "Amoi",
'xda' => "XDA",
'mda' => "MDA",
'vario' => "Vario",
'htc' => "HTC",
'samsung' => "Samsung",
'sharp' => "Sharp",
'sie-' => "Siemens",
'alcatel' => "Alcatel",
'benq' => "BenQ",
'ipaq' => "HP iPaq",
'mot-' => "Motorola",
'playstation portable' => "PlayStation Portable",
'hiptop' => "Danger Hiptop",
'nec-' => "NEC",
'panasonic' => "Panasonic",
'philips' => "Philips",
'sagem' => "Sagem",
'sanyo' => "Sanyo",
'spv' => "SPV",
'zte' => "ZTE",
'sendo' => "Sendo",
// Operating Systems
'symbian' => "Symbian",
'SymbianOS' => "SymbianOS",
'elaine' => "Palm",
'palm' => "Palm",
'series60' => "Symbian S60",
'windows ce' => "Windows CE",
// Browsers
'obigo' => "Obigo",
'netfront' => "Netfront Browser",
'openwave' => "Openwave Browser",
'mobilexplorer' => "Mobile Explorer",
'operamini' => "Opera Mini",
'opera mini' => "Opera Mini",
// Other
'digital paths' => "Digital Paths",
'avantgo' => "AvantGo",
'xiino' => "Xiino",
'novarra' => "Novarra Transcoder",
'vodafone' => "Vodafone",
'docomo' => "NTT DoCoMo",
'o2' => "O2",
// Fallback
'mobile' => "Generic Mobile",
'wireless' => "Generic Mobile",
'j2me' => "Generic Mobile",
'midp' => "Generic Mobile",
'cldc' => "Generic Mobile",
'up.link' => "Generic Mobile",
'up.browser' => "Generic Mobile",
'smartphone' => "Generic Mobile",
'cellphone' => "Generic Mobile"
);
// There are hundreds of bots but these are the most common.
$robots = array(
'googlebot' => 'Googlebot',
'msnbot' => 'MSNBot',
'slurp' => 'Inktomi Slurp',
'yahoo' => 'Yahoo',
'askjeeves' => 'AskJeeves',
'fastcrawler' => 'FastCrawler',
'infoseek' => 'InfoSeek Robot 1.0',
'lycos' => 'Lycos'
);
/* End of file user_agents.php */
/* Location: ./application/config/user_agents.php */ | 069h-course-management | trunk/ci/application/config/user_agents.php | PHP | mit | 5,589 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| Hooks
| -------------------------------------------------------------------------
| This file lets you define "hooks" to extend CI without hacking the core
| files. Please see the user guide for info:
|
| http://codeigniter.com/user_guide/general/hooks.html
|
*/
/* End of file hooks.php */
/* Location: ./application/config/hooks.php */ | 069h-course-management | trunk/ci/application/config/hooks.php | PHP | mit | 498 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| Profiler Sections
| -------------------------------------------------------------------------
| This file lets you determine whether or not various sections of Profiler
| data are displayed when the Profiler is enabled.
| Please see the user guide for info:
|
| http://codeigniter.com/user_guide/general/profiling.html
|
*/
/* End of file profiler.php */
/* Location: ./application/config/profiler.php */ | 069h-course-management | trunk/ci/application/config/profiler.php | PHP | mit | 564 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$_doctypes = array(
'xhtml11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">',
'xhtml1-strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
'xhtml1-trans' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
'xhtml1-frame' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
'html5' => '<!DOCTYPE html>',
'html4-strict' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">',
'html4-trans' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
'html4-frame' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'
);
/* End of file doctypes.php */
/* Location: ./application/config/doctypes.php */ | 069h-course-management | trunk/ci/application/config/doctypes.php | PHP | mit | 1,138 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| SMILEYS
| -------------------------------------------------------------------
| This file contains an array of smileys for use with the emoticon helper.
| Individual images can be used to replace multiple simileys. For example:
| :-) and :) use the same image replacement.
|
| Please see user guide for more info:
| http://codeigniter.com/user_guide/helpers/smiley_helper.html
|
*/
$smileys = array(
// smiley image name width height alt
':-)' => array('grin.gif', '19', '19', 'grin'),
':lol:' => array('lol.gif', '19', '19', 'LOL'),
':cheese:' => array('cheese.gif', '19', '19', 'cheese'),
':)' => array('smile.gif', '19', '19', 'smile'),
';-)' => array('wink.gif', '19', '19', 'wink'),
';)' => array('wink.gif', '19', '19', 'wink'),
':smirk:' => array('smirk.gif', '19', '19', 'smirk'),
':roll:' => array('rolleyes.gif', '19', '19', 'rolleyes'),
':-S' => array('confused.gif', '19', '19', 'confused'),
':wow:' => array('surprise.gif', '19', '19', 'surprised'),
':bug:' => array('bigsurprise.gif', '19', '19', 'big surprise'),
':-P' => array('tongue_laugh.gif', '19', '19', 'tongue laugh'),
'%-P' => array('tongue_rolleye.gif', '19', '19', 'tongue rolleye'),
';-P' => array('tongue_wink.gif', '19', '19', 'tongue wink'),
':P' => array('raspberry.gif', '19', '19', 'raspberry'),
':blank:' => array('blank.gif', '19', '19', 'blank stare'),
':long:' => array('longface.gif', '19', '19', 'long face'),
':ohh:' => array('ohh.gif', '19', '19', 'ohh'),
':grrr:' => array('grrr.gif', '19', '19', 'grrr'),
':gulp:' => array('gulp.gif', '19', '19', 'gulp'),
'8-/' => array('ohoh.gif', '19', '19', 'oh oh'),
':down:' => array('downer.gif', '19', '19', 'downer'),
':red:' => array('embarrassed.gif', '19', '19', 'red face'),
':sick:' => array('sick.gif', '19', '19', 'sick'),
':shut:' => array('shuteye.gif', '19', '19', 'shut eye'),
':-/' => array('hmm.gif', '19', '19', 'hmmm'),
'>:(' => array('mad.gif', '19', '19', 'mad'),
':mad:' => array('mad.gif', '19', '19', 'mad'),
'>:-(' => array('angry.gif', '19', '19', 'angry'),
':angry:' => array('angry.gif', '19', '19', 'angry'),
':zip:' => array('zip.gif', '19', '19', 'zipper'),
':kiss:' => array('kiss.gif', '19', '19', 'kiss'),
':ahhh:' => array('shock.gif', '19', '19', 'shock'),
':coolsmile:' => array('shade_smile.gif', '19', '19', 'cool smile'),
':coolsmirk:' => array('shade_smirk.gif', '19', '19', 'cool smirk'),
':coolgrin:' => array('shade_grin.gif', '19', '19', 'cool grin'),
':coolhmm:' => array('shade_hmm.gif', '19', '19', 'cool hmm'),
':coolmad:' => array('shade_mad.gif', '19', '19', 'cool mad'),
':coolcheese:' => array('shade_cheese.gif', '19', '19', 'cool cheese'),
':vampire:' => array('vampire.gif', '19', '19', 'vampire'),
':snake:' => array('snake.gif', '19', '19', 'snake'),
':exclaim:' => array('exclaim.gif', '19', '19', 'excaim'),
':question:' => array('question.gif', '19', '19', 'question') // no comma after last item
);
/* End of file smileys.php */
/* Location: ./application/config/smileys.php */ | 069h-course-management | trunk/ci/application/config/smileys.php | PHP | mit | 3,295 |
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<h3>Your file was successfully uploaded!</h3>
<ul>
<?php foreach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>
<p><?php echo anchor('upload', 'Upload Another File!'); ?></p>
</body>
</html> | 069h-course-management | trunk/ci/application/views/upload_success.php | PHP | mit | 335 |
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html> | 069h-course-management | trunk/ci/application/views/index.html | HTML | mit | 114 |
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<input type="file" name="userfile" size="20" />
<br /><br />
<input type="submit" value="upload" />
</form>
</body>
</html> | 069h-course-management | trunk/ci/application/views/upload_form.php | PHP | mit | 281 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello </title>
<style type="text/css">
::selection{ background-color: #E13300; color: white; }
::moz-selection{ background-color: #E13300; color: white; }
::webkit-selection{ background-color: #E13300; color: white; }
body {
background-color: #fff;
margin: 40px;
font: 13px/20px normal Helvetica, Arial, sans-serif;
color: #4F5155;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 19px;
font-weight: normal;
margin: 0 0 14px 0;
padding: 14px 15px 10px 15px;
}
code {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
#body{
margin: 0 15px 0 15px;
}
p.footer{
text-align: right;
font-size: 11px;
border-top: 1px solid #D0D0D0;
line-height: 32px;
padding: 0 10px 0 10px;
margin: 20px 0 0 0;
}
#container{
margin: 10px;
border: 1px solid #D0D0D0;
-webkit-box-shadow: 0 0 8px #D0D0D0;
}
</style>
</head>
<body>
<div id="container">
<h1>Hello World!</h1>
</div>
</body>
</html> | 069h-course-management | trunk/ci/application/views/hello.php | Hack | mit | 1,333 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome </title>
<style type="text/css">
::selection{ background-color: #E13300; color: white; }
::moz-selection{ background-color: #E13300; color: white; }
::webkit-selection{ background-color: #E13300; color: white; }
body {
background-color: #fff;
margin: 40px;
font: 13px/20px normal Helvetica, Arial, sans-serif;
color: #4F5155;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 19px;
font-weight: normal;
margin: 0 0 14px 0;
padding: 14px 15px 10px 15px;
}
code {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
#body{
margin: 0 15px 0 15px;
}
p.footer{
text-align: right;
font-size: 11px;
border-top: 1px solid #D0D0D0;
line-height: 32px;
padding: 0 10px 0 10px;
margin: 20px 0 0 0;
}
#container{
margin: 10px;
border: 1px solid #D0D0D0;
-webkit-box-shadow: 0 0 8px #D0D0D0;
}
</style>
</head>
<body>
<div id="container">
<h1>Welcome!</h1>
<div id="body">
<p>The page you are looking at is being generated dynamically by CodeIgniter.</p>
<p>If you would like to edit this page you'll find it located at:</p>
<code>application/views/welcome_message.php</code>
<p>The corresponding controller for this page is found at:</p>
<code>application/controllers/welcome.php</code>
<p>If you are exploring CodeIgniter for the very first time, you should start by reading the <a href="user_guide/">User Guide</a>.</p>
</div>
<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p>
</div>
</body>
</html> | 069h-course-management | trunk/ci/application/views/welcome_message.php | Hack | mit | 1,904 |
<!DOCTYPE html>
<html lang="en">
<head>
<?php $this->load->view('admin/meta');?>
</head>
<body>
<?php $this->load->view('admin/nav');?>
<div class="container">
<h1>Add Exam for course </h1>
<p>From here you can add exam of Online Examination System.</p>
<br/> <br/>
<form class="form-horizontal" action = "<?php echo site_url('admin/exams/add');?>" method = "POST" enctype="multipart/form-data">
<div class="control-group <?php if(form_error('name')) echo "error";?>">
<label class="control-label" for="name">Exam Name </label>
<div class="controls">
<input type="text" id="name" name="name" value="<?php echo set_value('name');?>">
<span class="help-inline"><?php echo form_error('name'); ?></span>
</div>
</div>
<div class="control-group <?php if(form_error('description')) echo "error";?>">
<label class="control-label" for="description">Exam Description</label>
<div class="controls">
<textarea rows="3" id="description" name="description"><?php echo set_value('description');?></textarea>
<span class="help-inline"><?php echo form_error('description'); ?></span>
</div>
</div>
<div class="control-group <?php if (form_error('full_marks')) echo "error"; ?>">
<label class="control-label" for="full_marks">Full Mark</label>
<div class="controls">
<input type="text" id="full_marks" name="full_marks" value="<?php echo set_value('full_marks'); ?>">
<span class="help-inline"><?php echo form_error('full_marks'); ?></span>
</div>
</div>
<div class="control-group <?php if (form_error('pass_marks')) echo "error"; ?>">
<label class="control-label" for="pass_marks">Pass Mark</label>
<div class="controls">
<input type="text" id="pass_marks" name="pass_marks" value="<?php echo set_value('pass_marks'); ?>">
<span class="help-inline"><?php echo form_error('pass_marks'); ?></span>
</div>
</div>
<div class="control-group <?php if (isset($name_error)) echo "error"; ?>">
<label class="control-label" for="start_time">Start Time</label>
<div class="controls">
<input type="text" id="start_time" name="start_time" value="<?php echo set_value('start_time'); ?>">
<span class="help-inline"><?php echo form_error('start_time'); ?></span>
</div>
</div>
<div class="control-group <?php if (form_error('end_time')) echo "error"; ?>">
<label class="control-label" for="end_time">End Time</label>
<div class="controls">
<input type="text" id="end_time" name="end_time" value="<?php echo set_value('end_time'); ?>">
<span class="help-inline"><?php echo form_error('end_time'); ?></span>
</div>
</div>
<div class="control-group <?php if (form_error('date')) echo "error"; ?>">
<label class="control-label" for="date">Exam Date</label>
<div class="controls">
<input type="text" id="date" name="date" value="<?php echo set_value('date'); ?>">
<span class="help-inline"><?php echo form_error('date'); ?></span>
</div>
</div>
<div class="control-group <?php if (form_error('course_id')) echo "error"; ?>">
<label class="control-label" for="course_id">Course Name</label>
<div class="controls">
<?php echo form_dropdown('course_id', array('-- Select Course -- ') + $course_select, '40');?>
<span class="help-inline"><?php echo form_error('course_id'); ?></span>
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn btn-success" name="submit" value="Add Exam">
<button class="btn btn-success" onclick="exam.php" >Cancel</button>
</div>
</div>
</form>
</div> <!-- /container -->
<?php $this->load->view('admin/footer');?>
</body>
</html>
| 069h-course-management | trunk/ci/application/views/admin/add_exam.php | PHP | mit | 3,872 |
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<h3>Your file was successfully uploaded!</h3>
<ul>
<?php foreach ($upload_data as $item => $value):?>
<li><?php echo $item;?>: <?php echo $value;?></li>
<?php endforeach; ?>
</ul>
<p><?php echo anchor('upload', 'Upload Another File!'); ?></p>
</body>
</html> | 069h-course-management | trunk/ci/application/views/admin/upload_success.php | PHP | mit | 335 |
<!DOCTYPE html>
<html lang="en">
<head>
<?php $this->load->view('admin/meta'); ?>
</head>
<body>
<?php $this->load->view('admin/nav'); ?>
<div class="container">
<h1>Bootstrap starter template</h1>
<p>Use this document as a way to quick start any new project.<br> All you get is this message and a barebones HTML document.</p>
<table class="table table-bordered">
<thead>
<tr>
<th>S.No.</th>
<th>Name</th>
<th>Address</th>
<th>Phone</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>S.Nasdado.</td>
<td>Nameasdad</td>
<td>Addressasdads</td>
<td>Phoneasda sd</td>
<td>Action asd asd</td>
</tr>
</tbody>
</table>
</div> <!-- /container -->
<?php $this->load->view('admin/nav'); ?>
</body>
</html>
| 069h-course-management | trunk/ci/application/views/admin/base.php | PHP | mit | 1,031 |
<!DOCTYPE html>
<html lang="en">
<head>
<?php $this->load->view('admin/meta'); ?>
</head>
<body>
<?php $this->load->view('admin/nav'); ?>
<div class="container">
<h1>Add New Course</h1>
<p>From here you can add courses of Online Examination System.</p>
</br></br>
<form class="form-horizontal" action="" method="POST">
<div class="control-group">
<label class="control-label" for="name">Course Name</label>
<div class="controls">
<input type="text" id="name" name="name" value="<?php echo set_value('name'); ?>">
<span class="help-inline"><?php echo form_error('name'); ?></span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="description">Course Description</label>
<div class="controls">
<textarea class="ckeditor" rows="10" id="description" name="description" ><?php echo set_value('description'); ?></textarea>
<span class="help-inline"><?php echo form_error('description'); ?></span>
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn btn-success" name="submit" value="Add Course">
</div>
</div>
</form>
</div> <!-- /container -->
<?php $this->load->view('admin/footer'); ?>
</body>
</html>
| 069h-course-management | trunk/ci/application/views/admin/create_course.php | PHP | mit | 1,355 |
<!DOCTYPE html>
<html lang="en">
<head>
<?php $this->load->view('admin/meta'); ?>
</head>
<body>
<?php $this->load->view('admin/nav'); ?>
<div class="container">
<h1>Provided Feedback</h1>
<p>Manage the feedbacks</p>
<br/>
<h3 class="pull-left">Recent Feedacks</h3>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Course Name</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td> Java </td>
<td>jdhfjaksdfhjaskdf</td>
<td><a href="#">View Exams</a> | <a href="#">Edit</a> | <a onclick="return confirm('Are you sure you want to delete?')" href="#">Delete</a></td>
</tr>
<tr>
<td>2</td>
<td> PHP </td>
<td>hehehheheheheh</td>
<td><a href="#">View Exams</a> | <a href="#">Edit</a> | <a onclick="return confirm('Are you sure you want to delete?')" href="#">Delete</a></td>
</tr>
</tbody>
</table>
</div> <!-- /container -->
<?php $this->load->view('admin/nav'); ?>
</body>
</html>
| 069h-course-management | trunk/ci/application/views/admin/feedback.php | PHP | mit | 1,397 |
<!DOCTYPE html>
<html lang="en">
<head>
<?php $this->load->view('admin/meta'); ?>
</head>
<body>
<?php $this->load->view('admin/nav'); ?>
<div class="container">
<h1>Edit User</h1>
<p>From here you can Edit user of Online Examination System.</p>
<br /> <br />
<form class="form-horizontal"
action="<?php echo site_url('admin/users/edit/'.$user['users.id']);?>"
method="POST" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label" for="username">Username</label>
<div class="controls">
<input type="text" id="username" name="username"
value="<?php echo $user['username'];?>"> <span class="help-inline"><?php echo form_error('username'); ?>
</span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" id="password" name="password"
value="<?php echo $user['password'];?>">
</div>
<span class="help-inline"><?php echo form_error('password'); ?> </span>
</div>
<div class="control-group">
<label class="control-label" for="email">Email</label>
<div class="controls">
<input type="email" id="email" name="email"
value="<?php echo $user['email'];?>"> <span class="help-inline"><?php echo form_error('email'); ?>
</span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="usertype">User Type</label>
<div class="controls">
<select name="usertype" value="<?php echo $user['user_type'];?>">
<option value="1">Admin</option>
<option value="2">Teacher</option>
<option value="3" selected="selected">Student</option>
<select>
<?php echo form_dropdown('usertype', array('-- Select usertype -- ') + $usertype_select);?>
<span class="help-inline"><?php echo form_error('usertype'); ?> </span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="firstname">First Name</label>
<div class="controls">
<input type="text" id="firstname" name="firstname"
value="<?php echo $user['first_name'];?>"> <span
class="help-inline"><?php echo form_error('firstname'); ?> </span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="midname">Middle Name</label>
<div class="controls">
<input type="text" id="midname" name="midname"
value="<?php echo $user['mid_name'];?>">
</div>
</div>
<div class="control-group ">
<label class="control-label" for="lastname">Last Name</label>
<div class="controls">
<input type="text" id="lastname" name="lastname"
value="<?php echo $user['last_name'];?>"> <span
class="help-inline"><?php echo form_error('lastname'); ?> </span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="phone">Phone</label>
<div class="controls">
<input type="text" id="phone" name="phone"
value="<?php echo $user['phone'];?>"> <span class="help-inline"><?php echo form_error('phone'); ?>
</span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="address">Address</label>
<div class="controls">
<input type="text" id="address" name="address"
value="<?php echo $user['address'];?>"> <span class="help-inline"><?php echo form_error('address'); ?>
</span>
</div>
</div>
<div class="control-group">
<label class="control-label" for="website">Website</label>
<div class="controls">
<input type="text" id="website" name="website"
value="<?php echo $user['website'];?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="picture">Profile Picture</label>
<div class="controls">
<input type="file" id="picture" name="picture"
value="<?php echo $user['picture'];?>">
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn btn-success" name="submit"
value="Add User">
</div>
</div>
</form>
<?php $this->load->view('admin/nav'); ?>
</body>
</html>
| 069h-course-management | trunk/ci/application/views/admin/edit_user.php | PHP | mit | 4,327 |
<!DOCTYPE html>
<html lang="en">
<head>
<?php $this->load->view('admin/meta'); ?>
</head>
<body>
<?php $this->load->view('admin/nav'); ?>
<div class="container">
<h1>Manage Exams</h1>
<br />
<h3>
Recent Exams <span style="font-size: 14px;">(<a
href="<?php echo site_url("admin/exams/add"); ?>"> Add Exam </a>)</span>
</h3>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Exam Name</th>
<th>Description</th>
<th>Full Marks</th>
<th>Pass Marks</th>
<th>Start Time</th>
<th>End Time</th>
<th>Exam Date</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($exams as $exam) { ?>
<tr>
<td>1</td>
<td><?php echo $exam['name'];?></td>
<td><?php echo $exam['description']; ?></td>
<td><?php echo $exam['full_marks']; ?></td>
<td><?php echo $exam['pass_marks']; ?></td>
<td><?php echo $exam['start_time']; ?></td>
<td><?php echo $exam['end_time']; ?></td>
<td><?php echo $exam['date']; ?></td>
<td><a href="#">Details</a> | <a
href="<?php echo site_url("admin/exams/edit".$exam['id']);?>">Edit</a>
| <a
href="<?php echo site_url("admin/exams/delete/".$exam['id']); ?>">Delete</a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<!-- /container -->
<?php $this->load->view('admin/nav'); ?>
</body>
</html>
| 069h-course-management | trunk/ci/application/views/admin/exams.php | PHP | mit | 1,405 |
<meta charset="utf-8">
<title><?php echo $page_title ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">
<!-- Le styles -->
<link href="<?php echo base_url(); ?>assets/css/bootstrap.css" rel="stylesheet">
<style>
body {
padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */
}
</style>
<link href="<?php echo base_url(); ?>assets/css/bootstrap-responsive.css" rel="stylesheet">
<!-- HTML5 shim, for IE6-8 support of HTML5 elements -->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- Fav and touch icons -->
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png">
<link rel="apple-touch-icon-precomposed" href="assets/ico/apple-touch-icon-57-precomposed.png">
<link rel="shortcut icon" href="assets/ico/favicon.png"> | 069h-course-management | trunk/ci/application/views/admin/meta.php | PHP | mit | 1,372 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php $this->load->view('admin/meta'); ?>
</head>
<body>
<?php $this->load->view('admin/nav'); ?>
<div class="container">
<h1>Manage Courses</h1>
<p>From here you can manage Courses of Online Examination System.</p>
<br/>
<h3 class="pull-left">Recent Courses <span style="font-size:14px;">(<a href="<?php echo site_url("admin/courses/create/"); ?>"> Add Courses </a>)</span></h3>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Course Name</th>
<th>Description</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
$count = 0;
foreach ($courses as $course) {
$count++;
?>
<tr>
<td><?php echo $count; ?></td>
<td><?php echo $course->name; ?></td>
<td><?php echo $course->description; ?></td>
<td><a href="#">View Exams</a> | <a href="<?php echo site_url("admin/courses/update/".$course->id); ?>"> <?php echo $course->id;?>Edit</a> | <a href="<?php echo site_url("admin/courses/delete/".$course->id); ?>">Delete</a></td>
</tr>
<?php } ?>
</tbody>
</table>
</div> <!-- /container -->
<?php $this->load->view('admin/nav'); ?>
</body>
</html>
| 069h-course-management | trunk/ci/application/views/admin/courses.php | PHP | mit | 1,608 |
<!DOCTYPE html>
<html lang="en">
<head>
<?php $this->load->view('admin/meta');?>
</head>
<body>
<?php $this->load->view('admin/nav'); ?>
<div class="container">
<h1>Add New Course</h1>
<p>From here you can add courses of Online Examination System.</p>
</br> </br>
<form class="form-horizontal"
action="<?php echo site_url('admin/courses/update/'.$course['id']);?>"
method="POST">
<input type="hidden" id="courseid" name="courseid" placeholder=""
value="<?php echo $course['id']; ?>">
<div
class="control-group <?php if(isset($coursename_error)) echo "error";?>">
<label class="control-label" for="name">Course Name</label>
<div class="controls">
<input type="text" id="name" name="name" placeholder=""
value="<?php echo isset($coursename) ? $coursename : $course['name']; ?>">
<span class="help-inline"><?php echo form_error('name'); ?> </span>
</div>
</div>
<div
class="control-group <?php if(isset($description_error)) echo "error"?>">
<label class="control-label" for="description">Course Description</label>
<div class="controls">
<textarea rows="3" id="description" name="description">
<?php if(isset($description)) echo $description; else echo $course['description']; ?>
</textarea>
<span class="help-inline"><?php echo form_error('description'); ?>
</span>
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn btn-success" name="submit"
value="Update Course">
</div>
</div>
</form>
</div>
<!-- /container -->
<?php $this->load->view('admin/footer'); ?>
</body>
</html>
| 069h-course-management | trunk/ci/application/views/admin/edit_course.php | PHP | mit | 1,721 |
<!DOCTYPE html>
<html lang="en">
<head>
<?php $this->load->view('admin/meta'); ?>
</head>
<body>
<?php $this->load->view('admin/nav'); ?>
<div class="container">
<h1>Manage Questions</h1>
<p>From here you can manage Questions of Online Examination System.</p>
<br/>
<h3 class="pull-left">Recent Questions <span style="font-size:14px;">(<a href="<?php echo site_url("admin/questions/create/"); ?>"> Add Questions </a> | <a href=""> Questions Types</a>)</span></h3>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Question</th>
<th>Exam Name</th>
<th>Question Type</th>
<th>Marks</th>
<th>Remark</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
$count = 0;
foreach ($questions as $question){
$count++;
?>
<tr>
<td><?php echo $count;?></td>
<td><?php echo $question['question'];?></td>
<td><?php echo
$qid = $question['exam_id'];
// echo form_dropdown('course_id', array('-- Select Course -- ') + $course_select, '40');
?></td>
<td><?php echo $question['questiontype_id'];?></td>
<td><?php echo $question['marks'];?></td>
<td><?php echo $question['remark'];?></td>
<td><a href="#">Details</a> | <a href="">Edit</a> | <a onclick="return confirm('Are you sure you want to delete?')" href="<?php echo site_url("admin/questions/delete/".$question['id']);?>" >Delete</a></td>
</tr>
<?php } ?>
</tbody>
</table>
</div> <!-- /container -->
<?php $this->load->view('admin/nav'); ?>
</body>
</html>
| 069h-course-management | trunk/ci/application/views/admin/questions.php | PHP | mit | 2,001 |
<!-- Le javascript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="<?php echo base_url(); ?>assets/js/jquery.js"></script>
<script src="<?php echo base_url(); ?>assets/js/bootstrap-transition.js"></script>
<script src="<?php echo base_url(); ?>assets/js/bootstrap-alert.js"></script>
<script src="<?php echo base_url(); ?>assets/js/bootstrap-modal.js"></script>
<script src="<?php echo base_url(); ?>assets/js/bootstrap-dropdown.js"></script>
<script src="<?php echo base_url(); ?>assets/js/bootstrap-scrollspy.js"></script>
<script src="<?php echo base_url(); ?>assets/js/bootstrap-tab.js"></script>
<script src="<?php echo base_url(); ?>assets/js/bootstrap-tooltip.js"></script>
<script src="<?php echo base_url(); ?>assets/js/bootstrap-popover.js"></script>
<script src="<?php echo base_url(); ?>assets/js/bootstrap-button.js"></script>
<script src="<?php echo base_url(); ?>assets/js/bootstrap-collapse.js"></script>
<script src="<?php echo base_url(); ?>assets/js/bootstrap-carousel.js"></script>
<script src="<?php echo base_url(); ?>assets/js/bootstrap-typeahead.js"></script> | 069h-course-management | trunk/ci/application/views/admin/footer.php | PHP | mit | 1,246 |
<!DOCTYPE html>
<html lang="en">
<head>
<?php $this->load->view('admin/meta');?>
</head>
<body>
<?php $this->load->view('admin/nav');?>
<div class="container">
<h1>Edit Exam </h1>
<p>From here you can Edit exam of Online Examination System.</p>
<br/> <br/>
<form class="form-horizontal" action = "<?php echo site_url('admin/exams/add');?>" method = "POST" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label" for="name">Exam Name </label>
<div class="controls">
<input type="text" id="name" name="name" value="<?php echo set_value('name');?>">
<span class="help-inline"><?php echo form_error('name'); ?></span>
</div>
</div>
<div class="control-group ">
<label class="control-label" for="description">Exam Description</label>
<div class="controls">
<textarea rows="3" id="description" name="description"><?php echo set_value('description');?></textarea>
<span class="help-inline"><?php echo form_error('description'); ?></span>
</div>
</div>
<div class="control-group <?php if (isset($name_error)) echo "error"; ?>">
<label class="control-label" for="full_marks">Full Mark</label>
<div class="controls">
<input type="text" id="full_marks" name="full_marks" value="<?php echo set_value('full_marks'); ?>">
<span class="help-inline"><?php echo form_error('full_marks'); ?></span>
</div>
</div>
<div class="control-group <?php if (isset($name_error)) echo "error"; ?>">
<label class="control-label" for="pass_marks">Pass Mark</label>
<div class="controls">
<input type="text" id="pass_marks" name="pass_marks" value="<?php echo set_value('pass_marks'); ?>">
<span class="help-inline"><?php echo form_error('pass_marks'); ?></span>
</div>
</div>
<div class="control-group <?php if (isset($name_error)) echo "error"; ?>">
<label class="control-label" for="start_time">Start Time</label>
<div class="controls">
<input type="text" id="start_time" name="start_time" value="<?php echo set_value('start_time'); ?>">
<span class="help-inline"><?php echo form_error('start_time'); ?></span>
</div>
</div>
<div class="control-group <?php if (isset($name_error)) echo "error"; ?>">
<label class="control-label" for="end_time">End Time</label>
<div class="controls">
<input type="text" id="end_time" name="end_time" value="<?php echo set_value('end_time'); ?>">
<span class="help-inline"><?php echo form_error('end_time'); ?></span>
</div>
</div>
<div class="control-group <?php if (isset($name_error)) echo "error"; ?>">
<label class="control-label" for="date">Exam Date</label>
<div class="controls">
<input type="text" id="date" name="date" value="<?php echo set_value('date'); ?>">
<span class="help-inline"><?php echo form_error('date'); ?></span>
</div>
</div>
<div class="control-group <?php if (isset($name_error)) echo "error"; ?>">
<label class="control-label" for="course_id">Course Name</label>
<div class="controls">
<select id="course_id" name="course_id" value="<?php echo set_value('course_id'); ?>">
<option value="0" selected="selected" >-Select Course-</option><br>
<option value="42">java</option><br>
</select>
<span class="help-inline"><?php echo form_error('course_id'); ?></span>
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn btn-success" name="submit" value="Add Exam">
<button class="btn btn-success" onclick="exam.php" >Cancel</button>
</div>
</div>
</form>
</div> <!-- /container -->
<?php $this->load->view('admin/footer');?>
</body>
</html>
| 069h-course-management | trunk/ci/application/views/admin/edit_exam.php | PHP | mit | 3,844 |
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse"
data-target=".nav-collapse"> <span class="icon-bar"></span> <span
class="icon-bar"></span> <span class="icon-bar"></span> </a> <a
class="brand" href="<?php echo site_url('admin/home'); ?>">Online
Examination System</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="<?php echo ($page == "home") ? "active" : ""; ?>"><a
href="<?php echo site_url('admin/home'); ?>">Home</a></li>
<li class="<?php echo ($page == "users") ? "active" : ""; ?>"><a
href="<?php echo site_url('admin/users'); ?>">Users</a></li>
<li class="<?php echo ($page == "courses") ? "active" : ""; ?>"><a
href="<?php echo site_url('admin/courses'); ?>">Courses</a></li>
<li class="<?php echo ($page == "exams") ? "active" : ""; ?>"><a
href="<?php echo site_url('admin/exams'); ?>">Exams</a></li>
<li class="<?php echo ($page == "questions") ? "active" : ""; ?>"><a
href="<?php echo site_url('admin/questions'); ?>">Questions</a></li>
<li class="<?php echo ($page == "feedback") ? "active" : ""; ?>"><a
href="<?php echo site_url('admin/home/feedback'); ?>">Feedback</a>
</li>
</ul>
<form class="navbar-form pull-left" method="POST"
action="<?php echo site_url('admin/users/search')?>">
<input type="text" class="span2" name="query">
<button type="submit" class="btn">Submit</button>
</form>
</div>
<!--/.nav-collapse -->
</div>
</div>
</div>
| 069h-course-management | trunk/ci/application/views/admin/nav.php | PHP | mit | 1,663 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?php echo $page_title; ?> </title>
<style type="text/css">
::selection{ background-color: #E13300; color: white; }
::moz-selection{ background-color: #E13300; color: white; }
::webkit-selection{ background-color: #E13300; color: white; }
body {
background-color: #fff;
margin: 40px;
font: 13px/20px normal Helvetica, Arial, sans-serif;
color: #4F5155;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 19px;
font-weight: normal;
margin: 0 0 14px 0;
padding: 14px 15px 10px 15px;
}
code {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
#body{
margin: 0 15px 0 15px;
}
p.footer{
text-align: right;
font-size: 11px;
border-top: 1px solid #D0D0D0;
line-height: 32px;
padding: 0 10px 0 10px;
margin: 20px 0 0 0;
}
#container{
margin: 10px;
border: 1px solid #D0D0D0;
-webkit-box-shadow: 0 0 8px #D0D0D0;
}
</style>
</head>
<body>
<div id="container">
<h1>Admin Login!</h1>
<?php echo $page_title; ?>
<?php echo base_url(); ?>
<ul>
<?php foreach ($todo_list as $item):?>
<li><?php echo $item;?></li>
<?php endforeach;?>
</ul>
</div>
</body>
</html> | 069h-course-management | trunk/ci/application/views/admin/login.php | PHP | mit | 1,520 |
<!DOCTYPE html>
<html lang="en">
<head>
<?php $this->load->view('admin/meta'); ?>
</head>
<body>
<?php $this->load->view('admin/nav'); ?>
<div class="container">
</br>
<h1>Welcome to Online Examination System</h1>
<form id='login' action='login.php' method='post'>
<fieldset >
<h2>Login</h2>
<label for='username' >UserName*:</label>
<input type='text' name='username' id='username' />
<label for='password' >Password*:</label>
<input type='password' name='password' id='password'/>
<br/>
<input type='submit' class="btn btn-success" name='Submit' value='Submit' />
</fieldset>
</form>
</div> <!-- /container -->
<?php $this->load->view('admin/nav'); ?>
</body>
</html>
| 069h-course-management | trunk/ci/application/views/admin/home.php | PHP | mit | 756 |
<!DOCTYPE html>
<html lang="en">
<head>
<?php $this->load->view('admin/meta'); ?>
</head>
<body>
<?php $this->load->view('admin/nav'); ?>
<div class="container">
<h1>Manage Users</h1>
<p>From here you can manage users of Online Examination System.</p>
<br/>
<h3 class="pull-left">Recent Users <span style="font-size:14px;">(<a href="<?php echo site_url("admin/users/create/"); ?>"> Add Users </a> | <a href=""> User Types</a>)</span></h3>
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>Picture</th>
<th>Username</th>
<th>Email</th>
<th>Full Name</th>
<th>Phone</th>
<th>User Type</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php foreach ($users as $user) { ?>
<tr>
<td>1</td>
<td><?php if ($user['picture']) {?>
<a id="lightbox" href="<?php echo base_url()."uploads/". $user['picture'];?>" >
<img width="80" height="80" src="<?php echo base_url()."uploads/". $user['picture'];?>" />
</a>
<?php } else { ?>
<img width="80" height="80" src="<?php echo "uploads/default.gif";?>" />
<?php } ?>
</td>
<td><?php echo $user['username']; ?></td>
<td><?php echo $user['email']; ?></td>
<td><?php echo $user['first_name']." ".$user['mid_name']." ".$user['last_name']; ?></td>
<td><?php echo $user['phone']; ?></td>
<td><?php echo $user['user_type_name']; ?></td>
<td><a href="#">Details</a> | <a href="<?php echo site_url("admin/users/edit/".$user['id']);?>">Edit</a> | <a onclick="return confirm('Are you sure you want to delete?')" href="<?php echo site_url("admin/users/delete/".$user['id']); ?>" >Delete</a></td>
</tr>
<?php } ?>
</tbody>
</table>
</div> <!-- /container -->
<?php $this->load->view('admin/nav'); ?>
</body>
</html>
| 069h-course-management | trunk/ci/application/views/admin/users.php | PHP | mit | 2,235 |
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html> | 069h-course-management | trunk/ci/application/errors/index.html | HTML | mit | 114 |
<!DOCTYPE html>
<html lang="en">
<head>
<title>Error</title>
<style type="text/css">
::selection{ background-color: #E13300; color: white; }
::moz-selection{ background-color: #E13300; color: white; }
::webkit-selection{ background-color: #E13300; color: white; }
body {
background-color: #fff;
margin: 40px;
font: 13px/20px normal Helvetica, Arial, sans-serif;
color: #4F5155;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 19px;
font-weight: normal;
margin: 0 0 14px 0;
padding: 14px 15px 10px 15px;
}
code {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
#container {
margin: 10px;
border: 1px solid #D0D0D0;
-webkit-box-shadow: 0 0 8px #D0D0D0;
}
p {
margin: 12px 15px 12px 15px;
}
</style>
</head>
<body>
<div id="container">
<h1><?php echo $heading; ?></h1>
<?php echo $message; ?>
</div>
</body>
</html> | 069h-course-management | trunk/ci/application/errors/error_general.php | PHP | mit | 1,147 |
<div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">
<h4>A PHP Error was encountered</h4>
<p>Severity: <?php echo $severity; ?></p>
<p>Message: <?php echo $message; ?></p>
<p>Filename: <?php echo $filepath; ?></p>
<p>Line Number: <?php echo $line; ?></p>
</div> | 069h-course-management | trunk/ci/application/errors/error_php.php | PHP | mit | 288 |
<!DOCTYPE html>
<html lang="en">
<head>
<title>Database Error</title>
<style type="text/css">
::selection{ background-color: #E13300; color: white; }
::moz-selection{ background-color: #E13300; color: white; }
::webkit-selection{ background-color: #E13300; color: white; }
body {
background-color: #fff;
margin: 40px;
font: 13px/20px normal Helvetica, Arial, sans-serif;
color: #4F5155;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 19px;
font-weight: normal;
margin: 0 0 14px 0;
padding: 14px 15px 10px 15px;
}
code {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
#container {
margin: 10px;
border: 1px solid #D0D0D0;
-webkit-box-shadow: 0 0 8px #D0D0D0;
}
p {
margin: 12px 15px 12px 15px;
}
</style>
</head>
<body>
<div id="container">
<h1><?php echo $heading; ?></h1>
<?php echo $message; ?>
</div>
</body>
</html> | 069h-course-management | trunk/ci/application/errors/error_db.php | PHP | mit | 1,156 |
<!DOCTYPE html>
<html lang="en">
<head>
<title>404 Page Not Found</title>
<style type="text/css">
::selection{ background-color: #E13300; color: white; }
::moz-selection{ background-color: #E13300; color: white; }
::webkit-selection{ background-color: #E13300; color: white; }
body {
background-color: #fff;
margin: 40px;
font: 13px/20px normal Helvetica, Arial, sans-serif;
color: #4F5155;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 19px;
font-weight: normal;
margin: 0 0 14px 0;
padding: 14px 15px 10px 15px;
}
code {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
#container {
margin: 10px;
border: 1px solid #D0D0D0;
-webkit-box-shadow: 0 0 8px #D0D0D0;
}
p {
margin: 12px 15px 12px 15px;
}
</style>
</head>
<body>
<div id="container">
<h1><?php echo $heading; ?></h1>
<?php echo $message; ?>
</div>
</body>
</html> | 069h-course-management | trunk/ci/application/errors/error_404.php | PHP | mit | 1,160 |
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html> | 069h-course-management | trunk/ci/application/index.html | HTML | mit | 114 |
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html> | 069h-course-management | trunk/ci/application/language/english/index.html | HTML | mit | 114 |
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html> | 069h-course-management | trunk/ci/application/helpers/index.html | HTML | mit | 114 |
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html> | 069h-course-management | trunk/ci/application/hooks/index.html | HTML | mit | 114 |
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html> | 069h-course-management | trunk/ci/application/models/index.html | HTML | mit | 114 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Exams_m extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_exams()
{
$query = $this->db->get('exam');
return $query->result_array();
}
function delete_exam($id)
{
$this->db->delete('exam', array('id' => $id));
}
function insert_exam($data){
return $this->db->insert('exam', $data);
}
function get_exambyid($id){
$this->db->where('id',$id);
$query = $this->db->get('exam');
return $query->row_array();
}
} ?> | 069h-course-management | trunk/ci/application/models/Exams_m.php | PHP | mit | 774 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users_m extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_users()
{
$this->db->select('*, user_type.name as user_type_name');
$this->db->from('users');
$this->db->join('user_type','users.user_type = user_type.id');
$query = $this->db->get();
return $query->result_array();
}
function search($q){
$this->db->select('*, user_type.name as user_type_name');
$this->db->from('users');
$this->db->join('user_type','users.user_type = user_type.id');
$this->db->like('username', $q);
$this->db->or_like('first_name', $q);
$query = $this->db->get();
return $query->result_array();
}
function get_user($id)
{
$this->db->select('*, user_type.name as user_type_name');
$this->db->join('user_type','users.user_type = user_type.id');
$this->db->where('users.id',$id);
$query = $this->db->get('users');
return $query->row_array();
}
function insert_user($data)
{
$data['created_at'] = time();
return $this->db->insert('users', $data);
}
function update_user($data, $id)
{
$data['created_at'] = time();
$this->db->where('id',$id);
return $this->db->update('users', $data);
}
function dalete_user($id)
{
return $this->db->delete('users', array('id' => $id));
}
} ?> | 069h-course-management | trunk/ci/application/models/users_m.php | PHP | mit | 1,796 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Questions_m extends CI_Model{
function __construct(){
parent::__construct();
}
function get_questions(){
$query = $this->db->get('questions');
return $query->result_array();
}
function delete_questions($id){
// $query = $this->delete('questions',array('id',$id));
return $this->db->delete('questions', array('id' => $id));
}
}
?>
| 069h-course-management | trunk/ci/application/models/questions_m.php | PHP | mit | 480 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Courses_m extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_courses()
{
$query = $this->db->get('courses');
return $query->result();
}
function get_coursebyid($id)
{
$this->db->where('id',$id);
$query = $this->db->get('courses');
return $query->row_array();
}
function delete_courses($id)
{
$this->db->where('id',$id);
return $this->db->delete('courses');
}
function insert_course($data)
{
return $this->db->insert('courses', $data);
}
function update_course($data, $id)
{
$this->db->where('id',$id);
return $this->db->update('courses', $data);
}
} ?> | 069h-course-management | trunk/ci/application/models/courses_m.php | PHP | mit | 965 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Usertype_m extends CI_Model {
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_usertype()
{
$query = $this->db->get('user_type');
return $query->result();
}
}
?> | 069h-course-management | trunk/ci/application/models/usertype_m.php | PHP | mit | 364 |
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html> | 069h-course-management | trunk/ci/application/logs/index.html | HTML | mit | 114 |
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html> | 069h-course-management | trunk/ci/application/libraries/index.html | HTML | mit | 114 |
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html> | 069h-course-management | trunk/ci/application/core/index.html | HTML | mit | 114 |
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html> | 069h-course-management | trunk/ci/application/controllers/index.html | HTML | mit | 114 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* @see http://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$this->load->view('welcome_message');
}
public function hello()
{
$this->load->view('hello');
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */ | 069h-course-management | trunk/ci/application/controllers/welcome.php | PHP | mit | 831 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Exams extends CI_Controller {
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->helper('url');
$this->load->model('Exams_m');
$this->load->model('Courses_m');
$this->load->library('form_validation');
$validation_rules = array(
array(
'field' => 'name',
'label' => 'Exam name',
'rules' => 'required'
),
array(
'field' => 'description',
'label' => 'Description',
'rules' => 'required'
),
array(
'field' => 'full_marks',
'label' => 'Full Marks',
'rules' => 'required|integer'
),
array(
'field' => 'pass_marks',
'label' => 'Pass Marks',
'rules' => 'required|integer'
),
array(
'field' => 'start_time',
'label' => 'Start Time',
'rules' => 'required|integer'
),
array(
'field' => 'end_time',
'label' => 'End time',
'rules' => 'required|integer'
),
array(
'field' => 'date',
'label' => 'Date',
'rules' => 'required|alpha_numeric'
),
array(
'field' => 'course_id',
'label' => 'Course',
'rules' => 'required'
),
);
$this->form_validation->set_rules($validation_rules);
}
public function index()
{
$data['exams'] = $this->Exams_m->get_exams();
$data['page_title'] = 'exams';
$data['page'] = 'exams';
$this->load->view('admin/exams', $data);
}
public function delete($id){
$this->Exams_m->delete_exam($id);
redirect('admin/exams');
}
public function add(){
$data['page'] = 'exams';
$data['page_title'] = 'Add Exam';
$all_courses = $this->Courses_m->get_courses();
/*echo "<pre>";
print_r($all_courses);
echo "</pre>"; */
$course_select = array();
foreach ($all_courses as $c){
$course_select [$c->id] = $c->name;
}
$data['course_select'] = $course_select;
/*echo "<pre>";
print_r($data['course_select']);
echo "</pre>";*/
if ($this->form_validation->run())
{
//$this->load->view('myform');
$examedata = array (
'name' => $this->input->post('name'),
'description' => $this->input->post('description'),
'full_marks' => $this->input->post('full_marks'),
'pass_marks' => $this->input->post('pass_marks'),
'start_time' => $this->input->post('start_time'),
'end_time' => $this->input->post('end_time'),
'date' => $this->input->post('date'),
'course_id' => $this->input->post('course_id'),
);
if ($this->Exams_m->insert_exam($examedata)){
redirect ('admin/exams');
}
}
$this->load->view('admin/add_exam',$data);
}
public function edit($id){
$data['page'] = 'exams';
$data['page_title'] = 'edit Exam';
$data['exam']= $this->Exams_m->get_exambyid($id);
$this->load->view('admin/edit_exam',$data);
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */ | 069h-course-management | trunk/ci/application/controllers/admin/exams.php | PHP | mit | 3,785 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Courses extends CI_Controller {
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->helper('url');
$this->load->model('Courses_m');
$this->load->library('form_validation');
$validation_rules = array(
array(
'field' => 'name',
'label' => 'Coursename',
'rules' => 'required'
),
array(
'field' => 'description',
'label' => 'Description',
'rules' => 'required'
),
);
$this->form_validation->set_rules($validation_rules);
}
public function index()
{
$data['courses'] = $this->Courses_m->get_courses();
$data['page_title'] = 'Courses';
$data['page'] = 'courses';
$this->load->view('admin/courses', $data);
}
public function delete($id){
$this->Courses_m->delete_courses($id);
redirect('admin/courses');
}
public function create(){
$data['page'] = 'courses';
$data['page_title'] = 'Add Course';
if ($this->form_validation->run())
{
//$this->load->view('myform');
$coursedata = array (
'name' => $this->input->post('name'),
'description' => $this->input->post('description'),
);
if ($this->Courses_m->insert_course($coursedata)){
redirect ('admin/courses');
}
}
$this->load->view('admin/create_course',$data);
}
public function update($id){
$data['page'] = 'edit_course';
$data['page_title'] = 'Edit Course';
$data['course']= $this->Courses_m->get_coursebyid($id);
if ($this->form_validation->run())
{
$coursedata = array (
'name' => $this->input->post('name'),
'description' => $this->input->post('description'),
);
if ($this->Courses_m->update_course($coursedata, $id)){
redirect ('admin/courses');
}
}
$this->load->view('admin/edit_course',$data);
}
}
| 069h-course-management | trunk/ci/application/controllers/admin/courses.php | PHP | mit | 2,191 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Usertype extends CI_Controller {
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->helper('url');
$this->load->model('Users_m');
}
public function index()
{
$data['usertype'] = $this->Usertype_m->get_usertype();
$data['page'] = 'usertype';
$data['page_title'] = 'Recent usertype';
$this->load->view('admin/usertype', $data);
}
}
?> | 069h-course-management | trunk/ci/application/controllers/admin/usertype.php | PHP | mit | 573 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Questions extends CI_Controller {
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->helper('url');
$this->load->model('Questions_m');
}
public function index()
{
$data['page_title'] = 'Questions';
$data['page'] = 'questions';
$data['questions'] = $this->Questions_m->get_questions();
$this->load->view('admin/questions', $data);
}
public function create(){
$data['page'] = "questions";
$data['page_title'] = "Add Questions";
$coursedata = array (
'name' => $this->input->post('name'),
'description' => $this->input->post('description'),
);
if ($this->Courses_m->insert_course($coursedata)){
redirect ('admin/courses');
}
$this->load->view('admin/create_course',$data);
}
public function delete($id)
{
$this->Questions_m->delete_questions($id);
redirect('admin/questions');
}
}
| 069h-course-management | trunk/ci/application/controllers/admin/questions.php | PHP | mit | 1,067 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* @see http://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$this->load->helper('url');
$data['page_title'] = 'Recent Users';
$this->load->view('admin/users', $data);
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */ | 069h-course-management | trunk/ci/application/controllers/admin/login.php | PHP | mit | 855 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends CI_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* @see http://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$this->load->helper('url');
$data['page_title'] = 'Welcome to Administration';
$data['page'] = 'home';
$this->load->view('admin/home', $data);
}
public function feedback()
{
$this->load->helper('url');
$data['page_title'] = 'Feedbacks';
$data['page'] = 'feedback';
$this->load->view('admin/feedback', $data);
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */ | 069h-course-management | trunk/ci/application/controllers/admin/home.php | PHP | mit | 1,097 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Users extends CI_Controller {
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->load->helper('url');
$this->load->model('Users_m');
// $this->load->library('upload');
$this->load->library('form_validation');
$this->load->model('Usertype_m');
$validation_rules = array(
array(
'field' => 'username',
'label' => 'Username',
'rules' => 'required'
),
array(
'field' => 'password',
'label' => 'Password',
'rules' => 'required'
),
array(
'field' => 'email',
'label' => 'Email',
'rules' => 'required|valid_email'
),
array(
'field' => 'usertype',
'label' => 'User Type',
'rules' => 'required'
),
array(
'field' => 'firstname',
'label' => 'First Name',
'rules' => 'required'
),
array(
'field' => 'midname',
'label' => 'Middle Name',
'rules' => ''
),
array(
'field' => 'lastname',
'label' => 'Last Name',
'rules' => 'required'
),
array(
'field' => 'phone',
'label' => 'Phone',
'rules' => 'required'
),
array(
'field' => 'address',
'label' => 'Address',
'rules' => 'required'
),
array(
'field' => 'website',
'label' => 'Website',
'rules' => ''
),
array(
'field' => 'picture',
'label' => 'Picture',
'rules' => ''
),
);
$this->form_validation->set_rules($validation_rules);
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$this->load->library('upload', $config);
}
public function index()
{
$data['users'] = $this->Users_m->get_users();
$data['page'] = 'users';
//echo $this->db->last_query();
/*
echo "<pre>";
print_r($data['users']);
echo "</pre>"; */
$data['page_title'] = 'Recent Users';
$this->load->view('admin/users', $data);
}
public function delete($id){
$this->Users_m->dalete_user($id);
redirect('admin/users');
}
public function create(){
$data['page'] = 'users';
$data['page_title'] = 'Create user';
$all_usertype = $this->Usertype_m->get_usertype();
$usertype_select = array();
foreach ($all_usertype as $u){
$usertype_select [$u->id] = $u->name;
}
$data['usertype_select'] = $usertype_select;
if ($this->form_validation->run())
{
//$this->load->view('myform');
$field_name = "picture";
if ( ! $this->upload->do_upload('picture'))
{
$error = array('error' => $this->upload->display_errors());
//$this->load->view('upload_form', $error);
$this->form_validation->set_message('picture', 'Error Message');
}
else
{
$upload_data = $this->upload->data();
/*
echo "<pre>";
print_r($upload_data);
exit;
*/
$userdata = array (
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'email' => $this->input->post('email'),
'user_type' => $this->input->post('usertype'),
'first_name' => $this->input->post('firstname'),
'mid_name' => $this->input->post('midname'),
'last_name' => $this->input->post('lastname'),
'phone' => $this->input->post('phone'),
'address' => $this->input->post('address'),
'website' => $this->input->post('website'),
'picture' => $upload_data['file_name']
);
if ($this->Users_m->insert_user($userdata)){
redirect ('admin/users');
}
$this->load->view('upload_success', $data);
}
//insert date
//redirect
}
$this->load->view('admin/create_user',$data);
}
public function edit($id){
$data['page'] = 'edit_user';
$data['page_title'] = 'Edit user';
$all_usertype = $this->Usertype_m->get_usertype();
$usertype_select = array();
foreach ($all_usertype as $u){
$usertype_select [$u->id] = $u->name;
}
$data['usertype_select'] = $usertype_select;
$data['user']= $this->Users_m->get_user($id);
if ($this->form_validation->run())
{
//$this->load->view('myform');
$userdata = array (
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'email' => $this->input->post('email'),
'user_type' => $this->input->post('usertype'),
'first_name' => $this->input->post('firstname'),
'mid_name' => $this->input->post('midname'),
'last_name' => $this->input->post('lastname'),
'phone' => $this->input->post('phone'),
'address' => $this->input->post('address'),
'website' => $this->input->post('website')
);
if ($this->Users_m->update_user($userdata, $id)){
redirect ('admin/users');
}
}
$this->load->view('admin/edit_user',$data);
}
function search(){
$data['page'] = 'users';
$q = $this->input->post('query');
//$this->data->search_result = $this->Users_m->search($q);
$data['users'] = $this->Users_m->search($q);
$this->load->view('admin/users', $data);
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */ | 069h-course-management | trunk/ci/application/controllers/admin/users.php | PHP | mit | 6,292 |
<?php
class Upload extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view('upload_form', array('error' => ' ' ));
}
function do_upload()
{
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('upload_form', $error);
}
else
{
$data = array('upload_data' => $this->upload->data());
$this->load->view('upload_success', $data);
}
}
}
?> | 069h-course-management | trunk/ci/application/controllers/upload.php | PHP | mit | 806 |
<?php
/*
*---------------------------------------------------------------
* APPLICATION ENVIRONMENT
*---------------------------------------------------------------
*
* You can load different configurations depending on your
* current environment. Setting the environment also influences
* things like logging and error reporting.
*
* This can be set to anything, but default usage is:
*
* development
* testing
* production
*
* NOTE: If you change these, also change the error_reporting() code below
*
*/
define('ENVIRONMENT', 'development');
/*
*---------------------------------------------------------------
* ERROR REPORTING
*---------------------------------------------------------------
*
* Different environments will require different levels of error reporting.
* By default development will show errors but testing and live will hide them.
*/
if (defined('ENVIRONMENT'))
{
switch (ENVIRONMENT)
{
case 'development':
error_reporting(E_ALL);
break;
case 'testing':
case 'production':
error_reporting(0);
break;
default:
exit('The application environment is not set correctly.');
}
}
/*
*---------------------------------------------------------------
* SYSTEM FOLDER NAME
*---------------------------------------------------------------
*
* This variable must contain the name of your "system" folder.
* Include the path if the folder is not in the same directory
* as this file.
*
*/
$system_path = 'system';
/*
*---------------------------------------------------------------
* APPLICATION FOLDER NAME
*---------------------------------------------------------------
*
* If you want this front controller to use a different "application"
* folder then the default one you can set its name here. The folder
* can also be renamed or relocated anywhere on your server. If
* you do, use a full server path. For more info please see the user guide:
* http://codeigniter.com/user_guide/general/managing_apps.html
*
* NO TRAILING SLASH!
*
*/
$application_folder = 'application';
/*
* --------------------------------------------------------------------
* DEFAULT CONTROLLER
* --------------------------------------------------------------------
*
* Normally you will set your default controller in the routes.php file.
* You can, however, force a custom routing by hard-coding a
* specific controller class/function here. For most applications, you
* WILL NOT set your routing here, but it's an option for those
* special instances where you might want to override the standard
* routing in a specific front controller that shares a common CI installation.
*
* IMPORTANT: If you set the routing here, NO OTHER controller will be
* callable. In essence, this preference limits your application to ONE
* specific controller. Leave the function name blank if you need
* to call functions dynamically via the URI.
*
* Un-comment the $routing array below to use this feature
*
*/
// The directory name, relative to the "controllers" folder. Leave blank
// if your controller is not in a sub-folder within the "controllers" folder
// $routing['directory'] = '';
// The controller class file name. Example: Mycontroller
// $routing['controller'] = '';
// The controller function you wish to be called.
// $routing['function'] = '';
/*
* -------------------------------------------------------------------
* CUSTOM CONFIG VALUES
* -------------------------------------------------------------------
*
* The $assign_to_config array below will be passed dynamically to the
* config class when initialized. This allows you to set custom config
* items or override any default config values found in the config.php file.
* This can be handy as it permits you to share one application between
* multiple front controller files, with each file containing different
* config values.
*
* Un-comment the $assign_to_config array below to use this feature
*
*/
// $assign_to_config['name_of_config_item'] = 'value of config item';
// --------------------------------------------------------------------
// END OF USER CONFIGURABLE SETTINGS. DO NOT EDIT BELOW THIS LINE
// --------------------------------------------------------------------
/*
* ---------------------------------------------------------------
* Resolve the system path for increased reliability
* ---------------------------------------------------------------
*/
// Set the current directory correctly for CLI requests
if (defined('STDIN'))
{
chdir(dirname(__FILE__));
}
if (realpath($system_path) !== FALSE)
{
$system_path = realpath($system_path).'/';
}
// ensure there's a trailing slash
$system_path = rtrim($system_path, '/').'/';
// Is the system path correct?
if ( ! is_dir($system_path))
{
exit("Your system folder path does not appear to be set correctly. Please open the following file and correct this: ".pathinfo(__FILE__, PATHINFO_BASENAME));
}
/*
* -------------------------------------------------------------------
* Now that we know the path, set the main path constants
* -------------------------------------------------------------------
*/
// The name of THIS file
define('SELF', pathinfo(__FILE__, PATHINFO_BASENAME));
// The PHP file extension
// this global constant is deprecated.
define('EXT', '.php');
// Path to the system folder
define('BASEPATH', str_replace("\\", "/", $system_path));
// Path to the front controller (this file)
define('FCPATH', str_replace(SELF, '', __FILE__));
// Name of the "system folder"
define('SYSDIR', trim(strrchr(trim(BASEPATH, '/'), '/'), '/'));
// The path to the "application" folder
if (is_dir($application_folder))
{
define('APPPATH', $application_folder.'/');
}
else
{
if ( ! is_dir(BASEPATH.$application_folder.'/'))
{
exit("Your application folder path does not appear to be set correctly. Please open the following file and correct this: ".SELF);
}
define('APPPATH', BASEPATH.$application_folder.'/');
}
/*
* --------------------------------------------------------------------
* LOAD THE BOOTSTRAP FILE
* --------------------------------------------------------------------
*
* And away we go...
*
*/
require_once BASEPATH.'core/CodeIgniter.php';
/* End of file index.php */
/* Location: ./index.php */ | 069h-course-management | trunk/ci/index.php | PHP | mit | 6,357 |
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html> | 069h-course-management | trunk/ci/system/index.html | HTML | mit | 114 |
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html> | 069h-course-management | trunk/ci/system/language/index.html | HTML | mit | 114 |
<?php
$lang['date_year'] = "Year";
$lang['date_years'] = "Years";
$lang['date_month'] = "Month";
$lang['date_months'] = "Months";
$lang['date_week'] = "Week";
$lang['date_weeks'] = "Weeks";
$lang['date_day'] = "Day";
$lang['date_days'] = "Days";
$lang['date_hour'] = "Hour";
$lang['date_hours'] = "Hours";
$lang['date_minute'] = "Minute";
$lang['date_minutes'] = "Minutes";
$lang['date_second'] = "Second";
$lang['date_seconds'] = "Seconds";
$lang['UM12'] = '(UTC -12:00) Baker/Howland Island';
$lang['UM11'] = '(UTC -11:00) Samoa Time Zone, Niue';
$lang['UM10'] = '(UTC -10:00) Hawaii-Aleutian Standard Time, Cook Islands, Tahiti';
$lang['UM95'] = '(UTC -9:30) Marquesas Islands';
$lang['UM9'] = '(UTC -9:00) Alaska Standard Time, Gambier Islands';
$lang['UM8'] = '(UTC -8:00) Pacific Standard Time, Clipperton Island';
$lang['UM7'] = '(UTC -7:00) Mountain Standard Time';
$lang['UM6'] = '(UTC -6:00) Central Standard Time';
$lang['UM5'] = '(UTC -5:00) Eastern Standard Time, Western Caribbean Standard Time';
$lang['UM45'] = '(UTC -4:30) Venezuelan Standard Time';
$lang['UM4'] = '(UTC -4:00) Atlantic Standard Time, Eastern Caribbean Standard Time';
$lang['UM35'] = '(UTC -3:30) Newfoundland Standard Time';
$lang['UM3'] = '(UTC -3:00) Argentina, Brazil, French Guiana, Uruguay';
$lang['UM2'] = '(UTC -2:00) South Georgia/South Sandwich Islands';
$lang['UM1'] = '(UTC -1:00) Azores, Cape Verde Islands';
$lang['UTC'] = '(UTC) Greenwich Mean Time, Western European Time';
$lang['UP1'] = '(UTC +1:00) Central European Time, West Africa Time';
$lang['UP2'] = '(UTC +2:00) Central Africa Time, Eastern European Time, Kaliningrad Time';
$lang['UP3'] = '(UTC +3:00) Moscow Time, East Africa Time';
$lang['UP35'] = '(UTC +3:30) Iran Standard Time';
$lang['UP4'] = '(UTC +4:00) Azerbaijan Standard Time, Samara Time';
$lang['UP45'] = '(UTC +4:30) Afghanistan';
$lang['UP5'] = '(UTC +5:00) Pakistan Standard Time, Yekaterinburg Time';
$lang['UP55'] = '(UTC +5:30) Indian Standard Time, Sri Lanka Time';
$lang['UP575'] = '(UTC +5:45) Nepal Time';
$lang['UP6'] = '(UTC +6:00) Bangladesh Standard Time, Bhutan Time, Omsk Time';
$lang['UP65'] = '(UTC +6:30) Cocos Islands, Myanmar';
$lang['UP7'] = '(UTC +7:00) Krasnoyarsk Time, Cambodia, Laos, Thailand, Vietnam';
$lang['UP8'] = '(UTC +8:00) Australian Western Standard Time, Beijing Time, Irkutsk Time';
$lang['UP875'] = '(UTC +8:45) Australian Central Western Standard Time';
$lang['UP9'] = '(UTC +9:00) Japan Standard Time, Korea Standard Time, Yakutsk Time';
$lang['UP95'] = '(UTC +9:30) Australian Central Standard Time';
$lang['UP10'] = '(UTC +10:00) Australian Eastern Standard Time, Vladivostok Time';
$lang['UP105'] = '(UTC +10:30) Lord Howe Island';
$lang['UP11'] = '(UTC +11:00) Magadan Time, Solomon Islands, Vanuatu';
$lang['UP115'] = '(UTC +11:30) Norfolk Island';
$lang['UP12'] = '(UTC +12:00) Fiji, Gilbert Islands, Kamchatka Time, New Zealand Standard Time';
$lang['UP1275'] = '(UTC +12:45) Chatham Islands Standard Time';
$lang['UP13'] = '(UTC +13:00) Phoenix Islands Time, Tonga';
$lang['UP14'] = '(UTC +14:00) Line Islands';
/* End of file date_lang.php */
/* Location: ./system/language/english/date_lang.php */ | 069h-course-management | trunk/ci/system/language/english/date_lang.php | PHP | mit | 3,177 |
<?php
$lang['terabyte_abbr'] = "TB";
$lang['gigabyte_abbr'] = "GB";
$lang['megabyte_abbr'] = "MB";
$lang['kilobyte_abbr'] = "KB";
$lang['bytes'] = "Bytes";
/* End of file number_lang.php */
/* Location: ./system/language/english/number_lang.php */ | 069h-course-management | trunk/ci/system/language/english/number_lang.php | PHP | mit | 249 |
<html>
<head>
<title>403 Forbidden</title>
</head>
<body>
<p>Directory access is forbidden.</p>
</body>
</html> | 069h-course-management | trunk/ci/system/language/english/index.html | HTML | mit | 114 |
<?php
$lang['email_must_be_array'] = "The email validation method must be passed an array.";
$lang['email_invalid_address'] = "Invalid email address: %s";
$lang['email_attachment_missing'] = "Unable to locate the following email attachment: %s";
$lang['email_attachment_unreadable'] = "Unable to open this attachment: %s";
$lang['email_no_recipients'] = "You must include recipients: To, Cc, or Bcc";
$lang['email_send_failure_phpmail'] = "Unable to send email using PHP mail(). Your server might not be configured to send mail using this method.";
$lang['email_send_failure_sendmail'] = "Unable to send email using PHP Sendmail. Your server might not be configured to send mail using this method.";
$lang['email_send_failure_smtp'] = "Unable to send email using PHP SMTP. Your server might not be configured to send mail using this method.";
$lang['email_sent'] = "Your message has been successfully sent using the following protocol: %s";
$lang['email_no_socket'] = "Unable to open a socket to Sendmail. Please check settings.";
$lang['email_no_hostname'] = "You did not specify a SMTP hostname.";
$lang['email_smtp_error'] = "The following SMTP error was encountered: %s";
$lang['email_no_smtp_unpw'] = "Error: You must assign a SMTP username and password.";
$lang['email_failed_smtp_login'] = "Failed to send AUTH LOGIN command. Error: %s";
$lang['email_smtp_auth_un'] = "Failed to authenticate username. Error: %s";
$lang['email_smtp_auth_pw'] = "Failed to authenticate password. Error: %s";
$lang['email_smtp_data_failure'] = "Unable to send data: %s";
$lang['email_exit_status'] = "Exit status code: %s";
/* End of file email_lang.php */
/* Location: ./system/language/english/email_lang.php */ | 069h-course-management | trunk/ci/system/language/english/email_lang.php | PHP | mit | 1,707 |
<?php
$lang['required'] = "The %s field is required.";
$lang['isset'] = "The %s field must have a value.";
$lang['valid_email'] = "The %s field must contain a valid email address.";
$lang['valid_emails'] = "The %s field must contain all valid email addresses.";
$lang['valid_url'] = "The %s field must contain a valid URL.";
$lang['valid_ip'] = "The %s field must contain a valid IP.";
$lang['min_length'] = "The %s field must be at least %s characters in length.";
$lang['max_length'] = "The %s field can not exceed %s characters in length.";
$lang['exact_length'] = "The %s field must be exactly %s characters in length.";
$lang['alpha'] = "The %s field may only contain alphabetical characters.";
$lang['alpha_numeric'] = "The %s field may only contain alpha-numeric characters.";
$lang['alpha_dash'] = "The %s field may only contain alpha-numeric characters, underscores, and dashes.";
$lang['numeric'] = "The %s field must contain only numbers.";
$lang['is_numeric'] = "The %s field must contain only numeric characters.";
$lang['integer'] = "The %s field must contain an integer.";
$lang['regex_match'] = "The %s field is not in the correct format.";
$lang['matches'] = "The %s field does not match the %s field.";
$lang['is_unique'] = "The %s field must contain a unique value.";
$lang['is_natural'] = "The %s field must contain only positive numbers.";
$lang['is_natural_no_zero'] = "The %s field must contain a number greater than zero.";
$lang['decimal'] = "The %s field must contain a decimal number.";
$lang['less_than'] = "The %s field must contain a number less than %s.";
$lang['greater_than'] = "The %s field must contain a number greater than %s.";
/* End of file form_validation_lang.php */
/* Location: ./system/language/english/form_validation_lang.php */ | 069h-course-management | trunk/ci/system/language/english/form_validation_lang.php | PHP | mit | 1,819 |
<?php
$lang['imglib_source_image_required'] = "You must specify a source image in your preferences.";
$lang['imglib_gd_required'] = "The GD image library is required for this feature.";
$lang['imglib_gd_required_for_props'] = "Your server must support the GD image library in order to determine the image properties.";
$lang['imglib_unsupported_imagecreate'] = "Your server does not support the GD function required to process this type of image.";
$lang['imglib_gif_not_supported'] = "GIF images are often not supported due to licensing restrictions. You may have to use JPG or PNG images instead.";
$lang['imglib_jpg_not_supported'] = "JPG images are not supported.";
$lang['imglib_png_not_supported'] = "PNG images are not supported.";
$lang['imglib_jpg_or_png_required'] = "The image resize protocol specified in your preferences only works with JPEG or PNG image types.";
$lang['imglib_copy_error'] = "An error was encountered while attempting to replace the file. Please make sure your file directory is writable.";
$lang['imglib_rotate_unsupported'] = "Image rotation does not appear to be supported by your server.";
$lang['imglib_libpath_invalid'] = "The path to your image library is not correct. Please set the correct path in your image preferences.";
$lang['imglib_image_process_failed'] = "Image processing failed. Please verify that your server supports the chosen protocol and that the path to your image library is correct.";
$lang['imglib_rotation_angle_required'] = "An angle of rotation is required to rotate the image.";
$lang['imglib_writing_failed_gif'] = "GIF image.";
$lang['imglib_invalid_path'] = "The path to the image is not correct.";
$lang['imglib_copy_failed'] = "The image copy routine failed.";
$lang['imglib_missing_font'] = "Unable to find a font to use.";
$lang['imglib_save_failed'] = "Unable to save the image. Please make sure the image and file directory are writable.";
/* End of file imglib_lang.php */
/* Location: ./system/language/english/imglib_lang.php */ | 069h-course-management | trunk/ci/system/language/english/imglib_lang.php | PHP | mit | 2,011 |
<?php
$lang['cal_su'] = "Su";
$lang['cal_mo'] = "Mo";
$lang['cal_tu'] = "Tu";
$lang['cal_we'] = "We";
$lang['cal_th'] = "Th";
$lang['cal_fr'] = "Fr";
$lang['cal_sa'] = "Sa";
$lang['cal_sun'] = "Sun";
$lang['cal_mon'] = "Mon";
$lang['cal_tue'] = "Tue";
$lang['cal_wed'] = "Wed";
$lang['cal_thu'] = "Thu";
$lang['cal_fri'] = "Fri";
$lang['cal_sat'] = "Sat";
$lang['cal_sunday'] = "Sunday";
$lang['cal_monday'] = "Monday";
$lang['cal_tuesday'] = "Tuesday";
$lang['cal_wednesday'] = "Wednesday";
$lang['cal_thursday'] = "Thursday";
$lang['cal_friday'] = "Friday";
$lang['cal_saturday'] = "Saturday";
$lang['cal_jan'] = "Jan";
$lang['cal_feb'] = "Feb";
$lang['cal_mar'] = "Mar";
$lang['cal_apr'] = "Apr";
$lang['cal_may'] = "May";
$lang['cal_jun'] = "Jun";
$lang['cal_jul'] = "Jul";
$lang['cal_aug'] = "Aug";
$lang['cal_sep'] = "Sep";
$lang['cal_oct'] = "Oct";
$lang['cal_nov'] = "Nov";
$lang['cal_dec'] = "Dec";
$lang['cal_january'] = "January";
$lang['cal_february'] = "February";
$lang['cal_march'] = "March";
$lang['cal_april'] = "April";
$lang['cal_mayl'] = "May";
$lang['cal_june'] = "June";
$lang['cal_july'] = "July";
$lang['cal_august'] = "August";
$lang['cal_september'] = "September";
$lang['cal_october'] = "October";
$lang['cal_november'] = "November";
$lang['cal_december'] = "December";
/* End of file calendar_lang.php */
/* Location: ./system/language/english/calendar_lang.php */ | 069h-course-management | trunk/ci/system/language/english/calendar_lang.php | PHP | mit | 1,437 |
<?php
$lang['ftp_no_connection'] = "Unable to locate a valid connection ID. Please make sure you are connected before peforming any file routines.";
$lang['ftp_unable_to_connect'] = "Unable to connect to your FTP server using the supplied hostname.";
$lang['ftp_unable_to_login'] = "Unable to login to your FTP server. Please check your username and password.";
$lang['ftp_unable_to_makdir'] = "Unable to create the directory you have specified.";
$lang['ftp_unable_to_changedir'] = "Unable to change directories.";
$lang['ftp_unable_to_chmod'] = "Unable to set file permissions. Please check your path. Note: This feature is only available in PHP 5 or higher.";
$lang['ftp_unable_to_upload'] = "Unable to upload the specified file. Please check your path.";
$lang['ftp_unable_to_download'] = "Unable to download the specified file. Please check your path.";
$lang['ftp_no_source_file'] = "Unable to locate the source file. Please check your path.";
$lang['ftp_unable_to_rename'] = "Unable to rename the file.";
$lang['ftp_unable_to_delete'] = "Unable to delete the file.";
$lang['ftp_unable_to_move'] = "Unable to move the file. Please make sure the destination directory exists.";
/* End of file ftp_lang.php */
/* Location: ./system/language/english/ftp_lang.php */ | 069h-course-management | trunk/ci/system/language/english/ftp_lang.php | PHP | mit | 1,285 |
<?php
$lang['migration_none_found'] = "No migrations were found.";
$lang['migration_not_found'] = "This migration could not be found.";
$lang['migration_multiple_version'] = "This are multiple migrations with the same version number: %d.";
$lang['migration_class_doesnt_exist'] = "The migration class \"%s\" could not be found.";
$lang['migration_missing_up_method'] = "The migration class \"%s\" is missing an 'up' method.";
$lang['migration_missing_down_method'] = "The migration class \"%s\" is missing an 'down' method.";
$lang['migration_invalid_filename'] = "Migration \"%s\" has an invalid filename.";
/* End of file migration_lang.php */
/* Location: ./system/language/english/migration_lang.php */ | 069h-course-management | trunk/ci/system/language/english/migration_lang.php | PHP | mit | 715 |
<?php
$lang['ut_test_name'] = 'Test Name';
$lang['ut_test_datatype'] = 'Test Datatype';
$lang['ut_res_datatype'] = 'Expected Datatype';
$lang['ut_result'] = 'Result';
$lang['ut_undefined'] = 'Undefined Test Name';
$lang['ut_file'] = 'File Name';
$lang['ut_line'] = 'Line Number';
$lang['ut_passed'] = 'Passed';
$lang['ut_failed'] = 'Failed';
$lang['ut_boolean'] = 'Boolean';
$lang['ut_integer'] = 'Integer';
$lang['ut_float'] = 'Float';
$lang['ut_double'] = 'Float'; // can be the same as float
$lang['ut_string'] = 'String';
$lang['ut_array'] = 'Array';
$lang['ut_object'] = 'Object';
$lang['ut_resource'] = 'Resource';
$lang['ut_null'] = 'Null';
$lang['ut_notes'] = 'Notes';
/* End of file unit_test_lang.php */
/* Location: ./system/language/english/unit_test_lang.php */ | 069h-course-management | trunk/ci/system/language/english/unit_test_lang.php | PHP | mit | 808 |
<?php
$lang['profiler_database'] = 'DATABASE';
$lang['profiler_controller_info'] = 'CLASS/METHOD';
$lang['profiler_benchmarks'] = 'BENCHMARKS';
$lang['profiler_queries'] = 'QUERIES';
$lang['profiler_get_data'] = 'GET DATA';
$lang['profiler_post_data'] = 'POST DATA';
$lang['profiler_uri_string'] = 'URI STRING';
$lang['profiler_memory_usage'] = 'MEMORY USAGE';
$lang['profiler_config'] = 'CONFIG VARIABLES';
$lang['profiler_session_data'] = 'SESSION DATA';
$lang['profiler_headers'] = 'HTTP HEADERS';
$lang['profiler_no_db'] = 'Database driver is not currently loaded';
$lang['profiler_no_queries'] = 'No queries were run';
$lang['profiler_no_post'] = 'No POST data exists';
$lang['profiler_no_get'] = 'No GET data exists';
$lang['profiler_no_uri'] = 'No URI data exists';
$lang['profiler_no_memory'] = 'Memory Usage Unavailable';
$lang['profiler_no_profiles'] = 'No Profile data - all Profiler sections have been disabled.';
$lang['profiler_section_hide'] = 'Hide';
$lang['profiler_section_show'] = 'Show';
/* End of file profiler_lang.php */
/* Location: ./system/language/english/profiler_lang.php */ | 069h-course-management | trunk/ci/system/language/english/profiler_lang.php | PHP | mit | 1,117 |
<?php
$lang['db_invalid_connection_str'] = 'Unable to determine the database settings based on the connection string you submitted.';
$lang['db_unable_to_connect'] = 'Unable to connect to your database server using the provided settings.';
$lang['db_unable_to_select'] = 'Unable to select the specified database: %s';
$lang['db_unable_to_create'] = 'Unable to create the specified database: %s';
$lang['db_invalid_query'] = 'The query you submitted is not valid.';
$lang['db_must_set_table'] = 'You must set the database table to be used with your query.';
$lang['db_must_use_set'] = 'You must use the "set" method to update an entry.';
$lang['db_must_use_index'] = 'You must specify an index to match on for batch updates.';
$lang['db_batch_missing_index'] = 'One or more rows submitted for batch updating is missing the specified index.';
$lang['db_must_use_where'] = 'Updates are not allowed unless they contain a "where" clause.';
$lang['db_del_must_use_where'] = 'Deletes are not allowed unless they contain a "where" or "like" clause.';
$lang['db_field_param_missing'] = 'To fetch fields requires the name of the table as a parameter.';
$lang['db_unsupported_function'] = 'This feature is not available for the database you are using.';
$lang['db_transaction_failure'] = 'Transaction failure: Rollback performed.';
$lang['db_unable_to_drop'] = 'Unable to drop the specified database.';
$lang['db_unsuported_feature'] = 'Unsupported feature of the database platform you are using.';
$lang['db_unsuported_compression'] = 'The file compression format you chose is not supported by your server.';
$lang['db_filepath_error'] = 'Unable to write data to the file path you have submitted.';
$lang['db_invalid_cache_path'] = 'The cache path you submitted is not valid or writable.';
$lang['db_table_name_required'] = 'A table name is required for that operation.';
$lang['db_column_name_required'] = 'A column name is required for that operation.';
$lang['db_column_definition_required'] = 'A column definition is required for that operation.';
$lang['db_unable_to_set_charset'] = 'Unable to set client connection character set: %s';
$lang['db_error_heading'] = 'A Database Error Occurred';
/* End of file db_lang.php */
/* Location: ./system/language/english/db_lang.php */ | 069h-course-management | trunk/ci/system/language/english/db_lang.php | PHP | mit | 2,273 |
<?php
$lang['upload_userfile_not_set'] = "Unable to find a post variable called userfile.";
$lang['upload_file_exceeds_limit'] = "The uploaded file exceeds the maximum allowed size in your PHP configuration file.";
$lang['upload_file_exceeds_form_limit'] = "The uploaded file exceeds the maximum size allowed by the submission form.";
$lang['upload_file_partial'] = "The file was only partially uploaded.";
$lang['upload_no_temp_directory'] = "The temporary folder is missing.";
$lang['upload_unable_to_write_file'] = "The file could not be written to disk.";
$lang['upload_stopped_by_extension'] = "The file upload was stopped by extension.";
$lang['upload_no_file_selected'] = "You did not select a file to upload.";
$lang['upload_invalid_filetype'] = "The filetype you are attempting to upload is not allowed.";
$lang['upload_invalid_filesize'] = "The file you are attempting to upload is larger than the permitted size.";
$lang['upload_invalid_dimensions'] = "The image you are attempting to upload exceedes the maximum height or width.";
$lang['upload_destination_error'] = "A problem was encountered while attempting to move the uploaded file to the final destination.";
$lang['upload_no_filepath'] = "The upload path does not appear to be valid.";
$lang['upload_no_file_types'] = "You have not specified any allowed file types.";
$lang['upload_bad_filename'] = "The file name you submitted already exists on the server.";
$lang['upload_not_writable'] = "The upload destination folder does not appear to be writable.";
/* End of file upload_lang.php */
/* Location: ./system/language/english/upload_lang.php */ | 069h-course-management | trunk/ci/system/language/english/upload_lang.php | PHP | mit | 1,619 |
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
* CodeIgniter
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author ExpressionEngine Dev Team
* @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
* @license http://codeigniter.com/user_guide/license.html
* @link http://codeigniter.com
* @since Version 1.0
* @filesource
*/
// ------------------------------------------------------------------------
/**
* CodeIgniter Number Helpers
*
* @package CodeIgniter
* @subpackage Helpers
* @category Helpers
* @author ExpressionEngine Dev Team
* @link http://codeigniter.com/user_guide/helpers/number_helper.html
*/
// ------------------------------------------------------------------------
/**
* Formats a numbers as bytes, based on size, and adds the appropriate suffix
*
* @access public
* @param mixed // will be cast as int
* @return string
*/
if ( ! function_exists('byte_format'))
{
function byte_format($num, $precision = 1)
{
$CI =& get_instance();
$CI->lang->load('number');
if ($num >= 1000000000000)
{
$num = round($num / 1099511627776, $precision);
$unit = $CI->lang->line('terabyte_abbr');
}
elseif ($num >= 1000000000)
{
$num = round($num / 1073741824, $precision);
$unit = $CI->lang->line('gigabyte_abbr');
}
elseif ($num >= 1000000)
{
$num = round($num / 1048576, $precision);
$unit = $CI->lang->line('megabyte_abbr');
}
elseif ($num >= 1000)
{
$num = round($num / 1024, $precision);
$unit = $CI->lang->line('kilobyte_abbr');
}
else
{
$unit = $CI->lang->line('bytes');
return number_format($num).' '.$unit;
}
return number_format($num, $precision).' '.$unit;
}
}
/* End of file number_helper.php */
/* Location: ./system/helpers/number_helper.php */ | 069h-course-management | trunk/ci/system/helpers/number_helper.php | PHP | mit | 1,859 |