This commit is contained in:
dmose%netscape.com 2001-08-04 19:31:13 +00:00
parent 350e1dd1c3
commit eb07f987fc
84 changed files with 10691 additions and 674 deletions

View File

@ -37,6 +37,11 @@ REQUIRES = xpcom string addrbook necko msgcompose mime msgbase rdf rdfutil docsh
CPPSRCS = nsAbFactory.cpp
EXPORTS = nsAbBaseCID.h
ifdef MOZ_LDAP_XPCOM
REQUIRES += mozldap
DEFINES += -DMOZ_LDAP_XPCOM
endif
SHARED_LIBRARY_LIBS = \
$(DIST)/lib/libaddrbook_s.$(LIB_SUFFIX) \
$(NULL)

View File

@ -35,6 +35,10 @@ EXPORTS= \
################################################################################
## library
!if !defined(DISABLE_LDAP)
LCFLAGS = $(LCFLAGS) -DMOZ_LDAP_XPCOM
!endif
CPP_OBJS= \
.\$(OBJDIR)\nsAbFactory.obj \
$(NULL)

View File

@ -26,6 +26,7 @@
#include "nsISupports.h"
#include "nsIFactory.h"
#include "nsIComponentManager.h"
#include "nsAbDirFactoryService.h"
//
// nsAddressBook
@ -73,7 +74,7 @@
// nsAbBSDirectory
//
#define NS_ABDIRECTORY_CONTRACTID \
NS_RDF_RESOURCE_FACTORY_CONTRACTID_PREFIX "abdirectory"
NS_RDF_RESOURCE_FACTORY_CONTRACTID_PREFIX "moz-abdirectory"
#define NS_ABDIRECTORY_CID \
{ /* {012D3C24-1DD2-11B2-BA79-B4AD359FC461}*/ \
@ -86,7 +87,7 @@
// nsAbMDBDirectory
//
#define NS_ABMDBDIRECTORY_CONTRACTID \
NS_RDF_RESOURCE_FACTORY_CONTRACTID_PREFIX "abmdbdirectory"
NS_RDF_RESOURCE_FACTORY_CONTRACTID_PREFIX "moz-abmdbdirectory"
#define NS_ABMDBDIRECTORY_CID \
{ /* {e618f894-1dd1-11b2-889c-9aaefaa90dde}*/ \
@ -98,7 +99,7 @@
// nsAbMDBCard
//
#define NS_ABMDBCARD_CONTRACTID \
NS_RDF_RESOURCE_FACTORY_CONTRACTID_PREFIX "abmdbcard"
NS_RDF_RESOURCE_FACTORY_CONTRACTID_PREFIX "moz-abmdbcard"
#define NS_ABMDBCARD_CID \
{ /* {f578a5d2-1dd1-11b2-8841-f45cc5e765f8} */ \
@ -206,4 +207,143 @@
{0xff, 0xcc, 0x0, 0x60, 0xb0, 0xfc, 0x4, 0x44} \
}
//
// directory factory service
//
#define NS_ABDIRFACTORYSERVICE_CONTRACTID \
"@mozilla.org/addressbook/directory-factory-service;1"
#define NS_ABDIRFACTORYSERVICE_CID \
{ /* {F8B212F2-742B-4A48-B7A0-4C44D4DDB121}*/ \
0xF8B212F2, 0x742B, 0x4A48, \
{0xB7, 0xA0, 0x4C, 0x44, 0xD4, 0xDD, 0xB1, 0x21} \
}
//
// mdb directory factory
//
#define NS_ABMDBDIRFACTORY_CONTRACTID \
NS_AB_DIRECTORY_FACTORY_CONTRACTID_PREFIX "moz-abmdbdirectory"
#define NS_ABMDBDIRFACTORY_CID \
{ /* {E1CB9C8A-722D-43E4-9D7B-7CCAE4B0338A}*/ \
0xE1CB9C8A, 0x722D, 0x43E4, \
{0x9D, 0x7B, 0x7C, 0xCA, 0xE4, 0xB0, 0x33, 0x8A} \
}
#ifdef XP_WIN
//
// nsAbOutlookDirectory
//
#define NS_ABOUTLOOKDIRECTORY_CONTRACTID \
NS_RDF_RESOURCE_FACTORY_CONTRACTID_PREFIX "moz-aboutlookdirectory"
#define NS_ABOUTLOOKDIRECTORY_CID \
{ /* {9cc57822-0599-4c47-a399-1c6fa185a05c}*/ \
0x9cc57822, 0x0599, 0x4c47, \
{0xa3, 0x99, 0x1c, 0x6f, 0xa1, 0x85, 0xa0, 0x5c} \
}
//
// nsAbOutlookCard
//
#define NS_ABOUTLOOKCARD_CONTRACTID \
NS_RDF_RESOURCE_FACTORY_CONTRACTID_PREFIX "moz-aboutlookcard"
#define NS_ABOUTLOOKCARD_CID \
{ /* {32cf9734-4ee8-4f5d-acfc-71b75eee1819}*/ \
0x32cf9734, 0x4ee8, 0x4f5d, \
{0xac, 0xfc, 0x71, 0xb7, 0x5e, 0xee, 0x18, 0x19} \
}
//
// Outlook directory factory
//
#define NS_ABOUTLOOKDIRFACTORY_CONTRACTID \
NS_AB_DIRECTORY_FACTORY_CONTRACTID_PREFIX "moz-aboutlookdirectory"
#define NS_ABOUTLOOKDIRFACTORY_CID \
{ /* {558ccc0f-2681-4dac-a066-debd8d26faf6}*/ \
0x558ccc0f, 0x2681, 0x4dac, \
{0xa0, 0x66, 0xde, 0xbd, 0x8d, 0x26, 0xfa, 0xf6} \
}
#endif
//
// Addressbook Query support
//
#define NS_ABDIRECTORYQUERYARGUMENTS_CONTRACTID \
"@mozilla.org/addressbook/directory/query-arguments;1"
#define NS_ABDIRECTORYQUERYARGUMENTS_CID \
{ /* {f7dc2aeb-8e62-4750-965c-24b9e09ed8d2} */ \
0xf7dc2aeb, 0x8e62, 0x4750, \
{ 0x96, 0x5c, 0x24, 0xb9, 0xe0, 0x9e, 0xd8, 0xd2 } \
}
#define NS_BOOLEANCONDITIONSTRING_CONTRACTID \
"@mozilla.org/boolean-expression/condition-string;1"
#define NS_BOOLEANCONDITIONSTRING_CID \
{ /* {ca1944a9-527e-4c77-895d-d0466dd41cf5} */ \
0xca1944a9, 0x527e, 0x4c77, \
{ 0x89, 0x5d, 0xd0, 0x46, 0x6d, 0xd4, 0x1c, 0xf5 } \
}
#define NS_BOOLEANEXPRESSION_CONTRACTID \
"@mozilla.org/boolean-expression/n-peer;1"
#define NS_BOOLEANEXPRESSION_CID \
{ /* {2c2e75c8-6f56-4a50-af1c-72af5d0e8d41} */ \
0x2c2e75c8, 0x6f56, 0x4a50, \
{ 0xaf, 0x1c, 0x72, 0xaf, 0x5d, 0x0e, 0x8d, 0x41 } \
}
#define NS_ABDIRECTORYQUERYPROXY_CONTRACTID \
"@mozilla.org/addressbook/directory-query/proxy;1"
#define NS_ABDIRECTORYQUERYPROXY_CID \
{ /* {E162E335-541B-43B4-AAEA-FE591E240CAF}*/ \
0xE162E335, 0x541B, 0x43B4, \
{0xAA, 0xEA, 0xFE, 0x59, 0x1E, 0x24, 0x0C, 0xAF} \
}
// nsAbLDAPDirectory
//
#define NS_ABLDAPDIRECTORY_CONTRACTID \
NS_RDF_RESOURCE_FACTORY_CONTRACTID_PREFIX "moz-abldapdirectory"
#define NS_ABLDAPDIRECTORY_CID \
{ /* {783E2777-66D7-4826-9E4B-8AB58C228A52}*/ \
0x783E2777, 0x66D7, 0x4826, \
{0x9E, 0x4B, 0x8A, 0xB5, 0x8C, 0x22, 0x8A, 0x52} \
}
//
// nsAbLDAPCard
//
#define NS_ABLDAPCARD_CONTRACTID \
NS_RDF_RESOURCE_FACTORY_CONTRACTID_PREFIX "moz-abldapcard"
#define NS_ABLDAPCARD_CID \
{ /* {10307B01-EBD6-465F-B972-1630410F70E6}*/ \
0x10307B01, 0xEBD6, 0x465F, \
{0xB9, 0x72, 0x16, 0x30, 0x41, 0x0F, 0x70, 0xE6} \
}
//
// LDAP directory factory
//
#define NS_ABLDAPDIRFACTORY_CONTRACTID \
NS_AB_DIRECTORY_FACTORY_CONTRACTID_PREFIX "moz-abldapdirectory"
#define NS_ABLDAPDIRFACTORY_CID \
{ /* {8e3701af-8828-426c-84ac-124825c778f8} */ \
0x8e3701af, 0x8828, 0x426c, \
{0x84, 0xac, 0x12, 0x48, 0x25, 0xc7, 0x78, 0xf8} \
}
#endif // nsAbBaseCID_h__

View File

@ -44,6 +44,9 @@
#include "nsAbMDBDirectory.h"
#include "nsAbMDBCard.h"
#include "nsAbDirFactoryService.h"
#include "nsAbMDBDirFactory.h"
#include "nsAddrDatabase.h"
#include "nsAddressBook.h"
#include "nsAddrBookSession.h"
@ -53,6 +56,22 @@
#include "nsAddbookProtocolHandler.h"
#include "nsAddbookUrl.h"
#ifdef XP_WIN
#include "nsAbOutlookDirectory.h"
#include "nsAbOutlookCard.h"
#include "nsAbOutlookDirFactory.h"
#endif
#include "nsAbDirectoryQuery.h"
#include "nsAbBooleanExpression.h"
#include "nsAbDirectoryQueryProxy.h"
#if defined(MOZ_LDAP_XPCOM)
#include "nsAbLDAPDirectory.h"
#include "nsAbLDAPCard.h"
#include "nsAbLDAPDirFactory.h"
#endif
NS_GENERIC_FACTORY_CONSTRUCTOR(nsAddressBook)
NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsAbDirectoryDataSource,Init)
@ -72,6 +91,27 @@ NS_GENERIC_FACTORY_CONSTRUCTOR(nsAbAutoCompleteSession)
NS_GENERIC_FACTORY_CONSTRUCTOR(nsAbAddressCollecter)
NS_GENERIC_FACTORY_CONSTRUCTOR(nsAddbookUrl)
NS_GENERIC_FACTORY_CONSTRUCTOR(nsAbDirFactoryService)
NS_GENERIC_FACTORY_CONSTRUCTOR(nsAbMDBDirFactory)
#ifdef XP_WIN
NS_GENERIC_FACTORY_CONSTRUCTOR(nsAbOutlookDirectory)
NS_GENERIC_FACTORY_CONSTRUCTOR(nsAbOutlookCard)
NS_GENERIC_FACTORY_CONSTRUCTOR(nsAbOutlookDirFactory)
#endif
NS_GENERIC_FACTORY_CONSTRUCTOR(nsAbDirectoryQueryArguments)
NS_GENERIC_FACTORY_CONSTRUCTOR(nsAbBooleanConditionString)
NS_GENERIC_FACTORY_CONSTRUCTOR(nsAbBooleanExpression)
#if defined(MOZ_LDAP_XPCOM)
NS_GENERIC_FACTORY_CONSTRUCTOR(nsAbLDAPDirectory)
NS_GENERIC_FACTORY_CONSTRUCTOR(nsAbLDAPCard)
NS_GENERIC_FACTORY_CONSTRUCTOR(nsAbLDAPDirFactory)
#endif
NS_GENERIC_FACTORY_CONSTRUCTOR(nsAbDirectoryQueryProxy)
//NS_GENERIC_FACTORY_CONSTRUCTOR(nsAddbookProtocolHandler)
static nsModuleComponentInfo components[] =
@ -148,10 +188,75 @@ static nsModuleComponentInfo components[] =
NS_ADDBOOKURL_CID,
NS_ADDBOOKURL_CONTRACTID,
nsAddbookUrlConstructor },
{ "The addbook Protocol Handler",
NS_ADDBOOK_HANDLER_CID,
NS_NETWORK_PROTOCOL_CONTRACTID_PREFIX "addbook",
nsAddbookProtocolHandler::Create }
nsAddbookProtocolHandler::Create },
{ "The directory factory service interface",
NS_ABDIRFACTORYSERVICE_CID,
NS_ABDIRFACTORYSERVICE_CONTRACTID,
nsAbDirFactoryServiceConstructor },
{ "The MDB directory factory interface",
NS_ABMDBDIRFACTORY_CID,
NS_ABMDBDIRFACTORY_CONTRACTID,
nsAbMDBDirFactoryConstructor },
#ifdef XP_WIN
{ "Address OUTLOOK Book Directory",
NS_ABOUTLOOKDIRECTORY_CID,
NS_ABOUTLOOKDIRECTORY_CONTRACTID,
nsAbOutlookDirectoryConstructor },
{ "Address OUTLOOK Book Card",
NS_ABOUTLOOKCARD_CID,
NS_ABOUTLOOKCARD_CONTRACTID,
nsAbOutlookCardConstructor },
{ "The outlook factory Interface",
NS_ABOUTLOOKDIRFACTORY_CID,
NS_ABOUTLOOKDIRFACTORY_CONTRACTID,
nsAbOutlookDirFactoryConstructor },
#endif
{ "The addbook query arguments",
NS_ABDIRECTORYQUERYARGUMENTS_CID,
NS_ABDIRECTORYQUERYARGUMENTS_CONTRACTID,
nsAbDirectoryQueryArgumentsConstructor },
{ "The query boolean condition string",
NS_BOOLEANCONDITIONSTRING_CID,
NS_BOOLEANCONDITIONSTRING_CONTRACTID,
nsAbBooleanConditionStringConstructor },
{ "The query n-peer expression",
NS_BOOLEANEXPRESSION_CID,
NS_BOOLEANEXPRESSION_CONTRACTID,
nsAbBooleanExpressionConstructor },
#if defined(MOZ_LDAP_XPCOM)
{ "Address LDAP Book Directory",
NS_ABLDAPDIRECTORY_CID,
NS_ABLDAPDIRECTORY_CONTRACTID,
nsAbLDAPDirectoryConstructor },
{ "Address LDAP Book Card",
NS_ABLDAPCARD_CID,
NS_ABLDAPCARD_CONTRACTID,
nsAbLDAPCardConstructor },
{ "Address LDAP factory Interface",
NS_ABLDAPDIRFACTORY_CID,
NS_ABLDAPDIRFACTORY_CONTRACTID,
nsAbLDAPDirFactoryConstructor },
#endif
{ "The directory query proxy interface",
NS_ABDIRECTORYQUERYPROXY_CID,
NS_ABDIRECTORYQUERYPROXY_CONTRACTID,
nsAbDirectoryQueryProxyConstructor }
};
NS_IMPL_NSGETMODULE(nsAbModule, components)

View File

@ -44,6 +44,12 @@ XPIDLSRCS = \
nsIAbAddressCollecter.idl \
nsIAbUpgrader.idl \
nsIAddbookUrl.idl \
nsIAbDirFactory.idl \
nsIAbDirFactoryService.idl \
nsIAbDirectoryQueryProxy.idl \
nsIAbDirectoryQuery.idl \
nsIAbBooleanExpression.idl \
nsIAbDirectorySearch.idl \
$(NULL)
ifdef MOZ_LDAP_XPCOM
XPIDLSRCS += nsILDAPPrefsService.idl

View File

@ -38,6 +38,12 @@ XPIDLSRCS = \
.\nsIAbAddressCollecter.idl \
.\nsIAbUpgrader.idl \
.\nsIAddbookUrl.idl \
.\nsIAbDirFactory.idl \
.\nsIAbDirFactoryService.idl \
.\nsIAbDirectoryQueryProxy.idl \
.\nsIAbDirectoryQuery.idl \
.\nsIAbBooleanExpression.idl \
.\nsIAbDirectorySearch.idl \
!if !defined(DISABLE_LDAP)
.\nsILDAPPrefsService.idl \
!endif

View File

@ -0,0 +1,153 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#include "nsISupports.idl"
#include "nsISupportsArray.idl"
typedef long nsAbBooleanConditionType;
/**
* Condition types
*
* Constants defining the types of condition
* to obtain a boolean result of TRUE or FALSE
*
*/
[scriptable, uuid(F51387B1-5AEF-4A1C-830E-7CD3B02366CE)]
interface nsIAbBooleanConditionTypes
{
const long Exists = 0;
const long DoesNotExist = 1;
const long Contains = 2;
const long DoesNotContain = 3;
const long Is = 4;
const long IsNot = 5;
const long BeginsWith = 6;
const long EndsWith = 7;
const long LessThan = 8;
const long GreaterThan = 9;
const long SoundsLike = 10;
const long RegExp = 11;
};
typedef long nsAbBooleanOperationType;
/*
* Operation types
*
* Constants defining the boolean operation that
* should be performed between two boolean expressions
*
*/
interface nsIAbBooleanOperationTypes
{
const long AND = 0;
const long OR = 1;
const long NOT = 2;
};
/**
* String condition
*
* A string condition represents a leaf node in a
* boolean expression tree and represents
* test which will return TRUE or FALSE
*
* Condition is an expression which is a
* leaf node in a boolean expression tree
*
*/
[scriptable, uuid(C3869D72-CFD0-45F0-A0EC-3F67D83C7110)]
interface nsIAbBooleanConditionString : nsISupports
{
/**
* The condition for how the a value
* should be compared
*
*/
attribute nsAbBooleanConditionType condition;
/**
* The lhs of the condition
*
* Represents a property name which
* should be evaluated to obtain the
* lhs.
*
*/
attribute string name;
/**
* The rhs of the condition
*
* <name> [condition] value
*
*/
attribute wstring value;
};
/**
* N Boolean expression type
*
* Supports Unary Binary and N boolean expressions
*
* An operation represents a node in a boolean
* expression tree which may contain one or more
* child conditions or expressions
*
*/
[scriptable, uuid(67F87C44-2C63-41A2-9545-AFF1D9F09623)]
interface nsIAbBooleanExpression: nsISupports
{
/**
* The boolean operation to be applied to
* results of all evaluated expressions
*
*/
attribute nsAbBooleanOperationType operation;
/**
* List of peer expressions
*
* e1 [op] e2 [op] .... en
*
*/
attribute nsISupportsArray expressions;
/**
* expressions attribute defined explicitly as an
* array of nsISupports
*
*/
void asetExpressions (in unsigned long aExpressionsSize,
[array, size_is(aExpressionsSize)]
in nsISupports aExpressionsArray);
void agetExpressions (out unsigned long aExpressionsSize,
[retval, array, size_is(aExpressionsSize)]
out nsISupports aExpressionsArray);
};

View File

@ -0,0 +1,65 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s): Csaba Borbola <csaba.borbola@sun.com>
*
*/
#include "nsISupports.idl"
#include "nsIEnumerator.idl"
interface nsIAbDirectory;
[scriptable, uuid(C2308606-1DD1-11B2-87D4-85FCA9B1DC08)]
interface nsIAbDirFactory : nsISupports
{
/**
* Instantiate new top level address book
* directories given an array of property names
* and values. More than one directory may be
* returned depending on the implementation
* and integration with the associated address book
* sources
*
* @param propertiesSize
* The number of properties
* @param propertyNamesArray
* The array of property names
* @param propertyValuesArray
* The array of property values
* @return
* Enumeration of nsIAbDirectory
* interfaces
*/
nsISimpleEnumerator createDirectory (
in unsigned long propertiesSize,
[array, size_is(propertiesSize)]
in string propertyNamesArray,
[array, size_is(propertiesSize)]
in wstring propertyValuesArray);
/**
* Delete a top level address book directory
*
*/
void deleteDirectory (in nsIAbDirectory directory);
};

View File

@ -0,0 +1,54 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
* Csaba Borbola <csaba.borbola@sun.com>
*
*/
#include "nsISupports.idl"
interface nsIAbDirFactory;
[scriptable, uuid(BE2075A8-1DD1-11B2-99BA-BCB9DB1D77CC)]
interface nsIAbDirFactoryService : nsISupports
{
/**
* Obtain a directory factory component
* given a uri representing an address book
*
* The scheme is extracted from the uri and
* contract id is generated of the form:
* @mozilla.org/addressbook/directory-factory;1?type=<scheme>
*
* This id is used to instantiate a registered
* component which implemented the nsIAbDirFactory
* interface
*
* @param uri
* The uri which contains the scheme that
* defines what directory factory instance
* is returned
*/
nsIAbDirFactory getDirFactory (in string uri);
};

View File

@ -25,7 +25,6 @@
#include "nsISupportsArray.idl"
[ptr] native nsFileSpec(nsFileSpec);
[ptr] native DIR_Server(DIR_Server);
%{C++
#include "nsFileSpec.h"
@ -35,11 +34,26 @@
[scriptable, uuid(AA920C90-1DD1-11B2-96D3-AA81268ADAFC)]
interface nsIAbDirectory : nsISupports {
// Types of operation
// Perform linear reading of directory card
// content
const long opRead = 1;
// Perform modification and deletion on a
// directories content
const long opWrite = 2;
// Perform searching on a directory card
// content via the uri format:
// scheme://path?query
const long opSearch = 4;
// The supported operations
readonly attribute long operations;
// The name of the directory
attribute wstring dirName;
attribute unsigned long lastModifiedDate;
// Defines wether this directory is a mail
// Defines whether this directory is a mail
// list or not
attribute PRBool isMailList;
@ -58,11 +72,16 @@ interface nsIAbDirectory : nsISupports {
// preferences
void deleteDirectory(in nsIAbDirectory dierctory);
// Delete the
// Delete the array of cards
void deleteCards(in nsISupportsArray cards);
// Check if directory contains card
// If the implementation is asynchronous the card
// may not yet have arrived. If it is in the process
// of obtaining cards the method will throw an
// NS_ERROR_NOT_AVAILABLE exception if the card
// cannot be found.
boolean hasCard(in nsIAbCard cards);
// Check if directory contains directory
@ -125,4 +144,11 @@ interface nsIAbDirectory : nsISupports {
/* create a directory by passing the display name and address book uri */
void CreateDirectoryByURI(in wstring displayName, in string uri, in boolean migrating);
// Returns the total number of cards
// If the implementation is asynchronous the total number
// is representative of the current number of cards obtained
// For example a search on LDAP will return card asynchronously
// and may take n seconds to complete the search.
unsigned long getTotalCards(in boolean subDirectoryCount);
};

View File

@ -0,0 +1,225 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#include "nsISupports.idl"
#include "nsISupportsArray.idl"
#include "nsIAbBooleanExpression.idl"
/**
* The arguments for a query.
*
* Contains an expression for perform matches
* and an array of properties which should be
* returned if a match is found from the expression
*
*/
[scriptable, uuid(41EC291E-1DD2-11B2-B583-C44757081F64)]
interface nsIAbDirectoryQueryArguments : nsISupports
{
/**
* Defines the boolean expression for
* the matching of cards
*
*/
attribute nsISupports expression;
/**
* Defines if sub directories should be
* queried
*
*/
attribute boolean querySubDirectories;
/**
* The list of properties which should
* be returned if a match occurs on a card
*
*/
void setReturnProperties (in unsigned long returnPropertiesSize,
[array, size_is(returnPropertiesSize)]
in string returnPropertiesArray);
void getReturnProperties (out unsigned long returnPropertiesSize,
[retval, array, size_is(returnPropertiesSize)]
out string returnPropertiesArray);
};
[scriptable, uuid(3A6E0C0C-1DD2-11B2-B23D-EA3A8CCB333C)]
interface nsIAbDirectoryQueryPropertyValue : nsISupports
{
/**
* The property which should be matched
*
* For example 'primaryEmail' or 'homePhone'
* for card properties.
*
* Two further properties are defined that
* do not exist as properties on a card.
* 'card:URI' which represents the URI property
* of the card as an RDF resource
* 'card:nsIAbCard' which represents the interface
* of a card component
*
*/
readonly attribute string name;
/**
* The value of the property
*
*/
readonly attribute wstring value;
/**
* The value of the property
* as an interface
*
* Only valid if the corresponding
* property name is related to an
* interface instead of a wstring
*
*/
readonly attribute nsISupports valueISupports;
};
[scriptable, uuid(42E600BA-1DD2-11B2-BC39-C363AC0C93E3)]
interface nsIAbDirectoryQueryResult : nsISupports
{
/**
* The context ID of the query
*
*/
readonly attribute long contextID;
/**
* The context of the query which
* corresponds to the arguments that
* define the query
*
*/
readonly attribute nsIAbDirectoryQueryArguments contextArgs;
/**
* List of defined query results
*
*/
const long queryResultMatch = 0;
const long queryResultComplete = 1;
const long queryResultStopped = 2;
const long queryResultError = 3;
/**
* The type of result
*
* Identifies a query entry, the query has finished
* or that an error has occured
*/
readonly attribute long type;
/**
* The result of a singular match for a card
*
* Only valid when the attribute type is
* of 'query match'
*
* nsISupportsArray<nsIAbDirectoryQueryPropertyValue>
* Multiple entries corresponding to card
* properties
* nsISupportsArray<nsIAbCard>
* Only one entry makese sense
*
*/
readonly attribute nsISupportsArray result;
/**
* result attribute defined explicitly as an
* array of nsISupport interfaces
*
*/
void agetResult (out unsigned long aResultSize,
[retval, array, size_is(aResultSize)]
out nsISupports aResultArray);
};
[scriptable, uuid(4290E508-1DD2-11B2-AC3E-9597BBCB25D7)]
interface nsIAbDirectoryQueryResultListener : nsISupports
{
/**
* Called when a match is found. May be
* called from a different thread to the
* one that initiates the query
*
* @param result
* A individual result associated returned
* from a query
*/
void onQueryItem (in nsIAbDirectoryQueryResult result);
};
[scriptable, uuid(4241C46E-1DD2-11B2-978D-A2FBD0A72AC2)]
interface nsIAbDirectoryQuery : nsISupports
{
/**
* Initiates a query on a directory and
* sub-directories for properties on cards
*
* @param arguments
* The properties and values to match
* Value could of type nsIAbDirectoryQueryMatchItem
* for matches other than ?contains?
* @param listener
* The listener which will obtain individual
* query results
* @param resultLimit
* Limits the results returned to a specifed
* maximum value
* @return
* Unique number representing the context ID of
* the query
*
*/
long doQuery (in nsIAbDirectoryQueryArguments arguments,
in nsIAbDirectoryQueryResultListener listener,
in long resultLimit,
in long timeOut);
/**
* Stops an existing query operation if
* query operation is asynchronous
*
* The nsIAbDirectoryQueryResultListener will
* be notified when query has stopped
*
* It is implementation specific if notification
* synchronous or asynchronous
*
* @param contextID
* The unique number returned from
* the doQuery methods
*
*/
void stopQuery (in long contextID);
};

View File

@ -0,0 +1,34 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#include "nsIAbDirectoryQuery.idl"
#include "nsIAbDirectory.idl"
[scriptable, uuid(CFA60E0C-94D5-4292-A675-28C737950B3B)]
interface nsIAbDirectoryQueryProxy : nsIAbDirectoryQuery
{
void initiate (in nsIAbDirectory directory);
};

View File

@ -0,0 +1,72 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#include "nsISupports.idl"
/**
* Searching of cards on a directory.
*
* The search data is defined in the query
* section of the directory URI, for example
*
* moz-abldapdirectory://ldap1.holland/dc=sun,dc=com?<query>
*
* If no search data is defined then the methods
* will return immediately with no error.
*/
[scriptable, uuid(ABF26047-37E3-44FD-A28A-6D37A1B9CCB3)]
interface nsIAbDirectorySearch : nsISupports
{
/**
* Starts a search on the directory.
*
* If a search is already being performed
* it is stopped.
*
* The results from a search, cards, will
* returned by informing the address book
* session that a new card has been added
* to the directory.
*
* The nsIAbDirectoryQuery implementation
* of the directory component (or a proxy)
* may be used as an implementation for
* this specialization of query.
*
* This method is semantically equivalent
* to the nsIAbDirectory.getChildCards
* method when there is search criteria
* defined in the directory uri.
*
*/
void startSearch ();
/**
* Stops a search on the directory.
*
*/
void stopSearch ();
};

View File

@ -14,10 +14,10 @@
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1999 Netscape Communications Corporation. All
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s): Paul Sandoz
* Contributor(s): Paul Sandoz <paul.sandoz@sun.com>
*/

View File

@ -14,10 +14,10 @@
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s): Paul Sandoz
* Contributor(s): Paul Sandoz <paul.sandoz@sun.com>
*/
#include "nsISupports.idl"

View File

@ -47,5 +47,7 @@ interface nsIAddressBook : nsISupports {
boolean mailListNameExistsInDB(in wstring name, in string URI);
boolean mailListNameExists(in wstring name);
unsigned long getTotalCards(in string URI);
void createCollationKey(in wstring source, out wstring result);
};

View File

@ -43,7 +43,7 @@ function OnLoadNewCard()
if ("selectedAB" in window.arguments[0])
editCard.selectedAB = window.arguments[0].selectedAB;
else
editCard.selectedAB = "abmdbdirectory://abook.mab";
editCard.selectedAB = "moz-abmdbdirectory://abook.mab";
// we may have been given properties to pre-initialize the window with....
// we'll fill these in here...

View File

@ -27,7 +27,7 @@ Rights Reserved.
<!-- FIX ME - remove document.commandDispatcher.updateCommands() when tree selection calls this automatically -->
<tree id="dirTree"
class="abDirectory"
ref="abdirectory://"
ref="moz-abdirectory://"
datasources="rdf:addressdirectory"
containment="http://home.netscape.com/NC-rdf#child"
ignore="http://home.netscape.com/NC-rdf#CardChild"

View File

@ -178,7 +178,7 @@ function OnLoadMailList()
if ( window.arguments[0].selectedAB )
selectedAB = window.arguments[0].selectedAB;
else
selectedAB = "abmdbdirectory://abook.mab";
selectedAB = "moz-abmdbdirectory://abook.mab";
}
// set popup with address book names

View File

@ -43,7 +43,7 @@ Rights Reserved.
<hbox autostretch="never" valign="center">
<text for="abPopup" value="&addToAddressBook.label;"/>
<menulist id="abPopup">
<menupopup id="abPopup-menupopup" ref="abdirectory://" datasources="rdf:addressdirectory">
<menupopup id="abPopup-menupopup" ref="moz-abdirectory://" datasources="rdf:addressdirectory">
<template>
<rule nc:IsMailList="false">
<menuitem uri="..."

View File

@ -43,7 +43,7 @@ Rights Reserved.
<text for="abPopup" value="&chooseAddressBook.label;"/>
<menulist id="abPopup">
<menupopup id="abPopup-menupopup" ref="abdirectory://" datasources="rdf:addressdirectory">
<menupopup id="abPopup-menupopup" ref="moz-abdirectory://" datasources="rdf:addressdirectory">
<template>
<rule nc:IsMailList="false">
<menuitem uri="..."

View File

@ -3,25 +3,48 @@ var addressbook = 0;
var gUpdateCardView = 0;
var gAddressBookBundle;
var gAddressBookSession;
var gTotalCardsElement = null;
var addressBookListener = {
onItemAdded: function(parentItem, item)
{ UpdateAddDeleteCounts(); },
var addressBookObserver = {
onAssert: function(aDataSource, aSource, aProperty, aTarget)
{
UpdateAddDeleteCounts();
},
onItemRemoved: function(parentItem, item)
{ UpdateAddDeleteCounts(); },
onUnassert: function(aDataSource, aSource, aProperty, aTarget)
{
UpdateAddDeleteCounts();
},
onItemPropertyChanged: function(item, property, oldValue, newValue) {}
onChange: function(aDataSource, aSource, aProperty, aOldTarget, aNewTarget)
{ },
onMove: function(aDataSource,
aOldSource,
aNewSource,
aProperty,
aTarget)
{},
beginUpdateBatch: function(aDataSource)
{},
endUpdateBatch: function(aDataSource)
{}
}
function OnUnloadAddressBook()
{
if (gAddressBookSession)
{
gAddressBookSession.removeAddressBookListener(addressBookListener);
}
try
{
var dataSource = top.rdf.GetDataSource("rdf:addressdirectory");
dataSource.RemoveObserver (addressBookObserver);
}
catch (ex)
{
dump(ex + "\n");
dump("Error removing from RDF datasource\n");
}
}
function OnLoadAddressBook()
@ -33,15 +56,6 @@ function OnLoadAddressBook()
top.addressbook = top.addressbook.QueryInterface(Components.interfaces.nsIAddressBook);
top.gUpdateCardView = UpdateCardView;
try {
gAddressBookSession = Components.classes["@mozilla.org/addressbook/services/session;1"].getService(Components.interfaces.nsIAddrBookSession);
gAddressBookSession.addAddressBookListener(addressBookListener);
}
catch (ex)
{
dump("Error adding to address book session\n");
}
InitCommonJS();
GetCurrentPrefs();
@ -59,6 +73,17 @@ function OnLoadAddressBook()
//workaround - add setTimeout to make sure dynamic overlays get loaded first
setTimeout('SelectFirstAddressBook()',0);
try
{
var dataSource = top.rdf.GetDataSource("rdf:addressdirectory");
dataSource.AddObserver (addressBookObserver);
}
catch (ex)
{
dump(ex + "\n");
dump("Error adding to RDF datasource\n");
}
}
@ -301,14 +326,14 @@ function AbDeleteDirectory()
// check to see if personal or collected address books is selected for deletion.
// if yes, prompt the user an appropriate message saying these cannot be deleted
// if no, mark the selected items for deletion
if ((selArray[i].getAttribute("id") != "abmdbdirectory://history.mab") &&
(selArray[i].getAttribute("id") != "abmdbdirectory://abook.mab"))
if ((selArray[i].getAttribute("id") != "moz-abmdbdirectory://history.mab") &&
(selArray[i].getAttribute("id") != "moz-abmdbdirectory://abook.mab"))
{
var parent = selArray[i].parentNode.parentNode;
if (parent)
{
if (parent == dirTree)
var parentId = "abdirectory://";
var parentId = "moz-abdirectory://";
else
var parentId = parent.getAttribute("id");
@ -384,7 +409,7 @@ function UpdateStatusCardCounts(uri)
{
try
{
var totalCards = top.addressbook.getTotalCards(uri);
var totalCards = parentDir.getTotalCards(false);
SetTotalCardStatus(parentDir.dirName, totalCards);
}
catch(ex)

View File

@ -21,4 +21,5 @@
#
nsDirPrefs.h
nsAbDirFactoryService.h

View File

@ -51,6 +51,15 @@ CPPSRCS = \
nsAbMDBCard.cpp \
nsAbBSDirectory.cpp \
nsAddbookUrl.cpp \
nsAbDirFactoryService.cpp \
nsAbMDBDirFactory.cpp \
nsAbUtils.cpp \
nsAbDirectoryQuery.cpp \
nsAbDirectoryQueryProxy.cpp \
nsAbDirSearchListener.cpp \
nsAbBooleanExpression.cpp \
nsAbDirectoryRDFResource.cpp \
nsAbQueryStringToExpression.cpp \
$(NULL)
EXPORTS = \
@ -73,8 +82,33 @@ EXPORTS = \
nsAbMDBCardProperty.h \
nsAbMDBCard.h \
nsAbBSDirectory.h \
nsAbDirFactoryService.h \
nsAbMDBDirFactory.h \
nsAbDirectoryQuery.h \
nsAbDirectoryQueryProxy.h \
nsAbDirSearchListener.h \
nsAbBooleanExpression.h \
nsAbDirectoryRDFResource.h \
$(NULL)
ifdef MOZ_LDAP_XPCOM
REQUIRES += mozldap
EXPORTS += nsAbLDAPDirectoryQuery.h \
nsAbLDAPDirectory.h \
nsAbLDAPDirFactory.h \
nsAbLDAPCard.h \
$(NULL)
CPPSRCS += nsAbLDAPDirectory.cpp \
nsAbLDAPDirFactory.cpp \
nsAbLDAPCard.cpp \
nsAbLDAPProperties.cpp \
nsAbLDAPDirectoryQuery.cpp \
nsAbBoolExprToLDAPFilter.cpp \
$(NULL)
endif
# we don't want the shared lib, but we want to force the creation of a static lib.
FORCE_STATIC_LIB = 1

View File

@ -46,7 +46,23 @@ EXPORTS= \
nsAbMDBCardProperty.h \
nsAbMDBCard.h \
nsAbBSDirectory.h \
nsAbOutlookDirFactory.h \
nsAbDirFactoryService.h \
nsAddbookUrl.h \
nsAbOutlookDirectory.h \
nsAbOutlookCard.h \
nsAbMDBDirFactory.h \
nsAbDirectoryQuery.h \
nsAbDirectoryQueryProxy.h \
nsAbDirSearchListener.h \
!if !defined(DISABLE_LDAP)
nsAbLDAPDirectoryQuery.h \
nsAbLDAPDirectory.h \
nsAbLDAPDirFactory.h \
nsAbLDAPCard.h \
!endif
nsAbDirectoryRDFResource.h \
nsAbBooleanExpression.h \
$(NULL)
################################################################################
@ -74,6 +90,27 @@ CPP_OBJS= \
.\$(OBJDIR)\nsAbMDBCard.obj \
.\$(OBJDIR)\nsAbBSDirectory.obj \
.\$(OBJDIR)\nsAddbookUrl.obj \
.\$(OBJDIR)\nsAbDirFactoryService.obj \
.\$(OBJDIR)\nsAbMDBDirFactory.obj \
.\$(OBJDIR)\nsAbOutlookDirectory.obj \
.\$(OBJDIR)\nsAbOutlookCard.obj \
.\$(OBJDIR)\nsAbOutlookDirFactory.obj \
.\$(OBJDIR)\nsMapiAddressBook.obj \
.\$(OBJDIR)\nsAbUtils.obj \
.\$(OBJDIR)\nsAbDirectoryQuery.obj \
.\$(OBJDIR)\nsAbDirectoryQueryProxy.obj \
.\$(OBJDIR)\nsAbDirSearchListener.obj \
!if !defined(DISABLE_LDAP)
.\$(OBJDIR)\nsAbLDAPDirectory.obj \
.\$(OBJDIR)\nsAbLDAPDirFactory.obj \
.\$(OBJDIR)\nsAbLDAPCard.obj \
.\$(OBJDIR)\nsAbLDAPProperties.obj \
.\$(OBJDIR)\nsAbLDAPDirectoryQuery.obj \
.\$(OBJDIR)\nsAbBoolExprToLDAPFilter.obj \
!endif
.\$(OBJDIR)\nsAbBooleanExpression.obj \
.\$(OBJDIR)\nsAbDirectoryRDFResource.obj \
.\$(OBJDIR)\nsAbQueryStringToExpression.obj \
$(NULL)
include <$(DEPTH)\config\rules.mak>

View File

@ -14,17 +14,18 @@
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s): Paul Sandoz
* Contributor(s): Paul Sandoz <paul.sandoz@sun.com>
* Csaba Borbola <csaba.borbola@sun.com>
*/
#include "nsAbBSDirectory.h"
#include "nsAbUtils.h"
#include "nsRDFCID.h"
#include "nsIRDFService.h"
#include "nsIRDFResource.h"
#include "nsDirPrefs.h"
#include "nsAbBaseCID.h"
@ -33,14 +34,16 @@
#include "nsAddrDatabase.h"
#include "nsIAddrBookSession.h"
#include "nsIAbMDBDirectory.h"
#include "nsHashtable.h"
#include "nsIAbUpgrader.h"
#include "nsIMessengerMigrator.h"
#include "nsAbDirFactoryService.h"
#include "nsAbMDBDirFactory.h"
#include "prmem.h"
#include "prprf.h"
static NS_DEFINE_CID(kRDFServiceCID, NS_RDFSERVICE_CID);
static NS_DEFINE_CID(kAddrBookCID, NS_ADDRESSBOOK_CID);
@ -48,6 +51,11 @@ static NS_DEFINE_CID(kAddressBookDBCID, NS_ADDRDATABASE_CID);
static NS_DEFINE_CID(kAddrBookSessionCID, NS_ADDRBOOKSESSION_CID);
static NS_DEFINE_CID(kMessengerMigratorCID, NS_MESSENGERMIGRATOR_CID);
const char* kDescriptionPropertyName = "description";
const char* kFileNamePropertyName = "filename";
const char* kURIPropertyName = "uri";
const char* kMigratingPropertyName = "migrating";
nsAbBSDirectory::nsAbBSDirectory()
: nsRDFResource(),
mInitialized(PR_FALSE),
@ -71,30 +79,6 @@ nsAbBSDirectory::~nsAbBSDirectory()
NS_IMPL_ISUPPORTS_INHERITED(nsAbBSDirectory, nsRDFResource, nsIAbDirectory)
nsresult nsAbBSDirectory::AddDirectory(const char *uriName, nsIAbDirectory **childDir)
{
if (!childDir || !uriName)
return NS_ERROR_NULL_POINTER;
nsresult rv = NS_OK;
nsCOMPtr<nsIRDFService> rdf(do_GetService(kRDFServiceCID, &rv));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIRDFResource> res;
rv = rdf->GetResource(uriName, getter_AddRefs(res));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAbDirectory> directory(do_QueryInterface(res, &rv));
NS_ENSURE_SUCCESS(rv, rv);
mSubDirectories->AppendElement(directory);
*childDir = directory;
NS_IF_ADDREF(*childDir);
return rv;
}
nsresult nsAbBSDirectory::NotifyItemAdded(nsISupports *item)
{
nsresult rv = NS_OK;
@ -116,186 +100,253 @@ nsresult nsAbBSDirectory::NotifyItemDeleted(nsISupports *item)
return NS_OK;
}
nsresult nsAbBSDirectory::CreateDirectoriesFromFactory(
const char* URI,
DIR_Server* server,
PRUint32 propertiesSize,
const char** propertyNameArray,
const PRUnichar** propertyValueArray,
PRBool notify)
{
nsresult rv;
// Get the directory factory service
nsCOMPtr<nsIAbDirFactoryService> dirFactoryService =
do_GetService(NS_ABDIRFACTORYSERVICE_CONTRACTID,&rv);
NS_ENSURE_SUCCESS (rv, rv);
// Get the directory factory from the URI
nsCOMPtr<nsIAbDirFactory> dirFactory;
rv = dirFactoryService->GetDirFactory (URI, getter_AddRefs(dirFactory));
NS_ENSURE_SUCCESS (rv, rv);
// Create the directories
nsCOMPtr<nsISimpleEnumerator> newDirEnumerator;
rv = dirFactory->CreateDirectory(propertiesSize,
propertyNameArray,
propertyValueArray,
getter_AddRefs(newDirEnumerator));
NS_ENSURE_SUCCESS (rv, rv);
// Enumerate through the directories adding them
// to the sub directories array
PRBool hasMore;
while (NS_SUCCEEDED(newDirEnumerator->HasMoreElements(&hasMore)) && hasMore)
{
nsCOMPtr<nsISupports> newDirSupports;
rv = newDirEnumerator->GetNext(getter_AddRefs(newDirSupports));
if(NS_FAILED(rv))
continue;
nsCOMPtr<nsIAbDirectory> childDir = do_QueryInterface(newDirSupports, &rv);
if(NS_FAILED(rv))
continue;
// Define realtion ship between the preference
// entry and the directory
nsVoidKey key((void *)childDir);
mServers.Put (&key, (void *)server);
mSubDirectories->AppendElement(childDir);
// Inform the listener, i.e. the RDF directory data
// source that a new address book has been added
if (notify == PR_TRUE)
NotifyItemAdded(childDir);
}
return NS_OK;
}
NS_IMETHODIMP nsAbBSDirectory::GetChildNodes(nsIEnumerator* *result)
{
if (!mInitialized)
{/*
nsresult rv;
nsCOMPtr <nsIAbUpgrader> abUpgrader = do_GetService(NS_AB4xUPGRADER_CONTRACTID, &rv);
if (NS_SUCCEEDED(rv) && abUpgrader)
{
nsCOMPtr <nsIMessengerMigrator> migrator = do_GetService(kMessengerMigratorCID, &rv);
if (NS_SUCCEEDED(rv) || migrator)
migrator->UpgradePrefs();
}*/
{
nsresult rv;
nsCOMPtr<nsIAbDirFactoryService> dirFactoryService =
do_GetService(NS_ABDIRFACTORYSERVICE_CONTRACTID,&rv);
NS_ENSURE_SUCCESS (rv, rv);
if (!PL_strcmp(mURI, kAllDirectoryRoot) && GetDirList())
if (!GetDirList())
return NS_ERROR_FAILURE;
PRInt32 count = GetDirList()->Count();
for (PRInt32 i = 0; i < count; i++)
{
PRInt32 count = GetDirList()->Count();
/* check: only show personal address book for now */
/* not showing 4.x address book unitl we have the converting done */
PRInt32 i;
for (i = 0; i < count; i++)
DIR_Server *server = (DIR_Server *)GetDirList()->ElementAt(i);
NS_ConvertUTF8toUCS2 fileName (server->fileName);
PRInt32 pos = fileName.Find("na2");
if (pos >= 0) // check: this is a 4.x file, remove when conversion is done
continue;
nsHashtable propertySet;
// Set the description property
nsCStringKey descriptionKey (kDescriptionPropertyName, -1, nsCStringKey::NEVER_OWN);
NS_ConvertUTF8toUCS2 description (server->description);
propertySet.Put (&descriptionKey, (void* )description.get ());
// Set the file name property
nsCStringKey fileNameKey (kFileNamePropertyName, -1, nsCStringKey::NEVER_OWN);
propertySet.Put (&fileNameKey, (void* )fileName.get ());
// Set the uri property
nsCStringKey URIKey (kURIPropertyName, -1, nsCStringKey::NEVER_OWN);
nsCAutoString URIUTF8 (server->uri);
// This is in case the uri is never set
// in the nsDirPref.cpp code.
if (!server->uri)
{
DIR_Server *server = (DIR_Server *)GetDirList()->ElementAt(i);
if (server->dirType == PABDirectory)
{
nsAutoString name; name.AssignWithConversion(server->fileName);
PRInt32 pos = name.Find("na2");
if (pos >= 0) /* check: this is a 4.x file, remove when conversion is done */
continue;
char* uriStr = nsnull;
uriStr = PR_smprintf("%s%s", kMDBDirectoryRoot, server->fileName);
if (uriStr == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
nsCOMPtr<nsIAbDirectory> childDir;
AddDirectory(uriStr, getter_AddRefs(childDir));
nsCOMPtr<nsIAbMDBDirectory> dbchildDir(do_QueryInterface(childDir));
if (uriStr)
PR_smprintf_free(uriStr);
if (childDir)
{
PRUnichar *unichars = nsnull;
PRInt32 descLength = PL_strlen(server->description);
INTL_ConvertToUnicode((const char *)server->description,
descLength, (void**)&unichars);
childDir->SetDirName(unichars);
PR_FREEIF(unichars);
nsVoidKey key((void *)childDir);
mServers.Put (&key, (void *)server);
}
nsresult rv = NS_OK;
nsCOMPtr<nsIAddrDatabase> listDatabase;
nsCOMPtr<nsIAddrBookSession> abSession =
do_GetService(kAddrBookSessionCID, &rv);
if (NS_SUCCEEDED(rv))
{
nsFileSpec* dbPath;
abSession->GetUserProfileDirectory(&dbPath);
nsAutoString file; file.AssignWithConversion(server->fileName);
(*dbPath) += file;
nsCOMPtr<nsIAddrDatabase> addrDBFactory =
do_GetService(kAddressBookDBCID, &rv);
if (NS_SUCCEEDED(rv) && addrDBFactory)
rv = addrDBFactory->Open(dbPath, PR_TRUE, getter_AddRefs(listDatabase), PR_TRUE);
if (NS_SUCCEEDED(rv) && listDatabase)
{
listDatabase->GetMailingListsFromDB(childDir);
}
delete dbPath;
}
}
URIUTF8 = kMDBDirectoryRoot;
URIUTF8.Append (server->fileName);
}
/*
* Check that we are not converting from a
* a 4.x address book file e.g. pab.na2
*/
nsCAutoString uriName (URIUTF8.get());
pos = uriName.Find("na2");
if (pos >= 0)
{
const char* tempFileName = nsnull;
const char* uri = URIUTF8.get ();
if (PL_strstr(uri, kMDBDirectoryRoot)) // for moz-abmdbdirectory://
{
tempFileName = &(uri[PL_strlen(kMDBDirectoryRoot)]);
uriName.ReplaceSubstring (tempFileName,server->fileName);
}
}
NS_ConvertUTF8toUCS2 URIUCS2 (uriName.get ());
propertySet.Put (&URIKey, (void* )URIUCS2.get ());
// Convert the hastable (property set) to pointer
// arrays, using the array guards
CharPtrArrayGuard factoryPropertyNames (PR_FALSE);
PRUnicharPtrArrayGuard factoryPropertyValues (PR_FALSE);
HashtableToPropertyPtrArrays::Convert (propertySet,
factoryPropertyNames.GetSizeAddr (),
factoryPropertyNames.GetArrayAddr (),
factoryPropertyValues.GetArrayAddr ());
*(factoryPropertyNames.GetSizeAddr ()) = factoryPropertyNames.GetSize ();
// Create the directories
rv = CreateDirectoriesFromFactory (uriName.get (),
server,
factoryPropertyNames.GetSize (),
factoryPropertyNames.GetArray(),
factoryPropertyValues.GetArray(),
PR_FALSE);
}
mInitialized = PR_TRUE;
}
return mSubDirectories->Enumerate(result);
}
NS_IMETHODIMP nsAbBSDirectory::CreateNewDirectory(PRUint32 prefCount, const char **prefName, const PRUnichar **prefValue)
nsresult nsAbBSDirectory::CreateNewDirectory(nsHashtable &propertySet, const char *uri, DIR_Server* server)
{
if (!*prefValue || !*prefName)
return NS_ERROR_NULL_POINTER;
PRUnichar *unicharDescription = nsnull;
char *charFileName = nsnull;
PRBool migrating = PR_FALSE;
char *charMigrate = nsnull;
nsresult rv;
for (PRUint32 jk=0; jk < prefCount; jk++)
{
switch (tolower(prefName[jk][0]))
{
case 'd':
if (!nsCRT::strcasecmp(prefName[jk], "description"))
{
unicharDescription = (PRUnichar *)prefValue[jk];
}
break;
case 'f':
if (!nsCRT::strcasecmp(prefName[jk], "fileName"))
{
nsString descString(prefValue[jk]);
PRInt32 unicharLength = descString.Length();
INTL_ConvertFromUnicode(prefValue[jk], unicharLength, &charFileName);
}
break;
case 'm':
if (!nsCRT::strcasecmp(prefName[jk], "migrating"))
{
nsString descString(prefValue[jk]);
PRInt32 unicharLength = descString.Length();
INTL_ConvertFromUnicode(prefValue[jk], unicharLength, &charMigrate);
if (!nsCRT::strcasecmp(charMigrate, "true"))
{
migrating = PR_TRUE;
}
}
break;
}
}
// Convert the hastable (property set) to pointer
// arrays, using the array guards
// This is done because the original hashtable
// has been modified (added the uri and changed
// the file name)
CharPtrArrayGuard factoryPropertyNames (PR_FALSE);
PRUnicharPtrArrayGuard factoryPropertyValues (PR_FALSE);
HashtableToPropertyPtrArrays::Convert (propertySet,
factoryPropertyNames.GetSizeAddr (),
factoryPropertyNames.GetArrayAddr (),
factoryPropertyValues.GetArrayAddr ());
*(factoryPropertyNames.GetSizeAddr ()) = factoryPropertyNames.GetSize ();
if (unicharDescription == nsnull)
{
rv = NS_ERROR_NULL_POINTER;
}
else
{
rv = CreateDirectoryPAB(unicharDescription, charFileName, migrating);
}
if (charFileName)
nsMemory::Free(charFileName);
if (charMigrate)
nsMemory::Free(charMigrate);
// Create the directories
rv = CreateDirectoriesFromFactory (uri,
server,
factoryPropertyNames.GetSize (),
factoryPropertyNames.GetArray(),
factoryPropertyValues.GetArray());
return rv;
}
nsresult nsAbBSDirectory::CreateDirectoryPAB(const PRUnichar *displayName, const char *fileName, PRBool migrating)
NS_IMETHODIMP nsAbBSDirectory::CreateNewDirectory(PRUint32 propCount, const char **propName, const PRUnichar **propValue)
{
if (!displayName )
{
return NS_ERROR_NULL_POINTER;
}
/*
* TODO
* This procedure is still MDB specific
* due to the dependence on the current
* nsDirPref.cpp code
*
*/
DIR_Server * server = nsnull;
DirectoryType dirType = PABDirectory;
if (!propValue || !propName)
return NS_ERROR_NULL_POINTER;
DIR_AddNewAddressBook(displayName, fileName, migrating, dirType, &server);
if (propCount == 0)
return NS_ERROR_FAILURE;
char *uri = PR_smprintf("%s%s",kMDBDirectoryRoot, server->fileName);
nsresult rv;
nsCOMPtr<nsIAbDirectory> newDir;
nsresult rv = AddDirectory(uri, getter_AddRefs(newDir));
// Create hash table from property arrays
nsHashtable propertySet;
rv = PropertyPtrArraysToHashtable::Convert (propertySet, propCount, propName, propValue);
NS_ENSURE_SUCCESS (rv, rv);
if (uri)
PR_smprintf_free(uri);
if (NS_SUCCEEDED(rv) && newDir)
{
newDir->SetDirName((PRUnichar *)displayName);
nsVoidKey key((void *)newDir);
mServers.Put (&key, (void *)server);
NotifyItemAdded(newDir);
return NS_OK;
}
else
return NS_ERROR_FAILURE;
// Get description property
nsCStringKey descriptionKey (kDescriptionPropertyName, -1, nsCStringKey::NEVER_OWN);
const PRUnichar* description = (PRUnichar* )propertySet.Get (&descriptionKey);
// Get file name property
nsCStringKey fileNameKey (kFileNamePropertyName, -1, nsCStringKey::NEVER_OWN);
const PRUnichar* fileName = (PRUnichar* )propertySet.Get (&fileNameKey);
NS_ConvertUCS2toUTF8 fileNameUTF8(fileName);
// Get migrating property
nsCStringKey migratingKey (kMigratingPropertyName, -1, nsCStringKey::NEVER_OWN);
const PRUnichar* migrating = (PRUnichar* )propertySet.Get (&migratingKey);
PRBool is_migrating = PR_FALSE;
if (migrating && nsCRT::strcmp (migrating, "true"))
is_migrating = PR_TRUE;
/*
* The creation of the address book in the preferences
* is very MDB implementation specific.
* If the fileName attribute is null then it will
* create an appropriate file name.
* Somehow have to resolve this issue so that it
* is more general.
*
*/
DIR_Server* server = nsnull;
rv = DIR_AddNewAddressBook(description,
(fileNameUTF8.Length ()) ? fileNameUTF8.get () : nsnull,
is_migrating,
PABDirectory,
&server);
NS_ENSURE_SUCCESS (rv, rv);
// Update the file name property
NS_ConvertUTF8toUCS2 fileNameUCS2(server->fileName);
propertySet.Put (&fileNameKey, (void* )fileNameUCS2.get ());
// Add the URI property
nsAutoString URI;
URI.AssignWithConversion (kMDBDirectoryRoot);
URI.Append (fileNameUCS2);
nsCStringKey URIKey (kURIPropertyName, -1, nsCStringKey::NEVER_OWN);
propertySet.Put (&URIKey, (void* )URI.get ());
// Get the directory factory from the URI
NS_ConvertUCS2toUTF8 URIUTF8(URI);
rv = CreateNewDirectory (propertySet, URIUTF8.get (), server);
return rv;
}
NS_IMETHODIMP nsAbBSDirectory::CreateDirectoryByURI(const PRUnichar *displayName, const char *uri, PRBool migrating)
@ -303,29 +354,65 @@ NS_IMETHODIMP nsAbBSDirectory::CreateDirectoryByURI(const PRUnichar *displayName
if (!displayName || !uri)
return NS_ERROR_NULL_POINTER;
nsresult rv = NS_OK;
const char* fileName = nsnull;
if (PL_strstr(uri, kMDBDirectoryRoot)) // for moz-abmdbdirectory://
fileName = &(uri[nsCRT::strlen(kMDBDirectoryRoot)]);
DIR_Server * server = nsnull;
DirectoryType dirType = PABDirectory;
const char* fileName = nsnull;
if (PL_strstr(uri, kMDBDirectoryRoot)) // for abmdbdirectory://
{
fileName = &(uri[PL_strlen(kMDBDirectoryRoot)]);
dirType = PABDirectory;
}
DIR_AddNewAddressBook(displayName, fileName, migrating, dirType, &server);
rv = DIR_AddNewAddressBook(displayName, fileName, migrating, PABDirectory, &server);
NS_ENSURE_SUCCESS(rv,rv);
nsCOMPtr<nsIAbDirectory> newDir;
nsresult rv = AddDirectory(uri, getter_AddRefs(newDir));
if (NS_SUCCEEDED(rv) && newDir)
nsHashtable propertySet;
// Set the description property
nsCStringKey descriptionKey (kDescriptionPropertyName, -1, nsCStringKey::NEVER_OWN);
propertySet.Put (&descriptionKey, (void* )displayName);
// Set the file name property
nsCStringKey fileNameKey (kFileNamePropertyName, -1, nsCStringKey::NEVER_OWN);
NS_ConvertUTF8toUCS2 fileNameUCS2 (server->fileName);
propertySet.Put (&fileNameKey, (void* )fileNameUCS2.get ());
// Set the uri property
nsCStringKey URIKey (kURIPropertyName, -1, nsCStringKey::NEVER_OWN);
NS_ConvertUTF8toUCS2 URIUCS2 (uri);
propertySet.Put (&URIKey, (void* )URIUCS2.get ());
rv = CreateNewDirectory (propertySet, uri, server);
return rv;
}
struct GetDirectories
{
GetDirectories (DIR_Server* aServer) :
mServer (aServer)
{
NS_NewISupportsArray(getter_AddRefs(directories));
}
nsCOMPtr<nsISupportsArray> directories;
DIR_Server* mServer;
};
PRBool GetDirectories_getDirectory (nsHashKey *aKey, void *aData, void* closure)
{
GetDirectories* getDirectories = (GetDirectories* )closure;
DIR_Server* server = (DIR_Server*) aData;
if (server == getDirectories->mServer)
{
newDir->SetDirName((PRUnichar *)displayName);
nsVoidKey key((void *)newDir);
mServers.Put (&key, (void *)server);
NotifyItemAdded(newDir);
return NS_OK;
nsVoidKey* voidKey = (nsVoidKey* )aKey;
nsIAbDirectory* directory = (nsIAbDirectory* )voidKey->GetValue ();
getDirectories->directories->AppendElement (directory);
}
else
return NS_ERROR_FAILURE;
return PR_TRUE;
}
NS_IMETHODIMP nsAbBSDirectory::DeleteDirectory(nsIAbDirectory *directory)
@ -333,51 +420,51 @@ NS_IMETHODIMP nsAbBSDirectory::DeleteDirectory(nsIAbDirectory *directory)
nsresult rv = NS_OK;
if (!directory)
return NS_ERROR_FAILURE;
nsCOMPtr<nsIAbMDBDirectory> dbdirectory(do_QueryInterface(directory, &rv));
NS_ENSURE_SUCCESS(rv, rv);
return NS_ERROR_NULL_POINTER;
DIR_Server *server = nsnull;
nsVoidKey key((void *)directory);
server = (DIR_Server* )mServers.Get (&key);
if (server)
{ //it's an address book
if (!server)
return NS_ERROR_FAILURE;
nsISupportsArray* pAddressLists;
directory->GetAddressLists(&pAddressLists);
if (pAddressLists)
{ //remove mailing list node
PRUint32 total;
rv = pAddressLists->Count(&total);
if (total)
{
PRInt32 i;
for (i = total - 1; i >= 0; i--)
{
nsCOMPtr<nsISupports> pSupport = getter_AddRefs(pAddressLists->ElementAt(i));
if (pSupport)
{
nsCOMPtr<nsIAbDirectory> listDir(do_QueryInterface(pSupport, &rv));
nsCOMPtr<nsIAbMDBDirectory> dblistDir(do_QueryInterface(pSupport, &rv));
if (listDir && dblistDir)
{
directory->DeleteDirectory(listDir);
dblistDir->RemoveElementsFromAddressList();
}
}
pAddressLists->RemoveElement(pSupport);
}
}
}
DIR_DeleteServerFromList(server);
mServers.Remove(&key);
dbdirectory->ClearDatabase();
GetDirectories getDirectories (server);
mServers.Enumerate (GetDirectories_getDirectory, (void *)&getDirectories);
rv = mSubDirectories->RemoveElement(directory);
NotifyItemDeleted(directory);
DIR_DeleteServerFromList(server);
nsCOMPtr<nsIAbDirFactoryService> dirFactoryService =
do_GetService(NS_ABDIRFACTORYSERVICE_CONTRACTID,&rv);
NS_ENSURE_SUCCESS (rv, rv);
PRUint32 count;
rv = getDirectories.directories->Count (&count);
NS_ENSURE_SUCCESS(rv, rv);
for (PRUint32 i = 0; i < count; i++)
{
nsCOMPtr<nsIAbDirectory> d;
getDirectories.directories->GetElementAt (i, getter_AddRefs(d));
nsVoidKey k((void *)d);
mServers.Remove(&k);
rv = mSubDirectories->RemoveElement(d);
NotifyItemDeleted(d);
nsCOMPtr<nsIRDFResource> resource (do_QueryInterface (d, &rv));
const char* uri;
resource->GetValueConst (&uri);
nsCOMPtr<nsIAbDirFactory> dirFactory;
rv = dirFactoryService->GetDirFactory (uri, getter_AddRefs(dirFactory));
if (NS_FAILED(rv))
continue;
rv = dirFactory->DeleteDirectory(d);
}
return rv;
}

View File

@ -14,7 +14,7 @@
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s): Paul Sandoz
@ -26,8 +26,8 @@
#include "nsRDFResource.h"
#include "nsAbDirProperty.h"
#include "nsHashtable.h"
#include "nsHashtable.h"
#include "nsISupportsArray.h"
class nsAbBSDirectory : public nsRDFResource, public nsAbDirProperty
@ -52,7 +52,17 @@ protected:
nsresult NotifyItemAdded(nsISupports *item);
nsresult NotifyItemDeleted(nsISupports *item);
nsresult CreateDirectoryPAB(const PRUnichar *displayName, const char *fileName, PRBool migrating);
nsresult CreateDirectoriesFromFactory(
const char* URI,
DIR_Server* server,
PRUint32 propertiesSize,
const char** propertyNameArray,
const PRUnichar** propertyValueArray,
PRBool notify = PR_TRUE);
nsresult CreateNewDirectory(nsHashtable &propertySet,
const char *uri,
DIR_Server* server);
protected:
PRBool mInitialized;

View File

@ -0,0 +1,253 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#include "nsAbBoolExprToLDAPFilter.h"
#include "nsAbLDAPProperties.h"
#include "nsXPIDLString.h"
const int nsAbBoolExprToLDAPFilter::TRANSLATE_CARD_PROPERTY = 1 << 0 ;
const int nsAbBoolExprToLDAPFilter::ALLOW_NON_CONVERTABLE_CARD_PROPERTY = 1 << 1 ;
nsresult nsAbBoolExprToLDAPFilter::Convert (
nsIAbBooleanExpression* expression,
nsCString& filter,
int flags)
{
nsresult rv;
nsCString f;
rv = FilterExpression (expression, f, flags);
NS_ENSURE_SUCCESS(rv, rv);
filter = f;
return rv;
}
nsresult nsAbBoolExprToLDAPFilter::FilterExpression (
nsIAbBooleanExpression* expression,
nsCString& filter,
int flags)
{
nsresult rv;
nsAbBooleanOperationType operation;
rv = expression->GetOperation (&operation);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsISupportsArray> childExpressions;
rv = expression->GetExpressions (getter_AddRefs (childExpressions));
NS_ENSURE_SUCCESS(rv, rv);
PRUint32 count;
rv = childExpressions->Count (&count);
NS_ENSURE_SUCCESS(rv, rv);
if (count == 0)
return NS_OK;
filter.Append ("(");
switch (operation)
{
case nsIAbBooleanOperationTypes::AND:
filter.Append ("&");
rv = FilterExpressions (childExpressions, filter, flags);
break;
case nsIAbBooleanOperationTypes::OR:
filter.Append ("|");
rv = FilterExpressions (childExpressions, filter, flags);
break;
case nsIAbBooleanOperationTypes::NOT:
if (count > 1)
return NS_ERROR_FAILURE;
filter.Append ("!");
rv = FilterExpressions (childExpressions, filter, flags);
break;
default:
break;
}
filter.Append (")");
return rv;
}
nsresult nsAbBoolExprToLDAPFilter::FilterExpressions (
nsISupportsArray* expressions,
nsCString& filter,
int flags)
{
nsresult rv;
PRUint32 count;
rv = expressions->Count (&count);
NS_ENSURE_SUCCESS(rv, rv);
for (PRUint32 i = 0; i < count; i++)
{
nsCOMPtr<nsISupports> item;
rv = expressions->GetElementAt (i, getter_AddRefs (item));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAbBooleanConditionString> childCondition(do_QueryInterface(item, &rv));
if (NS_SUCCEEDED(rv))
{
rv = FilterCondition (childCondition, filter, flags);
NS_ENSURE_SUCCESS(rv, rv);
continue;
}
nsCOMPtr<nsIAbBooleanExpression> childExpression(do_QueryInterface(item, &rv));
if (NS_SUCCEEDED(rv))
{
rv = FilterExpression (childExpression, filter, flags);
NS_ENSURE_SUCCESS(rv, rv);
continue;
}
}
return rv;
}
nsresult nsAbBoolExprToLDAPFilter::FilterCondition (
nsIAbBooleanConditionString* condition,
nsCString& filter,
int flags)
{
nsresult rv;
nsAbBooleanConditionType conditionType;
rv = condition->GetCondition (&conditionType);
NS_ENSURE_SUCCESS(rv, rv);
nsXPIDLCString name;
rv = condition->GetName (getter_Copies (name));
NS_ENSURE_SUCCESS(rv, rv);
const char* ldapProperty = name.get ();
if (flags & TRANSLATE_CARD_PROPERTY)
{
const MozillaLdapPropertyRelation* p =
MozillaLdapPropertyRelator::findLdapPropertyFromMozilla (name.get ());
if (p)
ldapProperty = p->ldapProperty;
else if (!(flags & ALLOW_NON_CONVERTABLE_CARD_PROPERTY))
return NS_OK;
}
nsXPIDLString value;
rv = condition->GetValue (getter_Copies (value));
NS_ENSURE_SUCCESS(rv, rv);
NS_ConvertUCS2toUTF8 vUTF8 (value);
switch (conditionType)
{
case nsIAbBooleanConditionTypes::DoesNotExist:
filter.Append ("(!(");
filter.Append (ldapProperty);
filter.Append ("=*");
filter.Append ("))");
break;
case nsIAbBooleanConditionTypes::Exists:
filter.Append ("(");
filter.Append (ldapProperty);
filter.Append ("=*");
filter.Append (")");
break;
case nsIAbBooleanConditionTypes::Contains:
filter.Append ("(");
filter.Append (ldapProperty);
filter.Append ("=");
filter.Append ("*");
filter.Append (vUTF8);
filter.Append ("*");
filter.Append (")");
break;
case nsIAbBooleanConditionTypes::DoesNotContain:
filter.Append ("(!(");
filter.Append (ldapProperty);
filter.Append ("=");
filter.Append ("*");
filter.Append (vUTF8);
filter.Append ("*");
filter.Append ("))");
break;
case nsIAbBooleanConditionTypes::Is:
filter.Append ("(");
filter.Append (ldapProperty);
filter.Append ("=");
filter.Append (vUTF8);
filter.Append (")");
break;
case nsIAbBooleanConditionTypes::IsNot:
filter.Append ("(!(");
filter.Append (ldapProperty);
filter.Append ("=");
filter.Append (vUTF8);
filter.Append ("))");
break;
case nsIAbBooleanConditionTypes::BeginsWith:
filter.Append ("(");
filter.Append (ldapProperty);
filter.Append ("=");
filter.Append (vUTF8);
filter.Append ("*");
filter.Append (")");
break;
case nsIAbBooleanConditionTypes::EndsWith:
filter.Append ("(");
filter.Append (ldapProperty);
filter.Append ("=");
filter.Append ("*");
filter.Append (vUTF8);
filter.Append (")");
break;
case nsIAbBooleanConditionTypes::LessThan:
filter.Append ("(");
filter.Append (ldapProperty);
filter.Append ("<=");
filter.Append (vUTF8);
filter.Append (")");
break;
case nsIAbBooleanConditionTypes::GreaterThan:
filter.Append ("(");
filter.Append (ldapProperty);
filter.Append (">=");
filter.Append (vUTF8);
filter.Append (")");
break;
case nsIAbBooleanConditionTypes::SoundsLike:
filter.Append ("(");
filter.Append (ldapProperty);
filter.Append ("~=");
filter.Append (vUTF8);
filter.Append (")");
break;
case nsIAbBooleanConditionTypes::RegExp:
break;
default:
break;
}
return rv;
}

View File

@ -0,0 +1,58 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#ifndef nsBooleanExpressionToLDAPFilter_h__
#define nsBooleanExpressionToLDAPFilter_h__
#include "nsIAbBooleanExpression.h"
#include "nsCOMPtr.h"
#include "nsString.h"
class nsAbBoolExprToLDAPFilter
{
public:
static const int TRANSLATE_CARD_PROPERTY ;
static const int ALLOW_NON_CONVERTABLE_CARD_PROPERTY ;
static nsresult Convert (
nsIAbBooleanExpression* expression,
nsCString& filter,
int flags = TRANSLATE_CARD_PROPERTY);
protected:
static nsresult FilterExpression (
nsIAbBooleanExpression* expression,
nsCString& filter,
int flags);
static nsresult FilterExpressions (
nsISupportsArray* expressions,
nsCString& filter,
int flags);
static nsresult FilterCondition (
nsIAbBooleanConditionString* condition,
nsCString& filter,
int flags);
};
#endif

View File

@ -0,0 +1,216 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#include "nsAbBooleanExpression.h"
NS_IMPL_THREADSAFE_ISUPPORTS1(nsAbBooleanConditionString, nsIAbBooleanConditionString)
nsAbBooleanConditionString::nsAbBooleanConditionString() :
mCondition (nsIAbBooleanConditionTypes::Exists)
{
NS_INIT_ISUPPORTS();
}
nsAbBooleanConditionString::~nsAbBooleanConditionString()
{
}
/* attribute nsAbBooleanConditionType condition; */
NS_IMETHODIMP nsAbBooleanConditionString::GetCondition(nsAbBooleanConditionType *aCondition)
{
if (!aCondition)
return NS_ERROR_NULL_POINTER;
*aCondition = mCondition;
return NS_OK;
}
NS_IMETHODIMP nsAbBooleanConditionString::SetCondition(nsAbBooleanConditionType aCondition)
{
mCondition = aCondition;
return NS_OK;
}
/* attribute string name; */
NS_IMETHODIMP nsAbBooleanConditionString::GetName(char** aName)
{
if (!aName)
return NS_ERROR_NULL_POINTER;
const char* value = mName.get ();
if (!value)
*aName = 0;
else
*aName = mName.ToNewCString ();
return NS_OK;
}
NS_IMETHODIMP nsAbBooleanConditionString::SetName(const char* aName)
{
if (!aName)
return NS_ERROR_NULL_POINTER;
mName = aName;
return NS_OK;
}
/* attribute wstring value; */
NS_IMETHODIMP nsAbBooleanConditionString::GetValue(PRUnichar** aValue)
{
if (!aValue)
return NS_ERROR_NULL_POINTER;
*aValue = mValue.ToNewUnicode();
return NS_OK;
}
NS_IMETHODIMP nsAbBooleanConditionString::SetValue(const PRUnichar * aValue)
{
if (!aValue)
return NS_ERROR_NULL_POINTER;
mValue = aValue;
return NS_OK;
}
NS_METHOD nsAbBooleanConditionString::Create(nsISupports* aOuter, REFNSIID aIID, void* *aResult)
{
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsAbBooleanConditionString* it = new nsAbBooleanConditionString ();
if (it == NULL)
return NS_ERROR_OUT_OF_MEMORY;
NS_IF_ADDREF(it);
nsresult rv = it->QueryInterface(aIID, aResult);
NS_RELEASE(it);
return rv;
}
nsresult NS_NewIAbBooleanConditionString(nsIAbBooleanConditionString** aInstancePtrResult)
{
nsresult rv;
rv = nsAbBooleanConditionString::Create(NULL, NS_GET_IID(nsIAbBooleanConditionString), NS_REINTERPRET_CAST(void**,aInstancePtrResult));
return rv;
}
NS_IMPL_THREADSAFE_ISUPPORTS1(nsAbBooleanExpression, nsIAbBooleanExpression)
nsAbBooleanExpression::nsAbBooleanExpression() :
mOperation (nsIAbBooleanOperationTypes::AND)
{
NS_INIT_ISUPPORTS();
}
nsAbBooleanExpression::~nsAbBooleanExpression()
{
}
/* attribute nsAbBooleanOperationType operation; */
NS_IMETHODIMP nsAbBooleanExpression::GetOperation(nsAbBooleanOperationType *aOperation)
{
if (!aOperation)
return NS_ERROR_NULL_POINTER;
*aOperation = mOperation;
return NS_OK;
}
NS_IMETHODIMP nsAbBooleanExpression::SetOperation(nsAbBooleanOperationType aOperation)
{
mOperation = aOperation;
return NS_OK;
}
/* attribute nsISupportsArray expressions; */
NS_IMETHODIMP nsAbBooleanExpression::GetExpressions(nsISupportsArray** aExpressions)
{
if (!aExpressions)
return NS_ERROR_NULL_POINTER;
if (!mExpressions)
NS_NewISupportsArray(getter_AddRefs(mExpressions));
*aExpressions = mExpressions;
NS_IF_ADDREF(*aExpressions);
return NS_OK;
}
NS_IMETHODIMP nsAbBooleanExpression::SetExpressions(nsISupportsArray* aExpressions)
{
if (!aExpressions)
return NS_ERROR_NULL_POINTER;
mExpressions = aExpressions;
return NS_OK;
}
/* void asetExpressions (in unsigned long aExpressionsSize, [array, size_is (aExpressionsSize)] in nsISupports aExpressionsArray); */
NS_IMETHODIMP nsAbBooleanExpression::AsetExpressions(PRUint32 aExpressionsSize, nsISupports **aExpressionsArray)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void agetExpressions (out unsigned long aExpressionsSize, [array, size_is (aExpressionsSize), retval] out nsISupports aExpressionsArray); */
NS_IMETHODIMP nsAbBooleanExpression::AgetExpressions(PRUint32 *aExpressionsSize, nsISupports ***aExpressionsArray)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_METHOD nsAbBooleanExpression::Create(nsISupports* aOuter, REFNSIID aIID, void* *aResult)
{
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsAbBooleanExpression* it = new nsAbBooleanExpression();
if (it == NULL)
return NS_ERROR_OUT_OF_MEMORY;
NS_IF_ADDREF(it);
nsresult rv = it->QueryInterface(aIID, aResult);
NS_RELEASE(it);
return rv;
}
nsresult NS_NewIAbBooleanExpression(nsIAbBooleanExpression** aInstancePtrResult)
{
nsresult rv;
rv = nsAbBooleanExpression::Create(NULL, NS_GET_IID(nsIAbBooleanExpression), NS_REINTERPRET_CAST(void**, aInstancePtrResult));
return rv;
}

View File

@ -0,0 +1,70 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#ifndef nsAbBooleanExpression_h__
#define nsAbBooleanExpression_h__
#include "nsIAbBooleanExpression.h"
#include "nsCOMPtr.h"
#include "nsString.h"
class nsAbBooleanConditionString : public nsIAbBooleanConditionString
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIABBOOLEANCONDITIONSTRING
nsAbBooleanConditionString();
virtual ~nsAbBooleanConditionString();
static NS_METHOD Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
protected:
nsAbBooleanConditionType mCondition;
nsCString mName;
nsString mValue;
};
class nsAbBooleanExpression: public nsIAbBooleanExpression
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIABBOOLEANEXPRESSION
nsAbBooleanExpression();
virtual ~nsAbBooleanExpression();
static NS_METHOD Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
protected:
nsAbBooleanOperationType mOperation;
nsCOMPtr<nsISupportsArray> mExpressions;
};
nsresult
NS_NewIAbBooleanConditionString(nsIAbBooleanConditionString** aInstancePtrResult);
nsresult
NS_NewIAbBooleanExpression(nsIAbBooleanExpression** aInstancePtrResult);
#endif

View File

@ -35,8 +35,8 @@
#include "nsIPref.h"
#include "nsIAbDirectory.h"
#include "nsIAddressBook.h"
static NS_DEFINE_CID(kPrefCID, NS_PREF_CID);
static NS_DEFINE_CID(kRDFServiceCID, NS_RDFSERVICE_CID);
nsAbCardProperty::nsAbCardProperty(void)
@ -223,8 +223,25 @@ NS_IMETHODIMP nsAbCardProperty::GetCardValue(const char *attrname, PRUnichar **v
else if (!PL_strcmp(attrname, kNotesColumn))
GetNotes(value);
else if (!PL_strcmp(attrname, kPreferMailFormatColumn))
{ // PreferMailFormat is interger, not a string
return NS_OK;
{
PRUint32 format = nsIAbPreferMailFormat::unknown;
GetPreferMailFormat(&format);
nsString formatStr;
switch (format) {
case nsIAbPreferMailFormat::unknown :
formatStr.AssignWithConversion("unknown");
break;
case nsIAbPreferMailFormat::plaintext :
formatStr.AssignWithConversion("plaintext");
break;
case nsIAbPreferMailFormat::html :
formatStr.AssignWithConversion("html");
break;
default :
formatStr.AssignWithConversion("unknown");
break;
}
*value = (PRUnichar *) formatStr.ToNewUnicode ();
}
/* else handle pass down attribute */
@ -310,11 +327,19 @@ NS_IMETHODIMP nsAbCardProperty::SetCardValue(const char *attrname, const PRUnich
else if (!PL_strcmp(attrname, kCompanyColumn))
rv = SetCompany((PRUnichar *)value);
else if (!PL_strcmp(attrname, kPreferMailFormatColumn))
{ // PreferMailFormat is interger, not a string
return NS_OK;
}
{
PRUint32 format = nsIAbPreferMailFormat::unknown;
nsString formatStr(value);
if (formatStr.CompareWithConversion("unknown", PR_TRUE))
format = nsIAbPreferMailFormat::unknown;
if (formatStr.CompareWithConversion("plaintext", PR_TRUE))
format = nsIAbPreferMailFormat::plaintext;
if (formatStr.CompareWithConversion("html", PR_TRUE))
format = nsIAbPreferMailFormat::html;
SetPreferMailFormat(format);
}
else
rv = NS_ERROR_FAILURE;
rv = NS_ERROR_FAILURE;
return rv;
}
@ -629,7 +654,7 @@ nsAbCardProperty::GetName(PRUnichar * *aName)
nsresult rv = NS_OK;
// get name depend on "mail.addr_book.lastnamefirst"
// 0= displayname, 1= lastname first, 2=firstname first
nsCOMPtr<nsIPref> pPref(do_GetService(kPrefCID, &rv));
nsCOMPtr<nsIPref> pPref = do_GetService(NS_PREF_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
PRInt32 lastNameFirst = 0;
@ -816,6 +841,22 @@ NS_IMETHODIMP nsAbCardProperty::DropCardToDatabase(const char *uri, nsIAbCard **
return rv;
}
NS_IMETHODIMP nsAbCardProperty::GetCollationKey(const PRUnichar *str, PRUnichar **key)
{
nsresult rv;
if (!addressBook)
{
// Keep a local copy of the addressBook service
// for performance reasons
addressBook = do_GetService (NS_ADDRESSBOOK_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
}
rv = addressBook->CreateCollationKey(str, key);
return rv;
}
// nsIAbCard NOT IMPLEMENTED methods
@ -828,8 +869,3 @@ NS_IMETHODIMP nsAbCardProperty::GetPrintCardUrl(char * *aPrintCardUrl)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsAbCardProperty::GetCollationKey(const PRUnichar *str, PRUnichar **key)
{
return NS_ERROR_NOT_IMPLEMENTED;
}

View File

@ -33,6 +33,7 @@
#include "nsISupportsArray.h"
#include "nsVoidArray.h"
#include "nsCOMPtr.h"
#include "nsIAddressBook.h"
#include "nsIAddrDatabase.h"
/*
@ -91,11 +92,13 @@ protected:
nsString m_Custom4;
nsString m_Note;
PRUint32 m_LastModDate;
PRUint32 m_Key;
PRUint32 m_Key;
PRUint32 m_PreferMailFormat;
PRBool m_bIsMailList;
char* m_MailListURI;
nsCOMPtr<nsIAddressBook> addressBook;
};
#endif

View File

@ -0,0 +1,185 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
* Chris Waterson <waterson@netscape.com>
* Csaba Borbola <csaba.borbola@sun.com>
*/
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsIIOService.h"
#include "nsNetCID.h"
#include "nsMemory.h"
#include "nsCRT.h"
#include "plstr.h"
#include "nsAbDirFactoryService.h"
#include "nsIAbDirFactory.h"
NS_IMPL_ISUPPORTS1(nsAbDirFactoryService, nsIAbDirFactoryService)
nsAbDirFactoryService::nsAbDirFactoryService()
{
NS_INIT_ISUPPORTS();
}
nsAbDirFactoryService::~nsAbDirFactoryService()
{
}
/* nsIAbDirFactory getDirFactory (in string uri); */
NS_IMETHODIMP nsAbDirFactoryService::GetDirFactory(const char* aURI,
nsIAbDirFactory** aDirFactory)
{
nsresult rv;
NS_PRECONDITION(aURI != nsnull, "null ptr");
if (!aURI)
return NS_ERROR_NULL_POINTER;
NS_PRECONDITION(aDirFactory != nsnull, "null ptr");
if (!aDirFactory)
return NS_ERROR_NULL_POINTER;
// Obtain the network IO service
nsCOMPtr<nsIIOService> nsService = do_GetService (NS_IOSERVICE_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv,rv);
// Extract the scheme
// Use only the start and end for efficiency
PRUint32 start;
PRUint32 end;
rv = nsService->ExtractScheme (aURI, &start, &end, nsnull);
NS_ENSURE_SUCCESS(rv,rv);
// TODO
// Change to use string classes
// Try to find a factory using the component manager.
static const char kAbDirFactoryContractIDPrefix[]
= NS_AB_DIRECTORY_FACTORY_CONTRACTID_PREFIX;
PRInt32 pos = end - start - 1;
PRInt32 len = pos + sizeof(kAbDirFactoryContractIDPrefix) - 1;
// Safely convert to a C-string for the XPCOM APIs
char buf[128];
char* contractID = buf;
if (len >= PRInt32(sizeof buf))
contractID = NS_STATIC_CAST(char *,nsMemory::Alloc(len + 1));
if (contractID == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
PL_strcpy(contractID, kAbDirFactoryContractIDPrefix);
PL_strncpy(contractID + sizeof(kAbDirFactoryContractIDPrefix) - 1, aURI, pos);
contractID[len] = '\0';
nsCID cid;
rv = nsComponentManager::ContractIDToClassID(contractID, &cid);
NS_ENSURE_SUCCESS(rv,rv);
if (contractID != buf)
nsCRT::free(contractID);
nsCOMPtr<nsIFactory> factory;
rv = nsComponentManager::FindFactory(cid, getter_AddRefs(factory));
NS_ASSERTION(NS_SUCCEEDED(rv), "factory registered, but couldn't load");
NS_ENSURE_SUCCESS(rv,rv);
rv = factory->CreateInstance(nsnull, NS_GET_IID(nsIAbDirFactory), NS_REINTERPRET_CAST(void**, aDirFactory));
return rv;
}
/* nsIAbDirFactory getDirFactory (in string uri); */
/*
NS_IMETHODIMP nsAbDirFactoryService::GetDirFactory(const char* aURI,
nsIAbDirFactory** aDirFactory)
{
NS_PRECONDITION(aURI != nsnull, "null ptr");
if (!aURI)
return NS_ERROR_NULL_POINTER;
NS_PRECONDITION(aDirFactory != nsnull, "null ptr");
if (!aDirFactory)
return NS_ERROR_NULL_POINTER;
// Compute the scheme of the URI. Scan forward until we either:
//
// 1. Reach the end of the string
// 2. Encounter a non-alpha character
// 3. Encouter a colon.
//
// If we encounter a colon _before_ encountering a non-alpha
// character, then assume it's the scheme.
//
// XXX Although it's really not correct, we'll allow underscore
// characters ('_'), too.
const char* p = aURI;
while (IsLegalSchemeCharacter(*p))
++p;
if (*p != ':')
return NS_ERROR_FAILURE;
nsresult rv;
nsCOMPtr<nsIFactory> factory;
PRUint32 prefixlen = 0;
prefixlen = (p - aURI);
// Try to find a factory using the component manager.
static const char kAbDirFactoryContractIDPrefix[]
= NS_AB_DIRECTORY_FACTORY_CONTRACTID_PREFIX;
PRInt32 pos = p - aURI;
PRInt32 len = pos + sizeof(kAbDirFactoryContractIDPrefix) - 1;
// Safely convert to a C-string for the XPCOM APIs
char buf[128];
char* contractID = buf;
if (len >= PRInt32(sizeof buf))
contractID = NS_STATIC_CAST(char *,nsMemory::Alloc(len + 1));
if (contractID == nsnull)
return NS_ERROR_OUT_OF_MEMORY;
PL_strcpy(contractID, kAbDirFactoryContractIDPrefix);
PL_strncpy(contractID + sizeof(kAbDirFactoryContractIDPrefix) - 1, aURI, pos);
contractID[len] = '\0';
nsCID cid;
rv = nsComponentManager::ContractIDToClassID(contractID, &cid);
NS_ENSURE_SUCCESS(rv,rv);
if (contractID != buf)
nsCRT::free(contractID);
rv = nsComponentManager::FindFactory(cid, getter_AddRefs(factory));
NS_ASSERTION(NS_SUCCEEDED(rv), "factory registered, but couldn't load");
NS_ENSURE_SUCCESS(rv,rv);
rv = factory->CreateInstance(nsnull, NS_GET_IID(nsIAbDirFactory), NS_REINTERPRET_CAST(void**, aDirFactory));
return rv;
}
*/

View File

@ -0,0 +1,42 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#ifndef nsAbDirFactoryService_h__
#define nsAbDirFactoryService_h__
#include "nsIAbDirFactoryService.h"
#define NS_AB_DIRECTORY_FACTORY_CONTRACTID_PREFIX "@mozilla.org/addressbook/directory-factory;1?name="
class nsAbDirFactoryService : public nsIAbDirFactoryService
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIABDIRFACTORYSERVICE
nsAbDirFactoryService();
virtual ~nsAbDirFactoryService();
};
#endif

View File

@ -71,6 +71,22 @@ NS_IMETHODIMP nsAbDirProperty::QueryInterface(REFNSIID aIID, void** aResult)
////////////////////////////////////////////////////////////////////////////////
/* readonly attribute long operations; */
NS_IMETHODIMP nsAbDirProperty::GetOperations(PRInt32 *aOperations)
{
/*
* Default is to support all operations.
* Inheriting implementations may override
* to reduce supported operations
*
*/
*aOperations = nsIAbDirectory::opRead |
nsIAbDirectory::opWrite |
nsIAbDirectory::opSearch;
return NS_OK;
}
NS_IMETHODIMP nsAbDirProperty::GetDirName(PRUnichar **aDirName)
{
if (aDirName)
@ -271,3 +287,6 @@ NS_IMETHODIMP nsAbDirProperty::AddCard(nsIAbCard *childCard, nsIAbCard **_retval
NS_IMETHODIMP nsAbDirProperty::DropCard(nsIAbCard *childCard, nsIAbCard **_retval)
{ return NS_ERROR_NOT_IMPLEMENTED; }
NS_IMETHODIMP nsAbDirProperty::GetTotalCards(PRBool subDirectoryCount, PRUint32 *_retval)
{ return NS_ERROR_NOT_IMPLEMENTED; }

View File

@ -0,0 +1,96 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#include "nsAbDirSearchListener.h"
#include "nsCOMPtr.h"
#include "nsString.h"
#include "nsXPIDLString.h"
NS_IMPL_THREADSAFE_ISUPPORTS1(nsAbDirSearchListener, nsIAbDirectoryQueryResultListener)
nsAbDirSearchListener::nsAbDirSearchListener (nsAbDirSearchListenerContext* searchContext) :
mSearchContext (searchContext)
{
NS_INIT_ISUPPORTS();
}
nsAbDirSearchListener::~nsAbDirSearchListener ()
{
}
/* void onQueryItem (in nsIAbDirectoryQueryResult result); */
NS_IMETHODIMP nsAbDirSearchListener::OnQueryItem(nsIAbDirectoryQueryResult* result)
{
nsresult rv;
PRInt32 resultType;
rv = result->GetType (&resultType);
NS_ENSURE_SUCCESS(rv, rv);
if (resultType != nsIAbDirectoryQueryResult::queryResultMatch)
{
rv = mSearchContext->OnSearchFinished (resultType);
return rv;
}
nsCOMPtr<nsISupportsArray> properties;
rv = result->GetResult (getter_AddRefs (properties));
NS_ENSURE_SUCCESS(rv, rv);
PRUint32 count;
rv = properties->Count (&count);
NS_ENSURE_SUCCESS(rv, rv);
if (count != 1)
return NS_ERROR_FAILURE;
nsCOMPtr<nsISupports> item;
rv = properties->GetElementAt (0, getter_AddRefs (item));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAbDirectoryQueryPropertyValue> property(do_QueryInterface(item, &rv));
NS_ENSURE_SUCCESS(rv, rv);
nsXPIDLCString name;
rv = property->GetName (getter_Copies (name));
NS_ENSURE_SUCCESS(rv, rv);
if (nsCRT::strcasecmp (name, "card:nsIAbCard") != 0)
return NS_ERROR_FAILURE;
nsCOMPtr<nsISupports> cardSupports;
rv = property->GetValueISupports (getter_AddRefs (cardSupports));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAbCard> card(do_QueryInterface(cardSupports, &rv));
NS_ENSURE_SUCCESS(rv, rv);
rv = mSearchContext->OnSearchFoundCard (card);
return rv;
}

View File

@ -0,0 +1,55 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#ifndef nsAbDirSearchListener_h__
#define nsAbDirSearchListener_h__
#include "nsIAbDirectoryQuery.h"
#include "nsIAbCard.h"
class nsAbDirSearchListenerContext
{
public:
nsAbDirSearchListenerContext () {}
virtual ~nsAbDirSearchListenerContext () {}
virtual nsresult OnSearchFinished (PRInt32 result) = 0;
virtual nsresult OnSearchFoundCard (nsIAbCard* card) = 0;
};
class nsAbDirSearchListener : public nsIAbDirectoryQueryResultListener
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIABDIRECTORYQUERYRESULTLISTENER
nsAbDirSearchListener(nsAbDirSearchListenerContext* directory);
virtual ~nsAbDirSearchListener();
protected:
nsAbDirSearchListenerContext* mSearchContext;
};
#endif

View File

@ -0,0 +1,847 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#include "nsAbDirectoryQuery.h"
#include "nsAbDirectoryQueryProxy.h"
#include "nsAbUtils.h"
#include "nsAbBooleanExpression.h"
#include "nsIRDFResource.h"
#include "nsXPIDLString.h"
#include "prthread.h"
NS_IMPL_THREADSAFE_ISUPPORTS1(nsAbDirectoryQuerySimpleBooleanExpression, nsIAbBooleanExpression)
nsAbDirectoryQuerySimpleBooleanExpression::nsAbDirectoryQuerySimpleBooleanExpression() :
mOperation (nsIAbBooleanOperationTypes::AND)
{
NS_INIT_ISUPPORTS();
}
nsAbDirectoryQuerySimpleBooleanExpression::~nsAbDirectoryQuerySimpleBooleanExpression()
{
}
/* attribute nsAbBooleanOperationType operation; */
NS_IMETHODIMP nsAbDirectoryQuerySimpleBooleanExpression::GetOperation(nsAbBooleanOperationType *aOperation)
{
if (!aOperation)
return NS_ERROR_NULL_POINTER;
*aOperation = mOperation;
return NS_OK;
}
NS_IMETHODIMP nsAbDirectoryQuerySimpleBooleanExpression::SetOperation(nsAbBooleanOperationType aOperation)
{
if (aOperation != nsIAbBooleanOperationTypes::AND &&
aOperation != nsIAbBooleanOperationTypes::OR)
return NS_ERROR_FAILURE;
mOperation = aOperation;
return NS_OK;
}
/* attribute nsISupportsArray expressions; */
NS_IMETHODIMP nsAbDirectoryQuerySimpleBooleanExpression::GetExpressions(nsISupportsArray** aExpressions)
{
if (!aExpressions)
return NS_ERROR_NULL_POINTER;
if (!mExpressions)
NS_NewISupportsArray(getter_AddRefs(mExpressions));
*aExpressions = mExpressions;
NS_IF_ADDREF(*aExpressions);
return NS_OK;
}
NS_IMETHODIMP nsAbDirectoryQuerySimpleBooleanExpression::SetExpressions(nsISupportsArray* aExpressions)
{
if (!aExpressions)
return NS_ERROR_NULL_POINTER;
nsresult rv;
PRUint32 count;
rv = aExpressions->Count (&count);
NS_ENSURE_SUCCESS(rv, rv);
for (PRUint32 i = 0; i < count; i++)
{
nsCOMPtr<nsISupports> item;
rv = aExpressions->GetElementAt (i, getter_AddRefs (item));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAbBooleanConditionString> queryExpression (do_QueryInterface (item, &rv));
NS_ENSURE_SUCCESS(rv, rv);
}
mExpressions = aExpressions;
return NS_OK;
}
/* void asetExpressions (in unsigned long aExpressionsSize, [array, size_is (aExpressionsSize)] in nsISupports aExpressionsArray); */
NS_IMETHODIMP nsAbDirectoryQuerySimpleBooleanExpression::AsetExpressions(PRUint32 aExpressionsSize, nsISupports **aExpressionsArray)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void agetExpressions (out unsigned long aExpressionsSize, [array, size_is (aExpressionsSize), retval] out nsISupports aExpressionsArray); */
NS_IMETHODIMP nsAbDirectoryQuerySimpleBooleanExpression::AgetExpressions(PRUint32 *aExpressionsSize, nsISupports ***aExpressionsArray)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_METHOD nsAbDirectoryQuerySimpleBooleanExpression::Create(nsISupports* aOuter, REFNSIID aIID, void** aResult)
{
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsAbDirectoryQuerySimpleBooleanExpression* it = new nsAbDirectoryQuerySimpleBooleanExpression ();
if (it == NULL)
return NS_ERROR_OUT_OF_MEMORY;
NS_IF_ADDREF(it);
nsresult rv = it->QueryInterface(aIID, aResult);
NS_ENSURE_SUCCESS(rv, rv);
NS_RELEASE(it);
return rv;
}
nsresult NS_NewAbDirectoryQuerySimpleBooleanExpression(nsIAbBooleanExpression** aInstancePtrResult)
{
nsresult rv;
rv = nsAbDirectoryQuerySimpleBooleanExpression::Create(NULL, NS_GET_IID(nsIAbBooleanExpression), NS_REINTERPRET_CAST(void**, aInstancePtrResult));
return rv;
}
NS_IMPL_THREADSAFE_ISUPPORTS1(nsAbDirectoryQueryArguments, nsIAbDirectoryQueryArguments)
nsAbDirectoryQueryArguments::nsAbDirectoryQueryArguments() :
mQuerySubDirectories (PR_TRUE)
{
NS_INIT_ISUPPORTS();
}
nsAbDirectoryQueryArguments::~nsAbDirectoryQueryArguments()
{
}
/* attribute nsISupportsArray matchItems; */
NS_IMETHODIMP nsAbDirectoryQueryArguments::GetExpression(nsISupports** aExpression)
{
if (!aExpression)
return NS_ERROR_NULL_POINTER;
*aExpression = mExpression;
NS_IF_ADDREF(*aExpression);
return NS_OK;
}
NS_IMETHODIMP nsAbDirectoryQueryArguments::SetExpression(nsISupports* aExpression)
{
mExpression = aExpression;
return NS_OK;
}
/* attribute boolean querySubDirectories; */
NS_IMETHODIMP nsAbDirectoryQueryArguments::GetQuerySubDirectories(PRBool* aQuerySubDirectories)
{
if (!aQuerySubDirectories)
return NS_ERROR_NULL_POINTER;
*aQuerySubDirectories = mQuerySubDirectories;
return NS_OK;
}
NS_IMETHODIMP nsAbDirectoryQueryArguments::SetQuerySubDirectories(PRBool aQuerySubDirectories)
{
mQuerySubDirectories = aQuerySubDirectories;
return NS_OK;
}
/* void setReturnProperties (in unsigned long returnPropertiesSize,
* [array, size_is (returnPropertiesSize)] in string returnPropertiesArray); */
NS_IMETHODIMP nsAbDirectoryQueryArguments::SetReturnProperties(PRUint32 returnPropertiesSize,
const char** returnPropertiesArray)
{
nsresult rv;
rv = CharPtrArrayToCStringArray::Convert (mReturnProperties,
returnPropertiesSize,
returnPropertiesArray);
return rv;
}
/* void getReturnProperties (out unsigned long returnPropertiesSize,
* [array, size_is (returnPropertiesSize), retval] out string returnPropertiesArray); */
NS_IMETHODIMP nsAbDirectoryQueryArguments::GetReturnProperties(PRUint32* returnPropertiesSize,
char*** returnPropertiesArray)
{
nsresult rv;
rv = CStringArrayToCharPtrArray::Convert (mReturnProperties,
returnPropertiesSize, returnPropertiesArray);
return rv;
}
NS_METHOD nsAbDirectoryQueryArguments::Create(nsISupports* aOuter, REFNSIID aIID, void* *aResult)
{
if (aOuter)
return NS_ERROR_NO_AGGREGATION;
nsAbDirectoryQueryArguments* it = new nsAbDirectoryQueryArguments();
if (it == NULL)
return NS_ERROR_OUT_OF_MEMORY;
NS_IF_ADDREF(it);
nsresult rv = it->QueryInterface(aIID, aResult);
NS_RELEASE(it);
return rv;
}
nsresult NS_NewIAbDirectoryQueryArguments(nsIAbDirectoryQueryArguments** aInstancePtrResult)
{
nsresult rv;
rv = nsAbDirectoryQueryArguments::Create(NULL, NS_GET_IID(nsIAbDirectoryQueryArguments),
NS_REINTERPRET_CAST(void**,aInstancePtrResult));
return rv;
}
NS_IMPL_THREADSAFE_ISUPPORTS1(nsAbDirectoryQueryPropertyValue, nsIAbDirectoryQueryPropertyValue)
nsAbDirectoryQueryPropertyValue::nsAbDirectoryQueryPropertyValue()
{
NS_INIT_ISUPPORTS();
}
nsAbDirectoryQueryPropertyValue::nsAbDirectoryQueryPropertyValue(const char* aName,
const PRUnichar* aValue)
{
NS_INIT_ISUPPORTS();
mName = aName;
mValue = aValue;
}
nsAbDirectoryQueryPropertyValue::nsAbDirectoryQueryPropertyValue(const char* aName,
nsISupports* aValueISupports)
{
NS_INIT_ISUPPORTS();
mName = aName;
mValueISupports = aValueISupports;
}
nsAbDirectoryQueryPropertyValue::~nsAbDirectoryQueryPropertyValue()
{
}
/* read only attribute string name; */
NS_IMETHODIMP nsAbDirectoryQueryPropertyValue::GetName(char* *aName)
{
const char* value = mName.get ();
if (!value)
*aName = 0;
else
*aName = mName.ToNewCString ();
return NS_OK;
}
/* read only attribute wstring value; */
NS_IMETHODIMP nsAbDirectoryQueryPropertyValue::GetValue(PRUnichar* *aValue)
{
*aValue = mValue.ToNewUnicode();
if (!(*aValue))
return NS_ERROR_OUT_OF_MEMORY;
else
return NS_OK;
}
/* readonly attribute nsISupports valueISupports; */
NS_IMETHODIMP nsAbDirectoryQueryPropertyValue::GetValueISupports(nsISupports* *aValueISupports)
{
if (!mValueISupports)
return NS_ERROR_NULL_POINTER;
*aValueISupports = mValueISupports;
NS_IF_ADDREF(*aValueISupports);
return NS_OK;
}
NS_IMPL_THREADSAFE_ISUPPORTS1(nsAbDirectoryQueryResult, nsIAbDirectoryQueryResult)
nsAbDirectoryQueryResult::nsAbDirectoryQueryResult() :
mContextID (-1),
mType (queryResultError)
{
NS_INIT_ISUPPORTS();
}
nsAbDirectoryQueryResult::nsAbDirectoryQueryResult(PRInt32 aContextID,
nsIAbDirectoryQueryArguments* aContextArgs,
PRInt32 aType,
nsCOMPtr<nsISupportsArray> aResult)
{
NS_INIT_ISUPPORTS();
mContextID = aContextID;
mContextArgs = aContextArgs;
mType = aType;
mResult = aResult;
}
nsAbDirectoryQueryResult::~nsAbDirectoryQueryResult()
{
}
/* readonly attribute long contextID; */
NS_IMETHODIMP nsAbDirectoryQueryResult::GetContextID(PRInt32 *aContextID)
{
*aContextID = mContextID;
return NS_OK;
}
/* readonly attribute nsIAbDirectoryQueryArguments contextArgs; */
NS_IMETHODIMP nsAbDirectoryQueryResult::GetContextArgs(nsIAbDirectoryQueryArguments* *aContextArgs)
{
if (!mContextArgs)
return NS_ERROR_NULL_POINTER;
*aContextArgs = mContextArgs;
NS_IF_ADDREF(*aContextArgs);
return NS_OK;
}
/* readonly attribute long type; */
NS_IMETHODIMP nsAbDirectoryQueryResult::GetType(PRInt32 *aType)
{
*aType = mType;
return NS_OK;
}
/* readonly attribute nsISupportsArray result; */
NS_IMETHODIMP nsAbDirectoryQueryResult::GetResult(nsISupportsArray* *aResult)
{
if (!mResult)
return NS_ERROR_NULL_POINTER;
*aResult = mResult;
NS_IF_ADDREF(*aResult);
return NS_OK;
}
/* void agetResult (out unsigned long aResultSize, [array, size_is (aResultSize), retval] out nsISupports aResultArray); */
NS_IMETHODIMP nsAbDirectoryQueryResult::AgetResult(PRUint32 *aResultSize, nsISupports* **aResultArray)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsAbDirectoryQuery, nsIAbDirectoryQuery)
nsAbDirectoryQuery::nsAbDirectoryQuery(nsIAbDirectory* aDirectory)
{
NS_INIT_ISUPPORTS();
mDirectory = aDirectory;
}
nsAbDirectoryQuery::~nsAbDirectoryQuery()
{
}
/* long doQuery (in nsIAbDirectoryQueryArguments arguments, in nsIAbDirectoryQueryResultListener listener, in long resultLimit, in long timeOut); */
NS_IMETHODIMP nsAbDirectoryQuery::DoQuery(nsIAbDirectoryQueryArguments* arguments, nsIAbDirectoryQueryResultListener* listener, PRInt32 resultLimit, PRInt32 timeOut, PRInt32* _retval)
{
nsresult rv;
rv = query (mDirectory, arguments, listener, &resultLimit);
if (NS_FAILED(rv))
rv = queryError (arguments, listener);
else
rv = queryFinished (arguments, listener);
*_retval = 0;
return rv;
}
/* void stopQuery (in long contextID); */
NS_IMETHODIMP nsAbDirectoryQuery::StopQuery(PRInt32 contextID)
{
return NS_OK;
}
nsresult nsAbDirectoryQuery::query (nsIAbDirectory* directory,
nsIAbDirectoryQueryArguments* arguments,
nsIAbDirectoryQueryResultListener* listener,
PRInt32* resultLimit)
{
nsresult rv = NS_OK;
if (*resultLimit == 0)
return rv;
rv = queryCards (directory, arguments, listener, resultLimit);
NS_ENSURE_SUCCESS(rv, rv);
PRBool doSubDirectories;
arguments->GetQuerySubDirectories (&doSubDirectories);
if (doSubDirectories == PR_TRUE && *resultLimit != 0)
{
rv = queryChildren (directory, arguments, listener, resultLimit);
NS_ENSURE_SUCCESS(rv, rv);
}
return rv;
}
nsresult nsAbDirectoryQuery::queryChildren (nsIAbDirectory* directory,
nsIAbDirectoryQueryArguments* arguments,
nsIAbDirectoryQueryResultListener* listener,
PRInt32* resultLimit)
{
nsresult rv = NS_OK;
nsCOMPtr<nsIEnumerator> subDirectories;
rv = directory->GetChildNodes(getter_AddRefs(subDirectories));
NS_ENSURE_SUCCESS(rv, rv);
rv = subDirectories->First ();
if (NS_FAILED(rv))
return NS_OK;
do
{
nsCOMPtr<nsISupports> item;
rv = subDirectories->CurrentItem (getter_AddRefs (item));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAbDirectory> subDirectory(do_QueryInterface(item, &rv));
NS_ENSURE_SUCCESS(rv, rv);
rv = query (subDirectory, arguments, listener, resultLimit);
NS_ENSURE_SUCCESS(rv, rv);
rv = subDirectories->Next ();
}
while (rv == NS_OK);
return NS_OK;
}
nsresult nsAbDirectoryQuery::queryCards (nsIAbDirectory* directory,
nsIAbDirectoryQueryArguments* arguments,
nsIAbDirectoryQueryResultListener* listener,
PRInt32* resultLimit)
{
nsresult rv = NS_OK;
nsCOMPtr<nsIEnumerator> cards;
rv = directory->GetChildCards(getter_AddRefs(cards));
if (NS_FAILED(rv))
{
if (rv != NS_ERROR_NOT_IMPLEMENTED)
NS_ENSURE_SUCCESS(rv, rv);
else
return NS_OK;
}
if (!cards)
return NS_OK;
rv = cards->First ();
if (NS_FAILED(rv))
return NS_OK;
do
{
nsCOMPtr<nsISupports> item;
rv = cards->CurrentItem (getter_AddRefs (item));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAbCard> card(do_QueryInterface(item, &rv));
NS_ENSURE_SUCCESS(rv, rv);
rv = matchCard (card, arguments, listener, resultLimit);
NS_ENSURE_SUCCESS(rv, rv);
if (*resultLimit == 0)
return NS_OK;
rv = cards->Next ();
}
while (rv == NS_OK);
return NS_OK;
}
nsresult nsAbDirectoryQuery::matchCard (nsIAbCard* card,
nsIAbDirectoryQueryArguments* arguments,
nsIAbDirectoryQueryResultListener* listener,
PRInt32* resultLimit)
{
nsresult rv = NS_OK;
nsCOMPtr<nsISupports> supportsExpression;
rv = arguments->GetExpression (getter_AddRefs (supportsExpression));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAbBooleanExpression> expression(do_QueryInterface(supportsExpression, &rv));
NS_ENSURE_SUCCESS(rv, rv);
PRBool matchFound = PR_FALSE;
rv = matchCardExpression (card, expression, &matchFound);
NS_ENSURE_SUCCESS(rv, rv);
if (matchFound == PR_TRUE)
{
(*resultLimit)--;
rv = queryMatch (card, arguments, listener);
NS_ENSURE_SUCCESS(rv, rv);
}
return rv;
}
nsresult nsAbDirectoryQuery::matchCardExpression (nsIAbCard* card,
nsIAbBooleanExpression* expression,
PRBool* result)
{
nsresult rv = NS_OK;
nsAbBooleanOperationType operation;
rv = expression->GetOperation (&operation);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsISupportsArray> childExpressions;
rv = expression->GetExpressions (getter_AddRefs (childExpressions));
NS_ENSURE_SUCCESS(rv, rv);
PRUint32 count;
rv = childExpressions->Count (&count);
NS_ENSURE_SUCCESS(rv, rv);
if (operation == nsIAbBooleanOperationTypes::NOT &&
count > 1)
return NS_ERROR_FAILURE;
PRBool value = *result = PR_FALSE;
for (PRUint32 i = 0; i < count; i++)
{
nsCOMPtr<nsISupports> item;
rv = childExpressions->GetElementAt (i, getter_AddRefs (item));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAbBooleanConditionString>
childCondition(do_QueryInterface(item, &rv));
if (NS_SUCCEEDED(rv))
{
rv = matchCardCondition (card, childCondition, &value);
NS_ENSURE_SUCCESS(rv, rv);
}
else
{
nsCOMPtr<nsIAbBooleanExpression>
childExpression(do_QueryInterface(item, &rv));
if (NS_SUCCEEDED(rv))
{
rv = matchCardExpression (card, childExpression, &value);
NS_ENSURE_SUCCESS(rv, rv);
}
else
return NS_ERROR_FAILURE;
}
if (operation == nsIAbBooleanOperationTypes::OR &&
value == PR_TRUE)
break;
else if (operation == nsIAbBooleanOperationTypes::AND &&
value == PR_FALSE)
break;
else if (operation == nsIAbBooleanOperationTypes::NOT)
value = (value == PR_TRUE) ? PR_FALSE : PR_TRUE;
}
*result = value;
return NS_OK;
}
nsresult nsAbDirectoryQuery::matchCardCondition (nsIAbCard* card,
nsIAbBooleanConditionString* condition,
PRBool* matchFound)
{
nsresult rv = NS_OK;
nsAbBooleanConditionType conditionType;
rv = condition->GetCondition (&conditionType);
NS_ENSURE_SUCCESS(rv, rv);
nsXPIDLCString name;
rv = condition->GetName (getter_Copies (name));
NS_ENSURE_SUCCESS(rv, rv);
if (name.Equals ("card:URI") ||
name.Equals ("card:nsIAbCard"))
{
if (conditionType == nsIAbBooleanConditionTypes::Exists)
*matchFound = PR_TRUE;
else
*matchFound = PR_FALSE;
return NS_OK;
}
nsXPIDLString _value;
rv = card->GetCardValue (name.get (), getter_Copies (_value));
NS_ENSURE_SUCCESS(rv, rv);
nsString value (_value.get ());
if (!value.get () || value.Length () == 0)
{
if (conditionType == nsIAbBooleanConditionTypes::DoesNotExist)
*matchFound = PR_TRUE;
else
*matchFound = PR_FALSE;
return NS_OK;
}
nsXPIDLString matchValue;
rv = condition->GetValue (getter_Copies (matchValue));
NS_ENSURE_SUCCESS(rv, rv);
/* TODO
* What about allowing choice between case insensitive
* and case sensitive comparisions?
*
*/
switch (conditionType)
{
case nsIAbBooleanConditionTypes::Exists:
*matchFound = PR_TRUE;
break;
case nsIAbBooleanConditionTypes::Contains:
*matchFound = value.Find (matchValue, PR_TRUE) >= 0;
break;
case nsIAbBooleanConditionTypes::DoesNotContain:
*matchFound = value.Find (matchValue, PR_TRUE) < 0;
break;
case nsIAbBooleanConditionTypes::Is:
*matchFound = value.CompareWithConversion (matchValue, PR_TRUE) == 0;
break;
case nsIAbBooleanConditionTypes::IsNot:
*matchFound = value.CompareWithConversion (matchValue, PR_TRUE) != 0;
break;
case nsIAbBooleanConditionTypes::BeginsWith:
*matchFound = value.Find (matchValue, PR_TRUE) == 0;
break;
case nsIAbBooleanConditionTypes::LessThan:
*matchFound = value.CompareWithConversion (matchValue, PR_TRUE) < 0;
break;
case nsIAbBooleanConditionTypes::GreaterThan:
*matchFound = value.CompareWithConversion (matchValue, PR_TRUE) > 0;
break;
case nsIAbBooleanConditionTypes::EndsWith:
{
PRInt32 vl = value.Length ();
PRInt32 mvl = matchValue.Length ();
if (mvl > vl)
{
*matchFound = PR_FALSE;
break;
}
*matchFound = value.Find (matchValue, PR_TRUE, vl - mvl) == (vl - mvl);
break;
}
case nsIAbBooleanConditionTypes::SoundsLike:
case nsIAbBooleanConditionTypes::RegExp:
*matchFound = PR_FALSE;
break;
default:
*matchFound = PR_FALSE;
}
return rv;
}
nsresult nsAbDirectoryQuery::queryMatch (nsIAbCard* card,
nsIAbDirectoryQueryArguments* arguments,
nsIAbDirectoryQueryResultListener* listener)
{
nsresult rv;
nsCOMPtr<nsISupportsArray> propertyValues;
CharPtrArrayGuard properties;
rv = arguments->GetReturnProperties (properties.GetSizeAddr(), properties.GetArrayAddr());
NS_ENSURE_SUCCESS(rv, rv);
nsCAutoString n;
for (PRUint32 i = 0; i < properties.GetSize(); i++)
{
n.Assign (properties[i]);
nsAbDirectoryQueryPropertyValue* _propertyValue = 0;
if (n.EqualsWithConversion ("card:nsIAbCard"))
{
nsCOMPtr<nsISupports> supports(do_QueryInterface(card, &rv));
NS_ENSURE_SUCCESS(rv, rv);
_propertyValue = new nsAbDirectoryQueryPropertyValue(n.get (), supports);
if (_propertyValue == NULL)
return NS_ERROR_OUT_OF_MEMORY;
}
else if (n.EqualsWithConversion ("card:URI"))
{
nsCOMPtr<nsIRDFResource> rdfResource(do_QueryInterface(card, &rv));
NS_ENSURE_SUCCESS(rv, rv);
nsXPIDLCString uri;
rv = rdfResource->GetValue (getter_Copies (uri));
NS_ENSURE_SUCCESS(rv, rv);
nsAutoString v;
v.AssignWithConversion (uri.get ());
_propertyValue = new nsAbDirectoryQueryPropertyValue(n.get (), v.get ());
if (_propertyValue == NULL)
return NS_ERROR_OUT_OF_MEMORY;
}
else
{
nsXPIDLString value;
rv = card->GetCardValue (n.get (), getter_Copies (value));
NS_ENSURE_SUCCESS(rv, rv);
if (!value.get () || value.Length () == 0)
continue;
_propertyValue = new nsAbDirectoryQueryPropertyValue(n.get (), value.get ());
if (_propertyValue == NULL)
return NS_ERROR_OUT_OF_MEMORY;
}
if (_propertyValue)
{
nsCOMPtr<nsIAbDirectoryQueryPropertyValue> propertyValue;
propertyValue = _propertyValue;
if (!propertyValues)
{
NS_NewISupportsArray(getter_AddRefs(propertyValues));
}
nsCOMPtr<nsISupports> supports(do_QueryInterface(propertyValue, &rv));
NS_ENSURE_SUCCESS(rv, rv);
propertyValues->AppendElement (supports);
}
}
if (!propertyValues)
return NS_OK;
nsCOMPtr<nsIAbDirectoryQueryResult> queryResult;
nsAbDirectoryQueryResult* _queryResult = new nsAbDirectoryQueryResult (0,
arguments,
nsIAbDirectoryQueryResult::queryResultMatch,
propertyValues);
if (_queryResult == NULL)
return NS_ERROR_OUT_OF_MEMORY;
queryResult = _queryResult;
rv = listener->OnQueryItem (queryResult);
return rv;
}
nsresult nsAbDirectoryQuery::queryFinished (nsIAbDirectoryQueryArguments* arguments,
nsIAbDirectoryQueryResultListener* listener)
{
nsCOMPtr<nsIAbDirectoryQueryResult> queryResult;
nsAbDirectoryQueryResult* _queryResult = new nsAbDirectoryQueryResult (0,
arguments,
nsIAbDirectoryQueryResult::queryResultComplete,
0);
if (_queryResult == NULL)
return NS_ERROR_OUT_OF_MEMORY;
queryResult = _queryResult;
return listener->OnQueryItem (queryResult);
}
nsresult nsAbDirectoryQuery::queryError (nsIAbDirectoryQueryArguments* arguments,
nsIAbDirectoryQueryResultListener* listener)
{
nsCOMPtr<nsIAbDirectoryQueryResult> queryResult;
nsAbDirectoryQueryResult* _queryResult = new nsAbDirectoryQueryResult (0,
arguments,
nsIAbDirectoryQueryResult::queryResultError,
0);
if (_queryResult == NULL)
return NS_ERROR_OUT_OF_MEMORY;
queryResult = _queryResult;
return listener->OnQueryItem (queryResult);
}

View File

@ -0,0 +1,165 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#ifndef nsAbDirectoryQuery_h__
#define nsAbDirectoryQuery_h__
#include "nsIAbDirectoryQuery.h"
#include "nsCOMPtr.h"
#include "nsString.h"
#include "nsVoidArray.h"
class nsAbDirectoryQuerySimpleBooleanExpression : public nsIAbBooleanExpression
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIABBOOLEANEXPRESSION
nsAbDirectoryQuerySimpleBooleanExpression();
virtual ~nsAbDirectoryQuerySimpleBooleanExpression();
static NS_METHOD Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
public:
nsCOMPtr<nsISupportsArray> mExpressions;
nsAbBooleanOperationType mOperation;
};
class nsAbDirectoryQueryArguments : public nsIAbDirectoryQueryArguments
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIABDIRECTORYQUERYARGUMENTS
nsAbDirectoryQueryArguments();
virtual ~nsAbDirectoryQueryArguments();
static NS_METHOD Create(nsISupports *aOuter, REFNSIID aIID, void **aResult);
protected:
nsCOMPtr<nsISupports> mExpression;
PRBool mQuerySubDirectories;
nsCStringArray mReturnProperties;
};
class nsAbDirectoryQueryPropertyValue : public nsIAbDirectoryQueryPropertyValue
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIABDIRECTORYQUERYPROPERTYVALUE
nsAbDirectoryQueryPropertyValue();
nsAbDirectoryQueryPropertyValue(const char* aName,
const PRUnichar* aValue);
nsAbDirectoryQueryPropertyValue(const char* aName,
nsISupports* aValueISupports);
virtual ~nsAbDirectoryQueryPropertyValue();
protected:
nsCString mName;
nsString mValue;
nsCOMPtr<nsISupports> mValueISupports;
};
class nsAbDirectoryQueryResult : public nsIAbDirectoryQueryResult
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIABDIRECTORYQUERYRESULT
nsAbDirectoryQueryResult();
nsAbDirectoryQueryResult(PRInt32 aContextID,
nsIAbDirectoryQueryArguments* aContextArgs,
PRInt32 aType,
nsCOMPtr<nsISupportsArray> aResult);
virtual ~nsAbDirectoryQueryResult();
protected:
PRInt32 mContextID;
nsCOMPtr<nsIAbDirectoryQueryArguments> mContextArgs;
PRInt32 mType;
nsCOMPtr<nsISupportsArray> mResult;
};
#include "nsIAbDirectory.h"
class nsAbDirectoryQuery : public nsIAbDirectoryQuery
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIABDIRECTORYQUERY
nsAbDirectoryQuery(nsIAbDirectory* aDirectory);
virtual ~nsAbDirectoryQuery();
protected:
nsresult query (nsIAbDirectory* directory,
nsIAbDirectoryQueryArguments* arguments,
nsIAbDirectoryQueryResultListener* listener,
PRInt32* resultLimit);
nsresult queryChildren (nsIAbDirectory* directory,
nsIAbDirectoryQueryArguments* arguments,
nsIAbDirectoryQueryResultListener* listener,
PRInt32* resultLimit);
nsresult queryCards (nsIAbDirectory* directory,
nsIAbDirectoryQueryArguments* arguments,
nsIAbDirectoryQueryResultListener* listener,
PRInt32* resultLimit);
nsresult matchCard (nsIAbCard* card,
nsIAbDirectoryQueryArguments* arguments,
nsIAbDirectoryQueryResultListener* listener,
PRInt32* resultLimit);
nsresult matchCardExpression (nsIAbCard* card,
nsIAbBooleanExpression* expression,
PRBool* result);
nsresult matchCardCondition (nsIAbCard* card,
nsIAbBooleanConditionString* condition,
PRBool* matchFound);
nsresult queryMatch (nsIAbCard* card,
nsIAbDirectoryQueryArguments* arguments,
nsIAbDirectoryQueryResultListener* listener);
nsresult queryFinished (nsIAbDirectoryQueryArguments* arguments,
nsIAbDirectoryQueryResultListener* listener);
nsresult queryError (nsIAbDirectoryQueryArguments* arguments,
nsIAbDirectoryQueryResultListener* listener);
protected:
nsCOMPtr<nsIAbDirectory> mDirectory;
};
nsresult
NS_NewAbDirectoryQuerySimpleBooleanExpression(nsIAbBooleanExpression** aInstancePtrResult);
nsresult
NS_NewIAbDirectoryQueryArguments(nsIAbDirectoryQueryArguments** aInstancePtrResult);
#endif

View File

@ -0,0 +1,54 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#include "nsAbDirectoryQuery.h"
#include "nsAbDirectoryQueryProxy.h"
NS_IMPL_ISUPPORTS2(nsAbDirectoryQueryProxy, nsIAbDirectoryQueryProxy, nsIAbDirectoryQuery)
nsAbDirectoryQueryProxy::nsAbDirectoryQueryProxy() :
mInitiated (PR_FALSE)
{
NS_INIT_ISUPPORTS();
}
nsAbDirectoryQueryProxy::~nsAbDirectoryQueryProxy()
{
}
/* void initiate (in nsIAbDirectory directory); */
NS_IMETHODIMP nsAbDirectoryQueryProxy::Initiate(nsIAbDirectory *directory)
{
if (mInitiated == PR_TRUE)
return NS_OK;
nsAbDirectoryQuery* _directoryQuery = new nsAbDirectoryQuery (directory);
mDirectoryQuery = _directoryQuery;
mInitiated = PR_TRUE;
return NS_OK;
}

View File

@ -0,0 +1,46 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#ifndef nsAbDirectoryQueryProxy_h__
#define nsAbDirectoryQueryProxy_h__
#include "nsIAbDirectoryQueryProxy.h"
#include "nsCOMPtr.h"
class nsAbDirectoryQueryProxy : public nsIAbDirectoryQueryProxy
{
public:
NS_DECL_ISUPPORTS
NS_FORWARD_NSIABDIRECTORYQUERY(mDirectoryQuery->)
NS_DECL_NSIABDIRECTORYQUERYPROXY
nsAbDirectoryQueryProxy();
virtual ~nsAbDirectoryQueryProxy();
protected:
PRBool mInitiated;
nsCOMPtr<nsIAbDirectoryQuery> mDirectoryQuery;
};
#endif

View File

@ -0,0 +1,90 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Contributor(s): Paul Sandoz <paul.sandoz@sun.com>
*/
#include "nsAbDirectoryRDFResource.h"
#include "nsIURL.h"
#include "nsNetCID.h"
#include "nsIServiceManager.h"
#include "nsCOMPtr.h"
#include "nsXPIDLString.h"
#include "nsString.h"
#include "nsAbQueryStringToExpression.h"
#include "nsAbBoolExprToLDAPFilter.h"
nsAbDirectoryRDFResource::nsAbDirectoryRDFResource () :
nsRDFResource (),
mIsValidURI (PR_FALSE),
mIsQueryURI (PR_FALSE)
{
}
nsAbDirectoryRDFResource::~nsAbDirectoryRDFResource ()
{
}
NS_IMPL_ISUPPORTS_INHERITED0(nsAbDirectoryRDFResource, nsRDFResource)
NS_IMETHODIMP nsAbDirectoryRDFResource::Init(const char* aURI)
{
nsresult rv;
rv = nsRDFResource::Init (aURI);
NS_ENSURE_SUCCESS(rv, rv);
mURINoQuery = aURI;
nsCOMPtr<nsIURI> uri = do_CreateInstance (NS_STANDARDURL_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = uri->SetSpec(aURI);
NS_ENSURE_SUCCESS(rv, rv);
mIsValidURI = PR_TRUE;
nsCOMPtr<nsIURL> url = do_QueryInterface(uri);
NS_ENSURE_SUCCESS(rv, rv);
nsXPIDLCString queryString;
rv = url->GetEscapedQuery (getter_Copies(queryString));
nsXPIDLCString path;
rv = url->GetPath (getter_Copies(path));
mPath = path;
PRUint32 queryStringLength;
if (queryString.get () && (queryStringLength = nsCRT::strlen (queryString)))
{
int pathLength = nsCRT::strlen (path) - queryStringLength - 1;
mPath.Truncate (pathLength);
mURINoQuery.Truncate (mURINoQuery.Length () - queryStringLength - 1);
mQueryString = queryString;
mIsQueryURI = PR_TRUE;
}
return rv;
}

View File

@ -0,0 +1,50 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Contributor(s): Paul Sandoz <paul.sandoz@sun.com>
*/
#ifndef nsAbDirectoryRDFResource_h__
#define nsAbDirectoryRDFResource_h__
#include "nsRDFResource.h"
#include "nsIAbBooleanExpression.h"
#include "nsString.h"
class nsAbDirectoryRDFResource : public nsRDFResource
{
public:
NS_DECL_ISUPPORTS_INHERITED
nsAbDirectoryRDFResource ();
virtual ~nsAbDirectoryRDFResource ();
// nsIRDFResource methods:
NS_IMETHOD Init(const char* aURI);
protected:
PRBool mIsValidURI;
PRBool mIsQueryURI;
nsCString mPath;
nsCString mQueryString;
nsCString mURINoQuery;
};
#endif

View File

@ -0,0 +1,36 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#include "nsAbLDAPCard.h"
nsAbLDAPCard::nsAbLDAPCard()
{
}
nsAbLDAPCard::~nsAbLDAPCard()
{
}
NS_IMPL_ISUPPORTS_INHERITED(nsAbLDAPCard, nsRDFResource, nsIAbCard)

View File

@ -0,0 +1,43 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#ifndef nsAbLDAPCard_h__
#define nsAbLDAPCard_h__
#include "nsRDFResource.h"
#include "nsAbCardProperty.h"
#include "nsISupportsArray.h"
class nsAbLDAPCard : public nsRDFResource, public nsAbCardProperty
{
public:
NS_DECL_ISUPPORTS_INHERITED
nsAbLDAPCard();
virtual ~nsAbLDAPCard();
protected:
};
#endif

View File

@ -0,0 +1,118 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s): Csaba Borbola <csaba.borbola@sun.com>
*/
#include "nsAbLDAPDirFactory.h"
#include "nsAbUtils.h"
#include "nsIServiceManager.h"
#include "nsIRDFService.h"
#include "nsIRDFResource.h"
#include "nsIAbDirectory.h"
#include "nsAbLDAPDirectory.h"
#include "nsAbDirFactoryService.h"
#include "nsIAddressBook.h"
#include "nsEnumeratorUtils.h"
#include "nsAbBaseCID.h"
extern const char* kDescriptionPropertyName;
extern const char* kURIPropertyName;
NS_IMPL_ISUPPORTS1(nsAbLDAPDirFactory, nsIAbDirFactory);
nsAbLDAPDirFactory::nsAbLDAPDirFactory()
{
NS_INIT_ISUPPORTS();
}
nsAbLDAPDirFactory::~nsAbLDAPDirFactory()
{
}
/* nsISimpleEnumerator createDirectory (in unsigned long propertiesSize, [array, size_is (propertiesSize)] in string propertyNamesArray, [array, size_is (propertiesSize)] in wstring propertyValuesArray); */
NS_IMETHODIMP nsAbLDAPDirFactory::CreateDirectory(
PRUint32 propertiesSize,
const char **propertyNamesArray,
const PRUnichar **propertyValuesArray,
nsISimpleEnumerator **_retval)
{
if (!*propertyNamesArray || !*propertyValuesArray)
return NS_ERROR_NULL_POINTER;
if (propertiesSize == 0)
return NS_ERROR_FAILURE;
nsresult rv;
// Create hash table from property arrays
nsHashtable propertySet;
rv = PropertyPtrArraysToHashtable::Convert (
propertySet,
propertiesSize,
propertyNamesArray,
propertyValuesArray);
NS_ENSURE_SUCCESS (rv, rv);
// Get description property
nsCStringKey descriptionKey (kDescriptionPropertyName, -1, nsCStringKey::NEVER_OWN);
const PRUnichar* description = NS_REINTERPRET_CAST(PRUnichar* ,propertySet.Get (&descriptionKey));
// Get uri property
nsCStringKey URIKey (kURIPropertyName, -1, nsCStringKey::NEVER_OWN);
const PRUnichar* URIUCS2 = NS_REINTERPRET_CAST(PRUnichar* ,propertySet.Get (&URIKey));
if (!URIUCS2)
return NS_ERROR_FAILURE;
NS_ConvertUCS2toUTF8 URIUTF8(URIUCS2);
nsCOMPtr<nsIRDFService> rdf = do_GetService (NS_RDF_CONTRACTID "/rdf-service;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIRDFResource> resource;
rv = rdf->GetResource(URIUTF8.get (), getter_AddRefs(resource));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAbDirectory> directory(do_QueryInterface(resource, &rv));
NS_ENSURE_SUCCESS(rv, rv);
directory->SetDirName(description);
NS_IF_ADDREF(*_retval = new nsSingletonEnumerator(directory));
return *_retval ? NS_OK : NS_ERROR_OUT_OF_MEMORY;
}
/* void deleteDirectory (in nsIAbDirectory directory); */
NS_IMETHODIMP nsAbLDAPDirFactory::DeleteDirectory(nsIAbDirectory *directory)
{
return NS_OK;
}

View File

@ -0,0 +1,41 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s): Csaba Borbola <csaba.borbola@sun.com>
*/
#ifndef nsAbLDAPDirFactory_h__
#define nsAbLDAPDirFactory_h__
#include "nsIAbDirFactory.h"
class nsAbLDAPDirFactory : public nsIAbDirFactory
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIABDIRFACTORY
nsAbLDAPDirFactory();
virtual ~nsAbLDAPDirFactory();
};
#endif

View File

@ -0,0 +1,393 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#include "nsAbLDAPDirectory.h"
#include "nsAbLDAPProperties.h"
#include "nsAbUtils.h"
#include "nsAbQueryStringToExpression.h"
#include "nsAbBaseCID.h"
#include "nsIAddrBookSession.h"
#include "nsIRDFService.h"
#include "nsString.h"
#include "nsXPIDLString.h"
#include "prprf.h"
#include "nsAutoLock.h"
nsAbLDAPDirectory::nsAbLDAPDirectory() :
nsAbDirectoryRDFResource(),
nsAbLDAPDirectoryQuery (),
mInitialized(PR_FALSE),
mInitializedConnection(PR_FALSE),
mPerformingQuery(PR_FALSE),
mContext(0),
mLock(0)
{
}
nsAbLDAPDirectory::~nsAbLDAPDirectory()
{
if (mLock)
PR_DestroyLock (mLock);
}
NS_IMPL_ISUPPORTS_INHERITED3(nsAbLDAPDirectory, nsAbDirectoryRDFResource, nsIAbDirectory, nsIAbDirectoryQuery, nsIAbDirectorySearch)
nsresult nsAbLDAPDirectory::Initiate ()
{
if (mIsQueryURI == PR_FALSE)
return NS_ERROR_FAILURE;
if (mInitialized == PR_TRUE)
return NS_OK;
nsresult rv;
mLock = PR_NewLock ();
if(!mLock)
{
return NS_ERROR_OUT_OF_MEMORY;
}
rv = nsAbQueryStringToExpression::Convert (mQueryString.get (),
getter_AddRefs(mExpression));
NS_ENSURE_SUCCESS(rv, rv);
rv = InitiateConnection ();
mInitialized = PR_TRUE;
return rv;
}
nsresult nsAbLDAPDirectory::InitiateConnection ()
{
if (mInitializedConnection == PR_TRUE)
return NS_OK;
nsresult rv;
mURL = do_CreateInstance(NS_LDAPURL_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
nsCAutoString uriString (mURINoQuery);
uriString.ReplaceSubstring ("moz-abldapdirectory:", "ldap:");
rv = mURL->SetSpec(uriString.get ());
NS_ENSURE_SUCCESS(rv, rv);
mConnection = do_CreateInstance(NS_LDAPCONNECTION_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
nsXPIDLCString host;
rv = mURL->GetHost(getter_Copies (host));
NS_ENSURE_SUCCESS(rv, rv);
PRInt32 port;
rv = mURL->GetPort(&port);
NS_ENSURE_SUCCESS(rv, rv);
nsXPIDLCString dn;
rv = mURL->GetDn(getter_Copies (dn));
NS_ENSURE_SUCCESS(rv, rv);
rv = mConnection->Init(host, port, NS_ConvertASCIItoUCS2(dn).get());
NS_ENSURE_SUCCESS(rv, rv);
mInitializedConnection = PR_TRUE;
return rv;
}
/*
*
* nsIAbDirectory methods
*
*/
NS_IMETHODIMP nsAbLDAPDirectory::GetOperations(PRInt32 *aOperations)
{
*aOperations = nsIAbDirectory::opSearch;
return NS_OK;
}
NS_IMETHODIMP nsAbLDAPDirectory::GetChildNodes(nsIEnumerator* *result)
{
nsCOMPtr<nsISupportsArray> array;
NS_NewISupportsArray(getter_AddRefs(array));
if (!array)
return NS_ERROR_OUT_OF_MEMORY;
return array->Enumerate(result);
}
NS_IMETHODIMP nsAbLDAPDirectory::GetChildCards(nsIEnumerator** result)
{
nsresult rv;
// Start the search
rv = StartSearch ();
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsISupportsArray> array;
NS_NewISupportsArray(getter_AddRefs(array));
if (!array)
return NS_ERROR_OUT_OF_MEMORY;
return array->Enumerate(result);
}
NS_IMETHODIMP nsAbLDAPDirectory::HasCard(nsIAbCard* card, PRBool* hasCard)
{
nsresult rv;
rv = Initiate ();
NS_ENSURE_SUCCESS(rv, rv);
nsVoidKey key (NS_STATIC_CAST(void* ,card));
// Enter lock
nsAutoLock lock (mLock);
*hasCard = mCache.Exists (&key);
if (*hasCard == PR_FALSE && mPerformingQuery == PR_TRUE)
return NS_ERROR_NOT_AVAILABLE;
return NS_OK;
}
NS_IMETHODIMP nsAbLDAPDirectory::GetTotalCards(PRBool subDirectoryCount,
PRUint32 *_retval)
{
nsresult rv;
rv = Initiate ();
NS_ENSURE_SUCCESS(rv, rv);
// Enter lock
nsAutoLock lock (mLock);
*_retval = NS_STATIC_CAST(PRUint32 ,mCache.Count ());
return NS_OK;
}
/*
*
* nsAbLDAPDirectoryQuery methods
*
*/
nsresult nsAbLDAPDirectory::GetLDAPConnection (nsILDAPConnection** connection)
{
nsresult rv;
rv = InitiateConnection ();
NS_ENSURE_SUCCESS(rv, rv);
*connection = mConnection;
NS_IF_ADDREF(*connection);
return rv;
}
nsresult nsAbLDAPDirectory::GetLDAPURL (nsILDAPURL** url)
{
nsresult rv;
rv = InitiateConnection ();
NS_ENSURE_SUCCESS(rv, rv);
*url = mURL;
NS_IF_ADDREF(*url);
return rv;
}
nsresult nsAbLDAPDirectory::CreateCard (nsILDAPURL* uri, const char* dn, nsIAbCard** card)
{
nsresult rv;
nsXPIDLCString cardUri;
rv = CreateCardURI (uri, dn, getter_Copies (cardUri));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIRDFResource> res;
rv = gRDFService->GetResource(cardUri, getter_AddRefs(res));
NS_ENSURE_SUCCESS(rv, rv);
rv = res->QueryInterface(NS_GET_IID(nsIAbCard), NS_REINTERPRET_CAST(void**, card));
NS_IF_ADDREF(*card);
return rv;
}
nsresult nsAbLDAPDirectory::CreateCardURI (nsILDAPURL* uri, const char* dn, char** cardUri)
{
nsresult rv;
nsXPIDLCString host;
rv = uri->GetHost(getter_Copies (host));
NS_ENSURE_SUCCESS(rv, rv);
PRInt32 port;
rv = uri->GetPort(&port);
NS_ENSURE_SUCCESS(rv, rv);
*cardUri = PR_smprintf("moz-abldapcard://%s:%d/%s", host.get (), port, dn);
if(!cardUri)
{
return NS_ERROR_OUT_OF_MEMORY;
}
return rv;
}
/*
*
* nsIAbDirectorySearch methods
*
*/
NS_IMETHODIMP nsAbLDAPDirectory::StartSearch ()
{
nsresult rv;
if (mIsQueryURI == PR_FALSE ||
mQueryString.Length () == 0)
return NS_OK;
rv = Initiate ();
NS_ENSURE_SUCCESS(rv, rv);
rv = StopSearch ();
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAbDirectoryQueryArguments> arguments;
NS_NewIAbDirectoryQueryArguments (getter_AddRefs(arguments));
rv = arguments->SetExpression (mExpression);
NS_ENSURE_SUCCESS(rv, rv);
// Set the return properties to
// return nsIAbCard interfaces
nsCStringArray properties;
properties.AppendCString (nsCAutoString ("card:nsIAbCard"));
CharPtrArrayGuard returnProperties (PR_FALSE);
rv = CStringArrayToCharPtrArray::Convert (properties,returnProperties.GetSizeAddr(),
returnProperties.GetArrayAddr(), PR_FALSE);
NS_ENSURE_SUCCESS(rv, rv);
rv = arguments->SetReturnProperties (returnProperties.GetSize(), returnProperties.GetArray());
NS_ENSURE_SUCCESS(rv, rv);
rv = arguments->SetQuerySubDirectories (PR_TRUE);
NS_ENSURE_SUCCESS(rv, rv);
// Set the the query listener
nsCOMPtr<nsIAbDirectoryQueryResultListener> queryListener;
nsAbDirSearchListener* _queryListener =
new nsAbDirSearchListener (this);
queryListener = _queryListener;
// Perform the query
rv = DoQuery (arguments, queryListener, 100, 0, &mContext);
NS_ENSURE_SUCCESS(rv, rv);
// Enter lock
nsAutoLock lock (mLock);
mPerformingQuery = PR_TRUE;
mCache.Reset ();
return rv;
}
NS_IMETHODIMP nsAbLDAPDirectory::StopSearch ()
{
nsresult rv;
rv = Initiate ();
NS_ENSURE_SUCCESS(rv, rv);
// Enter lock
{
nsAutoLock lockGuard (mLock);
if (mPerformingQuery == PR_FALSE)
return NS_OK;
mPerformingQuery = PR_FALSE;
}
// Exit lock
rv = StopQuery (mContext);
return rv;
}
/*
*
* nsAbDirSearchListenerContext methods
*
*/
nsresult nsAbLDAPDirectory::OnSearchFinished (PRInt32 result)
{
nsresult rv;
rv = Initiate ();
NS_ENSURE_SUCCESS(rv, rv);
nsAutoLock lock (mLock);
mPerformingQuery = PR_FALSE;
return NS_OK;
}
nsresult nsAbLDAPDirectory::OnSearchFoundCard (nsIAbCard* card)
{
nsresult rv;
rv = Initiate ();
NS_ENSURE_SUCCESS(rv, rv);
nsVoidKey key (NS_STATIC_CAST(void* ,card));
// Enter lock
{
nsAutoLock lock (mLock);
mCache.Put (&key, card);
}
// Exit lock
nsCOMPtr<nsIAddrBookSession> abSession = do_GetService(NS_ADDRBOOKSESSION_CONTRACTID, &rv);;
if(NS_SUCCEEDED(rv))
abSession->NotifyDirectoryItemAdded(this, card);
return NS_OK;
}

View File

@ -0,0 +1,88 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#ifndef nsAbLDAPDirectory_h__
#define nsAbLDAPDirectory_h__
#include "nsAbDirectoryRDFResource.h"
#include "nsAbDirProperty.h"
#include "nsAbLDAPDirectoryQuery.h"
#include "nsIAbDirectorySearch.h"
#include "nsAbDirSearchListener.h"
#include "nsHashtable.h"
class nsAbLDAPDirectory :
public nsAbDirectoryRDFResource, // nsIRDFResource
public nsAbDirProperty, // nsIAbDirectory
public nsAbLDAPDirectoryQuery, // nsIAbDirectoryQuery
public nsIAbDirectorySearch,
public nsAbDirSearchListenerContext
{
public:
NS_DECL_ISUPPORTS_INHERITED
nsAbLDAPDirectory();
virtual ~nsAbLDAPDirectory();
// nsIAbDirectory methods
NS_IMETHOD GetOperations(PRInt32 *aOperations);
NS_IMETHOD GetChildNodes(nsIEnumerator* *result);
NS_IMETHOD GetChildCards(nsIEnumerator* *result);
NS_IMETHOD HasCard(nsIAbCard *cards, PRBool *hasCard);
NS_IMETHOD GetTotalCards(PRBool subDirectoryCount, PRUint32 *_retval);
// nsAbLDAPDirectoryQuery methods
nsresult GetLDAPConnection (nsILDAPConnection** connection);
nsresult GetLDAPURL (nsILDAPURL** url);
nsresult CreateCard (nsILDAPURL* uri, const char* dn, nsIAbCard** card);
nsresult CreateCardURI (nsILDAPURL* uri, const char* dn, char** cardUri);
// nsIAbDirectorySearch methods
NS_DECL_NSIABDIRECTORYSEARCH
// nsAbDirSearchListenerContext methods
nsresult OnSearchFinished (PRInt32 result);
nsresult OnSearchFoundCard (nsIAbCard* card);
protected:
nsresult Initiate ();
nsresult InitiateConnection ();
protected:
PRBool mInitialized;
PRBool mInitializedConnection;
PRBool mPerformingQuery;
PRInt32 mContext;
nsCOMPtr<nsILDAPURL> mURL ;
nsCOMPtr<nsILDAPConnection> mConnection;
nsCOMPtr<nsIAbBooleanExpression> mExpression;
nsSupportsHashtable mCache;
PRLock* mLock;
};
#endif

View File

@ -0,0 +1,733 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#include "nsAbLDAPDirectoryQuery.h"
#include "nsAbBoolExprToLDAPFilter.h"
#include "nsAbLDAPProperties.h"
#include "nsILDAPErrors.h"
#include "nsILDAPOperation.h"
#include "nsAbUtils.h"
#include "nsXPIDLString.h"
#include "nsAutoLock.h"
class nsAbQueryLDAPMessageListener : public nsILDAPMessageListener
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSILDAPMESSAGELISTENER
nsAbQueryLDAPMessageListener (
nsAbLDAPDirectoryQuery* directoryQuery,
PRInt32 contextID,
nsILDAPURL* url,
nsILDAPConnection* connection,
nsIAbDirectoryQueryArguments* queryArguments,
nsIAbDirectoryQueryResultListener* queryListener,
PRInt32 resultLimit = -1,
PRInt32 timeOut = 0);
virtual ~nsAbQueryLDAPMessageListener ();
protected:
nsresult OnLDAPMessageBind (nsILDAPMessage *aMessage);
nsresult OnLDAPMessageSearchEntry (nsILDAPMessage *aMessage,
nsIAbDirectoryQueryResult** result);
nsresult OnLDAPMessageSearchResult (nsILDAPMessage *aMessage,
nsIAbDirectoryQueryResult** result);
nsresult QueryMatch (nsISupportsArray* properties,
nsIAbDirectoryQueryResult** result);
nsresult QueryComplete (nsIAbDirectoryQueryResult** result);
nsresult QueryStopped (nsIAbDirectoryQueryResult** result);
nsresult QueryError (nsIAbDirectoryQueryResult** result);
protected:
friend class nsAbLDAPDirectoryQuery;
nsresult Cancel ();
nsresult Initiate ();
protected:
nsAbLDAPDirectoryQuery* mDirectoryQuery;
PRInt32 mContextID;
nsCOMPtr<nsILDAPURL> mUrl;
nsCOMPtr<nsILDAPConnection> mConnection;
nsCOMPtr<nsIAbDirectoryQueryArguments> mQueryArguments;
nsCOMPtr<nsIAbDirectoryQueryResultListener> mQueryListener;
PRInt32 mResultLimit;
PRInt32 mTimeOut;
PRBool mBound;
PRBool mFinished;
PRBool mInitialized;
PRBool mCanceled;
nsCOMPtr<nsILDAPOperation> mSearchOperation;
PRLock* mLock;
};
NS_IMPL_THREADSAFE_ISUPPORTS1(nsAbQueryLDAPMessageListener, nsILDAPMessageListener)
nsAbQueryLDAPMessageListener::nsAbQueryLDAPMessageListener (
nsAbLDAPDirectoryQuery* directoryQuery,
PRInt32 contextID,
nsILDAPURL* url,
nsILDAPConnection* connection,
nsIAbDirectoryQueryArguments* queryArguments,
nsIAbDirectoryQueryResultListener* queryListener,
PRInt32 resultLimit,
PRInt32 timeOut) :
mDirectoryQuery (directoryQuery),
mContextID (contextID),
mUrl (url),
mConnection (connection),
mQueryArguments (queryArguments),
mQueryListener (queryListener),
mResultLimit (resultLimit),
mTimeOut (timeOut),
mBound (PR_FALSE),
mFinished (PR_FALSE),
mInitialized(PR_FALSE),
mCanceled (PR_FALSE),
mLock(0)
{
NS_INIT_ISUPPORTS();
NS_ADDREF(mDirectoryQuery);
}
nsAbQueryLDAPMessageListener::~nsAbQueryLDAPMessageListener ()
{
if (mLock)
PR_DestroyLock (mLock);
NS_RELEASE(mDirectoryQuery);
}
nsresult nsAbQueryLDAPMessageListener::Initiate ()
{
if(mInitialized == PR_TRUE)
return NS_OK;
mLock = PR_NewLock ();
if(!mLock)
{
return NS_ERROR_OUT_OF_MEMORY;
}
mInitialized = PR_TRUE;
return NS_OK;
}
nsresult nsAbQueryLDAPMessageListener::Cancel ()
{
nsresult rv;
rv = Initiate();
NS_ENSURE_SUCCESS(rv, rv);
nsAutoLock lock(mLock);
if (mFinished == PR_TRUE || mCanceled == PR_TRUE)
return NS_OK;
mCanceled = PR_TRUE;
return NS_OK;
}
NS_IMETHODIMP nsAbQueryLDAPMessageListener::OnLDAPMessage(nsILDAPMessage *aMessage)
{
nsresult rv;
rv = Initiate();
NS_ENSURE_SUCCESS(rv, rv);
PRInt32 messageType;
rv = aMessage->GetType(&messageType);
NS_ENSURE_SUCCESS(rv, rv);
PRBool cancelOperation = PR_FALSE;
// Enter lock
{
nsAutoLock lock (mLock);
if (mFinished == PR_TRUE)
return NS_OK;
if (messageType == nsILDAPMessage::RES_SEARCH_RESULT)
mFinished = PR_TRUE;
else if (mCanceled == PR_TRUE)
{
mFinished = PR_TRUE;
cancelOperation = PR_TRUE;
}
}
// Leave lock
nsCOMPtr<nsIAbDirectoryQueryResult> queryResult;
if (cancelOperation == PR_FALSE)
{
switch (messageType)
{
case nsILDAPMessage::RES_BIND:
rv = OnLDAPMessageBind (aMessage);
NS_ENSURE_SUCCESS(rv, rv);
break;
case nsILDAPMessage::RES_SEARCH_ENTRY:
rv = OnLDAPMessageSearchEntry (aMessage, getter_AddRefs (queryResult));
NS_ENSURE_SUCCESS(rv, rv);
break;
case nsILDAPMessage::RES_SEARCH_RESULT:
rv = OnLDAPMessageSearchResult (aMessage, getter_AddRefs (queryResult));
NS_ENSURE_SUCCESS(rv, rv);
default:
break;
}
}
else
{
if (mSearchOperation)
rv = mSearchOperation->Abandon ();
rv = QueryStopped (getter_AddRefs (queryResult));
}
if (queryResult)
rv = mQueryListener->OnQueryItem (queryResult);
return rv;
}
nsresult nsAbQueryLDAPMessageListener::OnLDAPMessageBind (nsILDAPMessage *aMessage)
{
if (mBound == PR_TRUE)
return NS_OK;
nsresult rv;
mSearchOperation = do_CreateInstance(NS_LDAPOPERATION_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = mSearchOperation->Init (mConnection, this);
NS_ENSURE_SUCCESS(rv, rv);
nsXPIDLCString dn;
rv = mUrl->GetDn (getter_Copies (dn));
NS_ENSURE_SUCCESS(rv, rv);
PRInt32 scope;
rv = mUrl->GetScope (&scope);
NS_ENSURE_SUCCESS(rv, rv);
nsXPIDLCString filter;
rv = mUrl->GetFilter (getter_Copies (filter));
NS_ENSURE_SUCCESS(rv, rv);
CharPtrArrayGuard attributes;
rv = mUrl->GetAttributes (attributes.GetSizeAddr (), attributes.GetArrayAddr ());
NS_ENSURE_SUCCESS(rv, rv);
rv = mSearchOperation->SearchExt (NS_ConvertASCIItoUCS2(dn).get(), scope,
NS_ConvertASCIItoUCS2(filter).get(),
attributes.GetSize (), attributes.GetArray (),
mTimeOut, mResultLimit);
NS_ENSURE_SUCCESS(rv, rv);
mBound = PR_TRUE;
return rv;
}
nsresult nsAbQueryLDAPMessageListener::OnLDAPMessageSearchEntry (nsILDAPMessage *aMessage,
nsIAbDirectoryQueryResult** result)
{
nsresult rv;
nsCOMPtr<nsISupportsArray> propertyValues;
CharPtrArrayGuard properties;
rv = mQueryArguments->GetReturnProperties (properties.GetSizeAddr(), properties.GetArrayAddr());
NS_ENSURE_SUCCESS(rv, rv);
CharPtrArrayGuard attrs;
rv = aMessage->GetAttributes(attrs.GetSizeAddr(), attrs.GetArrayAddr());
NS_ENSURE_SUCCESS(rv, rv);
nsCAutoString n;
for (PRUint32 i = 0; i < properties.GetSize(); i++)
{
n.Assign (properties[i]);
nsAbDirectoryQueryPropertyValue* _propertyValue = 0;
if (n.EqualsWithConversion ("card:URI"))
{
// Meta property
//
nsXPIDLString dn;
rv = aMessage->GetDn (getter_Copies (dn));
NS_ENSURE_SUCCESS(rv, rv);
nsXPIDLCString uri;
rv = mDirectoryQuery->CreateCardURI (mUrl, NS_ConvertUCS2toUTF8(dn).get(), getter_Copies (uri));
NS_ENSURE_SUCCESS(rv, rv);
NS_ConvertUTF8toUCS2 v (uri.get ());
_propertyValue = new nsAbDirectoryQueryPropertyValue(n.get (), v.get ());
if (_propertyValue == NULL)
return NS_ERROR_OUT_OF_MEMORY;
}
else if (n.EqualsWithConversion ("card:nsIAbCard"))
{
// Meta property
//
nsXPIDLString dn;
rv = aMessage->GetDn (getter_Copies (dn));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAbCard> card;
rv = mDirectoryQuery->CreateCard (mUrl, NS_ConvertUCS2toUTF8(dn).get(), getter_AddRefs (card));
NS_ENSURE_SUCCESS(rv, rv);
PRBool hasSetCardProperty = PR_FALSE;
rv = MozillaLdapPropertyRelator::createCardPropertyFromLDAPMessage (aMessage,
card,
&hasSetCardProperty);
NS_ENSURE_SUCCESS(rv, rv);
if (hasSetCardProperty == PR_FALSE)
continue;
_propertyValue = new nsAbDirectoryQueryPropertyValue(n.get (), card);
if (_propertyValue == NULL)
return NS_ERROR_OUT_OF_MEMORY;
}
else
{
const MozillaLdapPropertyRelation* p =
MozillaLdapPropertyRelator::findLdapPropertyFromMozilla (n.get ());
if (!p)
continue;
for (PRUint32 j = 0; j < attrs.GetSize(); j++)
{
if (nsCRT::strcasecmp (p->ldapProperty, attrs[j]) == 0)
{
PRUnicharPtrArrayGuard vals;
rv = aMessage->GetValues (attrs[j], vals.GetSizeAddr(), vals.GetArrayAddr());
NS_ENSURE_SUCCESS(rv, rv);
if (vals.GetSize() == 0)
break;
_propertyValue = new nsAbDirectoryQueryPropertyValue(n.get (), vals[0]);
if (_propertyValue == NULL)
return NS_ERROR_OUT_OF_MEMORY;
break;
}
}
}
if (_propertyValue)
{
nsCOMPtr<nsIAbDirectoryQueryPropertyValue> propertyValue;
propertyValue = _propertyValue;
if (!propertyValues)
{
NS_NewISupportsArray(getter_AddRefs(propertyValues));
}
propertyValues->AppendElement (propertyValue);
}
}
if (!propertyValues)
return NS_OK;
return QueryMatch (propertyValues, result);
}
nsresult nsAbQueryLDAPMessageListener::OnLDAPMessageSearchResult (nsILDAPMessage *aMessage,
nsIAbDirectoryQueryResult** result)
{
mDirectoryQuery->RemoveListener (mContextID);
nsresult rv;
PRInt32 errorCode;
rv = aMessage->GetErrorCode(&errorCode);
NS_ENSURE_SUCCESS(rv, rv);
if (errorCode == nsILDAPErrors::SUCCESS || errorCode == nsILDAPErrors::SIZELIMIT_EXCEEDED)
rv = QueryComplete (result);
else
rv = QueryError (result);
return rv;
}
nsresult nsAbQueryLDAPMessageListener::QueryMatch (nsISupportsArray* properties,
nsIAbDirectoryQueryResult** result)
{
nsAbDirectoryQueryResult* _queryResult = new nsAbDirectoryQueryResult (
mContextID,
mQueryArguments,
nsIAbDirectoryQueryResult::queryResultMatch,
properties);
if (_queryResult == NULL)
return NS_ERROR_OUT_OF_MEMORY;
*result = _queryResult;
NS_IF_ADDREF(*result);
return NS_OK;
}
nsresult nsAbQueryLDAPMessageListener::QueryComplete (nsIAbDirectoryQueryResult** result)
{
nsAbDirectoryQueryResult* _queryResult = new nsAbDirectoryQueryResult (
mContextID,
mQueryArguments,
nsIAbDirectoryQueryResult::queryResultComplete,
0);
if (_queryResult == NULL)
return NS_ERROR_OUT_OF_MEMORY;
*result = _queryResult;
NS_IF_ADDREF(*result);
return NS_OK;
}
nsresult nsAbQueryLDAPMessageListener::QueryStopped (nsIAbDirectoryQueryResult** result)
{
nsAbDirectoryQueryResult* _queryResult = new nsAbDirectoryQueryResult (
mContextID,
mQueryArguments,
nsIAbDirectoryQueryResult::queryResultStopped,
0);
if (_queryResult == NULL)
return NS_ERROR_OUT_OF_MEMORY;
*result = _queryResult;
NS_IF_ADDREF(*result);
return NS_OK;
}
nsresult nsAbQueryLDAPMessageListener::QueryError (nsIAbDirectoryQueryResult** result)
{
nsAbDirectoryQueryResult* _queryResult = new nsAbDirectoryQueryResult (
mContextID,
mQueryArguments,
nsIAbDirectoryQueryResult::queryResultError,
0);
if (_queryResult == NULL)
return NS_ERROR_OUT_OF_MEMORY;
*result = _queryResult;
NS_IF_ADDREF(*result);
return NS_OK;
}
NS_IMPL_THREADSAFE_ISUPPORTS1(nsAbLDAPDirectoryQuery, nsIAbDirectoryQuery)
nsAbLDAPDirectoryQuery::nsAbLDAPDirectoryQuery() :
mInitialized(PR_FALSE),
mCounter (1),
mLock (nsnull)
{
NS_INIT_ISUPPORTS();
}
nsAbLDAPDirectoryQuery::~nsAbLDAPDirectoryQuery()
{
if(mLock)
PR_DestroyLock (mLock);
}
nsresult nsAbLDAPDirectoryQuery::Initiate ()
{
if(mInitialized == PR_TRUE)
return NS_OK;
mLock = PR_NewLock ();
if(!mLock)
{
return NS_ERROR_OUT_OF_MEMORY;
}
mInitialized = PR_TRUE;
return NS_OK;
}
NS_IMETHODIMP nsAbLDAPDirectoryQuery::DoQuery(nsIAbDirectoryQueryArguments* arguments,
nsIAbDirectoryQueryResultListener* listener,
PRInt32 resultLimit,
PRInt32 timeOut,
PRInt32* _retval)
{
nsresult rv;
rv = Initiate ();
NS_ENSURE_SUCCESS(rv, rv);
// Get the scope
nsCAutoString scope;
PRBool doSubDirectories;
rv = arguments->GetQuerySubDirectories (&doSubDirectories);
NS_ENSURE_SUCCESS(rv, rv);
if (doSubDirectories == PR_TRUE)
scope = "sub";
else
scope = "one";
// Get the return attributes
nsCAutoString returnAttributes;
rv = getLdapReturnAttributes (arguments, returnAttributes);
NS_ENSURE_SUCCESS(rv, rv);
// Get the filter
nsCOMPtr<nsISupports> supportsExpression;
rv = arguments->GetExpression (getter_AddRefs (supportsExpression));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAbBooleanExpression> expression (do_QueryInterface (supportsExpression, &rv));
nsCString filter;
rv = nsAbBoolExprToLDAPFilter::Convert (expression, filter);
NS_ENSURE_SUCCESS(rv, rv);
// Set up the search ldap url
nsCOMPtr<nsILDAPURL> directoryUrl;
rv = GetLDAPURL (getter_AddRefs (directoryUrl));
NS_ENSURE_SUCCESS(rv, rv);
nsXPIDLCString host;
rv = directoryUrl->GetHost(getter_Copies (host));
NS_ENSURE_SUCCESS(rv, rv);
PRInt32 port;
rv = directoryUrl->GetPort(&port);
NS_ENSURE_SUCCESS(rv, rv);
nsXPIDLCString dn;
rv = directoryUrl->GetDn(getter_Copies (dn));
NS_ENSURE_SUCCESS(rv, rv);
nsCString ldapSearchUrlString;
char* _ldapSearchUrlString = PR_smprintf ("ldap://%s:%d/%s?%s?%s?%s",
host.get (),
port,
dn.get (),
returnAttributes.get (),
scope.get (),
filter.get ());
if (!_ldapSearchUrlString)
return NS_ERROR_OUT_OF_MEMORY;
ldapSearchUrlString = _ldapSearchUrlString;
PR_smprintf_free (_ldapSearchUrlString);
nsCOMPtr<nsILDAPURL> url;
url = do_CreateInstance(NS_LDAPURL_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = url->SetSpec(ldapSearchUrlString.get ());
NS_ENSURE_SUCCESS(rv, rv);
// Get the ldap connection
nsCOMPtr<nsILDAPConnection> ldapConnection;
rv = GetLDAPConnection (getter_AddRefs (ldapConnection));
NS_ENSURE_SUCCESS(rv, rv);
// Initiate contextID for message listener
PRInt32 contextID;
// Enter lock
{
nsAutoLock lock (mLock);
contextID = mCounter++;
}
// Exit lock
// Initiate LDAP message listener
nsCOMPtr<nsILDAPMessageListener> messageListener;
nsAbQueryLDAPMessageListener* _messageListener =
new nsAbQueryLDAPMessageListener (
this,
contextID,
url,
ldapConnection,
arguments,
listener,
resultLimit,
timeOut);
if (_messageListener == NULL)
return NS_ERROR_OUT_OF_MEMORY;
messageListener = _messageListener;
nsVoidKey key (NS_REINTERPRET_CAST(void *,contextID));
// Enter lock
{
nsAutoLock lock1(mLock);
mListeners.Put (&key, _messageListener);
}
// Exit lock
*_retval = contextID;
// Initiate the LDAP operation
nsCOMPtr<nsILDAPOperation> ldapOperation = do_CreateInstance(NS_LDAPOPERATION_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = ldapOperation->Init(ldapConnection, messageListener);
NS_ENSURE_SUCCESS(rv, rv);
// Bind
rv = ldapOperation->SimpleBind(NULL);
NS_ENSURE_SUCCESS(rv, rv);
return rv;
}
/* void stopQuery (in long contextID); */
NS_IMETHODIMP nsAbLDAPDirectoryQuery::StopQuery(PRInt32 contextID)
{
nsresult rv;
rv = Initiate ();
NS_ENSURE_SUCCESS(rv, rv);
nsAbQueryLDAPMessageListener* _messageListener;
// Enter Lock
{
nsAutoLock lock(mLock);
nsVoidKey key (NS_REINTERPRET_CAST(void *,contextID));
_messageListener = (nsAbQueryLDAPMessageListener* )mListeners.Remove (&key);
if (!_messageListener)
return NS_OK;
}
// Exit Lock
rv = _messageListener->Cancel ();
return rv;
}
void nsAbLDAPDirectoryQuery::setLdapUrl (const char* aLdapUrl)
{
mLdapUrl = aLdapUrl;
}
nsresult nsAbLDAPDirectoryQuery::RemoveListener (PRInt32 contextID)
{
nsresult rv;
rv = Initiate ();
NS_ENSURE_SUCCESS(rv, rv);
nsAutoLock lock(mLock);
nsVoidKey key (NS_REINTERPRET_CAST(void *,contextID));
mListeners.Remove (&key);
return NS_OK;
}
nsresult nsAbLDAPDirectoryQuery::getLdapReturnAttributes (
nsIAbDirectoryQueryArguments* arguments,
nsCString& returnAttributes)
{
nsresult rv;
CharPtrArrayGuard properties;
rv = arguments->GetReturnProperties (properties.GetSizeAddr(), properties.GetArrayAddr());
NS_ENSURE_SUCCESS(rv, rv);
nsCAutoString n;
for (PRUint32 i = 0; i < properties.GetSize(); i++)
{
n.Assign (properties[i]);
if (n.EqualsWithConversion ("card:URI"))
{
// Meta property
//
continue;
}
else if (n.EqualsWithConversion ("card:nsIAbCard"))
{
// Meta property
// require all attributes
//
returnAttributes = "";
break;
}
const MozillaLdapPropertyRelation* p=
MozillaLdapPropertyRelator::findLdapPropertyFromMozilla (n.get ());
if (!p)
continue;
if (i)
returnAttributes.Append (",");
returnAttributes.Append (p->ldapProperty);
}
return rv;
}

View File

@ -0,0 +1,72 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#ifndef nsAbLDAPDirectoryQuery_h__
#define nsAbLDAPDirectoryQuery_h__
#include "nsAbDirectoryQuery.h"
#include "nsILDAPConnection.h"
#include "nsILDAPMessageListener.h"
#include "nsILDAPURL.h"
#include "nsString.h"
#include "nsHashtable.h"
class nsAbLDAPDirectoryQuery : public nsIAbDirectoryQuery
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIABDIRECTORYQUERY
nsAbLDAPDirectoryQuery();
virtual ~nsAbLDAPDirectoryQuery();
void setLdapUrl (const char* aldapUrl);
virtual nsresult GetLDAPConnection (nsILDAPConnection** connection) = 0;
virtual nsresult GetLDAPURL (nsILDAPURL** url) = 0;
virtual nsresult CreateCard (nsILDAPURL* url, const char* dn, nsIAbCard** card) = 0;
virtual nsresult CreateCardURI (nsILDAPURL* url, const char* dn, char** cardUri) = 0;
protected:
nsresult getLdapReturnAttributes (
nsIAbDirectoryQueryArguments* arguments,
nsCString& returnAttributes);
protected:
friend class nsAbQueryLDAPMessageListener;
nsresult RemoveListener (PRInt32 contextID);
nsresult Initiate ();
private:
nsCString mLdapUrl;
nsHashtable mListeners;
PRBool mInitialized;
PRInt32 mCounter;
PRLock* mLock;
};
#endif // nsAbLDAPDirectoryQuery_h__

View File

@ -0,0 +1,223 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#include "nsAbLDAPProperties.h"
#include "nsAbUtils.h"
#include "nsCOMPtr.h"
#include "nsString.h"
/*
Table defining the relationship between
mozilla card properties and corresponding
ldap properties.
Multiple entries for a mozilla property define
there is a many to one relationship between
ldap properties and the mozilla counterpart.
There is a one to one relationship between
a mozilla property and the ldap counterpart.
If there are multiple entries for a mozilla
property the first takes precedence.
This ensures that
1) Generality is maintained when mapping from
ldap properties to mozilla.
2) Consistent round tripping when editing
mozilla properties which are stored on
an ldap server
Ldap properties were obtained from existing
mozilla code that imported from ldif files,
comments above each table row indicate which
class of ldap object the property belongs.
*/
MozillaLdapPropertyRelation mozillaLdapPropertyTable[] =
{
// inetOrgPerson
{MozillaProperty_String, "FirstName", "givenname"},
// person
{MozillaProperty_String, "LastName", "sn"},
// person
{MozillaProperty_String, "LastName", "surname"},
// person
{MozillaProperty_String, "DisplayName", "cn"},
// person
{MozillaProperty_String, "DisplayName", "commonname"},
// inetOrfPerson
{MozillaProperty_String, "DisplayName", "displayname"},
// mozilla specific
{MozillaProperty_String, "NickName", "xmozillanickname"},
// inetOrfPerson
{MozillaProperty_String, "PrimaryEmail", "mail"},
// mozilla specific
{MozillaProperty_String, "SecondEmail", "xmozillasecondemail"},
// person
{MozillaProperty_String, "WorkPhone", "telephonenumber"},
// inetOrgPerson
{MozillaProperty_String, "HomePhone", "homephone"},
// ?
{MozillaProperty_String, "FaxNumber", "fax"},
// organizationalPerson
{MozillaProperty_String, "FaxNumber", "facsimiletelephonenumber"},
// inetOrgPerson
{MozillaProperty_String, "PagerNumber", "pager"},
// ?
{MozillaProperty_String, "PagerNumber", "pagerphone"},
// inetOrgPerson
{MozillaProperty_String, "CellularNumber", "mobile"},
// ?
{MozillaProperty_String, "CellularNumber", "cellphone"},
// ?
{MozillaProperty_String, "CellularNumber", "carphone"},
// No Home* properties defined yet
// organizationalPerson
{MozillaProperty_String, "WorkAddress", "postofficebox"},
// ?
{MozillaProperty_String, "WorkAddress", "streetaddress"},
// ?
{MozillaProperty_String, "WorkCity", "l"},
// ?
{MozillaProperty_String, "WorkCity", "locality"},
// ?
{MozillaProperty_String, "WorkState", "st"},
// ?
{MozillaProperty_String, "WorkState", "region"},
// organizationalPerson
{MozillaProperty_String, "WorkZipCode", "postalcode"},
// ?
{MozillaProperty_String, "WorkZipCode", "zip"},
// ?
{MozillaProperty_String, "WorkCountry", "countryname"},
// organizationalPerson
{MozillaProperty_String, "JobTitle", "title"},
// ?
{MozillaProperty_String, "Department", "ou"},
// ?
{MozillaProperty_String, "Department", "orgunit"},
// ?
{MozillaProperty_String, "Department", "department"},
// ?
{MozillaProperty_String, "Department", "departmentnumber"},
// inetOrgPerson
{MozillaProperty_String, "Company", "o"},
// ?
{MozillaProperty_String, "Company", "company"},
// ?
{MozillaProperty_String, "WorkCountry", "countryname"},
// ?
{MozillaProperty_String, "WebPage1", "homeurl"},
// ?
{MozillaProperty_String, "WebPage2", "workurl"},
// ?
{MozillaProperty_String, "BirthYear", "birthyear"},
// ?
{MozillaProperty_String, "Custom1", "custom1"},
// ?
{MozillaProperty_String, "Custom2", "custom2"},
// ?
{MozillaProperty_String, "Custom3", "custom3"},
// ?
{MozillaProperty_String, "Custom4", "custom4"},
// ?
{MozillaProperty_String, "Notes", "notes"},
// person
{MozillaProperty_String, "Notes", "description"},
// mozilla specfic
{MozillaProperty_Boolean, "SendPlainText", "xmozillausehtmlmail"},
// ?
{MozillaProperty_Int, "LastModifiedDate", "modifytimestamp"}
};
const MozillaLdapPropertyRelation* MozillaLdapPropertyRelator::table = mozillaLdapPropertyTable;
const int MozillaLdapPropertyRelator::tableSize = sizeof (mozillaLdapPropertyTable) / sizeof (MozillaLdapPropertyRelation);
const MozillaLdapPropertyRelation* MozillaLdapPropertyRelator::findMozillaPropertyFromLdap (const char* ldapProperty)
{
for (int i = 0; i < tableSize; i++)
if (nsCRT::strcasecmp (ldapProperty, table[i].ldapProperty) == 0)
return &table[i];
return 0;
}
const MozillaLdapPropertyRelation* MozillaLdapPropertyRelator::findLdapPropertyFromMozilla (const char* mozillaProperty)
{
for (int i = 0; i < tableSize; i++)
if (nsCRT::strcasecmp (mozillaProperty, table[i].mozillaProperty) == 0)
return &table[i];
return 0;
}
nsresult MozillaLdapPropertyRelator::createCardPropertyFromLDAPMessage (nsILDAPMessage* message,
nsIAbCard* card,
PRBool* hasSetCardProperty)
{
nsresult rv = NS_OK;
CharPtrArrayGuard attrs;
rv = message->GetAttributes(attrs.GetSizeAddr(), attrs.GetArrayAddr());
NS_ENSURE_SUCCESS(rv, rv);
*hasSetCardProperty = PR_FALSE;
for (PRUint32 i = 0; i < attrs.GetSize(); i++)
{
const MozillaLdapPropertyRelation* property = findMozillaPropertyFromLdap (attrs[i]);
if (!property)
continue;
PRUnicharPtrArrayGuard vals;
rv = message->GetValues(attrs.GetArray()[i], vals.GetSizeAddr(), vals.GetArrayAddr());
if (NS_FAILED(rv))
continue;
if (vals.GetSize())
{
rv = card->SetCardValue (property->mozillaProperty, vals[0]);
if (NS_SUCCEEDED(rv))
*hasSetCardProperty = PR_TRUE;
else
{
rv = NS_OK;
}
}
}
return rv;
}

View File

@ -0,0 +1,70 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#ifndef nsAbLDAPProperties_h__
#define nsAbLDAPProperties_h__
#include "prio.h"
#include "nsMemory.h"
#include "nsILDAPMessage.h"
#include "nsIAbCard.h"
#include "ldap.h"
#define NS_LDAPCONNECTION_CONTRACTID "@mozilla.org/network/ldap-connection;1"
#define NS_LDAPOPERATION_CONTRACTID "@mozilla.org/network/ldap-operation;1"
#define NS_LDAPMESSAGE_CONTRACTID "@mozilla.org/network/ldap-message;1"
#define NS_LDAPURL_CONTRACTID "@mozilla.org/network/ldap-url;1"
enum MozillaPropertyType
{
MozillaProperty_String,
MozillaProperty_Boolean,
MozillaProperty_Int
};
struct MozillaLdapPropertyRelation
{
MozillaPropertyType mozillaPropertyType;
const char* mozillaProperty;
const char* ldapProperty;
};
class MozillaLdapPropertyRelator
{
public:
static const MozillaLdapPropertyRelation* table;
static const int tableSize;
public:
static const MozillaLdapPropertyRelation* findMozillaPropertyFromLdap (const char* ldapProperty);
static const MozillaLdapPropertyRelation* findLdapPropertyFromMozilla (const char* mozillaProperty);
static nsresult createCardPropertyFromLDAPMessage (nsILDAPMessage* message,
nsIAbCard* card,
PRBool* hasSetCardProperty);
};
#endif

View File

@ -14,7 +14,7 @@
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s): Paul Sandoz

View File

@ -14,7 +14,7 @@
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s): Paul Sandoz
@ -481,23 +481,6 @@ NS_IMETHODIMP nsAbMDBCardProperty::EditCardToDatabase(const char *uri)
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP nsAbMDBCardProperty::GetCollationKey(const PRUnichar *str, PRUnichar **key)
{
nsresult rv = NS_OK;
nsAutoString resultStr;
if (mCardDatabase)
{
rv = mCardDatabase->CreateCollationKey(str, resultStr);
*key = resultStr.ToNewUnicode();
}
else
rv = NS_ERROR_FAILURE;
return rv;
}

View File

@ -14,7 +14,7 @@
*
* The Initial Developer of the Original Code is Netscape
* Communications Corporation. Portions created by Netscape are
* Copyright (C) 1998 Netscape Communications Corporation. All
* Copyright (C) 2001 Netscape Communications Corporation. All
* Rights Reserved.
*
* Contributor(s): Paul Sandoz
@ -41,7 +41,6 @@ public:
// nsIAbCard methods
NS_IMETHODIMP GetPrintCardUrl(char * *aPrintCardUrl);
NS_IMETHODIMP EditCardToDatabase(const char *uri);
NS_IMETHODIMP GetCollationKey(const PRUnichar *str, PRUnichar **key);
protected:
nsresult GetCardDatabase(const char *uri);

View File

@ -0,0 +1,238 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Contributor(s): Paul Sandoz <paul.sandoz@sun.com>
* Csaba Borbola <csaba.borbola@sun.com>
*/
#include "nsAbMDBDirFactory.h"
#include "nsAbUtils.h"
#include "nsIRDFService.h"
#include "nsIRDFResource.h"
#include "nsRDFResource.h"
#include "nsIAbMDBDirectory.h"
#include "nsAbDirFactoryService.h"
#include "nsAbMDBDirFactory.h"
#include "nsIAddressBook.h"
#include "nsIAddrBookSession.h"
#include "nsIAddrDBListener.h"
#include "nsEnumeratorUtils.h"
#include "nsAbBaseCID.h"
extern const char* kDescriptionPropertyName;
extern const char* kURIPropertyName;
NS_IMPL_ISUPPORTS1(nsAbMDBDirFactory, nsIAbDirFactory);
nsAbMDBDirFactory::nsAbMDBDirFactory()
{
NS_INIT_ISUPPORTS();
}
nsAbMDBDirFactory::~nsAbMDBDirFactory()
{
}
static nsresult RemoveMailListDBListeners (nsIAddrDatabase* database, nsIAbDirectory* directory)
{
nsresult rv;
nsCOMPtr<nsISupportsArray> pAddressLists;
rv = directory->GetAddressLists(getter_AddRefs(pAddressLists));
NS_ENSURE_SUCCESS(rv, rv);
PRUint32 total;
rv = pAddressLists->Count(&total);
NS_ENSURE_SUCCESS(rv, rv);
for (PRUint32 i = 0; i < total; i++)
{
nsCOMPtr<nsISupports> pSupport;
rv = pAddressLists->GetElementAt(i, getter_AddRefs(pSupport));
if (NS_FAILED(rv))
break;
nsCOMPtr<nsIAbDirectory> listDir(do_QueryInterface(pSupport, &rv));
if (NS_FAILED(rv))
break;
nsCOMPtr<nsIAddrDBListener> dbListener(do_QueryInterface(pSupport, &rv));
if (NS_FAILED(rv))
break;
database->RemoveListener(dbListener);
}
return NS_OK;
}
/* nsISimpleEnumerator createDirectory (in unsigned long propertiesSize, [array, size_is (propertiesSize)] in string propertyNamesArray, [array, size_is (propertiesSize)] in wstring propertyValuesArray); */
NS_IMETHODIMP nsAbMDBDirFactory::CreateDirectory(
PRUint32 propertiesSize,
const char **propertyNamesArray,
const PRUnichar **propertyValuesArray,
nsISimpleEnumerator **_retval)
{
if (!*propertyNamesArray || !*propertyValuesArray)
return NS_ERROR_NULL_POINTER;
if (propertiesSize == 0)
return NS_ERROR_FAILURE;
nsresult rv;
// Create hash table from property arrays
nsHashtable propertySet;
rv = PropertyPtrArraysToHashtable::Convert (
propertySet,
propertiesSize,
propertyNamesArray,
propertyValuesArray);
NS_ENSURE_SUCCESS (rv, rv);
// Get description property
nsCStringKey descriptionKey (kDescriptionPropertyName, -1, nsCStringKey::NEVER_OWN);
const PRUnichar* description = NS_REINTERPRET_CAST(PRUnichar*, propertySet.Get (&descriptionKey));
// Get uri property
nsCStringKey URIKey (kURIPropertyName, -1, nsCStringKey::NEVER_OWN);
const PRUnichar* URIUCS2 = NS_REINTERPRET_CAST(PRUnichar*, propertySet.Get (&URIKey));
if (!URIUCS2)
return NS_ERROR_FAILURE;
NS_ConvertUCS2toUTF8 URIUTF8(URIUCS2);
nsCOMPtr<nsIRDFService> rdf = do_GetService (NS_RDF_CONTRACTID "/rdf-service;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIRDFResource> resource;
rv = rdf->GetResource(URIUTF8.get (), getter_AddRefs(resource));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAbDirectory> directory(do_QueryInterface(resource, &rv));
NS_ENSURE_SUCCESS(rv, rv);
directory->SetDirName(description);
nsCOMPtr<nsIAddrBookSession> abSession = do_GetService(NS_ADDRBOOKSESSION_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
nsFileSpec* dbPath;
abSession->GetUserProfileDirectory(&dbPath);
const char* fileName = nsnull;
const char* uri = URIUTF8.get ();
if (PL_strstr(uri, kMDBDirectoryRoot)) // for moz-abmdbdirectory://
fileName = &(uri[PL_strlen(kMDBDirectoryRoot)]);
nsAutoString file;
file.AssignWithConversion(fileName);
(*dbPath) += file;
nsCOMPtr<nsIAddrDatabase> addrDBFactory = do_GetService(NS_ADDRDATABASE_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAddrDatabase> listDatabase;
rv = addrDBFactory->Open(dbPath, PR_TRUE, getter_AddRefs(listDatabase), PR_TRUE);
NS_ENSURE_SUCCESS(rv, rv);
rv = listDatabase->GetMailingListsFromDB(directory);
NS_ENSURE_SUCCESS(rv, rv);
/*
* This is a hack because of the way
* MDB databases reference MDB directories
* after the mail lists have been created.
*
* To stop assertions when the listDatabase
* goes out of scope it is necessary to remove
* all mail lists which have been added as
* listeners to the database
*/
rv = RemoveMailListDBListeners (listDatabase, directory);
NS_ENSURE_SUCCESS(rv, rv);
nsSingletonEnumerator* cursor = new nsSingletonEnumerator(directory);
if(!cursor)
return NS_ERROR_NULL_POINTER;
*_retval = cursor;
NS_IF_ADDREF(*_retval);
return rv;
}
/* void deleteDirectory (in nsIAbDirectory directory); */
NS_IMETHODIMP nsAbMDBDirFactory::DeleteDirectory(nsIAbDirectory *directory)
{
if (!directory)
return NS_ERROR_NULL_POINTER;
nsresult rv = NS_OK;
nsCOMPtr<nsISupportsArray> pAddressLists;
rv = directory->GetAddressLists(getter_AddRefs(pAddressLists));
NS_ENSURE_SUCCESS(rv, rv);
PRUint32 total;
rv = pAddressLists->Count(&total);
NS_ENSURE_SUCCESS(rv, rv);
for (PRUint32 i = 0; i < total; i++)
{
nsCOMPtr<nsISupports> pSupport;
rv = pAddressLists->GetElementAt(i, getter_AddRefs(pSupport));
if (NS_FAILED(rv))
break;
nsCOMPtr<nsIAbDirectory> listDir(do_QueryInterface(pSupport, &rv));
if (NS_FAILED(rv))
break;
nsCOMPtr<nsIAbMDBDirectory> dblistDir(do_QueryInterface(pSupport, &rv));
if (NS_FAILED(rv))
break;
rv = directory->DeleteDirectory(listDir);
if (NS_FAILED(rv))
break;
rv = dblistDir->RemoveElementsFromAddressList();
if (NS_FAILED(rv))
break;
pAddressLists->RemoveElement(pSupport);
}
nsCOMPtr<nsIAbMDBDirectory> dbdirectory(do_QueryInterface(directory, &rv));
NS_ENSURE_SUCCESS(rv, rv);
rv = dbdirectory->ClearDatabase ();
return rv;
}

View File

@ -0,0 +1,39 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Contributor(s): Paul Sandoz <paul.sandoz@sun.com>
*/
#ifndef nsAbMDBDirFactory_h__
#define nsAbMDBDirFactory_h__
#include "nsIAbDirFactory.h"
class nsAbMDBDirFactory : public nsIAbDirFactory
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIABDIRFACTORY
nsAbMDBDirFactory();
virtual ~nsAbMDBDirFactory();
};
#endif

View File

@ -135,40 +135,6 @@ NS_IMETHODIMP nsAbMDBDirProperty::CopyDBMailList(nsIAbMDBDirectory* srcListDB)
}
// nsIAbDirectory methods
NS_IMETHODIMP nsAbMDBDirProperty::EditMailListToDatabase(const char *uri)
{
nsresult rv = NS_OK;
nsCOMPtr<nsIAddrDatabase> listDatabase;
nsCOMPtr<nsIAddressBook> addresBook(do_GetService(kAddrBookCID, &rv));
if (NS_SUCCEEDED(rv))
rv = addresBook->GetAbDatabaseFromURI(uri, getter_AddRefs(listDatabase));
if (listDatabase)
{
listDatabase->EditMailList(this, PR_TRUE);
listDatabase->Commit(kLargeCommit);
listDatabase = null_nsCOMPtr();
return NS_OK;
}
else
return NS_ERROR_FAILURE;
}
// nsIAbMDBDirectory NOT IMPLEMENTED methods
/* nsIAbCard addChildCards (in string uriName); */

View File

@ -50,8 +50,6 @@ public:
NS_DECL_ISUPPORTS
NS_DECL_NSIABMDBDIRECTORY
// nsIAbDirectory methods
NS_IMETHODIMP EditMailListToDatabase(const char *uri);
protected:
PRUint32 m_dbRowID;

View File

@ -34,6 +34,12 @@
#include "nsIAbListener.h"
#include "nsIAddrBookSession.h"
#include "nsIAddressBook.h"
#include "nsIURL.h"
#include "nsNetCID.h"
#include "nsAbDirectoryQuery.h"
#include "nsIAbDirectoryQueryProxy.h"
#include "nsAbQueryStringToExpression.h"
#include "nsAbUtils.h"
#include "nsAbMDBCardProperty.h"
@ -45,14 +51,12 @@
static NS_DEFINE_CID(kRDFServiceCID, NS_RDFSERVICE_CID);
static NS_DEFINE_CID(kAbCardCID, NS_ABMDBCARD_CID);
static NS_DEFINE_CID(kAddressBookDBCID, NS_ADDRDATABASE_CID);
static NS_DEFINE_CID(kAddrBookSessionCID, NS_ADDRBOOKSESSION_CID);
static NS_DEFINE_CID(kAddrBookCID, NS_ADDRESSBOOK_CID);
nsAbMDBDirectory::nsAbMDBDirectory(void)
: nsAbMDBRDFResource(),
mInitialized(PR_FALSE),
mIsMailingList(-1)
mIsMailingList(-1),
mPerformingQuery(PR_FALSE)
{
NS_NewISupportsArray(getter_AddRefs(mSubDirectories));
}
@ -64,7 +68,7 @@ nsAbMDBDirectory::~nsAbMDBDirectory(void)
nsresult rv = NS_OK;
nsCOMPtr<nsIAddrDatabase> database;
nsCOMPtr<nsIAddressBook> addressBook(do_GetService(kAddrBookCID, &rv));
nsCOMPtr<nsIAddressBook> addressBook = do_GetService(NS_ADDRESSBOOK_CONTRACTID, &rv);;
if (NS_SUCCEEDED(rv) && addressBook)
{
rv = addressBook->GetAbDatabaseFromURI(mURI, getter_AddRefs(database));
@ -83,7 +87,7 @@ nsAbMDBDirectory::~nsAbMDBDirectory(void)
}
}
NS_IMPL_ISUPPORTS_INHERITED2(nsAbMDBDirectory, nsAbMDBRDFResource, nsIAbDirectory, nsIAbMDBDirectory)
NS_IMPL_ISUPPORTS_INHERITED3(nsAbMDBDirectory, nsAbMDBRDFResource, nsIAbDirectory, nsIAbMDBDirectory, nsIAbDirectorySearch)
////////////////////////////////////////////////////////////////////////////////
@ -160,7 +164,7 @@ NS_IMETHODIMP nsAbMDBDirectory::DeleteDirectory(nsIAbDirectory *directory)
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAddrDatabase> database;
nsCOMPtr<nsIAddressBook> addresBook(do_GetService(kAddrBookCID, &rv));
nsCOMPtr<nsIAddressBook> addresBook = do_GetService(NS_ADDRESSBOOK_CONTRACTID, &rv);;
if (NS_SUCCEEDED(rv))
{
rv = addresBook->GetAbDatabaseFromURI((const char *)uri, getter_AddRefs(database));
@ -189,8 +193,7 @@ nsresult nsAbMDBDirectory::NotifyPropertyChanged(char *property, PRUnichar* oldV
{
//Notify listeners who listen to every folder
nsresult rv;
nsCOMPtr<nsIAddrBookSession> abSession =
do_GetService(kAddrBookSessionCID, &rv);
nsCOMPtr<nsIAddrBookSession> abSession = do_GetService(NS_ADDRBOOKSESSION_CONTRACTID, &rv);;
if(NS_SUCCEEDED(rv))
abSession->NotifyItemPropertyChanged(supports, property, oldValue, newValue);
}
@ -201,8 +204,7 @@ nsresult nsAbMDBDirectory::NotifyPropertyChanged(char *property, PRUnichar* oldV
nsresult nsAbMDBDirectory::NotifyItemAdded(nsISupports *item)
{
nsresult rv = NS_OK;
nsCOMPtr<nsIAddrBookSession> abSession =
do_GetService(kAddrBookSessionCID, &rv);
nsCOMPtr<nsIAddrBookSession> abSession = do_GetService(NS_ADDRBOOKSESSION_CONTRACTID, &rv);;
if(NS_SUCCEEDED(rv))
abSession->NotifyDirectoryItemAdded(this, item);
return NS_OK;
@ -211,8 +213,7 @@ nsresult nsAbMDBDirectory::NotifyItemAdded(nsISupports *item)
nsresult nsAbMDBDirectory::NotifyItemDeleted(nsISupports *item)
{
nsresult rv = NS_OK;
nsCOMPtr<nsIAddrBookSession> abSession =
do_GetService(kAddrBookSessionCID, &rv);
nsCOMPtr<nsIAddrBookSession> abSession = do_GetService(NS_ADDRBOOKSESSION_CONTRACTID, &rv);;
if(NS_SUCCEEDED(rv))
abSession->NotifyDirectoryItemDeleted(this, item);
@ -225,12 +226,58 @@ nsresult nsAbMDBDirectory::NotifyItemDeleted(nsISupports *item)
// nsIRDFResaource methods
NS_IMETHODIMP nsAbMDBDirectory::Init(const char* aURI)
{
nsresult rv;
rv = nsAbMDBRDFResource::Init (aURI);
NS_ENSURE_SUCCESS(rv, rv);
mURINoQuery = aURI;
nsCOMPtr<nsIURI> uri = do_CreateInstance (NS_STANDARDURL_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = uri->SetSpec(aURI);
NS_ENSURE_SUCCESS(rv, rv);
mIsValidURI = PR_TRUE;
nsCOMPtr<nsIURL> url = do_QueryInterface(uri);
NS_ENSURE_SUCCESS(rv, rv);
nsXPIDLCString queryString;
rv = url->GetEscapedQuery (getter_Copies(queryString));
nsXPIDLCString path;
rv = url->GetPath (getter_Copies(path));
mPath = path;
PRUint32 queryStringLength;
if (queryString.get () && (queryStringLength = nsCRT::strlen (queryString)))
{
int pathLength = nsCRT::strlen (path) - queryStringLength - 1;
mPath.Truncate (pathLength);
mURINoQuery.Truncate (mURINoQuery.Length () - queryStringLength - 1);
mQueryString = queryString;
mIsQueryURI = PR_TRUE;
}
return rv;
}
// nsIAbMDBDirectory methods
NS_IMETHODIMP nsAbMDBDirectory::ClearDatabase()
{
if (mIsQueryURI == PR_TRUE)
return NS_ERROR_NOT_IMPLEMENTED;
if (mDatabase)
{
mDatabase->RemoveListener(this);
@ -241,6 +288,9 @@ NS_IMETHODIMP nsAbMDBDirectory::ClearDatabase()
NS_IMETHODIMP nsAbMDBDirectory::RemoveElementsFromAddressList()
{
if (mIsQueryURI == PR_TRUE)
return NS_ERROR_NOT_IMPLEMENTED;
if (m_AddressList)
{
PRUint32 count;
@ -256,6 +306,9 @@ NS_IMETHODIMP nsAbMDBDirectory::RemoveElementsFromAddressList()
NS_IMETHODIMP nsAbMDBDirectory::RemoveEmailAddressAt(PRUint32 aIndex)
{
if (mIsQueryURI == PR_TRUE)
return NS_ERROR_NOT_IMPLEMENTED;
if (m_AddressList)
{
return m_AddressList->RemoveElementAt(aIndex);
@ -266,6 +319,9 @@ NS_IMETHODIMP nsAbMDBDirectory::RemoveEmailAddressAt(PRUint32 aIndex)
NS_IMETHODIMP nsAbMDBDirectory::AddChildCards(const char *uriName, nsIAbCard **childCard)
{
if (mIsQueryURI == PR_TRUE)
return NS_ERROR_NOT_IMPLEMENTED;
if(!childCard)
return NS_ERROR_NULL_POINTER;
@ -294,6 +350,9 @@ NS_IMETHODIMP nsAbMDBDirectory::AddChildCards(const char *uriName, nsIAbCard **c
NS_IMETHODIMP nsAbMDBDirectory::AddDirectory(const char *uriName, nsIAbDirectory **childDir)
{
if (mIsQueryURI == PR_TRUE)
return NS_ERROR_NOT_IMPLEMENTED;
if (!childDir || !uriName)
return NS_ERROR_NULL_POINTER;
@ -329,10 +388,19 @@ NS_IMETHODIMP nsAbMDBDirectory::GetDirUri(char **uri)
return NS_RDF_NO_VALUE;
}
// nsIAbDirectory methods
NS_IMETHODIMP nsAbMDBDirectory::GetChildNodes(nsIEnumerator* *result)
{
if (mIsQueryURI == PR_TRUE)
{
nsCOMPtr<nsISupportsArray> array;
NS_NewISupportsArray(getter_AddRefs(array));
return array->Enumerate(result);
}
if (!mInitialized)
{
mInitialized = PR_TRUE;
@ -340,8 +408,32 @@ NS_IMETHODIMP nsAbMDBDirectory::GetChildNodes(nsIEnumerator* *result)
return mSubDirectories->Enumerate(result);
}
static PRBool enumerateSearchCache(nsHashKey *aKey, void *aData, void* closure)
{
nsISupportsArray* array = (nsISupportsArray* )closure;
nsIAbCard* card = (nsIAbCard* )aData;
array->AppendElement (card);
return PR_TRUE;
}
NS_IMETHODIMP nsAbMDBDirectory::GetChildCards(nsIEnumerator* *result)
{
if (mIsQueryURI == PR_TRUE)
{
nsresult rv;
rv = StartSearch ();
NS_ENSURE_SUCCESS(rv, rv);
// TODO
// Search is synchronous so need to return
// results after search is complete
nsCOMPtr<nsISupportsArray> array;
NS_NewISupportsArray(getter_AddRefs(array));
mSearchCache.Enumerate (enumerateSearchCache, (void* )array);
return array->Enumerate(result);
}
if (mURI && mIsMailingList == -1)
{
nsAutoString file; file.AssignWithConversion(&(mURI[PL_strlen(kMDBDirectoryRoot)]));
@ -369,6 +461,9 @@ NS_IMETHODIMP nsAbMDBDirectory::GetChildCards(nsIEnumerator* *result)
// Not called
nsresult nsAbMDBDirectory::DeleteDirectoryCards(nsIAbDirectory* directory, DIR_Server *server)
{
if (mIsQueryURI == PR_TRUE)
return NS_ERROR_NOT_IMPLEMENTED;
if (!server->fileName) // file name does not exist
return NS_OK;
if (PL_strlen(server->fileName) == 0) // file name does not exist
@ -379,8 +474,7 @@ nsresult nsAbMDBDirectory::DeleteDirectoryCards(nsIAbDirectory* directory, DIR_S
nsCOMPtr<nsIAddrDatabase> database;
nsCOMPtr<nsIAddrBookSession> abSession =
do_GetService(kAddrBookSessionCID, &rv);
nsCOMPtr<nsIAddrBookSession> abSession = do_GetService(NS_ADDRBOOKSESSION_CONTRACTID, &rv);;
if(NS_SUCCEEDED(rv))
abSession->GetUserProfileDirectory(&dbPath);
@ -389,13 +483,11 @@ nsresult nsAbMDBDirectory::DeleteDirectoryCards(nsIAbDirectory* directory, DIR_S
(*dbPath) += server->fileName;
// close file before delete it
nsCOMPtr<nsIAddrDatabase> addrDBFactory =
do_GetService(kAddressBookDBCID, &rv);
nsCOMPtr<nsIAddrDatabase> addrDBFactory = do_GetService(NS_ADDRDATABASE_CONTRACTID, &rv);;
if (NS_SUCCEEDED(rv) && addrDBFactory)
rv = addrDBFactory->Open(dbPath, PR_FALSE, getter_AddRefs(database), PR_TRUE);
delete dbPath;
delete dbPath;
}
/* delete cards */
@ -430,7 +522,7 @@ nsresult nsAbMDBDirectory::DeleteDirectoryCards(nsIAbDirectory* directory, DIR_S
{
PRUint32 cardCount;
rv = cardArray->Count(&cardCount);
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_SUCCESS(rv, rv);
for(PRUint32 i = 0; i < cardCount; i++)
{
nsCOMPtr<nsISupports> cardSupports = getter_AddRefs(cardArray->ElementAt(i));
@ -448,6 +540,9 @@ nsresult nsAbMDBDirectory::DeleteDirectoryCards(nsIAbDirectory* directory, DIR_S
NS_IMETHODIMP nsAbMDBDirectory::DeleteCards(nsISupportsArray *cards)
{
if (mIsQueryURI == PR_TRUE)
return NS_ERROR_NOT_IMPLEMENTED;
nsresult rv = NS_OK;
if (!mDatabase)
@ -559,6 +654,12 @@ NS_IMETHODIMP nsAbMDBDirectory::HasCard(nsIAbCard *cards, PRBool *hasCard)
if(!hasCard)
return NS_ERROR_NULL_POINTER;
if (mIsQueryURI == PR_TRUE)
{
nsVoidKey key (NS_STATIC_CAST(void*, cards));
*hasCard = mSearchCache.Exists (&key);
return NS_OK;
}
nsresult rv = NS_OK;
if (!mDatabase)
@ -581,7 +682,7 @@ NS_IMETHODIMP nsAbMDBDirectory::HasDirectory(nsIAbDirectory *dir, PRBool *hasDir
nsresult rv = NS_ERROR_FAILURE;
nsCOMPtr<nsIAbMDBDirectory> dbdir(do_QueryInterface(dir, &rv));
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_SUCCESS(rv, rv);
PRBool bIsMailingList = PR_FALSE;
dir->GetIsMailList(&bIsMailingList);
@ -589,9 +690,9 @@ NS_IMETHODIMP nsAbMDBDirectory::HasDirectory(nsIAbDirectory *dir, PRBool *hasDir
{
nsXPIDLCString uri;
rv = dbdir->GetDirUri(getter_Copies(uri));
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAddrDatabase> database;
nsCOMPtr<nsIAddressBook> addresBook(do_GetService(kAddrBookCID, &rv));
nsCOMPtr<nsIAddressBook> addresBook = do_GetService(NS_ADDRESSBOOK_CONTRACTID, &rv);;
if (NS_SUCCEEDED(rv))
{
rv = addresBook->GetAbDatabaseFromURI((const char *)uri, getter_AddRefs(database));
@ -621,6 +722,9 @@ NS_IMETHODIMP nsAbMDBDirectory::CreateDirectoryByURI(const PRUnichar *dirName, c
NS_IMETHODIMP nsAbMDBDirectory::AddMailList(nsIAbDirectory *list)
{
if (mIsQueryURI == PR_TRUE)
return NS_ERROR_NOT_IMPLEMENTED;
nsresult rv = NS_OK;
if (!mDatabase)
rv = GetAbDatabase();
@ -666,6 +770,9 @@ NS_IMETHODIMP nsAbMDBDirectory::AddMailList(nsIAbDirectory *list)
NS_IMETHODIMP nsAbMDBDirectory::AddCard(nsIAbCard* card, nsIAbCard **_retval)
{
if (mIsQueryURI == PR_TRUE)
return NS_ERROR_NOT_IMPLEMENTED;
nsresult rv = NS_OK;
if (!mDatabase)
rv = GetAbDatabase();
@ -715,6 +822,9 @@ NS_IMETHODIMP nsAbMDBDirectory::AddCard(nsIAbCard* card, nsIAbCard **_retval)
NS_IMETHODIMP nsAbMDBDirectory::DropCard(nsIAbCard* card, nsIAbCard **_retval)
{
if (mIsQueryURI == PR_TRUE)
return NS_ERROR_NOT_IMPLEMENTED;
nsresult rv = NS_OK;
if (mURI && mIsMailingList == -1)
@ -737,7 +847,7 @@ NS_IMETHODIMP nsAbMDBDirectory::DropCard(nsIAbCard* card, nsIAbCard **_retval)
{
nsAbMDBCardProperty* dbcardproperty = new nsAbMDBCardProperty ();
NS_ADDREF(dbcardproperty);
nsCOMPtr<nsIAbCard> newcard = getter_AddRefs (NS_STATIC_CAST(nsIAbCard*, dbcardproperty));
nsCOMPtr<nsIAbCard> newcard = getter_AddRefs(NS_STATIC_CAST(nsIAbCard*, dbcardproperty));
newcard->Copy (card);
card = newcard;
dbcard = do_QueryInterface (card);
@ -773,6 +883,50 @@ NS_IMETHODIMP nsAbMDBDirectory::DropCard(nsIAbCard* card, nsIAbCard **_retval)
return NS_OK;
}
NS_IMETHODIMP nsAbMDBDirectory::EditMailListToDatabase(const char *uri)
{
if (mIsQueryURI == PR_TRUE)
return NS_ERROR_NOT_IMPLEMENTED;
nsresult rv = NS_OK;
nsCOMPtr<nsIAddrDatabase> listDatabase;
nsCOMPtr<nsIAddressBook> addresBook = do_GetService(NS_ADDRESSBOOK_CONTRACTID, &rv);;
if (NS_SUCCEEDED(rv))
rv = addresBook->GetAbDatabaseFromURI(uri, getter_AddRefs(listDatabase));
if (listDatabase)
{
listDatabase->EditMailList(this, PR_TRUE);
listDatabase->Commit(kLargeCommit);
listDatabase = null_nsCOMPtr();
return NS_OK;
}
else
return NS_ERROR_FAILURE;
}
NS_IMETHODIMP nsAbMDBDirectory::GetTotalCards(PRBool subDirectoryCount,
PRUint32 *_retval)
{
NS_ENSURE_ARG_POINTER(_retval);
nsresult rv;
if (!mDatabase)
{
rv = GetAbDatabase ();
NS_ENSURE_SUCCESS(rv, rv);
}
rv = mDatabase->GetCardCount (_retval);
NS_ENSURE_SUCCESS(rv, rv);
return rv;
}
@ -867,3 +1021,99 @@ NS_IMETHODIMP nsAbMDBDirectory::OnListEntryChange
return rv;
}
// nsIAbDirectorySearch methods
NS_IMETHODIMP nsAbMDBDirectory::StartSearch()
{
if (mIsQueryURI == PR_FALSE)
return NS_ERROR_FAILURE;
nsresult rv;
mPerformingQuery = PR_TRUE;
mSearchCache.Reset ();
nsCOMPtr<nsIAbDirectoryQueryArguments> arguments;
NS_NewIAbDirectoryQueryArguments (getter_AddRefs(arguments));
nsCOMPtr<nsIAbBooleanExpression> expression;
rv = nsAbQueryStringToExpression::Convert (mQueryString.get (),
getter_AddRefs(expression));
NS_ENSURE_SUCCESS(rv, rv);
rv = arguments->SetExpression (expression);
NS_ENSURE_SUCCESS(rv, rv);
// Set the return properties to
// return nsIAbCard interfaces
nsCStringArray properties;
properties.AppendCString (nsCAutoString ("card:nsIAbCard"));
CharPtrArrayGuard returnProperties (PR_FALSE);
rv = CStringArrayToCharPtrArray::Convert (properties,returnProperties.GetSizeAddr(),
returnProperties.GetArrayAddr(), PR_FALSE);
NS_ENSURE_SUCCESS(rv, rv);
rv = arguments->SetReturnProperties (returnProperties.GetSize(), returnProperties.GetArray());
NS_ENSURE_SUCCESS(rv, rv);
rv = arguments->SetQuerySubDirectories (PR_TRUE);
NS_ENSURE_SUCCESS(rv, rv);
// Set the the query listener
nsCOMPtr<nsIAbDirectoryQueryResultListener> queryListener;
nsAbDirSearchListener* _queryListener =
new nsAbDirSearchListener (this);
queryListener = _queryListener;
// Get the directory without the query
nsCOMPtr<nsIRDFResource> resource;
rv = gRDFService->GetResource (mURINoQuery.get (), getter_AddRefs (resource));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAbDirectory> directory (do_QueryInterface(resource, &rv));
NS_ENSURE_SUCCESS(rv, rv);
// Initiate the proxy query with the no query directory
nsCOMPtr<nsIAbDirectoryQueryProxy> queryProxy =
do_CreateInstance (NS_ABDIRECTORYQUERYPROXY_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = queryProxy->Initiate (directory);
NS_ENSURE_SUCCESS(rv, rv);
rv = queryProxy->DoQuery (arguments, queryListener, -1, 0, &mContext);
return NS_OK;
}
NS_IMETHODIMP nsAbMDBDirectory::StopSearch()
{
if (mIsQueryURI == PR_FALSE)
return NS_ERROR_FAILURE;
return NS_OK;
}
// nsAbDirSearchListenerContext methods
nsresult nsAbMDBDirectory::OnSearchFinished (PRInt32 result)
{
mPerformingQuery = PR_FALSE;
return NS_OK;
}
nsresult nsAbMDBDirectory::OnSearchFoundCard (nsIAbCard* card)
{
nsVoidKey key (NS_STATIC_CAST(void*, card));
mSearchCache.Put (&key, card);
// TODO
// Search is synchronous so asserting on the
// datasource will not work since the getChildCards
// method will not have returned with results.
// NotifyItemAdded (card);
return NS_OK;
}

View File

@ -35,12 +35,19 @@
#include "nsISupportsArray.h"
#include "nsCOMPtr.h"
#include "nsDirPrefs.h"
#include "nsIAbDirectorySearch.h"
#include "nsAbDirSearchListener.h"
#include "nsHashtable.h"
/*
* Address Book Directory
*/
class nsAbMDBDirectory: public nsAbMDBRDFResource, public nsAbMDBDirProperty
class nsAbMDBDirectory:
public nsAbMDBRDFResource, // nsIRDFResource
public nsAbMDBDirProperty, // nsIAbDirectory, nsIAbMDBDirectory
public nsIAbDirectorySearch,
public nsAbDirSearchListenerContext
{
public:
nsAbMDBDirectory(void);
@ -48,6 +55,9 @@ public:
NS_DECL_ISUPPORTS_INHERITED
// nsIRDFResource methods:
NS_IMETHOD Init(const char* aURI);
// nsIAbMDBDirectory methods
NS_IMETHOD ClearDatabase();
NS_IMETHOD NotifyDirItemAdded(nsISupports *item) { return NotifyItemAdded(item);}
@ -69,12 +79,20 @@ public:
NS_IMETHOD AddMailList(nsIAbDirectory *list);
NS_IMETHOD AddCard(nsIAbCard *card, nsIAbCard **_retval);
NS_IMETHOD DropCard(nsIAbCard *card, nsIAbCard **_retval);
NS_IMETHOD EditMailListToDatabase(const char *uri);
NS_IMETHOD GetTotalCards(PRBool subDirectoryCount, PRUint32 *_retval);
// nsIAddrDBListener methods:
NS_IMETHOD OnCardAttribChange(PRUint32 abCode, nsIAddrDBListener *instigator);
NS_IMETHOD OnCardEntryChange(PRUint32 abCode, nsIAbCard *card, nsIAddrDBListener *instigator);
NS_IMETHOD OnListEntryChange(PRUint32 abCode, nsIAbDirectory *list, nsIAddrDBListener *instigator);
// nsIAbDirectorySearch methods
NS_DECL_NSIABDIRECTORYSEARCH
// nsAbDirSearchListenerContext methods
nsresult OnSearchFinished (PRInt32 result);
nsresult OnSearchFoundCard (nsIAbCard* card);
PRBool IsMailingList(){ return (mIsMailingList == 1); }
@ -94,6 +112,16 @@ protected:
nsCOMPtr<nsISupportsArray> mSubDirectories;
PRBool mInitialized;
PRInt16 mIsMailingList;
PRBool mIsValidURI;
PRBool mIsQueryURI;
nsCString mPath;
nsCString mQueryString;
nsCString mURINoQuery;
PRInt32 mContext;
PRBool mPerformingQuery;
nsSupportsHashtable mSearchCache;
};
#endif

View File

@ -0,0 +1,320 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Contributor(s):
*
* Created by Cyrille Moureaux <Cyrille.Moureaux@sun.com>
*/
#include "nsAbOutlookCard.h"
#include "nsMapiAddressBook.h"
#include "nslog.h"
NS_IMPL_LOG(nsAbOutlookCardLog)
#define PRINTF NS_LOG_PRINTF(nsAbOutlookCardLog)
#define FLUSH NS_LOG_FLUSH(nsAbOutlookCardLog)
extern const char *kOutlookDirectoryScheme ;
extern const char *kOutlookCardScheme ;
nsAbOutlookCard::nsAbOutlookCard(void)
: nsRDFResource(), nsAbCardProperty(), mMapiData(nsnull)
{
mMapiData = new nsMapiEntry ;
}
nsAbOutlookCard::~nsAbOutlookCard(void)
{
if (mMapiData) { delete mMapiData ; }
}
NS_IMPL_ISUPPORTS_INHERITED(nsAbOutlookCard, nsRDFResource, nsIAbCard)
static void splitString(nsString& aSource, nsString& aTarget)
{
aTarget.Truncate() ;
PRInt32 offset = aSource.FindChar('\n') ;
if (offset >= 0) {
const PRUnichar *source = aSource.get() + offset + 1 ;
while (*source) {
if (*source == '\n' || *source == '\r') { aTarget.AppendWithConversion(' ') ; }
else { aTarget.Append(*source) ; }
++ source ;
}
aSource.Truncate(offset) ;
}
}
static void wordToUnicode(WORD aWord, nsString& aUnicode)
{
aUnicode.Truncate() ;
aUnicode.AppendInt((PRInt32) aWord) ;
}
enum
{
index_DisplayName = 0,
index_EmailAddress,
index_FirstName,
index_LastName,
index_NickName,
index_WorkPhoneNumber,
index_HomePhoneNumber,
index_WorkFaxNumber,
index_PagerNumber,
index_MobileNumber,
index_HomeCity,
index_HomeState,
index_HomeZip,
index_HomeCountry,
index_WorkCity,
index_WorkState,
index_WorkZip,
index_WorkCountry,
index_JobTitle,
index_Department,
index_Company,
index_WorkWebPage,
index_HomeWebPage,
index_Comments,
index_LastProp
} ;
static const ULONG OutlookCardMAPIProps [] =
{
PR_DISPLAY_NAME_W,
PR_EMAIL_ADDRESS_W,
PR_GIVEN_NAME_W,
PR_SURNAME_W,
PR_NICKNAME_W,
PR_BUSINESS_TELEPHONE_NUMBER_W,
PR_HOME_TELEPHONE_NUMBER_W,
PR_BUSINESS_FAX_NUMBER_W,
PR_PAGER_TELEPHONE_NUMBER_W,
PR_MOBILE_TELEPHONE_NUMBER_W,
PR_HOME_ADDRESS_CITY_W,
PR_HOME_ADDRESS_STATE_OR_PROVINCE_W,
PR_HOME_ADDRESS_POSTAL_CODE_W,
PR_HOME_ADDRESS_COUNTRY_W,
PR_BUSINESS_ADDRESS_CITY_W,
PR_BUSINESS_ADDRESS_STATE_OR_PROVINCE_W,
PR_BUSINESS_ADDRESS_POSTAL_CODE_W,
PR_BUSINESS_ADDRESS_COUNTRY_W,
PR_TITLE_W,
PR_DEPARTMENT_NAME_W,
PR_COMPANY_NAME_W,
PR_BUSINESS_HOME_PAGE_W,
PR_PERSONAL_HOME_PAGE_W,
PR_COMMENT_W
} ;
nsresult nsAbOutlookCard::Init(const char *aUri)
{
nsresult retCode = nsRDFResource::Init(aUri) ;
NS_ENSURE_SUCCESS(retCode, retCode) ;
nsMapiAddressBook mapiAddBook ;
nsCAutoString subUri ;
PRInt32 schemeLength = nsCRT::strlen(kOutlookCardScheme) ;
if (nsCRT::strncmp(mURI, kOutlookCardScheme, schemeLength) != 0) {
PRINTF("Huge problem URI=%s.\n", mURI) ;
return NS_ERROR_INVALID_ARG ;
}
subUri = mURI + schemeLength ;
if (!mapiAddBook.StringToEntry(subUri, *mMapiData)) {
PRINTF("Cannot parse string %s.\n", subUri.get()) ;
return NS_ERROR_INVALID_ARG ;
}
nsStringArray unichars ;
ULONG i = 0 ;
if (mapiAddBook.GetPropertiesUString(*mMapiData, OutlookCardMAPIProps, index_LastProp, unichars)) {
SetFirstName(unichars [index_FirstName]->get()) ;
SetLastName(unichars [index_LastName]->get()) ;
SetDisplayName(unichars [index_DisplayName]->get()) ;
SetNickName(unichars [index_NickName]->get()) ;
SetPrimaryEmail(unichars [index_EmailAddress]->get()) ;
SetWorkPhone(unichars [index_WorkPhoneNumber]->get()) ;
SetHomePhone(unichars [index_HomePhoneNumber]->get()) ;
SetFaxNumber(unichars [index_WorkFaxNumber]->get()) ;
SetPagerNumber(unichars [index_PagerNumber]->get()) ;
SetCellularNumber(unichars [index_MobileNumber]->get()) ;
SetHomeCity(unichars [index_HomeCity]->get()) ;
SetHomeState(unichars [index_HomeState]->get()) ;
SetHomeZipCode(unichars [index_HomeZip]->get()) ;
SetHomeCountry(unichars [index_HomeCountry]->get()) ;
SetWorkCity(unichars [index_WorkCity]->get()) ;
SetWorkState(unichars [index_WorkState]->get()) ;
SetWorkZipCode(unichars [index_WorkZip]->get()) ;
SetWorkCountry(unichars [index_WorkCountry]->get()) ;
SetJobTitle(unichars [index_JobTitle]->get()) ;
SetDepartment(unichars [index_Department]->get()) ;
SetCompany(unichars [index_Company]->get()) ;
SetWebPage1(unichars [index_WorkWebPage]->get()) ;
SetWebPage2(unichars [index_HomeWebPage]->get()) ;
SetNotes(unichars [index_Comments]->get()) ;
}
ULONG cardType = 0 ;
nsCAutoString normalChars ;
if (mapiAddBook.GetPropertyLong(*mMapiData, PR_OBJECT_TYPE, cardType)) {
SetIsMailList(cardType == MAPI_DISTLIST) ;
if (cardType == MAPI_DISTLIST) {
normalChars = kOutlookDirectoryScheme ;
normalChars.Append(subUri) ;
SetMailListURI(normalChars) ;
}
}
nsAutoString unichar ;
nsAutoString unicharBis ;
if (mapiAddBook.GetPropertyUString(*mMapiData, PR_HOME_ADDRESS_STREET, unichar)) {
splitString(unichar, unicharBis) ;
SetHomeAddress(unichar.get()) ;
SetHomeAddress2(unicharBis.get()) ;
}
if (mapiAddBook.GetPropertyUString(*mMapiData, PR_BUSINESS_ADDRESS_STREET, unichar)) {
splitString(unichar, unicharBis) ;
SetWorkAddress(unichar.get()) ;
SetWorkAddress2(unicharBis.get()) ;
}
WORD year = 0 ;
WORD month = 0 ;
WORD day = 0 ;
if (mapiAddBook.GetPropertyDate(*mMapiData, PR_BIRTHDAY, year, month, day)) {
wordToUnicode(year, unichar) ;
SetBirthYear(unichar.get()) ;
wordToUnicode(month, unichar) ;
SetBirthMonth(unichar.get()) ;
wordToUnicode(day, unichar) ;
SetBirthDay(unichar.get()) ;
}
return retCode ;
}
static void UnicodeToWord(const PRUnichar *aUnicode, WORD& aWord)
{
aWord = 0 ;
if (aUnicode == nsnull || *aUnicode == 0) { return ; }
PRInt32 errorCode = 0 ;
nsAutoString unichar (aUnicode) ;
aWord = NS_STATIC_CAST(WORD, unichar.ToInteger(&errorCode)) ;
if (errorCode != 0) {
PRINTF("Error conversion string %S: %08x.\n", unichar.get(), errorCode) ;
}
}
NS_IMETHODIMP nsAbOutlookCard::EditCardToDatabase(const char *aUri)
{
nsresult retCode = NS_OK ;
nsXPIDLString *properties = nsnull ;
nsMapiAddressBook mapiAddBook ;
nsAutoString utility ;
// First, all the standard properties in one go
properties = new nsXPIDLString [index_LastProp] ;
if (properties == nsnull) {
return NS_ERROR_OUT_OF_MEMORY ;
}
GetFirstName(getter_Copies(properties [index_FirstName])) ;
GetLastName(getter_Copies(properties [index_LastName])) ;
// This triple search for something to put in the name
// is because in the case of a mailing list edition in
// Mozilla, the display name will not be provided, and
// MAPI doesn't allow that, so we fall back on an optional
// name, and when all fails, on the email address.
GetDisplayName(getter_Copies(properties [index_DisplayName])) ;
if (*properties [index_DisplayName].get() == 0) {
GetName(getter_Copies(properties [index_DisplayName])) ;
if (*properties [index_DisplayName].get() == 0) {
GetPrimaryEmail(getter_Copies(properties [index_DisplayName])) ;
}
}
SetDisplayName(properties [index_DisplayName]) ;
GetNickName(getter_Copies(properties [index_NickName])) ;
GetPrimaryEmail(getter_Copies(properties [index_EmailAddress])) ;
GetWorkPhone(getter_Copies(properties [index_WorkPhoneNumber])) ;
GetHomePhone(getter_Copies(properties [index_HomePhoneNumber])) ;
GetFaxNumber(getter_Copies(properties [index_WorkFaxNumber])) ;
GetPagerNumber(getter_Copies(properties [index_PagerNumber])) ;
GetCellularNumber(getter_Copies(properties [index_MobileNumber])) ;
GetHomeCity(getter_Copies(properties [index_HomeCity])) ;
GetHomeState(getter_Copies(properties [index_HomeState])) ;
GetHomeZipCode(getter_Copies(properties [index_HomeZip])) ;
GetHomeCountry(getter_Copies(properties [index_HomeCountry])) ;
GetWorkCity(getter_Copies(properties [index_WorkCity])) ;
GetWorkState(getter_Copies(properties [index_WorkState])) ;
GetWorkZipCode(getter_Copies(properties [index_WorkZip])) ;
GetWorkCountry(getter_Copies(properties [index_WorkCountry])) ;
GetJobTitle(getter_Copies(properties [index_JobTitle])) ;
GetDepartment(getter_Copies(properties [index_Department])) ;
GetCompany(getter_Copies(properties [index_Company])) ;
GetWebPage1(getter_Copies(properties [index_WorkWebPage])) ;
GetWebPage2(getter_Copies(properties [index_HomeWebPage])) ;
GetNotes(getter_Copies(properties [index_Comments])) ;
if (!mapiAddBook.SetPropertiesUString(*mMapiData, OutlookCardMAPIProps,
index_LastProp, properties)) {
PRINTF("Cannot set general properties.\n") ;
}
delete [] properties ;
nsXPIDLString unichar ;
nsXPIDLString unichar2 ;
WORD year = 0 ;
WORD month = 0 ;
WORD day = 0 ;
GetHomeAddress(getter_Copies(unichar)) ;
GetHomeAddress2(getter_Copies(unichar2)) ;
utility.Assign(unichar.get()) ;
if (utility.Length() > 0) { utility.AppendWithConversion(CRLF) ; }
utility.Append(unichar2.get()) ;
if (!mapiAddBook.SetPropertyUString(*mMapiData, PR_HOME_ADDRESS_STREET_W, utility.get())) {
PRINTF("Cannot set home address.\n") ;
}
GetWorkAddress(getter_Copies(unichar)) ;
GetWorkAddress2(getter_Copies(unichar2)) ;
utility.Assign(unichar.get()) ;
if (utility.Length() > 0) { utility.AppendWithConversion(CRLF) ; }
utility.Append(unichar2.get()) ;
if (!mapiAddBook.SetPropertyUString(*mMapiData, PR_BUSINESS_ADDRESS_STREET_W, utility.get())) {
PRINTF("Cannot set work address.\n") ;
}
GetBirthYear(getter_Copies(unichar)) ;
UnicodeToWord(unichar.get(), year) ;
GetBirthMonth(getter_Copies(unichar)) ;
UnicodeToWord(unichar.get(), month) ;
GetBirthDay(getter_Copies(unichar)) ;
UnicodeToWord(unichar.get(), day) ;
if (!mapiAddBook.SetPropertyDate(*mMapiData, PR_BIRTHDAY, year, month, day)) {
PRINTF("Cannot set date.\n") ;
}
return retCode ;
}

View File

@ -0,0 +1,52 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Contributor(s):
*
* Created by Cyrille Moureaux <Cyrille.Moureaux@sun.com>
*/
#ifndef nsAbOutlookCard_h___
#define nsAbOutlookCard_h___
#include "nsRDFResource.h"
#include "nsAbCardProperty.h"
struct nsMapiEntry ;
class nsAbOutlookCard : public nsRDFResource,
public nsAbCardProperty
{
public:
NS_DECL_ISUPPORTS_INHERITED
nsAbOutlookCard();
virtual ~nsAbOutlookCard();
// nsIRDFResource method
NS_IMETHOD Init(const char *aUri) ;
// nsIAbCard methods
NS_IMETHOD EditCardToDatabase(const char *aUri) ;
protected:
nsMapiEntry *mMapiData ;
private:
};
#endif // nsAbOultlookCard_h___

View File

@ -0,0 +1,110 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Contributor(s):
*
* Created by Cyrille Moureaux <Cyrille.Moureaux@sun.com>
*/
#include "nsAbOutlookDirFactory.h"
#include "nsMapiAddressBook.h"
#include "nsIAbDirectory.h"
#include "nsIRDFService.h"
#include "nsIRDFResource.h"
#include "nsRDFResource.h"
#include "nsEnumeratorUtils.h"
#include "nsAbBaseCID.h"
#include "prprf.h"
#include "nslog.h"
NS_IMPL_LOG(nsAbOutlookDirFactoryLog)
#define PRINTF NS_LOG_PRINTF(nsAbOutlookDirFactoryLog)
#define FLUSH NS_LOG_FLUSH(nsAbOutlookDirFactoryLog)
// In case someone is wondering WHY I have to undefine CreateDirectory,
// it's because the windows files winbase.h and wininet.h define this
// to CreateDirectoryA/W (for reasons best left unknown) and with the
// MAPI stuff, I end up including this, which wreaks havoc on my symbol
// table.
#ifdef CreateDirectory
# undef CreateDirectory
#endif // CreateDirectory
NS_IMPL_ISUPPORTS1(nsAbOutlookDirFactory, nsIAbDirFactory)
nsAbOutlookDirFactory::nsAbOutlookDirFactory(void)
{
NS_INIT_ISUPPORTS() ;
}
nsAbOutlookDirFactory::~nsAbOutlookDirFactory(void)
{
}
extern const char *kOutlookDirectoryScheme ;
NS_IMETHODIMP nsAbOutlookDirFactory::CreateDirectory(PRUint32 aNbProperties,
const char **aPropertyNames,
const PRUnichar **aPropertyValues,
nsISimpleEnumerator **aDirectories)
{
if (aPropertyNames == nsnull ||
aPropertyValues == nsnull ||
aDirectories == nsnull) { return NS_ERROR_NULL_POINTER ; }
*aDirectories = nsnull ;
nsresult retCode = NS_OK ;
nsMapiAddressBook mapiAddBook ;
nsMapiEntryArray folders ;
ULONG nbFolders = 0 ;
nsCOMPtr<nsISupportsArray> directories ;
retCode = NS_NewISupportsArray(getter_AddRefs(directories)) ;
NS_ENSURE_SUCCESS(retCode, retCode) ;
if (!mapiAddBook.GetFolders(folders)) {
return NS_ERROR_FAILURE ;
}
nsCOMPtr<nsIRDFService> rdf = do_GetService (NS_RDF_CONTRACTID "/rdf-service;1", &retCode);
NS_ENSURE_SUCCESS(retCode, retCode);
nsCAutoString entryId ;
nsCAutoString uri ;
nsCOMPtr<nsIRDFResource> resource ;
for (ULONG i = 0 ; i < folders.mNbEntries ; ++ i) {
if (mapiAddBook.EntryToString(folders.mEntries [i], entryId)) {
uri.Assign(kOutlookDirectoryScheme) ;
uri.Append(entryId) ;
retCode = rdf->GetResource(uri, getter_AddRefs(resource)) ;
NS_ENSURE_SUCCESS(retCode, retCode) ;
directories->AppendElement(resource) ;
}
}
return NS_NewArrayEnumerator(aDirectories, directories) ;
}
// No actual deletion, since you cannot create the address books from Mozilla.
NS_IMETHODIMP nsAbOutlookDirFactory::DeleteDirectory(nsIAbDirectory *aDirectory)
{
return NS_OK ;
}

View File

@ -0,0 +1,43 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Contributor(s):
*
* Created by Cyrille Moureaux <Cyrille.Moureaux@sun.com>
*/
#ifndef nsAbOutlookDirFactory_h___
#define nsAbOutlookDirFactory_h___
#include "nsIAbDirFactory.h"
class nsAbOutlookDirFactory : public nsIAbDirFactory
{
public:
nsAbOutlookDirFactory(void) ;
virtual ~nsAbOutlookDirFactory(void) ;
NS_DECL_ISUPPORTS
NS_DECL_NSIABDIRFACTORY
protected:
private:
} ;
#endif // nsAbOutlookDirFactory_h___

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,104 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Contributor(s):
*
* Created by Cyrille Moureaux <Cyrille.Moureaux@sun.com>
*/
#ifndef nsAbOutlookDirectory_h___
#define nsAbOutlookDirectory_h___
#include "nsAbDirectoryRDFResource.h"
#include "nsAbDirProperty.h"
#include "nsIAbDirectoryQuery.h"
#include "nsIAbDirectorySearch.h"
#include "nsAbDirSearchListener.h"
#include "nsHashtable.h"
#include "nsISupportsArray.h"
struct nsMapiEntry ;
class nsAbOutlookDirectory : public nsAbDirectoryRDFResource, // nsIRDFResource
public nsAbDirProperty, // nsIAbDirectory
public nsIAbDirectoryQuery,
public nsIAbDirectorySearch,
public nsAbDirSearchListenerContext
{
public:
NS_DECL_ISUPPORTS_INHERITED
nsAbOutlookDirectory(void) ;
virtual ~nsAbOutlookDirectory(void) ;
// nsAbDirProperty methods
NS_IMETHOD GetChildCards(nsIEnumerator **aCards) ;
NS_IMETHOD GetChildNodes(nsIEnumerator **aNodes) ;
NS_IMETHOD HasCard(nsIAbCard *aCard, PRBool *aHasCard) ;
NS_IMETHOD HasDirectory(nsIAbDirectory *aDirectory, PRBool *aHasDirectory) ;
NS_IMETHOD DeleteCards(nsISupportsArray *aCardList) ;
NS_IMETHOD DeleteDirectory(nsIAbDirectory *aDirectory) ;
NS_IMETHOD AddCard(nsIAbCard *aData, nsIAbCard **aCard) ;
NS_IMETHOD DropCard(nsIAbCard *aData, nsIAbCard **aCard) ;
NS_IMETHOD AddMailList(nsIAbDirectory *aMailList) ;
NS_IMETHOD EditMailListToDatabase(const char *aUri) ;
NS_IMETHOD GetTotalCards(PRBool aSubDirectoryCount, PRUint32 *aNbCards) ;
// nsAbDirectoryRDFResource method
NS_IMETHOD Init(const char *aUri) ;
// nsIAbDirectoryQuery methods
NS_DECL_NSIABDIRECTORYQUERY
// nsIAbDirectorySearch methods
NS_DECL_NSIABDIRECTORYSEARCH
// nsAbDirSearchListenerContext methods
nsresult OnSearchFinished(PRInt32 aResult) ;
nsresult OnSearchFoundCard(nsIAbCard *aCard) ;
// Perform a MAPI query (function executed in a separate thread)
nsresult ExecuteQuery(nsIAbDirectoryQueryArguments *aArguments,
nsIAbDirectoryQueryResultListener *aListener,
PRInt32 aResultLimit, PRInt32 aTimeout,
PRInt32 aThreadId) ;
protected:
// Retrieve hierarchy as cards, with an optional restriction
nsresult GetChildCards(nsISupportsArray **aCards, void *aRestriction) ;
// Retrieve hierarchy as directories
nsresult GetChildNodes(nsISupportsArray **aNodes) ;
// Create a new card
nsresult CreateCard(nsIAbCard *aData, nsIAbCard **aNewCard) ;
// Notification for the UI
nsresult NotifyItemDeletion(nsISupports *aItem) ;
nsresult NotifyItemAddition(nsISupports *aItem) ;
// Force update of MAPI repository for mailing list
nsresult CommitAddressList(void) ;
// Read MAPI repository
nsresult UpdateAddressList(void) ;
nsMapiEntry *mMapiData ;
// Container for the query threads
nsHashtable mQueryThreads ;
PRInt32 mCurrentQueryId ;
PRLock *mProtector ;
// Data for the search interfaces
nsSupportsHashtable mCardList ;
PRInt32 mSearchContext ;
private:
};
#endif // nsAbOutlookDirectory_h___

View File

@ -0,0 +1,349 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#include "nsAbQueryStringToExpression.h"
#include "nsIComponentManager.h"
#include "nsIServiceManager.h"
#include "nsCOMPtr.h"
#include "nsXPIDLString.h"
#include "nsString.h"
#include "nsISupportsArray.h"
#include "nsITextToSubURI.h"
#include "nsAbBooleanExpression.h"
nsresult nsAbQueryStringToExpression::Convert (
const char* queryString,
nsIAbBooleanExpression** expression)
{
nsresult rv;
nsCAutoString q(queryString);
q.StripWhitespace ();
queryString = q.get ();
nsCOMPtr<nsISupports> s;
rv = ParseExpression (&queryString, getter_AddRefs(s));
NS_ENSURE_SUCCESS(rv, rv);
// Case: Not end of string
if (*queryString != 0)
return NS_ERROR_FAILURE;
nsCOMPtr<nsIAbBooleanExpression> e(do_QueryInterface(s, &rv));
NS_ENSURE_SUCCESS(rv, rv);
*expression = e;
NS_IF_ADDREF(*expression);
return rv;
}
nsresult nsAbQueryStringToExpression::ParseExpression (
const char** index,
nsISupports** expression)
{
nsresult rv;
if (**index != '(')
return NS_ERROR_FAILURE;
const char* indexBracket = *index + 1;
while (*indexBracket &&
*indexBracket != '(' && *indexBracket != ')')
indexBracket++;
// Case: End of string
if (*indexBracket == 0)
return NS_ERROR_FAILURE;
// Case: "((" or "()"
if (indexBracket == *index + 1)
{
return NS_ERROR_FAILURE;
}
// Case: "(*("
else if (*indexBracket == '(')
{
// printf ("Case: (*(: %s\n", *index);
nsXPIDLCString operation;
rv = ParseOperationEntry (
*index, indexBracket,
getter_Copies (operation));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAbBooleanExpression> e;
rv = CreateBooleanExpression(operation,
getter_AddRefs(e));
NS_ENSURE_SUCCESS(rv, rv);
// Case: "(*)(*)....(*))"
*index = indexBracket;
rv = ParseExpressions (index, e);
NS_ENSURE_SUCCESS(rv, rv);
*expression = e;
NS_IF_ADDREF(*expression);
}
// Case" "(*)"
else if (*indexBracket == ')')
{
// printf ("Case: (*): %s\n", *index);
nsCOMPtr<nsIAbBooleanConditionString> conditionString;
rv = ParseCondition (index, indexBracket,
getter_AddRefs(conditionString));
NS_ENSURE_SUCCESS(rv, rv);
*expression = conditionString;
NS_IF_ADDREF(*expression);
}
if (**index != ')')
return NS_ERROR_FAILURE;
(*index)++;
return NS_OK;
}
nsresult nsAbQueryStringToExpression::ParseExpressions (
const char** index,
nsIAbBooleanExpression* expression)
{
nsresult rv;
nsCOMPtr<nsISupportsArray> expressions;
NS_NewISupportsArray(getter_AddRefs(expressions));
// Case: ")(*)(*)....(*))"
// printf ("Case: )(*)(*)....(*)): %s\n", *index);
while (**index == '(')
{
nsCOMPtr<nsISupports> childExpression;
rv = ParseExpression (index, getter_AddRefs (childExpression));
NS_ENSURE_SUCCESS(rv, rv);
expressions->AppendElement (childExpression);
}
if (**index == 0)
return NS_ERROR_FAILURE;
// Case: "))"
// printf ("Case: )): %s\n", *index);
if (**index != ')')
return NS_ERROR_FAILURE;
expression->SetExpressions (expressions);
return NS_OK;
}
nsresult nsAbQueryStringToExpression::ParseCondition (
const char** index,
const char* indexBracketClose,
nsIAbBooleanConditionString** conditionString)
{
nsresult rv;
(*index)++;
nsXPIDLCString entries[3];
for (int i = 0; i < 3; i++)
{
rv = ParseConditionEntry (index, indexBracketClose,
getter_Copies (entries[i]));
NS_ENSURE_SUCCESS(rv, rv);
if (*index == indexBracketClose)
break;
}
if (*index != indexBracketClose)
return NS_ERROR_FAILURE;
nsCOMPtr<nsIAbBooleanConditionString> c;
rv = CreateBooleanConditionString (
entries[0],
entries[1],
entries[2],
getter_AddRefs (c));
NS_ENSURE_SUCCESS(rv, rv);
*conditionString = c;
NS_IF_ADDREF(*conditionString);
return NS_OK;
}
nsresult nsAbQueryStringToExpression::ParseConditionEntry (
const char** index,
const char* indexBracketClose,
char** entry)
{
const char* indexDeliminator = *index;
while (indexDeliminator != indexBracketClose &&
*indexDeliminator != ',')
indexDeliminator++;
int entryLength = indexDeliminator - *index;
if (entryLength)
*entry = nsCRT::strndup (*index, entryLength);
else
*entry = 0;
if (indexDeliminator != indexBracketClose)
*index = indexDeliminator + 1;
else
*index = indexDeliminator;
return NS_OK;
}
nsresult nsAbQueryStringToExpression::ParseOperationEntry (
const char* indexBracketOpen1,
const char* indexBracketOpen2,
char** operation)
{
int operationLength = indexBracketOpen2 - indexBracketOpen1 - 1;
if (operationLength)
*operation = nsCRT::strndup (indexBracketOpen1 + 1,
operationLength);
else
*operation = 0;
return NS_OK;
}
nsresult nsAbQueryStringToExpression::CreateBooleanExpression(
const char* operation,
nsIAbBooleanExpression** expression)
{
nsAbBooleanOperationType op;
if (nsCRT::strcasecmp (operation, "and") == 0)
op = nsIAbBooleanOperationTypes::AND;
else if (nsCRT::strcasecmp (operation, "or") == 0)
op = nsIAbBooleanOperationTypes::OR;
else if (nsCRT::strcasecmp (operation, "not") == 0)
op = nsIAbBooleanOperationTypes::NOT;
else
return NS_ERROR_FAILURE;
nsresult rv;
rv = NS_NewIAbBooleanExpression(expression);
NS_ENSURE_SUCCESS(rv, rv);
rv = (*expression)->SetOperation (op);
return rv;
}
nsresult nsAbQueryStringToExpression::CreateBooleanConditionString (
const char* attribute,
const char* condition,
const char* value,
nsIAbBooleanConditionString** conditionString)
{
if (attribute == 0 || condition == 0 || value == 0)
return NS_ERROR_FAILURE;
nsAbBooleanConditionType c;
if (nsCRT::strcasecmp (condition, "=") == 0)
c = nsIAbBooleanConditionTypes::Is;
else if (nsCRT::strcasecmp (condition, "!=") == 0)
c = nsIAbBooleanConditionTypes::IsNot;
else if (nsCRT::strcasecmp (condition, "lt") == 0)
c = nsIAbBooleanConditionTypes::LessThan;
else if (nsCRT::strcasecmp (condition, "gt") == 0)
c = nsIAbBooleanConditionTypes::GreaterThan;
else if (nsCRT::strcasecmp (condition, "bw") == 0)
c = nsIAbBooleanConditionTypes::BeginsWith;
else if (nsCRT::strcasecmp (condition, "ew") == 0)
c = nsIAbBooleanConditionTypes::EndsWith;
else if (nsCRT::strcasecmp (condition, "c")== 0)
c = nsIAbBooleanConditionTypes::Contains;
else if (nsCRT::strcasecmp (condition, "!c") == 0)
c = nsIAbBooleanConditionTypes::DoesNotContain;
else if (nsCRT::strcasecmp (condition, "~=") == 0)
c = nsIAbBooleanConditionTypes::SoundsLike;
else if (nsCRT::strcasecmp (condition, "regex") == 0)
c = nsIAbBooleanConditionTypes::RegExp;
else
return NS_ERROR_FAILURE;
nsresult rv;
nsCOMPtr<nsIAbBooleanConditionString> cs;
rv = NS_NewIAbBooleanConditionString (getter_AddRefs(cs));
NS_ENSURE_SUCCESS(rv, rv);
rv = cs->SetCondition (c);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsITextToSubURI> textToSubURI = do_GetService(NS_ITEXTTOSUBURI_CONTRACTID,&rv);
if (NS_SUCCEEDED(rv))
{
nsXPIDLString attributeUCS2;
nsXPIDLString valueUCS2;
rv = textToSubURI->UnEscapeAndConvert("UTF-8",
attribute, getter_Copies(attributeUCS2));
NS_ENSURE_SUCCESS(rv, rv);
rv = textToSubURI->UnEscapeAndConvert("UTF-8",
value, getter_Copies(valueUCS2));
NS_ENSURE_SUCCESS(rv, rv);
NS_ConvertUCS2toUTF8 attributeUTF8(attributeUCS2);
rv = cs->SetName (attributeUTF8.get ());
NS_ENSURE_SUCCESS(rv, rv);
rv = cs->SetValue (valueUCS2);
NS_ENSURE_SUCCESS(rv, rv);
}
else
{
NS_ConvertUTF8toUCS2 valueUCS2(value);
rv = cs->SetName (attribute);
NS_ENSURE_SUCCESS(rv, rv);
rv = cs->SetValue (valueUCS2.get ());
NS_ENSURE_SUCCESS(rv, rv);
}
*conditionString = cs;
NS_IF_ADDREF(*conditionString);
return NS_OK;
}

View File

@ -0,0 +1,68 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s):
*/
#ifndef nsAbQueryStringToExpression_h__
#define nsAbQueryStringToExpression_h__
#include "nsIAbBooleanExpression.h"
class nsAbQueryStringToExpression
{
public:
static nsresult Convert (
const char* queryString,
nsIAbBooleanExpression** expression);
protected:
static nsresult ParseExpression (
const char** index,
nsISupports** expression);
static nsresult ParseExpressions (
const char** index,
nsIAbBooleanExpression* expression);
static nsresult ParseCondition (
const char** index,
const char* indexBracketClose,
nsIAbBooleanConditionString** conditionString);
static nsresult ParseConditionEntry (
const char** index,
const char* indexBracketClose,
char** entry);
static nsresult ParseOperationEntry (
const char* indexBracketOpen1,
const char* indexBracketOpen2,
char** operation);
static nsresult CreateBooleanExpression(
const char* operation,
nsIAbBooleanExpression** expression);
static nsresult CreateBooleanConditionString (
const char* attribute,
const char* condition,
const char* value,
nsIAbBooleanConditionString** conditionString);
};
#endif

View File

@ -26,6 +26,7 @@
#include "nsIAbDirectory.h"
#include "nsIAddrBookSession.h"
#include "nsIAbCard.h"
#include "nsAbUtils.h"
#include "rdf.h"
#include "nsIRDFService.h"
@ -33,10 +34,14 @@
#include "nsIRDFNode.h"
#include "nsEnumeratorUtils.h"
#include "nsIServiceManager.h"
#include "nsIThread.h"
#include "nsIEventQueueService.h"
#include "nsIProxyObjectManager.h"
#include "nsString.h"
#include "nsCOMPtr.h"
#include "nsXPIDLString.h"
#include "nsAutoLock.h"
#include "prprf.h"
#include "prlog.h"
@ -60,9 +65,9 @@ static NS_DEFINE_CID(kRDFServiceCID, NS_RDFSERVICE_CID);
nsresult nsAbRDFDataSource::createNode(nsString& str, nsIRDFNode **node)
{
*node = nsnull;
nsresult rv;
nsCOMPtr<nsIRDFService> rdf(do_GetService(kRDFServiceCID, &rv));
NS_ENSURE_SUCCESS(rv, rv); // always check this before proceeding
nsresult rv;
nsCOMPtr<nsIRDFService> rdf(do_GetService(kRDFServiceCID, &rv));
NS_ENSURE_SUCCESS(rv, rv); // always check this before proceeding
nsCOMPtr<nsIRDFLiteral> value;
rv = rdf->GetLiteral(str.get(), getter_AddRefs(value));
if (NS_SUCCEEDED(rv))
@ -118,32 +123,167 @@ PRBool nsAbRDFDataSource::unassertEnumFunc(nsISupports *aElement, void *aData)
return PR_TRUE;
}
nsresult nsAbRDFDataSource::NotifyObservers(nsIRDFResource *subject,
nsIRDFResource *property,
nsIRDFNode *object,
PRBool assert,
PRBool change)
nsresult nsAbRDFDataSource::CreateProxyObserver (nsIRDFObserver* observer,
nsIRDFObserver** proxyObserver)
{
NS_ASSERTION(!(change && assert),
nsresult rv;
nsCOMPtr<nsIEventQueueService> eventQSvc = do_GetService (NS_EVENTQUEUESERVICE_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
// Get the UI event queue
nsCOMPtr<nsIEventQueue> uiQueue;
rv = eventQSvc->GetSpecialEventQueue (
nsIEventQueueService::UI_THREAD_EVENT_QUEUE,
getter_AddRefs (uiQueue));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIProxyObjectManager> proxyMgr =
do_GetService(NS_XPCOMPROXY_CONTRACTID, &rv);
NS_ENSURE_SUCCESS(rv, rv);
// Proxy the observer on the UI queue
/*
* TODO
* Currenly using PROXY_ASYNC, however
* this can flood the event queue if
* rate of events on the observer is
* greater that the time to process the
* events.
* This causes the UI to pause.
*/
rv = proxyMgr->GetProxyForObject (uiQueue,
NS_GET_IID(nsIRDFObserver),
observer,
PROXY_ASYNC | PROXY_ALWAYS,
(void** )proxyObserver);
return rv;
}
nsresult nsAbRDFDataSource::CreateProxyObservers ()
{
nsresult rv = NS_OK;
PRUint32 nObservers;
mObservers->Count (&nObservers);
if (!mProxyObservers)
{
rv = NS_NewISupportsArray(getter_AddRefs(mProxyObservers));
NS_ENSURE_SUCCESS(rv, rv);
}
PRUint32 nProxyObservers;
mProxyObservers->Count (&nProxyObservers);
/*
* For all the outstanding observers that
* have not been proxied
*/
for (PRUint32 i = nProxyObservers; i < nObservers; i++)
{
nsCOMPtr<nsISupports> supports;
rv = mObservers->GetElementAt (i, getter_AddRefs (supports));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIRDFObserver> observer (do_QueryInterface (supports, &rv));
NS_ENSURE_SUCCESS(rv, rv);
// Create the proxy
nsCOMPtr<nsIRDFObserver> proxyObserver;
rv = CreateProxyObserver (observer, getter_AddRefs (proxyObserver));
NS_ENSURE_SUCCESS(rv, rv);
mProxyObservers->AppendElement(proxyObserver);
}
return rv;
}
nsresult nsAbRDFDataSource::NotifyObservers(nsIRDFResource *subject,
nsIRDFResource *property,
nsIRDFNode *object,
PRBool assert,
PRBool change)
{
NS_ASSERTION(!(change && assert),
"Can't change and assert at the same time!\n");
if (mObservers)
if(!mLock)
{
nsAbRDFNotification note = { this, subject, property, object };
if (change)
mObservers->EnumerateForwards(changeEnumFunc, &note);
else if (assert)
mObservers->EnumerateForwards(assertEnumFunc, &note);
else
mObservers->EnumerateForwards(unassertEnumFunc, &note);
NS_ERROR("Error in AutoLock resource in nsAbRDFDataSource::NotifyObservers()");
return NS_ERROR_OUT_OF_MEMORY;
}
nsresult rv;
nsAutoLock lockGuard (mLock);
if (!mObservers)
return NS_OK;
// Get the current thread
nsCOMPtr<nsIThread> currentThread;
rv = nsIThread::GetCurrent (getter_AddRefs(currentThread));
NS_ENSURE_SUCCESS (rv, rv);
// Get the main thread, which is the UI thread
/*
* TODO
* Is the main thread always guaranteed to be
* the UI thread?
*
* Note that this also binds the data source
* to the UI which is supposedly the only
* place where it is used, but what about
* RDF datasources that are not UI specific
* but are used in the UI?
*/
nsCOMPtr<nsIThread> uiThread;
rv = nsIThread::GetMainThread (getter_AddRefs(uiThread));
NS_ENSURE_SUCCESS (rv, rv);
nsCOMPtr<nsISupportsArray> observers;
if (currentThread == uiThread)
{
/*
* Since this is the UI Thread use the
* observers list directly for performance
*/
observers = mObservers;
}
else
{
/*
* This is a different thread to the UI
* thread need to use proxies to the
* observers
*
* Create the proxies
*/
rv = CreateProxyObservers ();
NS_ENSURE_SUCCESS (rv, rv);
observers = mProxyObservers;
}
nsAbRDFNotification note = { this, subject, property, object };
if (change)
observers->EnumerateForwards(changeEnumFunc, &note);
else if (assert)
observers->EnumerateForwards(assertEnumFunc, &note);
else
observers->EnumerateForwards(unassertEnumFunc, &note);
return NS_OK;
}
nsresult nsAbRDFDataSource::NotifyPropertyChanged(nsIRDFResource *resource,
nsIRDFResource *propertyResource,
const PRUnichar *oldValue,
const PRUnichar *newValue)
nsIRDFResource *propertyResource,
const PRUnichar *oldValue,
const PRUnichar *newValue)
{
nsCOMPtr<nsIRDFNode> newValueNode;
nsString newValueStr(newValue);
@ -155,10 +295,14 @@ nsresult nsAbRDFDataSource::NotifyPropertyChanged(nsIRDFResource *resource,
nsAbRDFDataSource::nsAbRDFDataSource():
mObservers(nsnull),
mProxyObservers(nsnull),
mInitialized(PR_FALSE),
mRDFService(nsnull)
mRDFService(nsnull),
mLock(nsnull)
{
NS_INIT_REFCNT();
mLock = PR_NewLock ();
}
nsAbRDFDataSource::~nsAbRDFDataSource (void)
@ -169,14 +313,17 @@ nsAbRDFDataSource::~nsAbRDFDataSource (void)
nsServiceManager::ReleaseService(kRDFServiceCID, mRDFService);
mRDFService = nsnull;
}
if(mLock)
PR_DestroyLock (mLock);
}
nsresult nsAbRDFDataSource::Init()
{
nsresult rv = nsServiceManager::GetService(kRDFServiceCID,
NS_GET_IID(nsIRDFService),
(nsISupports**) &mRDFService);
NS_GET_IID(nsIRDFService),
(nsISupports**) &mRDFService);
NS_ENSURE_SUCCESS(rv, rv);
mRDFService->RegisterDataSource(this, PR_FALSE);
@ -184,7 +331,7 @@ nsresult nsAbRDFDataSource::Init()
return NS_OK;
}
NS_IMPL_ISUPPORTS1(nsAbRDFDataSource, nsIRDFDataSource)
NS_IMPL_THREADSAFE_ISUPPORTS1(nsAbRDFDataSource, nsIRDFDataSource)
// nsIRDFDataSource methods
NS_IMETHODIMP nsAbRDFDataSource::GetURI(char* *uri)
@ -268,25 +415,78 @@ NS_IMETHODIMP nsAbRDFDataSource::HasAssertion(nsIRDFResource* source,
return NS_OK;
}
NS_IMETHODIMP nsAbRDFDataSource::AddObserver(nsIRDFObserver* n)
NS_IMETHODIMP nsAbRDFDataSource::AddObserver(nsIRDFObserver* observer)
{
if (! mObservers) {
nsresult rv;
rv = NS_NewISupportsArray(getter_AddRefs(mObservers));
NS_ENSURE_SUCCESS(rv, rv);
}
mObservers->AppendElement(n);
return NS_OK;
if(!mLock)
{
NS_ERROR("Error in AutoLock resource in nsAbRDFDataSource::AddObservers()");
return NS_ERROR_OUT_OF_MEMORY;
}
nsresult rv;
// Lock the whole method
nsAutoLock lockGuard (mLock);
if (!mObservers)
{
rv = NS_NewISupportsArray(getter_AddRefs(mObservers));
NS_ENSURE_SUCCESS(rv, rv);
}
// Do not add if already present
PRInt32 i;
mObservers->GetIndexOf (observer, &i);
if (i >= 0)
return NS_OK;
mObservers->AppendElement(observer);
/*
* If the proxy observers has been created
* then do the work here to avoid unecessary
* delay when performing the notify from a
* different thread
*/
if (mProxyObservers)
{
nsCOMPtr<nsIRDFObserver> proxyObserver;
rv = CreateProxyObserver (observer,
getter_AddRefs(proxyObserver));
NS_ENSURE_SUCCESS(rv, rv);
mProxyObservers->AppendElement (proxyObserver);
}
return NS_OK;
}
NS_IMETHODIMP nsAbRDFDataSource::RemoveObserver(nsIRDFObserver* n)
NS_IMETHODIMP nsAbRDFDataSource::RemoveObserver(nsIRDFObserver* observer)
{
if (! mObservers)
return NS_OK;
mObservers->RemoveElement(n);
return NS_OK;
}
if(!mLock)
{
NS_ERROR("Error in AutoLock resource in nsAbRDFDataSource::RemoveObservers()");
return NS_ERROR_OUT_OF_MEMORY;
}
// Lock the whole method
nsAutoLock lockGuard (mLock);
if (!mObservers)
return NS_OK;
PRInt32 i;
mObservers->GetIndexOf (observer, &i);
if (i >= 0)
{
mObservers->RemoveElementAt(i);
if (mProxyObservers)
mProxyObservers->RemoveElementAt(i);
}
return NS_OK;
}
NS_IMETHODIMP
nsAbRDFDataSource::HasArcIn(nsIRDFNode *aNode, nsIRDFResource *aArc, PRBool *result)

View File

@ -35,20 +35,13 @@
*/
class nsAbRDFDataSource : public nsIRDFDataSource
{
private:
nsCOMPtr<nsISupportsArray> mObservers;
PRBool mInitialized;
// The cached service managers
nsIRDFService* mRDFService;
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIRDFDATASOURCE
nsAbRDFDataSource(void);
virtual ~nsAbRDFDataSource(void);
NS_DECL_NSIRDFDATASOURCE
nsAbRDFDataSource();
virtual ~nsAbRDFDataSource();
virtual nsresult Init();
protected:
@ -56,16 +49,38 @@ protected:
nsresult createNode(nsString& str, nsIRDFNode **node);
nsresult createNode(PRUint32 value, nsIRDFNode **node);
nsresult NotifyPropertyChanged(nsIRDFResource *resource, nsIRDFResource *propertyResource,
const PRUnichar *oldValue, const PRUnichar *newValue);
nsresult NotifyPropertyChanged(
nsIRDFResource *resource,
nsIRDFResource *propertyResource,
const PRUnichar *oldValue,
const PRUnichar *newValue);
nsresult NotifyObservers(nsIRDFResource *subject, nsIRDFResource *property,
nsIRDFNode *object, PRBool assert, PRBool change);
nsresult NotifyObservers(
nsIRDFResource *subject,
nsIRDFResource *property,
nsIRDFNode *object,
PRBool assert,
PRBool change);
nsresult CreateProxyObservers ();
nsresult CreateProxyObserver (
nsIRDFObserver* observer,
nsIRDFObserver** proxyObserver);
static PRBool assertEnumFunc(nsISupports *aElement, void *aData);
static PRBool unassertEnumFunc(nsISupports *aElement, void *aData);
static PRBool changeEnumFunc(nsISupports *aElement, void *aData);
private:
nsCOMPtr<nsISupportsArray> mObservers;
nsCOMPtr<nsISupportsArray> mProxyObservers;
PRBool mInitialized;
// The cached service managers
nsIRDFService* mRDFService;
PRLock* mLock;
};
#endif

View File

@ -0,0 +1,237 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s): Csaba Borbola <csaba.borbola@sun.com>
*/
#include "nsAbUtils.h"
#include "nsCRT.h"
#include "nsString.h"
/*
* Convert the nsCStringArray to a char* array
*/
nsresult CStringArrayToCharPtrArray::Convert (nsCStringArray& array,
PRUint32* returnPropertiesSize,
char*** returnPropertiesArray,
PRBool copyElements)
{
PRUint32 size = array.Count ();
if (size == 0)
return NS_ERROR_FAILURE;
if (!returnPropertiesSize || !returnPropertiesArray)
return NS_ERROR_NULL_POINTER;
*returnPropertiesSize = size;
*returnPropertiesArray = NS_STATIC_CAST(char**, nsMemory::Alloc (sizeof (char* ) * size));
if (!(*returnPropertiesArray))
return NS_ERROR_OUT_OF_MEMORY;
for (PRUint32 i = 0; i < size; i++)
{
if (copyElements == PR_TRUE)
(*returnPropertiesArray)[i] =
array[i]->ToNewCString();
else
(*returnPropertiesArray)[i] = NS_CONST_CAST(char *, (array[i]->ToNewCString()));
}
return NS_OK;
}
/*
* Convert the char* array to nsCStringArray
*/
nsresult CharPtrArrayToCStringArray::Convert (nsCStringArray& returnPropertiesArray,
PRUint32 arraySize,
const char** array)
{
if (!array)
return NS_ERROR_NULL_POINTER;
if (!arraySize)
return NS_OK;
returnPropertiesArray.Clear ();
for (PRUint32 i = 0; i < arraySize; i++)
returnPropertiesArray.AppendCString (nsCAutoString (array[i]));
return NS_OK;
}
/*
* Convert the PRUnichar* array to nsStringArray
*/
nsresult StringArrayToPRUnicharPtrArray::Convert (nsStringArray& array,
PRUint32* returnPropertiesSize,
PRUnichar*** returnPropertiesArray,
PRBool copyElements)
{
PRUint32 size = array.Count ();
if (size == 0)
return NS_ERROR_FAILURE;
if (!returnPropertiesSize || !returnPropertiesArray)
return NS_ERROR_NULL_POINTER;
*returnPropertiesSize = size;
*returnPropertiesArray = NS_STATIC_CAST(PRUnichar**, nsMemory::Alloc (sizeof (PRUnichar* ) * size));
if (!(*returnPropertiesArray))
return NS_ERROR_OUT_OF_MEMORY;
for (PRUint32 i = 0; i < size; i++)
{
if (copyElements == PR_TRUE)
(*returnPropertiesArray)[i] =
array[i]->ToNewUnicode();
else
(*returnPropertiesArray)[i] = NS_REINTERPRET_CAST(PRUnichar*,array[i]->ToNewCString());
}
return NS_OK;
}
/*
* Convert the PRUnichar* array to nsStringArray
*/
nsresult PRUnicharPtrArrayToStringArray::Convert (nsStringArray& returnPropertiesArray,
PRUint32 arraySize,
const PRUnichar** array)
{
if (!array)
return NS_ERROR_NULL_POINTER;
if (!arraySize)
return NS_OK;
returnPropertiesArray.Clear ();
for (PRUint32 i = 0; i < arraySize; i++)
returnPropertiesArray.AppendString (nsAutoString (array[i]));
return NS_OK;
}
/*
* Convert array of keys and values to nsHashtable
*/
nsresult PropertyPtrArraysToHashtable::Convert (
nsHashtable& propertySet,
PRUint32 propertiesSize,
const char** propertyNameArray,
const PRUnichar** propertyValueArray)
{
if (!propertyNameArray || !propertyValueArray)
return NS_ERROR_NULL_POINTER;
if (!propertiesSize)
return NS_OK;
propertySet.Reset ();
for (PRUint32 i = 0; i < propertiesSize; i++)
{
nsCStringKey key (propertyNameArray[i], -1, nsCStringKey::NEVER_OWN);
propertySet.Put (&key, NS_REINTERPRET_CAST(void *, NS_CONST_CAST(PRUnichar *, propertyValueArray[i])));
}
return NS_OK;
}
/*
* nsHashtable enumerator callback data
*
* Contains the key and value arrays and
* the current position a new entry may
* be added
*/
struct closureStruct
{
PRUint32 position;
char** propertyNameArray;
PRUnichar** propertyValueArray;
};
/*
* nsHashtable enumeration callback procedure
*
* References values from the hashtable entry
* into the associated position of the key and
* value arrays
*/
static PRBool enumerateEntries(nsHashKey *aKey, void *aData, void* closure)
{
closureStruct* s = NS_REINTERPRET_CAST(closureStruct*, closure);
nsCStringKey* key = NS_REINTERPRET_CAST(nsCStringKey*, aKey);
s->propertyNameArray[s->position] = NS_CONST_CAST(char* ,key->GetString ());
s->propertyValueArray[s->position] = NS_STATIC_CAST(PRUnichar *, aData);
s->position++;
return PR_TRUE;
}
/*
* Convert nsHashtable to array of keys and values
*/
nsresult HashtableToPropertyPtrArrays::Convert (
nsHashtable& propertySet,
PRUint32* propertiesSize,
char*** propertyNameArray,
PRUnichar*** propertyValueArray)
{
if (!propertyNameArray || !propertyValueArray || !propertiesSize)
return NS_ERROR_NULL_POINTER;
*propertiesSize = propertySet.Count ();
if (*propertiesSize == 0)
return NS_OK;
*propertyNameArray =
NS_STATIC_CAST(char**, nsMemory::Alloc (sizeof (char* ) * (*propertiesSize)));
if (!(*propertyNameArray))
return NS_ERROR_OUT_OF_MEMORY;
*propertyValueArray =
NS_STATIC_CAST(PRUnichar**, nsMemory::Alloc (sizeof (PRUnichar* ) * (*propertiesSize)));
if (!(*propertyValueArray))
{
nsMemory::Free (*propertyNameArray);
return NS_ERROR_OUT_OF_MEMORY;
}
// Set up enumerator callback structure
closureStruct s;
s.position = 0;
s.propertyNameArray = *propertyNameArray;
s.propertyValueArray = *propertyValueArray;
// Enumerate over hashtable entries
propertySet.Enumerate (enumerateEntries, NS_STATIC_CAST(void* ,&s));
return NS_OK;
}

View File

@ -0,0 +1,251 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Created by: Paul Sandoz <paul.sandoz@sun.com>
*
* Contributor(s): Csaba Borbola <csaba.borbola@sun.com>
*/
#ifndef nsAbUtils_h__
#define nsAbUtils_h__
#include "nsMemory.h"
#include "nsVoidArray.h"
#include "nsHashtable.h"
#include "prprf.h"
/*
* Wrapper class to automatically free an array of
* char* when class goes out of scope
*/
class CharPtrArrayGuard
{
public:
CharPtrArrayGuard (PRBool freeElements = PR_TRUE) :
mFreeElements (freeElements),
mArray (0),
mSize (0)
{
}
~CharPtrArrayGuard ()
{
Free ();
}
char* operator[](int i)
{
return mArray[i];
}
PRUint32* GetSizeAddr(void)
{
return &mSize;
}
PRUint32 GetSize(void)
{
return mSize;
}
char*** GetArrayAddr(void)
{
return &mArray;
}
const char** GetArray(void)
{
return (const char** ) mArray;
}
public:
private:
PRBool mFreeElements;
char **mArray;
PRUint32 mSize;
void Free ()
{
if (!mArray)
return;
if (mFreeElements == PR_TRUE)
NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(mSize, mArray);
}
};
/*
* Helper class to convert an nsCStringArray
* to an array of char*
* By default strings will be copied, unless
* the copyElements parameter is set to PR_FALSE.
*/
class CStringArrayToCharPtrArray
{
public:
static nsresult Convert (nsCStringArray& array,
PRUint32* returnPropertiesSize,
char*** returnPropertiesArray,
PRBool copyElements = PR_TRUE);
};
/*
* Helper class to convert an array of char*
* to an nsCStringArray
*/
class CharPtrArrayToCStringArray
{
public:
static nsresult Convert (nsCStringArray& array,
PRUint32 returnPropertiesSize,
const char** returnPropertiesArray);
};
/*
* Wrapper class to automatically free an array of
* PRUnichar* when class goes out of scope
*/
class PRUnicharPtrArrayGuard
{
public:
PRUnicharPtrArrayGuard (PRBool freeElements = PR_TRUE) :
mFreeElements (freeElements),
mArray (0),
mSize (0)
{
}
~PRUnicharPtrArrayGuard ()
{
Free ();
}
PRUnichar* operator[](int i)
{
return mArray[i];
}
PRUint32* GetSizeAddr(void)
{
return &mSize;
}
PRUint32 GetSize(void)
{
return mSize;
}
PRUnichar*** GetArrayAddr(void)
{
return &mArray;
}
const PRUnichar** GetArray(void)
{
return (const PRUnichar** ) mArray;
}
public:
private:
PRBool mFreeElements;
PRUnichar **mArray;
PRUint32 mSize;
void Free ()
{
if (!mArray)
return;
if (mFreeElements == PR_TRUE)
NS_FREE_XPCOM_ALLOCATED_POINTER_ARRAY(mSize, mArray);
}
};
/*
* Helper class to convert an nsStringArray
* to an array of PRUnichar*
* By default strings will be copied, unless
* the copyElements parameter is set to PR_FALSE.
*/
class StringArrayToPRUnicharPtrArray
{
public:
static nsresult Convert (nsStringArray& array,
PRUint32* returnPropertiesSize,
PRUnichar*** returnPropertiesArray,
PRBool copyElements = PR_TRUE);
};
/*
* Helper class to convert an array of PRUnichar*
* to an nsStringArray
*/
class PRUnicharPtrArrayToStringArray
{
public:
static nsresult Convert (nsStringArray& returnPropertiesArray,
PRUint32 returnPropertiesSize,
const PRUnichar** array);
};
/*
* Helper class to convert a pair of char*
* array of keys and corresponding PRUnichar*
* array of values to a nsHashtable
*
* Does not copy array values. The nsHashtable
* refers directly to the array elements thus
* the contents may only be valid for the scope
* of the arrays
*/
class PropertyPtrArraysToHashtable
{
public:
static nsresult Convert (
nsHashtable& propertySet,
PRUint32 propertiesSize,
const char** propertyNameArray,
const PRUnichar** propertyValueArray);
};
/*
* Helper class to convert a nsHashtable to
* corresponding char* key arrays and PRUnichar*
* arrays
*
* Does not copy nsHashtable keys and values
* thus the elements of the arrays may only be
* valid for the scope of the hashtable
*/
class HashtableToPropertyPtrArrays
{
public:
static nsresult Convert (
nsHashtable& propertySet,
PRUint32* propertiesSize,
char*** propertyNameArray,
PRUnichar*** propertyValueArray);
};
#endif

View File

@ -26,7 +26,6 @@
#include "nsAbBaseCID.h"
#include "nsDirPrefs.h"
#include "nsIAddrBookSession.h"
// #include "nsAbRDFResource.h"
#include "nsIAddrDatabase.h"
#include "plstr.h"
@ -38,8 +37,8 @@
#include "nsIDOMNodeList.h"
#include "nsIRDFCompositeDataSource.h"
#include "nsIRDFResource.h"
#include "nsRDFResource.h"
#include "nsIRDFService.h"
#include "nsRDFCID.h"
#include "nsIServiceManager.h"
#include "nsAppShellCIDs.h"
#include "nsIAppShellService.h"
@ -54,15 +53,21 @@
#include "nsIFilePicker.h"
#include "nsIPref.h"
#include "nsVoidArray.h"
#include "nsILocale.h"
#include "nsLocaleCID.h"
#include "nsILocaleService.h"
#include "nsCollationCID.h"
static NS_DEFINE_CID(kPrefCID, NS_PREF_CID);
static NS_DEFINE_CID(kRDFServiceCID, NS_RDFSERVICE_CID);
static NS_DEFINE_CID(kAppShellServiceCID, NS_APPSHELL_SERVICE_CID);
static NS_DEFINE_CID(kAddressBookDBCID, NS_ADDRDATABASE_CID);
static NS_DEFINE_CID(kAddrBookSessionCID, NS_ADDRBOOKSESSION_CID);
// static NS_DEFINE_CID(kAbDirectoryCID, NS_ABDIRECTORY_CID);
static NS_DEFINE_CID(kAbCardPropertyCID, NS_ABCARDPROPERTY_CID);
static NS_DEFINE_CID(kAB4xUpgraderServiceCID, NS_AB4xUPGRADER_CID);
/* Had hoped to replace this with the preferable contractid but
* unable to locate it.
*/
static NS_DEFINE_CID(kCollationFactoryCID, NS_COLLATIONFACTORY_CID);
static nsresult ConvertDOMListToResourceArray(nsIDOMNodeList *nodeList, nsISupportsArray **resourceArray)
@ -164,14 +169,11 @@ NS_IMETHODIMP nsAddressBook::NewAddressBook
return NS_ERROR_NULL_POINTER;
nsresult rv = NS_OK;
nsCOMPtr<nsIRDFService> rdfService(do_GetService(kRDFServiceCID, &rv));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIRDFService> rdfService = do_GetService (NS_RDF_CONTRACTID "/rdf-service;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIRDFResource> parentResource;
char *parentUri = PR_smprintf("%s", kAllDirectoryRoot);
rv = rdfService->GetResource(parentUri, getter_AddRefs(parentResource));
if (parentUri)
PR_smprintf_free(parentUri);
rv = rdfService->GetResource(kAllDirectoryRoot, getter_AddRefs(parentResource));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAbDirectory> parentDir = do_QueryInterface(parentResource, &rv);
@ -189,8 +191,6 @@ NS_IMETHODIMP nsAddressBook::DeleteAddressBooks
return NS_ERROR_NULL_POINTER;
nsresult rv = NS_OK;
nsCOMPtr<nsIRDFService> rdfService(do_GetService(kRDFServiceCID, &rv));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsISupportsArray> resourceArray;
rv = ConvertDOMListToResourceArray(nodeList, getter_AddRefs(resourceArray));
@ -204,9 +204,9 @@ nsresult nsAddressBook::DoCommand(nsIRDFCompositeDataSource* db, char *command,
nsISupportsArray *srcArray, nsISupportsArray *argumentArray)
{
nsresult rv;
nsresult rv = NS_OK;
nsCOMPtr<nsIRDFService> rdfService(do_GetService(kRDFServiceCID, &rv));
nsCOMPtr<nsIRDFService> rdfService = do_GetService (NS_RDF_CONTRACTID "/rdf-service;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIRDFResource> commandResource;
@ -413,11 +413,21 @@ NS_IMETHODIMP nsAddressBook::GetTotalCards(const char *URI, PRUint32 *count)
NS_ENSURE_ARG_POINTER(count);
*count = 0;
nsCOMPtr<nsIAddrDatabase> database;
nsresult rv = GetAbDatabaseFromURI(URI, getter_AddRefs(database));
NS_ENSURE_SUCCESS(rv,rv);
rv = database->GetCardCount(count);
NS_ENSURE_SUCCESS(rv,rv);
nsresult rv;
nsCOMPtr<nsIRDFService> rdfService = do_GetService (NS_RDF_CONTRACTID "/rdf-service;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIRDFResource> resource;
rv = rdfService->GetResource(URI, getter_AddRefs(resource));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIAbDirectory> directory = do_QueryInterface(resource, &rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = directory->GetTotalCards (PR_FALSE, count);
NS_ENSURE_SUCCESS(rv, rv);
return rv;
}
@ -499,7 +509,7 @@ nsresult AddressBookParser::ParseFile()
{
return ParseLDIFFile();
}
/* Get database file name */
char *leafName = nsnull;
nsAutoString fileString;
@ -553,8 +563,8 @@ nsresult AddressBookParser::ParseFile()
delete dbPath;
nsCOMPtr<nsIRDFService> rdfService(do_GetService(kRDFServiceCID, &rv));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIRDFService> rdfService = do_GetService (NS_RDF_CONTRACTID "/rdf-service;1", &rv);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsIRDFResource> parentResource;
char *parentUri = PR_smprintf("%s", kAllDirectoryRoot);
rv = rdfService->GetResource(parentUri, getter_AddRefs(parentResource));
@ -570,10 +580,10 @@ nsresult AddressBookParser::ParseFile()
nsCOMPtr<nsIPref> pPref(do_GetService(kPrefCID, &rv));
if (NS_FAILED(rv) || !pPref)
return nsnull;
PRUnichar *dirName = nsnull;
rv = pPref->GetLocalizedUnicharPref("ldap_2.servers.pab.description", &dirName);
nsXPIDLString dirName;
rv = pPref->GetLocalizedUnicharPref("ldap_2.servers.pab.description", getter_Copies(dirName));
parentDir->CreateDirectoryByURI(dirName, mDbUri, mMigrating);
nsMemory::Free(dirName);
}
else
parentDir->CreateDirectoryByURI(fileString.get(), mDbUri, mMigrating);
@ -675,75 +685,75 @@ void AddressBookParser::AddTabRowToDatabase()
{
case POS_FIRST_NAME:
if (column.Length() > 0)
mDatabase->AddFirstName(newRow, column);
mDatabase->AddFirstName(newRow, column.get());
break;
case POS_LAST_NAME:
if (column.Length() > 0)
mDatabase->AddLastName(newRow, column);
mDatabase->AddLastName(newRow, column.get());
break;
case POS_DISPLAY_NAME:
if (column.Length() > 0)
mDatabase ->AddDisplayName(newRow, column);
mDatabase ->AddDisplayName(newRow, column.get());
break;
case POS_NICK_NAME:
if (column.Length() > 0)
mDatabase->AddNickName(newRow, column);
mDatabase->AddNickName(newRow, column.get());
break;
case POS_EMAIL:
if (column.Length() > 0)
mDatabase->AddPrimaryEmail(newRow, column);
mDatabase->AddPrimaryEmail(newRow, column.get());
break;
case POS_WORK_NUMBER:
if (column.Length() > 0)
mDatabase->AddWorkPhone(newRow, column);
mDatabase->AddWorkPhone(newRow, column.get());
break;
case POS_HOME_NUMBER:
if (column.Length() > 0)
mDatabase->AddHomePhone(newRow, column);
mDatabase->AddHomePhone(newRow, column.get());
break;
case POS_PAGE_NUMBER:
if (column.Length() > 0)
mDatabase->AddPagerNumber(newRow, column);
mDatabase->AddPagerNumber(newRow, column.get());
break;
case POS_CELLULAR_NUMBER:
if (column.Length() > 0)
mDatabase->AddCellularNumber(newRow, column);
mDatabase->AddCellularNumber(newRow, column.get());
break;
case POS_FAX_NUMBER:
if (column.Length() > 0)
mDatabase->AddFaxNumber(newRow, column);
mDatabase->AddFaxNumber(newRow, column.get());
break;
case POS_ADDRESS:
if (column.Length() > 0)
mDatabase->AddWorkAddress(newRow, column);
mDatabase->AddWorkAddress(newRow, column.get());
break;
case POS_CITY:
if (column.Length() > 0)
mDatabase->AddWorkCity(newRow, column);
mDatabase->AddWorkCity(newRow, column.get());
break;
case POS_STATE:
if (column.Length() > 0)
mDatabase->AddWorkState(newRow, column);
mDatabase->AddWorkState(newRow, column.get());
break;
case POS_ZIP:
if (column.Length() > 0)
mDatabase->AddWorkZipCode(newRow, column);
mDatabase->AddWorkZipCode(newRow, column.get());
break;
case POS_COUNTRY:
if (column.Length() > 0)
mDatabase->AddWorkCountry(newRow, column);
mDatabase->AddWorkCountry(newRow, column.get());
break;
case POS_TITLE:
if (column.Length() > 0)
mDatabase->AddJobTitle(newRow, column);
mDatabase->AddJobTitle(newRow, column.get());
break;
case POS_ORGANIZATION:
if (column.Length() > 0)
mDatabase->AddDepartment(newRow, column);
mDatabase->AddDepartment(newRow, column.get());
break;
case POS_NOTE:
if (column.Length() > 0)
mDatabase->AddNotes(newRow, column);
mDatabase->AddNotes(newRow, column.get());
break;
case POS_UNKNOWN:
default:
@ -1095,30 +1105,30 @@ void AddressBookParser::AddLdifColToDatabase(nsIMdbRow* newRow, char* typeSlot,
{
case 'b':
if ( -1 != colType.Find("birthyear") )
mDatabase->AddBirthYear(newRow, column);
mDatabase->AddBirthYear(newRow, column.get());
break; // 'b'
case 'c':
if ( -1 != colType.Find("cn") || -1 != colType.Find("commonname") )
{
if (bIsList)
mDatabase->AddListName(newRow, column);
mDatabase->AddListName(newRow, column.get());
else
mDatabase->AddDisplayName(newRow, column);
mDatabase->AddDisplayName(newRow, column.get());
}
else if ( -1 != colType.Find("countryname") )
{
{
if (mStoreLocAsHome )
mDatabase->AddHomeCountry(newRow, column);
mDatabase->AddHomeCountry(newRow, column.get());
else
mDatabase->AddWorkCountry(newRow, column);
}
mDatabase->AddWorkCountry(newRow, column.get());
}
// else if ( -1 != colType.Find("charset") )
// ioRow->AddColumn(ev, this->ColCharset(), yarn);
else if ( -1 != colType.Find("cellphone") )
mDatabase->AddCellularNumber(newRow, column);
mDatabase->AddCellularNumber(newRow, column.get());
// else if ( -1 != colType.Find("calendar") )
// ioRow->AddColumn(ev, this->ColCalendar(), yarn);
@ -1127,41 +1137,41 @@ void AddressBookParser::AddLdifColToDatabase(nsIMdbRow* newRow, char* typeSlot,
// ioRow->AddColumn(ev, this->ColCar(), yarn);
else if ( -1 != colType.Find("carphone") )
mDatabase->AddCellularNumber(newRow, column);
mDatabase->AddCellularNumber(newRow, column.get());
// ioRow->AddColumn(ev, this->ColCarPhone(), yarn);
// else if ( -1 != colType.Find("carlicense") )
// ioRow->AddColumn(ev, this->ColCarLicense(), yarn);
else if ( -1 != colType.Find("custom1") )
mDatabase->AddCustom1(newRow, column);
mDatabase->AddCustom1(newRow, column.get());
else if ( -1 != colType.Find("custom2") )
mDatabase->AddCustom2(newRow, column);
mDatabase->AddCustom2(newRow, column.get());
else if ( -1 != colType.Find("custom3") )
mDatabase->AddCustom3(newRow, column);
mDatabase->AddCustom3(newRow, column.get());
else if ( -1 != colType.Find("custom4") )
mDatabase->AddCustom4(newRow, column);
mDatabase->AddCustom4(newRow, column.get());
else if ( -1 != colType.Find("company") )
mDatabase->AddCompany(newRow, column);
mDatabase->AddCompany(newRow, column.get());
break; // 'c'
case 'd':
if ( -1 != colType.Find("description") )
{
if (bIsList)
mDatabase->AddListDescription(newRow, column);
mDatabase->AddListDescription(newRow, column.get());
else
mDatabase->AddNotes(newRow, column);
mDatabase->AddNotes(newRow, column.get());
}
// else if ( -1 != colType.Find("dn") ) // distinuished name
// ioRow->AddColumn(ev, this->ColDistName(), yarn);
else if ( -1 != colType.Find("department") )
mDatabase->AddDepartment(newRow, column);
mDatabase->AddDepartment(newRow, column.get());
// else if ( -1 != colType.Find("departmentnumber") )
// ioRow->AddColumn(ev, this->ColDepartmentNumber(), yarn);
@ -1183,12 +1193,12 @@ void AddressBookParser::AddLdifColToDatabase(nsIMdbRow* newRow, char* typeSlot,
if ( -1 != colType.Find("fax") ||
-1 != colType.Find("facsimiletelephonenumber") )
mDatabase->AddFaxNumber(newRow, column);
mDatabase->AddFaxNumber(newRow, column.get());
break; // 'f'
case 'g':
if ( -1 != colType.Find("givenname") )
mDatabase->AddFirstName(newRow, column);
mDatabase->AddFirstName(newRow, column.get());
// else if ( -1 != colType.Find("gif") )
// ioRow->AddColumn(ev, this->ColGif(), yarn);
@ -1200,10 +1210,10 @@ void AddressBookParser::AddLdifColToDatabase(nsIMdbRow* newRow, char* typeSlot,
case 'h':
if ( -1 != colType.Find("homephone") )
mDatabase->AddHomePhone(newRow, column);
mDatabase->AddHomePhone(newRow, column.get());
else if ( -1 != colType.Find("homeurl") )
mDatabase->AddWebPage1(newRow, column);
mDatabase->AddWebPage1(newRow, column.get());
break; // 'h'
case 'i':
@ -1228,12 +1238,12 @@ void AddressBookParser::AddLdifColToDatabase(nsIMdbRow* newRow, char* typeSlot,
case 'l':
if ( -1 != colType.Find("l") || -1 != colType.Find("locality") )
{
{
if (mStoreLocAsHome )
mDatabase->AddHomeCity(newRow, column);
mDatabase->AddHomeCity(newRow, column.get());
else
mDatabase->AddWorkCity(newRow, column);
}
mDatabase->AddWorkCity(newRow, column.get());
}
// else if ( -1 != colType.Find("language") )
// ioRow->AddColumn(ev, this->ColLanguage(), yarn);
@ -1248,10 +1258,10 @@ void AddressBookParser::AddLdifColToDatabase(nsIMdbRow* newRow, char* typeSlot,
case 'm':
if ( -1 != colType.Find("mail") )
mDatabase->AddPrimaryEmail(newRow, column);
mDatabase->AddPrimaryEmail(newRow, column.get());
else if ( -1 != colType.Find("member") && bIsList )
mDatabase->AddLdifListMember(newRow, column);
mDatabase->AddLdifListMember(newRow, column.get());
// else if ( -1 != colType.Find("manager") )
// ioRow->AddColumn(ev, this->ColManager(), yarn);
@ -1269,7 +1279,7 @@ void AddressBookParser::AddLdifColToDatabase(nsIMdbRow* newRow, char* typeSlot,
// ioRow->AddColumn(ev, this->ColNote(), yarn);
if ( -1 != colType.Find("notes") )
mDatabase->AddNotes(newRow, column);
mDatabase->AddNotes(newRow, column.get());
// else if ( -1 != colType.Find("n") )
// ioRow->AddColumn(ev, this->ColN(), yarn);
@ -1284,10 +1294,10 @@ void AddressBookParser::AddLdifColToDatabase(nsIMdbRow* newRow, char* typeSlot,
break;
else if ( -1 != colType.Find("ou") || -1 != colType.Find("orgunit") )
mDatabase->AddDepartment(newRow, column);
mDatabase->AddDepartment(newRow, column.get());
else if ( -1 != colType.Find("o") ) // organization
mDatabase->AddCompany(newRow, column);
mDatabase->AddCompany(newRow, column.get());
break; // 'o'
@ -1295,17 +1305,17 @@ void AddressBookParser::AddLdifColToDatabase(nsIMdbRow* newRow, char* typeSlot,
if ( -1 != colType.Find("postalcode") )
{
if (mStoreLocAsHome )
mDatabase->AddHomeZipCode(newRow, column);
mDatabase->AddHomeZipCode(newRow, column);
else
mDatabase->AddWorkZipCode(newRow, column);
}
mDatabase->AddWorkZipCode(newRow, column.get());
}
else if ( -1 != colType.Find("postOfficeBox") )
mDatabase->AddWorkAddress(newRow, column);
mDatabase->AddWorkAddress(newRow, column.get());
else if ( -1 != colType.Find("pager") ||
-1 != colType.Find("pagerphone") )
mDatabase->AddPagerNumber(newRow, column);
mDatabase->AddPagerNumber(newRow, column.get());
// else if ( -1 != colType.Find("photo") )
// ioRow->AddColumn(ev, this->ColPhoto(), yarn);
@ -1326,12 +1336,12 @@ void AddressBookParser::AddLdifColToDatabase(nsIMdbRow* newRow, char* typeSlot,
case 'r':
if ( -1 != colType.Find("region") )
{
{
if (mStoreLocAsHome )
mDatabase->AddHomeState(newRow, column);
mDatabase->AddHomeZipCode(newRow, column.get());
else
mDatabase->AddWorkState(newRow, column);
}
mDatabase->AddWorkState(newRow, column.get());
}
// else if ( -1 != colType.Find("rfc822mailbox") )
// ioRow->AddColumn(ev, this->ColPrimaryEmail(), yarn);
@ -1345,22 +1355,23 @@ void AddressBookParser::AddLdifColToDatabase(nsIMdbRow* newRow, char* typeSlot,
case 's':
if ( -1 != colType.Find("sn") || -1 != colType.Find("surname") )
mDatabase->AddLastName(newRow, column);
mDatabase->AddLastName(newRow, column.get());
else if ( -1 != colType.Find("streetaddress") )
{
{
if (mStoreLocAsHome )
mDatabase->AddHomeAddress(newRow, column);
mDatabase->AddHomeAddress(newRow, column.get());
else
mDatabase->AddWorkAddress(newRow, column);
}
mDatabase->AddWorkAddress(newRow, column.get());
}
else if ( -1 != colType.Find("st") )
{
if (mStoreLocAsHome )
mDatabase->AddHomeState(newRow, column);
mDatabase->AddHomeState(newRow, column.get());
else
mDatabase->AddWorkState(newRow, column);
}
mDatabase->AddWorkState(newRow, column.get());
}
// else if ( -1 != colType.Find("secretary") )
// ioRow->AddColumn(ev, this->ColSecretary(), yarn);
@ -1375,12 +1386,12 @@ void AddressBookParser::AddLdifColToDatabase(nsIMdbRow* newRow, char* typeSlot,
case 't':
if ( -1 != colType.Find("title") )
mDatabase->AddJobTitle(newRow, column);
mDatabase->AddJobTitle(newRow, column.get());
else if ( -1 != colType.Find("telephonenumber") )
{
mDatabase->AddWorkPhone(newRow, column);
}
{
mDatabase->AddWorkPhone(newRow, column.get());
}
// else if ( -1 != colType.Find("tiff") )
// ioRow->AddColumn(ev, this->ColTiff(), yarn);
@ -1392,7 +1403,7 @@ void AddressBookParser::AddLdifColToDatabase(nsIMdbRow* newRow, char* typeSlot,
case 'u':
if ( -1 != colType.Find("uniquemember") && bIsList )
mDatabase->AddLdifListMember(newRow, column);
mDatabase->AddLdifListMember(newRow, column.get());
// else if ( -1 != colType.Find("uid") )
// ioRow->AddColumn(ev, this->ColUid(), yarn);
@ -1410,7 +1421,7 @@ void AddressBookParser::AddLdifColToDatabase(nsIMdbRow* newRow, char* typeSlot,
case 'w':
if ( -1 != colType.Find("workurl") )
mDatabase->AddWebPage2(newRow, column);
mDatabase->AddWebPage2(newRow, column.get());
break; // 'w'
@ -1418,9 +1429,9 @@ void AddressBookParser::AddLdifColToDatabase(nsIMdbRow* newRow, char* typeSlot,
if ( -1 != colType.Find("xmozillanickname") )
{
if (bIsList)
mDatabase->AddListNickName(newRow, column);
mDatabase->AddListNickName(newRow, column.get());
else
mDatabase->AddNickName(newRow, column);
mDatabase->AddNickName(newRow, column.get());
}
else if ( -1 != colType.Find("xmozillausehtmlmail") )
@ -1436,12 +1447,12 @@ void AddressBookParser::AddLdifColToDatabase(nsIMdbRow* newRow, char* typeSlot,
case 'z':
if ( -1 != colType.Find("zip") ) // alias for postalcode
{
{
if (mStoreLocAsHome )
mDatabase->AddHomeZipCode(newRow, column);
mDatabase->AddHomeZipCode(newRow, column.get());
else
mDatabase->AddWorkZipCode(newRow, column);
}
mDatabase->AddWorkZipCode(newRow, column.get());
}
break; // 'z'
@ -1477,13 +1488,13 @@ NS_IMETHODIMP nsAddressBook::ConvertLDIFtoMAB(nsIFileSpec *fileSpec, PRBool migr
nsresult rv;
if (!fileSpec) return NS_ERROR_FAILURE;
rv = fileSpec->OpenStreamForReading();
NS_ENSURE_SUCCESS(rv, rv);
rv = fileSpec->OpenStreamForReading();
NS_ENSURE_SUCCESS(rv, rv);
AddressBookParser abParser(fileSpec, migrating, db, bStoreLocAsHome, bImportingComm4x);
rv = abParser.ParseFile();
NS_ENSURE_SUCCESS(rv, rv);
NS_ENSURE_SUCCESS(rv, rv);
rv = fileSpec->CloseStream();
return rv;
@ -1546,7 +1557,7 @@ NS_IMETHODIMP nsAddressBook::ImportAddressBook()
nsCAutoString tmpFileName;
tmpFileName = (const char *)leafName;
tmpFileName += ".ldif";
rv = tmpLDIFFile->AppendRelativeUnixPath((const char *)tmpFileName);
rv = tmpLDIFFile->AppendRelativeUnixPath(tmpFileName.get());
NS_ENSURE_SUCCESS(rv, rv);
// todo:
@ -1578,4 +1589,59 @@ NS_IMETHODIMP nsAddressBook::ImportAddressBook()
return rv;
}
/* void createCollationKey (in wstring source, out wstring result); */
NS_IMETHODIMP nsAddressBook::CreateCollationKey(const PRUnichar *source,
PRUnichar **result)
{
nsresult rv;
if (!mCollationKeyGenerator)
{
nsCOMPtr<nsILocaleService> localeSvc = do_GetService(NS_LOCALESERVICE_CONTRACTID,&rv);
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr<nsILocale> locale;
rv = localeSvc->GetApplicationLocale(getter_AddRefs(locale));
NS_ENSURE_SUCCESS(rv, rv);
nsCOMPtr <nsICollationFactory> factory;
rv = nsComponentManager::CreateInstance(kCollationFactoryCID,
NULL,
NS_GET_IID(nsICollationFactory),
getter_AddRefs(factory));
NS_ENSURE_SUCCESS(rv, rv);
rv = factory->CreateCollation(locale,
getter_AddRefs(mCollationKeyGenerator));
NS_ENSURE_SUCCESS(rv, rv);
}
nsAutoString sourceString(source);
PRUint32 aLength;
rv = mCollationKeyGenerator->GetSortKeyLen(kCollationCaseInSensitive, sourceString, &aLength);
NS_ENSURE_SUCCESS(rv, rv);
PRUint8* aKey = (PRUint8* ) nsMemory::Alloc (aLength + 3); // plus three for null termination
if (!aKey)
return NS_ERROR_OUT_OF_MEMORY;
rv = mCollationKeyGenerator->CreateRawSortKey(kCollationCaseInSensitive,
sourceString, aKey, &aLength);
if (NS_FAILED(rv))
{
nsMemory::Free (aKey);
return rv;
}
// Generate a null terminated unicode string.
// Note using PRUnichar* to store collation key is not recommented since the key may contains 0x0000.
aKey[aLength] = 0;
aKey[aLength+1] = 0;
aKey[aLength+2] = 0;
*result = (PRUnichar *) aKey;
return rv;
}
CMDLINEHANDLER_IMPL(nsAddressBook,"-addressbook","general.startup.addressbook","chrome://messenger/content/addressbook/addressbook.xul","Start with the addressbook.",NS_ADDRESSBOOKSTARTUPHANDLER_CONTRACTID,"Addressbook Startup Handler",PR_FALSE,"", PR_TRUE)

View File

@ -31,6 +31,7 @@
#include "nsIScriptGlobalObject.h"
#include "nsICmdLineHandler.h"
#include "nsIComponentManager.h"
#include "nsICollation.h"
#define NC_RDF_NEWABCARD "http://home.netscape.com/NC-rdf#NewCard"
#define NC_RDF_DELETE "http://home.netscape.com/NC-rdf#Delete"
@ -57,6 +58,7 @@ protected:
private:
nsIDocShell *mDocShell; // weak reference
nsCOMPtr<nsICollation> mCollationKeyGenerator;
};
#endif

View File

@ -379,7 +379,7 @@ static nsresult dir_ConvertToMabFileName()
DIR_SavePrefsForOneServer(newServer);
PR_FREEIF (server->fileName);
server->fileName = PL_strdup(kPersonalAddressbook);
server->fileName = nsCRT::strdup(kPersonalAddressbook);
DIR_SavePrefsForOneServer(server);
}
}
@ -466,7 +466,7 @@ nsresult DIR_AddNewAddressBook(const PRUnichar *dirName, const char *fileName, P
server->position = count + 1;
if (fileName)
server->fileName = PL_strdup(fileName);
server->fileName = nsCRT::strdup(fileName);
else
DIR_SetFileName(&server->fileName, kPersonalAddressbook);
@ -520,7 +520,7 @@ nsresult DIR_InitServerWithType(DIR_Server * server, DirectoryType dirType)
DIR_InitServer(server);
if (dirType == LDAPDirectory)
{
server->columnAttributes = PL_strdup(kDefaultLDAPColumnHeaders);
server->columnAttributes = nsCRT::strdup(kDefaultLDAPColumnHeaders);
server->dirType = LDAPDirectory;
server->isOffline = PR_TRUE;
server->csid = CS_UTF8;
@ -528,7 +528,7 @@ nsresult DIR_InitServerWithType(DIR_Server * server, DirectoryType dirType)
}
else if (dirType == PABDirectory)
{
server->columnAttributes = PL_strdup(kDefaultPABColumnHeaders);
server->columnAttributes = nsCRT::strdup(kDefaultPABColumnHeaders);
server->dirType = PABDirectory;
server->isOffline = PR_FALSE;
server->csid = CS_UTF8;
@ -554,6 +554,7 @@ nsresult DIR_InitServer (DIR_Server *server)
server->position = kDefaultPosition;
server->csid = CS_UTF8;
server->locale = nsnull;
server->uri = nsnull;
}
return NS_OK;
}
@ -569,7 +570,7 @@ DIR_DescriptionCode DIR_ValidateDirectoryDescription(nsVoidArray * wholeList, DI
{
DIR_Server *s = (DIR_Server *)(dir_ServerList->ElementAt(i));
/* don't check the description if it is the same directory as the one we are comparing against */
if (s != serverToValidate && s->description && !PL_strcasecmp(s->description, serverToValidate->description))
if (s != serverToValidate && s->description && !nsCRT::strcasecmp(s->description, serverToValidate->description))
return DIR_DuplicateDescription;
}
@ -590,7 +591,7 @@ static DIR_Attribute *DIR_CopyAttribute (DIR_Attribute *inAttribute)
{
PRInt32 count = 0;
outAttribute->id = inAttribute->id;
outAttribute->prettyName = PL_strdup(inAttribute->prettyName);
outAttribute->prettyName = nsCRT::strdup(inAttribute->prettyName);
while (inAttribute->attrNames[count])
count++;
outAttribute->attrNames = (char**) PR_Malloc((count + 1) * sizeof(char*));
@ -598,7 +599,7 @@ static DIR_Attribute *DIR_CopyAttribute (DIR_Attribute *inAttribute)
{
PRInt32 i;
for (i = 0; i < count; i++)
outAttribute->attrNames[i] = PL_strdup(inAttribute->attrNames[i]);
outAttribute->attrNames[i] = nsCRT::strdup(inAttribute->attrNames[i]);
outAttribute->attrNames[i] = nsnull;
}
}
@ -612,7 +613,7 @@ static DIR_Filter *DIR_CopyFilter (DIR_Filter *inFilter)
if (outFilter)
{
outFilter->flags = inFilter->flags;
outFilter->string = PL_strdup(inFilter->string);
outFilter->string = nsCRT::strdup(inFilter->string);
}
return outFilter;
}
@ -628,7 +629,7 @@ static nsresult dir_CopyTokenList (char **inList, PRInt32 inCount, char ***outLi
{
PRInt32 i;
for (i = 0; i < inCount; i++)
(*outList)[i] = PL_strdup (inList[i]);
(*outList)[i] = nsCRT::strdup (inList[i]);
*outCount = inCount;
}
else
@ -645,15 +646,15 @@ static DIR_ReplicationInfo *dir_CopyReplicationInfo (DIR_ReplicationInfo *inInfo
{
outInfo->lastChangeNumber = inInfo->lastChangeNumber;
if (inInfo->description)
outInfo->description = PL_strdup (inInfo->description);
outInfo->description = nsCRT::strdup (inInfo->description);
if (inInfo->fileName)
outInfo->fileName = PL_strdup (inInfo->fileName);
outInfo->fileName = nsCRT::strdup (inInfo->fileName);
if (inInfo->dataVersion)
outInfo->dataVersion = PL_strdup (inInfo->dataVersion);
outInfo->dataVersion = nsCRT::strdup (inInfo->dataVersion);
if (inInfo->syncURL)
outInfo->syncURL = PL_strdup (inInfo->syncURL);
outInfo->syncURL = nsCRT::strdup (inInfo->syncURL);
if (inInfo->filter)
outInfo->filter = PL_strdup (inInfo->filter);
outInfo->filter = nsCRT::strdup (inInfo->filter);
dir_CopyTokenList (inInfo->excludedAttributes, inInfo->excludedAttributesCount,
&outInfo->excludedAttributes, &outInfo->excludedAttributesCount);
}
@ -671,49 +672,49 @@ nsresult DIR_CopyServer (DIR_Server *in, DIR_Server **out)
if (in->prefName)
{
(*out)->prefName = PL_strdup(in->prefName);
(*out)->prefName = nsCRT::strdup(in->prefName);
if (!(*out)->prefName)
err = NS_ERROR_OUT_OF_MEMORY;
}
if (in->description)
{
(*out)->description = PL_strdup(in->description);
(*out)->description = nsCRT::strdup(in->description);
if (!(*out)->description)
err = NS_ERROR_OUT_OF_MEMORY;
}
if (in->serverName)
{
(*out)->serverName = PL_strdup(in->serverName);
(*out)->serverName = nsCRT::strdup(in->serverName);
if (!(*out)->serverName)
err = NS_ERROR_OUT_OF_MEMORY;
}
if (in->searchBase)
{
(*out)->searchBase = PL_strdup(in->searchBase);
(*out)->searchBase = nsCRT::strdup(in->searchBase);
if (!(*out)->searchBase)
err = NS_ERROR_OUT_OF_MEMORY;
}
if (in->fileName)
{
(*out)->fileName = PL_strdup(in->fileName);
(*out)->fileName = nsCRT::strdup(in->fileName);
if (!(*out)->fileName)
err = NS_ERROR_OUT_OF_MEMORY;
}
if (in->columnAttributes)
{
(*out)->columnAttributes = PL_strdup(in->columnAttributes);
(*out)->columnAttributes = nsCRT::strdup(in->columnAttributes);
if (!(*out)->columnAttributes)
err = NS_ERROR_OUT_OF_MEMORY;
}
if (in->locale)
{
(*out)->locale = PL_strdup(in->locale);
(*out)->locale = nsCRT::strdup(in->locale);
if (!(*out)->locale)
err = NS_ERROR_OUT_OF_MEMORY;
}
@ -734,13 +735,13 @@ nsresult DIR_CopyServer (DIR_Server *in, DIR_Server **out)
(*out)->savePassword = in->savePassword;
if (in->authDn)
{
(*out)->authDn = PL_strdup (in->authDn);
(*out)->authDn = nsCRT::strdup (in->authDn);
if (!(*out)->authDn)
err = NS_ERROR_OUT_OF_MEMORY;
}
if (in->password)
{
(*out)->password = PL_strdup (in->password);
(*out)->password = nsCRT::strdup (in->password);
if (!(*out)->password)
err = NS_ERROR_OUT_OF_MEMORY;
}
@ -800,7 +801,7 @@ nsresult DIR_CopyServer (DIR_Server *in, DIR_Server **out)
if (in->autoCompleteFilter)
{
(*out)->autoCompleteFilter = PL_strdup(in->autoCompleteFilter);
(*out)->autoCompleteFilter = nsCRT::strdup(in->autoCompleteFilter);
if (!(*out)->autoCompleteFilter)
err = NS_ERROR_OUT_OF_MEMORY;
}
@ -827,9 +828,9 @@ nsresult DIR_CopyServer (DIR_Server *in, DIR_Server **out)
&(*out)->uriAttributes, &(*out)->uriAttributesCount);
if (in->customDisplayUrl)
(*out)->customDisplayUrl = PL_strdup (in->customDisplayUrl);
(*out)->customDisplayUrl = nsCRT::strdup (in->customDisplayUrl);
if (in->searchPairList)
(*out)->searchPairList = PL_strdup (in->searchPairList);
(*out)->searchPairList = nsCRT::strdup (in->searchPairList);
(*out)->refCount = 1;
}
@ -1730,6 +1731,8 @@ DIR_PrefId DIR_AtomizePrefName(const char *prefname)
rc = idUri;
break;
case 'v': /* vlvDisabled */
rc = idVLVDisabled;
break;
@ -1750,7 +1753,7 @@ static PRBool dir_AreLDAPServersSame (DIR_Server *first, DIR_Server *second, PRB
if (first->serverName && second->serverName)
{
if (PL_strcasecmp (first->serverName, second->serverName) == 0)
if (nsCRT::strcasecmp (first->serverName, second->serverName) == 0)
{
if (first->port == second->port)
{
@ -1760,7 +1763,7 @@ static PRBool dir_AreLDAPServersSame (DIR_Server *first, DIR_Server *second, PRB
/* otherwise check the strings */
else if ( first->searchBase
&& second->searchBase
&& PL_strcasecmp (first->searchBase, second->searchBase) == 0)
&& nsCRT::strcasecmp (first->searchBase, second->searchBase) == 0)
return PR_TRUE;
}
}
@ -1785,7 +1788,7 @@ static PRBool dir_AreServersSame (DIR_Server *first, DIR_Server *second, PRBool
{
PR_ASSERT(first->fileName && second->fileName);
if (first->fileName && second->fileName)
if (PL_strcasecmp(first->fileName, second->fileName) == 0)
if (nsCRT::strcasecmp(first->fileName, second->fileName) == 0)
return PR_TRUE;
return PR_FALSE;
@ -1817,8 +1820,8 @@ DIR_Server *DIR_LookupServer(char *serverName, PRInt32 port, char *searchBase)
{
server = (DIR_Server *)dir_ServerList->ElementAt(i);
if ( server->port == port
&& server->serverName && PL_strcasecmp(server->serverName, serverName) == 0
&& server->searchBase && PL_strcasecmp(server->searchBase, searchBase) == 0)
&& server->serverName && nsCRT::strcasecmp(server->serverName, serverName) == 0
&& server->searchBase && nsCRT::strcasecmp(server->searchBase, searchBase) == 0)
{
return server;
}
@ -1921,6 +1924,7 @@ static nsresult dir_DeleteServerContents (DIR_Server *server)
PR_FREEIF (server->password);
PR_FREEIF (server->columnAttributes);
PR_FREEIF (server->locale);
PR_FREEIF (server->uri);
if (server->customFilters)
{
@ -2168,7 +2172,7 @@ static char *DIR_GetStringPref(const char *prefRoot, const char *prefLeaf, char
if (!PL_strcmp(value, "(null)"))
{
PR_FREEIF(value); /* free old value because we are going to give it a new value.... */
value = defaultValue ? PL_strdup(defaultValue) : nsnull;
value = defaultValue ? nsCRT::strdup(defaultValue) : nsnull;
}
if (PL_strlen(value) == 0)
{
@ -2179,7 +2183,7 @@ static char *DIR_GetStringPref(const char *prefRoot, const char *prefLeaf, char
else
{
PR_FREEIF(value); /* the pref may have generated an error but we still might have something in value...... */
value = defaultValue ? PL_strdup(defaultValue) : nsnull;
value = defaultValue ? nsCRT::strdup(defaultValue) : nsnull;
}
return value;
}
@ -2214,7 +2218,7 @@ static char *DIR_GetLocalizedStringPref
INTL_ConvertFromUnicode(wvalue, unicharLength, &value);
}
else
value = defaultValue ? PL_strdup(defaultValue) : nsnull;
value = defaultValue ? nsCRT::strdup(defaultValue) : nsnull;
return value;
}
@ -2265,23 +2269,23 @@ nsresult DIR_AttributeNameToId(DIR_Server *server, const char *attrName, DIR_Att
switch (attrName[0])
{
case 'a':
if (!PL_strcasecmp(attrName, "auth"))
if (!nsCRT::strcasecmp(attrName, "auth"))
*id = auth;
else
status = NS_ERROR_FAILURE;
break;
case 'b':
if (!PL_strcasecmp(attrName, "businesscategory"))
if (!nsCRT::strcasecmp(attrName, "businesscategory"))
*id = businesscategory;
else
status = NS_ERROR_FAILURE;
break;
case 'c' :
if (!PL_strcasecmp(attrName, "cn"))
if (!nsCRT::strcasecmp(attrName, "cn"))
*id = cn;
else if (!PL_strcasecmp(attrName, "carlicense"))
else if (!nsCRT::strcasecmp(attrName, "carlicense"))
*id = carlicense;
else if (!PL_strncasecmp(attrName, "custom", 6))
else if (!nsCRT::strncasecmp(attrName, "custom", 6))
{
switch (attrName[6])
{
@ -2297,94 +2301,94 @@ nsresult DIR_AttributeNameToId(DIR_Server *server, const char *attrName, DIR_Att
status = NS_ERROR_FAILURE;
break;
case 'd':
if (!PL_strcasecmp(attrName, "departmentnumber"))
if (!nsCRT::strcasecmp(attrName, "departmentnumber"))
*id = departmentnumber;
else
if (!PL_strcasecmp(attrName, "description"))
if (!nsCRT::strcasecmp(attrName, "description"))
*id = description;
else
status = NS_ERROR_FAILURE;
break;
case 'e':
if (!PL_strcasecmp(attrName, "employeetype"))
if (!nsCRT::strcasecmp(attrName, "employeetype"))
*id = employeetype;
else
status = NS_ERROR_FAILURE;
break;
case 'f':
if (!PL_strcasecmp(attrName, "facsimiletelephonenumber"))
if (!nsCRT::strcasecmp(attrName, "facsimiletelephonenumber"))
*id = facsimiletelephonenumber;
else
status = NS_ERROR_FAILURE;
break;
case 'g':
if (!PL_strcasecmp(attrName, "givenname"))
if (!nsCRT::strcasecmp(attrName, "givenname"))
*id = givenname;
else
status = NS_ERROR_FAILURE;
break;
case 'h':
if (!PL_strcasecmp(attrName, "homephone"))
if (!nsCRT::strcasecmp(attrName, "homephone"))
*id = homephone;
else
status = NS_ERROR_FAILURE;
break;
case 'l':
if (!PL_strcasecmp(attrName, "l"))
if (!nsCRT::strcasecmp(attrName, "l"))
*id = l;
else
status = NS_ERROR_FAILURE;
break;
case 'm':
if (!PL_strcasecmp(attrName, "mail"))
if (!nsCRT::strcasecmp(attrName, "mail"))
*id = mail;
else if (!PL_strcasecmp(attrName, "manager"))
else if (!nsCRT::strcasecmp(attrName, "manager"))
*id = manager;
else if (!PL_strcasecmp(attrName, "mobiletelephonenumber"))
else if (!nsCRT::strcasecmp(attrName, "mobiletelephonenumber"))
*id = mobiletelephonenumber;
else
status = NS_ERROR_FAILURE;
break;
case 'n':
if (!PL_strcasecmp(attrName, "nickname"))
if (!nsCRT::strcasecmp(attrName, "nickname"))
*id = nickname;
else
status = NS_ERROR_FAILURE;
break;
case 'o':
if (!PL_strcasecmp(attrName, "o"))
if (!nsCRT::strcasecmp(attrName, "o"))
*id = o;
else if (!PL_strcasecmp(attrName, "ou"))
else if (!nsCRT::strcasecmp(attrName, "ou"))
*id = ou;
else if (!PL_strcasecmp(attrName, "objectclass"))
else if (!nsCRT::strcasecmp(attrName, "objectclass"))
*id = objectclass;
else
status = NS_ERROR_FAILURE;
break;
case 'p':
if (!PL_strcasecmp(attrName, "pager"))
if (!nsCRT::strcasecmp(attrName, "pager"))
*id = pager;
else if (!PL_strcasecmp(attrName, "postalcode"))
else if (!nsCRT::strcasecmp(attrName, "postalcode"))
*id = postalcode;
else if (!PL_strcasecmp(attrName, "postaladdress"))
else if (!nsCRT::strcasecmp(attrName, "postaladdress"))
*id = postaladdress;
else
status = NS_ERROR_FAILURE;
break;
case 's':
if (!PL_strcasecmp(attrName, "street"))
if (!nsCRT::strcasecmp(attrName, "street"))
*id = street;
else if (!PL_strcasecmp(attrName, "sn"))
else if (!nsCRT::strcasecmp(attrName, "sn"))
*id = sn;
else if (!PL_strcasecmp(attrName, "secretary"))
else if (!nsCRT::strcasecmp(attrName, "secretary"))
*id = secretary;
else
status = NS_ERROR_FAILURE;
break;
case 't':
if (!PL_strcasecmp(attrName, "telephonenumber"))
if (!nsCRT::strcasecmp(attrName, "telephonenumber"))
*id = telephonenumber;
else if (!PL_strcasecmp(attrName, "title"))
else if (!nsCRT::strcasecmp(attrName, "title"))
*id = title;
else
status = NS_ERROR_FAILURE;
@ -2424,7 +2428,7 @@ static nsresult DIR_AddCustomAttribute(DIR_Server *server, const char *attrName,
if (NS_SUCCEEDED(status))
{
char *scratchAttr = PL_strdup(jsAttrForTokenizing);
char *scratchAttr = nsCRT::strdup(jsAttrForTokenizing);
DIR_Attribute *attrStruct = (DIR_Attribute*) PR_Malloc(sizeof(DIR_Attribute));
if (!server->customAttributes)
server->customAttributes = new nsVoidArray();
@ -2438,7 +2442,7 @@ static nsresult DIR_AddCustomAttribute(DIR_Server *server, const char *attrName,
/* Try to pull out the pretty name into the struct */
attrStruct->id = id;
attrStruct->prettyName = PL_strdup(XP_STRTOK(scratchAttr, ":"));
attrStruct->prettyName = nsCRT::strdup(XP_STRTOK(scratchAttr, ":"));
/* Count up the attribute names */
while ((attrToken = XP_STRTOK(nsnull, ", ")) != nsnull)
@ -2452,7 +2456,7 @@ static nsresult DIR_AddCustomAttribute(DIR_Server *server, const char *attrName,
{
PRInt32 i = 0;
while ((attrToken = XP_STRTOK(nsnull, ", ")) != nsnull)
attrStruct->attrNames[i++] = PL_strdup(attrToken);
attrStruct->attrNames[i++] = nsCRT::strdup(attrToken);
attrStruct->attrNames[i] = nsnull; /* null-terminate the array */
}
@ -2480,7 +2484,7 @@ PRInt32 DIR_GetNumAttributeIDsForColumns(DIR_Server * server)
char * marker = nsnull;
if (server && server->columnAttributes)
{
buffer = PL_strdup(server->columnAttributes);
buffer = nsCRT::strdup(server->columnAttributes);
if (buffer)
{
marker = buffer;
@ -2509,7 +2513,7 @@ nsresult DIR_GetAttributeIDsForColumns(DIR_Server *server, DIR_AttributeId ** id
{
if (server->columnAttributes)
{
columnIDs = PL_strdup(server->columnAttributes);
columnIDs = nsCRT::strdup(server->columnAttributes);
numItems = DIR_GetNumAttributeIDsForColumns(server);
}
@ -2572,7 +2576,7 @@ static nsresult dir_CreateTokenListFromWholePref(const char *pref, char ***outLi
char *token = XP_STRTOK(commaSeparatedList, ", ");
for (i = 0; i < *outCount; i++)
{
(*outList)[i] = PL_strdup(token);
(*outList)[i] = nsCRT::strdup(token);
token = XP_STRTOK(nsnull, ", ");
}
}
@ -2799,7 +2803,7 @@ static void DIR_ConvertServerFileName(DIR_Server* pServer)
#else
newLeafName = XP_STRRCHR (leafName, '/');
#endif
pServer->fileName = newLeafName ? PL_strdup(newLeafName + 1) : PL_strdup(leafName);
pServer->fileName = newLeafName ? nsCRT::strdup(newLeafName + 1) : nsCRT::strdup(leafName);
if (leafName) PR_Free(leafName);
}
@ -2819,7 +2823,7 @@ void DIR_SetFileName(char** fileName, const char* defaultName)
dbPath->MakeUnique(defaultName);
char* file = nsnull;
file = dbPath->GetLeafName();
*fileName = PL_strdup(file);
*fileName = nsCRT::strdup(file);
if (file)
nsCRT::free(file);
@ -2861,7 +2865,7 @@ char * dir_ConvertDescriptionToPrefName(DIR_Server * server)
}
if (destIndex) /* have at least one character in the file name? */
fileName = PL_strdup(fileNameBuf);
fileName = nsCRT::strdup(fileNameBuf);
return fileName;
}
@ -2881,7 +2885,7 @@ void DIR_SetServerFileName(DIR_Server *server, const char* leafName)
/* set default personal address book file name*/
if (server->position == 1)
server->fileName = PL_strdup(kPersonalAddressbook);
server->fileName = nsCRT::strdup(kPersonalAddressbook);
else
{
/* now use the pref name as the file name since we know the pref name
@ -2892,7 +2896,7 @@ void DIR_SetServerFileName(DIR_Server *server, const char* leafName)
/* extract just the pref name part and not the ldap tree name portion from the string */
numHeaderBytes = PL_strlen(PREF_LDAP_SERVER_TREE_NAME) + 1; /* + 1 for the '.' b4 the name */
if (PL_strlen(prefName) > numHeaderBytes)
tempName = PL_strdup(prefName + numHeaderBytes);
tempName = nsCRT::strdup(prefName + numHeaderBytes);
if (tempName)
{
@ -2927,7 +2931,7 @@ void DIR_GetServerFileName(char** filename, const char* leafName)
nativeName = WH_FileName(realLeafName, xpAddrBookNew);
urlName = XP_PlatformFileToURL(nativeName);
(*filename) = PL_strdup(urlName + PL_strlen("file://"));
(*filename) = nsCRT::strdup(urlName + PL_strlen("file://"));
if (urlName) PR_Free(urlName);
#elif defined(XP_WIN)
/* jefft -- Bug 73349. To allow users share same address book.
@ -2970,7 +2974,7 @@ char *DIR_CreateServerPrefName (DIR_Server *server, char *name)
PRBool isUnique = PR_FALSE;
if (name)
leafName = PL_strdup(name);
leafName = nsCRT::strdup(name);
else
leafName = dir_ConvertDescriptionToPrefName (server);
if (leafName)
@ -2989,7 +2993,7 @@ char *DIR_CreateServerPrefName (DIR_Server *server, char *name)
PRInt16 i = 0;
while ( (pPref->NextChild(children, &i, &child)) == NS_OK && isUnique)
{
if (!PL_strcasecmp(child, prefName) ) /* are they the same name?? */
if (!nsCRT::strcasecmp(child, prefName) ) /* are they the same name?? */
isUnique = PR_FALSE;
}
PR_FREEIF(children);
@ -3083,6 +3087,11 @@ void DIR_GetPrefsForOneServer (DIR_Server *server, PRBool reinitialize, PRBool o
if (server->fileName && *server->fileName)
DIR_ConvertServerFileName(server);
// the string "s" is the default uri ( <scheme> + "://" + <filename> )
nsCString s(kMDBDirectoryRoot);
s.Append (server->fileName);
server->uri = DIR_GetStringPref (prefstring, "uri", tempstring, s.get ());
server->lastSearchString = DIR_GetStringPref (prefstring, "searchString", tempstring, "");
/* This is where site-configurable attributes and filters are read from JavaScript */
@ -3240,10 +3249,13 @@ static nsresult dir_GetPrefsFrom45Branch(nsVoidArray **list, nsVoidArray **obsol
if (server)
{
DIR_InitServer(server);
server->prefName = PL_strdup(child);
server->prefName = nsCRT::strdup(child);
DIR_GetPrefsForOneServer(server, PR_FALSE, PR_FALSE);
if ( server->description && server->description[0]
&& ( server->dirType == PABDirectory
&& ( (server->dirType == PABDirectory ||
server->dirType == MAPIDirectory ||
server->dirType == FixedQueryLDAPDirectory)
|| (server->serverName && server->serverName[0])))
{
if (!dir_IsServerDeleted(server))
@ -3343,7 +3355,7 @@ nsresult DIR_GetServerPreferences(nsVoidArray** list)
/* Copy any new prefs out of the new server.
*/
PR_FREEIF(oldServer->prefName);
oldServer->prefName = PL_strdup(newServer->prefName);
oldServer->prefName = nsCRT::strdup(newServer->prefName);
/* since the pref name has now been set, we can generate a proper
file name in case we don't have one already */
if (!oldServer->fileName || !*oldServer->fileName)
@ -3559,14 +3571,14 @@ static void DIR_SetStringPref (const char *prefRoot, const char *prefLeaf, char
char *userPref = nsnull;
if (PREF_NOERROR == pPref->CopyCharPref (scratch, &userPref))
{
if (value && (defaultValue ? PL_strcasecmp(value, defaultValue) : value != defaultValue))
if (value && (defaultValue ? nsCRT::strcasecmp(value, defaultValue) : value != defaultValue))
prefErr = pPref->SetCharPref (scratch, value);
else
DIR_ClearStringPref (scratch);
}
else
{
if (value && (defaultValue ? PL_strcasecmp(value, defaultValue) : value != defaultValue))
if (value && (defaultValue ? nsCRT::strcasecmp(value, defaultValue) : value != defaultValue))
prefErr = pPref->SetCharPref (scratch, value);
}
@ -4236,7 +4248,7 @@ static DIR_Filter *DIR_LookupFilter (DIR_Server *server, const char *filter)
for (i = 0; i < count; i++)
{
if ((walkFilter = (DIR_Filter *)list->ElementAt(i)) != nsnull)
if (!PL_strcasecmp(filter, walkFilter->string))
if (!nsCRT::strcasecmp(filter, walkFilter->string))
return walkFilter;
}
return nsnull;
@ -4301,7 +4313,7 @@ PRBool DIR_IsDnAttribute (DIR_Server *s, const char *attrib)
PRInt32 i;
for (i = 0; i < s->dnAttributesCount; i++)
{
if (!PL_strcasecmp(attrib, s->dnAttributes[i]))
if (!nsCRT::strcasecmp(attrib, s->dnAttributes[i]))
return PR_TRUE;
}
}
@ -4313,16 +4325,16 @@ PRBool DIR_IsDnAttribute (DIR_Server *s, const char *attrib)
switch (tolower(attrib[0]))
{
case 'm':
if (!PL_strcasecmp(attrib, "manager") ||
!PL_strcasecmp(attrib, "member"))
if (!nsCRT::strcasecmp(attrib, "manager") ||
!nsCRT::strcasecmp(attrib, "member"))
return PR_TRUE;
break;
case 'o':
if (!PL_strcasecmp(attrib, "owner"))
if (!nsCRT::strcasecmp(attrib, "owner"))
return PR_TRUE;
break;
case 'u':
if (!PL_strcasecmp(attrib, "uniquemember"))
if (!nsCRT::strcasecmp(attrib, "uniquemember"))
return PR_TRUE;
break;
}
@ -4341,7 +4353,7 @@ PRBool DIR_IsAttributeExcludedFromHtml (DIR_Server *s, const char *attrib)
PRInt32 i;
for (i = 0; i < s->suppressedAttributesCount; i++)
{
if (!PL_strcasecmp(attrib, s->suppressedAttributes[i]))
if (!nsCRT::strcasecmp(attrib, s->suppressedAttributes[i]))
return PR_TRUE;
}
}
@ -4360,7 +4372,7 @@ PRBool DIR_IsUriAttribute (DIR_Server *s, const char *attrib)
PRInt32 i;
for (i = 0; i < s->uriAttributesCount; i++)
{
if (!PL_strcasecmp(attrib, s->uriAttributes[i]))
if (!nsCRT::strcasecmp(attrib, s->uriAttributes[i]))
return PR_TRUE;
}
}
@ -4372,12 +4384,12 @@ PRBool DIR_IsUriAttribute (DIR_Server *s, const char *attrib)
switch (tolower(attrib[0]))
{
case 'l':
if ( !PL_strcasecmp(attrib, "labeleduri")
|| !PL_strcasecmp(attrib, "labeledurl"))
if ( !nsCRT::strcasecmp(attrib, "labeleduri")
|| !nsCRT::strcasecmp(attrib, "labeledurl"))
return PR_TRUE;
break;
case 'u':
if (!PL_strcasecmp(attrib, "url"))
if (!nsCRT::strcasecmp(attrib, "url"))
return PR_TRUE;
break;
}
@ -4395,7 +4407,7 @@ void DIR_SetAuthDN (DIR_Server *s, const char *dn)
if (s->authDn && !PL_strcmp(dn, s->authDn))
return; /* no change - no need to broadcast */
tmp = PL_strdup (dn);
tmp = nsCRT::strdup (dn);
if (tmp)
{
/* Always remember the authDn in the DIR_Server, so that users only
@ -4421,7 +4433,7 @@ void DIR_SetPassword (DIR_Server *s, const char *password)
if (s->password && !PL_strcmp(password, s->password))
return; /* no change - no need to broadcast */
tmp = PL_strdup (password);
tmp = nsCRT::strdup (password);
if (tmp)
{
/* Always remember the password in the DIR_Server, so that users only
@ -4446,15 +4458,15 @@ PRBool DIR_IsEscapedAttribute (DIR_Server *s, const char *attrib)
switch (tolower(attrib[0]))
{
case 'p':
if (!PL_strcasecmp(attrib, "postaladdress"))
if (!nsCRT::strcasecmp(attrib, "postaladdress"))
return PR_TRUE;
break;
case 'f':
if (!PL_strcasecmp(attrib, "facsimiletelephonenumber"))
if (!nsCRT::strcasecmp(attrib, "facsimiletelephonenumber"))
return PR_TRUE;
break;
case 'o':
if (!PL_strcasecmp(attrib, "othermail"))
if (!nsCRT::strcasecmp(attrib, "othermail"))
return PR_TRUE;
break;
}
@ -4595,5 +4607,5 @@ char *DIR_ConvertFromServerCharSet(DIR_Server *server, char *src, PRInt16 dstCSI
char *DIR_ConvertString(PRInt16 srcCSID, PRInt16 dstCSID, const char *string)
{
return PL_strdup(string);
return nsCRT::strdup(string);
}

View File

@ -39,14 +39,14 @@ PRInt32 INTL_ConvertFromUnicode(const PRUnichar* uniBuffer,
/* RDF roor for all types of address books */
/* use this to get all directories, create new directory*/
#define kAllDirectoryRoot "abdirectory://"
#define kAllDirectoryRoot "moz-abdirectory://"
#define kMDBCardRoot "abmdbcard://"
#define kMDBDirectoryRoot "abmdbdirectory://"
#define kMDBCardRoot "moz-abmdbcard://"
#define kMDBDirectoryRoot "moz-abmdbdirectory://"
#define kPersonalAddressbook "abook.mab"
#define kPersonalAddressbookUri "abmdbdirectory://abook.mab"
#define kPersonalAddressbookUri "moz-abmdbdirectory://abook.mab"
#define kCollectedAddressbook "history.mab"
#define kCollectedAddressbookUri "abmdbdirectory://history.mab"
#define kCollectedAddressbookUri "moz-abmdbdirectory://history.mab"
/* DIR_Server.dirType */
@ -54,7 +54,9 @@ typedef enum
{
LDAPDirectory,
HTMLDirectory,
PABDirectory
PABDirectory,
MAPIDirectory,
FixedQueryLDAPDirectory = 777
} DirectoryType;
typedef enum
@ -194,6 +196,7 @@ typedef struct DIR_Server
DirectoryType dirType;
PRInt16 csid; /* LDAP entries' codeset (normally UTF-8) */
char *locale; /* the locale associated with the address book or directory */
char *uri; // URI of the address book
/* Flags */
/* TBD: All the PRBool fields should eventually merge into "flags" */

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,141 @@
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* The contents of this file are subject to the Netscape Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/NPL/
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is Sun
* Microsystems, Inc. Portions created by Sun are
* Copyright (C) 2001 Sun Microsystems, Inc. All
* Rights Reserved.
*
* Contributor(s):
*
* Created by Cyrille Moureaux <Cyrille.Moureaux@sun.com>
*/
#ifndef nsMapiAddressBook_h___
#define nsMapiAddressBook_h___
#include <windows.h>
#include <mapix.h>
#include "nsString.h"
#include "nsVoidArray.h"
#include "nsXPIDLString.h"
struct nsMapiEntry
{
ULONG mByteCount ;
LPENTRYID mEntryId ;
nsMapiEntry(void) ;
~nsMapiEntry(void) ;
nsMapiEntry(ULONG aByteCount, LPENTRYID aEntryId) ;
void Assign(ULONG aByteCount, LPENTRYID aEntryId) ;
void Dump(void) const ;
} ;
struct nsMapiEntryArray
{
nsMapiEntry *mEntries ;
ULONG mNbEntries ;
nsMapiEntryArray(void) ;
~nsMapiEntryArray(void) ;
const nsMapiEntry& operator [] (int aIndex) const { return mEntries [aIndex] ; }
void CleanUp(void) ;
} ;
class nsMapiAddressBook
{
public :
nsMapiAddressBook(void) ;
~nsMapiAddressBook(void) ;
// Get the top address books
BOOL GetFolders(nsMapiEntryArray& aFolders) ;
// Get a list of entries for cards/mailing lists in a folder/mailing list
BOOL GetCards(const nsMapiEntry& aParent, LPSRestriction aRestriction,
nsMapiEntryArray& aCards) ;
// Get a list of mailing lists in a folder
BOOL GetNodes(const nsMapiEntry& aParent, nsMapiEntryArray& aNodes) ;
// Get the number of cards/mailing lists in a folder/mailing list
BOOL GetCardsCount(const nsMapiEntry& aParent, ULONG& aNbCards) ;
// Access last MAPI error
HRESULT LastError(void) const { return mLastError ; }
// Get the value of a MAPI property of type string
BOOL GetPropertyString(const nsMapiEntry& aObject, ULONG aPropertyTag, nsCString& aValue) ;
// Same as previous, but string is returned as unicode
BOOL GetPropertyUString(const nsMapiEntry& aObject, ULONG aPropertyTag, nsString& aValue) ;
// Get multiple string MAPI properties in one call.
BOOL GetPropertiesUString(const nsMapiEntry& aObject, const ULONG *aPropertiesTag,
ULONG aNbProperties, nsStringArray& aValues) ;
// Get the value of a MAPI property of type SYSTIME
BOOL GetPropertyDate(const nsMapiEntry& aObject, ULONG aPropertyTag,
WORD& aYear, WORD& aMonth, WORD& aDay) ;
// Get the value of a MAPI property of type LONG
BOOL GetPropertyLong(const nsMapiEntry& aObject, ULONG aPropertyTag, ULONG& aValue) ;
// Get the value of a MAPI property of type BIN
BOOL GetPropertyBin(const nsMapiEntry& aObject, ULONG aPropertyTag, nsMapiEntry& aValue) ;
// Convert MAPI entries into strings and back
BOOL StringToEntry(const nsCString& aString, nsMapiEntry& aEntry) const ;
BOOL EntryToString(const nsMapiEntry& aEntry, nsCString& aString) const ;
// Tests if a container contains an entry
BOOL TestOpenEntry(const nsMapiEntry& aContainer, const nsMapiEntry& aEntry) ;
// Delete an entry in the address book
BOOL DeleteEntry(const nsMapiEntry& aContainer, const nsMapiEntry& aEntry) ;
// Set the value of a MAPI property of type string in unicode
BOOL SetPropertyUString (const nsMapiEntry& aObject, ULONG aPropertyTag,
const PRUnichar *aValue) ;
// Same as previous, but with a bunch of properties in one call
BOOL SetPropertiesUString(const nsMapiEntry& aObject, const ULONG *aPropertiesTag,
ULONG aNbProperties, nsXPIDLString *aValues) ;
// Set the value of a MAPI property of type SYSTIME
BOOL SetPropertyDate(const nsMapiEntry& aObject, ULONG aPropertyTag,
WORD aYear, WORD aMonth, WORD aDay) ;
// Create entry in the address book
BOOL CreateEntry(const nsMapiEntry& aParent, nsMapiEntry& aNewEntry) ;
// Create a distribution list in the address book
BOOL CreateDistList(const nsMapiEntry& aParent, nsMapiEntry& aNewEntry) ;
// Copy an existing entry in the address book
BOOL CopyEntry(const nsMapiEntry& aContainer, const nsMapiEntry& aSource, nsMapiEntry& aTarget) ;
// Get a default address book container
BOOL GetDefaultContainer(nsMapiEntry& aContainer) ;
protected :
private :
LPMAPISESSION mSession ;
LPADRBOOK mAddressBook ;
BOOL mLogonDone ;
BOOL mInitialized ;
HRESULT mLastError ;
static ULONG mEntryCounter ;
// Load the MAPI environment
BOOL Initialize(void) ;
// Retrieve the contents of a container, with an optional restriction
BOOL GetContents(const nsMapiEntry& aParent, LPSRestriction aRestriction,
nsMapiEntry **aList, ULONG &aNbElements, ULONG aMapiType) ;
// Retrieve the values of a set of properties on a MAPI object
BOOL GetMAPIProperties(const nsMapiEntry& aObject, const ULONG *aPropertyTags,
ULONG aNbProperties,
LPSPropValue& aValues, ULONG& aValueCount) ;
// Set the values of a set of properties on a MAPI object
BOOL SetMAPIProperties(const nsMapiEntry& aObject, ULONG aNbProperties,
const LPSPropValue& aValues) ;
} ;
#endif // nsMapiAddressBook_h___

View File

@ -88,8 +88,8 @@ public:
/* boolean WantsProgress (); */
NS_IMETHOD WantsProgress(PRBool *_retval);
/* boolean BeginImport (in nsISupportsWString successLog, in nsISupportsWString errorLog, in boolean isAddrLocHome); */
NS_IMETHOD BeginImport(nsISupportsWString *successLog, nsISupportsWString *errorLog, PRBool isAddrLocHome, PRBool *_retval) ;
/* boolean BeginImport (in nsISupportsWString successLog, in nsISupportsWString errorLog, in boolean isAddrLocHome); */
NS_IMETHOD BeginImport(nsISupportsWString *successLog, nsISupportsWString *errorLog, PRBool isAddrLocHome, PRBool *_retval) ;
/* boolean ContinueImport (); */
NS_IMETHOD ContinueImport(PRBool *_retval);
@ -809,49 +809,28 @@ nsIAddrDatabase *GetAddressBook( const PRUnichar *name, PRBool makeNew)
NS_WITH_PROXIED_SERVICE(nsIRDFService, rdfService, kRDFServiceCID, NS_UI_THREAD_EVENTQ, &rv);
if (NS_SUCCEEDED(rv)) {
nsCOMPtr<nsIRDFResource> parentResource;
char *parentUri = PR_smprintf( "%s", kAllDirectoryRoot);
rv = rdfService->GetResource( parentUri, getter_AddRefs(parentResource));
rv = rdfService->GetResource( kAllDirectoryRoot, getter_AddRefs(parentResource));
nsCOMPtr<nsIAbDirectory> parentDir;
/*
* TODO
* This may not be required in the future since the
* primary listeners of the nsIAbDirectory will be
* RDF directory datasource which propagates events to
* RDF Observers. In the future the RDF directory datasource
* will proxy the observers because asynchronous directory
* implementations, such as LDAP, will assert results from
* a thread other than the UI thread.
*
*/
rv = proxyMgr->GetProxyForObject( NS_UI_THREAD_EVENTQ, NS_GET_IID( nsIAbDirectory),
parentResource, PROXY_SYNC | PROXY_ALWAYS, getter_AddRefs( parentDir));
if (parentUri)
PR_smprintf_free(parentUri);
parentResource, PROXY_SYNC | PROXY_ALWAYS, getter_AddRefs( parentDir));
if (parentDir)
{
PRUint32 prefCount = 2;
char **prefNames = (char **) nsMemory::Alloc(prefCount * (sizeof (char *)));
if (!prefNames)
return nsnull;
PRUnichar ** prefValues = (PRUnichar **) nsMemory::Alloc(prefCount * (sizeof(PRUnichar *)));
if (!prefValues)
return nsnull;
prefNames[0] = PR_smprintf("description");
prefNames[1] = PR_smprintf("fileName");
prefValues[0] = (PRUnichar *)name;
char *fileName = (*dbPath).GetLeafName();
PRInt32 descLength = PL_strlen(fileName);
NS_ConvertUTF8toUCS2 temp((const char *)fileName, descLength);
prefValues[1] = nsCRT::strdup(temp.get());
parentDir->CreateNewDirectory((unsigned int )prefCount, (const char** )prefNames, (const PRUnichar** )prefValues);
nsCAutoString URI("moz-abmdbdirectory://");
URI.Append((*dbPath).GetLeafName());
parentDir->CreateDirectoryByURI(name, URI.get (), PR_FALSE);
delete dbPath;
if (fileName)
nsCRT::free(fileName);
if (prefNames[0])
PR_smprintf_free(prefNames[0]);
if (prefNames[1])
PR_smprintf_free(prefNames[1]);
if (prefNames)
nsMemory::Free(prefNames);
if (prefValues)
nsMemory::Free(prefValues);
}
IMPORT_LOG0( "Added new address book to the UI\n");
@ -921,6 +900,21 @@ PR_STATIC_CALLBACK( void) ImportAddressThread( void *stuff)
PRUnichar *pSuccess = nsnull;
PRUnichar *pError = nsnull;
/*
if (pData->fieldMap) {
PRInt32 sz = 0;
PRInt32 mapIndex;
PRBool active;
pData->fieldMap->GetMapSize( &sz);
IMPORT_LOG1( "**** Field Map Size: %d\n", (int) sz);
for (PRInt32 i = 0; i < sz; i++) {
pData->fieldMap->GetFieldMap( i, &mapIndex);
pData->fieldMap->GetFieldActive( i, &active);
IMPORT_LOG3( "Field map #%d: index=%d, active=%d\n", (int) i, (int) mapIndex, (int) active);
}
}
*/
rv = pData->addressImport->ImportAddressBook( book,
pDestDB, // destination
pData->fieldMap, // fieldmap