DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Header

Mercurial (0ddcbf234291)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla 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/MPL/
 *
 * 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 the Initial Developer are Copyright (C) 2001
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Created by Cyrille Moureaux <Cyrille.Moureaux@sun.com>
 *   Mark Banner <mark@standard8.demon.co.uk>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either of the GNU General Public License Version 2 or later (the "GPL"),
 * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */
#include "nsAbOutlookDirectory.h"
#include "nsAbWinHelper.h"

#include "nsIRDFService.h"

#include "nsAbBaseCID.h"
#include "nsIAbCard.h"
#include "nsStringGlue.h"
#include "nsAbDirectoryQuery.h"
#include "nsIAbBooleanExpression.h"
#include "nsIAbManager.h"
#include "nsIAbMDBDirectory.h"
#include "nsAbQueryStringToExpression.h"
#include "nsAbUtils.h"
#include "nsIProxyObjectManager.h"
#include "nsEnumeratorUtils.h"
#include "nsServiceManagerUtils.h"
#include "prlog.h"
#include "prthread.h"
#include "nsIPrefService.h"
#include "nsIPrefBranch.h"
#include "nsCRTGlue.h"
#include "nsArrayUtils.h"
#include "nsArrayEnumerator.h"

#ifdef PR_LOGGING
static PRLogModuleInfo* gAbOutlookDirectoryLog
    = PR_NewLogModule("nsAbOutlookDirectoryLog");
#endif

#define PRINTF(args) PR_LOG(gAbOutlookDirectoryLog, PR_LOG_DEBUG, args)

nsAbOutlookDirectory::nsAbOutlookDirectory(void)
: nsAbDirectoryRDFResource(), nsAbDirProperty(),
mCurrentQueryId(0), mSearchContext(-1),
mAbWinType(nsAbWinType_Unknown), mMapiData(nsnull)
{
    mMapiData = new nsMapiEntry ;
    mProtector = PR_NewLock() ;
}

nsAbOutlookDirectory::~nsAbOutlookDirectory(void)
{
    if (mMapiData) { delete mMapiData ; }
    if (mProtector) { PR_DestroyLock(mProtector) ; }
}

NS_IMPL_ISUPPORTS_INHERITED4(nsAbOutlookDirectory, nsAbDirectoryRDFResource, 
                             nsIAbDirectory, nsIAbDirectoryQuery,
                             nsIAbDirectorySearch, nsIAbDirSearchListener)

// nsIRDFResource method
NS_IMETHODIMP nsAbOutlookDirectory::Init(const char *aUri)
{
  NS_ENSURE_TRUE(mQueryThreads.Init(), NS_ERROR_FAILURE);
  NS_ENSURE_TRUE(mCardList.Init(), NS_ERROR_FAILURE);
  nsresult retCode = nsAbDirectoryRDFResource::Init(aUri);

  NS_ENSURE_SUCCESS(retCode, retCode);

  nsCAutoString entry;
  nsCAutoString stub;

  mAbWinType = getAbWinType(kOutlookDirectoryScheme, mURINoQuery.get(), stub, entry);
  if (mAbWinType == nsAbWinType_Unknown) {
    PRINTF(("Huge problem URI=%s.\n", mURINoQuery));
    return NS_ERROR_INVALID_ARG;
  }
  nsAbWinHelperGuard mapiAddBook (mAbWinType);
  nsString prefix;
  nsAutoString unichars;
  ULONG objectType = 0;

  if (!mapiAddBook->IsOK())
    return NS_ERROR_FAILURE;

  mMapiData->Assign(entry);
  if (!mapiAddBook->GetPropertyLong(*mMapiData, PR_OBJECT_TYPE, objectType)) {
    PRINTF(("Cannot get type.\n"));
    return NS_ERROR_FAILURE;
  }
  if (!mapiAddBook->GetPropertyUString(*mMapiData, PR_DISPLAY_NAME_W, unichars)) {
    PRINTF(("Cannot get name.\n"));
    return NS_ERROR_FAILURE;
  }

  if (mAbWinType == nsAbWinType_Outlook)
    prefix.AssignLiteral("OP ");
  else
    prefix.AssignLiteral("OE ");
  prefix.Append(unichars);

  if (objectType == MAPI_DISTLIST) {
    m_IsMailList = PR_TRUE;
    SetDirName(unichars);
  }
  else {
    m_IsMailList = PR_FALSE;
    SetDirName(prefix);
  }

  return UpdateAddressList();
}

// nsIAbDirectory methods

NS_IMETHODIMP nsAbOutlookDirectory::GetDirType(PRInt32 *aDirType)
{
  NS_ENSURE_ARG_POINTER(aDirType);
  *aDirType = MAPIDirectory;
  return NS_OK;
}

NS_IMETHODIMP nsAbOutlookDirectory::GetURI(nsACString &aURI)
{
  if (mURI.IsEmpty())
    return NS_ERROR_NOT_INITIALIZED;

  aURI = mURI;
  return NS_OK;
}

NS_IMETHODIMP nsAbOutlookDirectory::GetChildNodes(nsISimpleEnumerator **aNodes)
{
  NS_ENSURE_ARG_POINTER(aNodes);

  *aNodes = nsnull;
    
  if (mIsQueryURI) {
    return NS_NewEmptyEnumerator(aNodes);
  }

  nsresult rv;
  nsCOMPtr<nsIMutableArray> nodeList(do_CreateInstance(NS_ARRAY_CONTRACTID, &rv));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = GetChildNodes(nodeList);
  NS_ENSURE_SUCCESS(rv, rv);

  return NS_NewArrayEnumerator(aNodes, nodeList);
}

NS_IMETHODIMP nsAbOutlookDirectory::GetChildCards(nsISimpleEnumerator **aCards)
{
    NS_ENSURE_ARG_POINTER(aCards);

    *aCards = nsnull;

    nsresult retCode;
    nsCOMPtr<nsIMutableArray> cardList(do_CreateInstance(NS_ARRAY_CONTRACTID, &retCode));

    mCardList.Clear();

    retCode = mIsQueryURI ? StartSearch() : GetChildCards(cardList, nsnull);

    if (NS_SUCCEEDED(retCode)) {
        if (!m_AddressList)
        {
          m_AddressList = do_CreateInstance(NS_ARRAY_CONTRACTID, &retCode);
          NS_ENSURE_SUCCESS(retCode, retCode);
        }

        // Fill the results array and update the card list
        // Also update the address list and notify any changes.
        PRUint32 nbCards = 0 ;
        
        NS_NewArrayEnumerator(aCards, cardList);
        cardList->GetLength(&nbCards);

        nsCOMPtr<nsIAbCard> card;

        for (PRUint32 i = 0; i < nbCards; ++i) {
            card = do_QueryElementAt(cardList, i, &retCode);
            if (NS_FAILED(retCode))
              continue;

            if (!mCardList.Get(card, nsnull)) {
                // We are dealing with a new element (probably directly
                // added from Outlook), we may need to sync m_AddressList
                mCardList.Put(card, card);

                PRBool isMailList = PR_FALSE ;

                retCode = card->GetIsMailList(&isMailList) ;
                NS_ENSURE_SUCCESS(retCode, retCode) ;
                if (isMailList) {
                    // We can have mailing lists only in folder, 
                    // we must add the directory to m_AddressList
                    nsCString mailListUri;

                    retCode = card->GetMailListURI(getter_Copies(mailListUri)) ;
                    NS_ENSURE_SUCCESS(retCode, retCode) ;
                    nsCOMPtr<nsIRDFResource> resource ;

                    retCode = gRDFService->GetResource(mailListUri, getter_AddRefs(resource)) ;
                    NS_ENSURE_SUCCESS(retCode, retCode) ;
                    nsCOMPtr<nsIAbDirectory> mailList(do_QueryInterface(resource, &retCode)) ;
                    
                    NS_ENSURE_SUCCESS(retCode, retCode) ;
                    m_AddressList->AppendElement(mailList, PR_FALSE);
                    NotifyItemAddition(mailList) ;
                }
                else if (m_IsMailList) {
                    m_AddressList->AppendElement(card, PR_FALSE);
                    NotifyItemAddition(card) ;
                }
            }
            else
              NS_WARNING("Card wasn't stored");
        }
    }
    return retCode ;
}

NS_IMETHODIMP nsAbOutlookDirectory::GetIsQuery(PRBool *aResult)
{
  NS_ENSURE_ARG_POINTER(aResult);
  *aResult = mIsQueryURI;
  return NS_OK;
}

NS_IMETHODIMP nsAbOutlookDirectory::HasCard(nsIAbCard *aCard, PRBool *aHasCard)
{
    if (!aCard || !aHasCard) { return NS_ERROR_NULL_POINTER ; }
    *aHasCard = mCardList.Get(aCard, nsnull);
    return NS_OK ;
}

NS_IMETHODIMP nsAbOutlookDirectory::HasDirectory(nsIAbDirectory *aDirectory, PRBool *aHasDirectory)
{
    NS_ENSURE_ARG_POINTER(aDirectory);
    NS_ENSURE_ARG_POINTER(aHasDirectory);

    *aHasDirectory = PR_FALSE;
    
    PRUint32 pos;
    if (m_AddressList && NS_SUCCEEDED(m_AddressList->IndexOf(0, aDirectory, &pos)))
        *aHasDirectory = PR_TRUE;

    return NS_OK ;
}

static nsresult ExtractEntryFromUri(nsIRDFResource *aResource, nsCString &aEntry,
                                    const char *aPrefix)
{
    aEntry.Truncate() ;
    if (!aPrefix ) { return NS_ERROR_NULL_POINTER ; }
    nsCString uri;
    nsresult retCode = aResource->GetValue(getter_Copies(uri)) ;
    
    NS_ENSURE_SUCCESS(retCode, retCode) ;
    nsCAutoString stub ;
    nsAbWinType objType = getAbWinType(aPrefix, uri.get(), stub, aEntry) ;

    return NS_OK ;
}

static nsresult ExtractCardEntry(nsIAbCard *aCard, nsCString& aEntry)
{
    aEntry.Truncate() ;

    nsCString uri;
    aCard->GetPropertyAsAUTF8String("OutlookEntryURI", uri);

    // If we don't have a URI, uri will be empty. getAbWinType doesn't set
    // aEntry to anything if uri is empty, so it will be truncated, allowing us
    // to accept cards not initialized by us.
    nsCAutoString stub;
    getAbWinType(kOutlookCardScheme, uri.get(), stub, aEntry);
    return NS_OK;
}

static nsresult ExtractDirectoryEntry(nsIAbDirectory *aDirectory, nsCString& aEntry)
{
    aEntry.Truncate() ;
    nsresult retCode = NS_OK ;
    nsCOMPtr<nsIRDFResource> resource (do_QueryInterface(aDirectory, &retCode)) ;
    
    // Receiving a non-RDF directory is accepted
    if (NS_FAILED(retCode)) { return NS_OK ; }
    return ExtractEntryFromUri(resource, aEntry, kOutlookDirectoryScheme) ;
}

NS_IMETHODIMP nsAbOutlookDirectory::DeleteCards(nsIArray *aCardList)
{
    if (mIsQueryURI) { return NS_ERROR_NOT_IMPLEMENTED ; }
    if (!aCardList) { return NS_ERROR_NULL_POINTER ; }
    PRUint32 nbCards = 0 ;
    nsresult retCode = NS_OK ;
    nsAbWinHelperGuard mapiAddBook (mAbWinType) ;

    if (!mapiAddBook->IsOK()) { return NS_ERROR_FAILURE ; }
    
    retCode = aCardList->GetLength(&nbCards);
    NS_ENSURE_SUCCESS(retCode, retCode) ;
    PRUint32 i = 0 ;
    nsCAutoString entryString ;
    nsMapiEntry cardEntry ;

    for (i = 0 ; i < nbCards ; ++ i) {
        nsCOMPtr<nsIAbCard> card(do_QueryElementAt(aCardList, i, &retCode));
        NS_ENSURE_SUCCESS(retCode, retCode);

        retCode = ExtractCardEntry(card, entryString) ;
        if (NS_SUCCEEDED(retCode) && !entryString.IsEmpty()) {

            cardEntry.Assign(entryString) ;
            if (!mapiAddBook->DeleteEntry(*mMapiData, cardEntry)) {
                PRINTF(("Cannot delete card %s.\n", entryString.get())) ;
            }
            else {
                mCardList.Remove(card);
                if (m_IsMailList && m_AddressList) 
                {
                    PRUint32 pos;
                    if (NS_SUCCEEDED(m_AddressList->IndexOf(0, card, &pos)))
                        m_AddressList->RemoveElementAt(pos);
                }
                retCode = NotifyItemDeletion(card);
                NS_ENSURE_SUCCESS(retCode, retCode) ;
            }
        }
        else {
            PRINTF(("Card doesn't belong in this directory.\n")) ;
        }
    }
    return NS_OK ;
}

NS_IMETHODIMP nsAbOutlookDirectory::DeleteDirectory(nsIAbDirectory *aDirectory)
{
    if (mIsQueryURI) { return NS_ERROR_NOT_IMPLEMENTED ; }
    if (!aDirectory) { return NS_ERROR_NULL_POINTER ; }
    nsresult retCode = NS_OK ;
    nsAbWinHelperGuard mapiAddBook (mAbWinType) ;
    nsCAutoString entryString ;

    if (!mapiAddBook->IsOK()) { return NS_ERROR_FAILURE ; }
    retCode = ExtractDirectoryEntry(aDirectory, entryString) ;
    if (NS_SUCCEEDED(retCode) && !entryString.IsEmpty()) {
        nsMapiEntry directoryEntry ;

        directoryEntry.Assign(entryString) ;
        if (!mapiAddBook->DeleteEntry(*mMapiData, directoryEntry)) {
            PRINTF(("Cannot delete directory %s.\n", entryString.get())) ;
        }
        else {
            PRUint32 pos;
            if (m_AddressList && NS_SUCCEEDED(m_AddressList->IndexOf(0, aDirectory, &pos)))
                m_AddressList->RemoveElementAt(pos);

            retCode = NotifyItemDeletion(aDirectory);
            NS_ENSURE_SUCCESS(retCode, retCode);
        }
    }
    else {
        PRINTF(("Directory doesn't belong to this folder.\n")) ;
    }
    return retCode ;
}

NS_IMETHODIMP nsAbOutlookDirectory::AddCard(nsIAbCard *aData, nsIAbCard **addedCard)
{
    if (mIsQueryURI)
      return NS_ERROR_NOT_IMPLEMENTED;

    NS_ENSURE_ARG_POINTER(aData);

    nsresult retCode = NS_OK ;
    PRBool hasCard = PR_FALSE ;
    
    retCode = HasCard(aData, &hasCard) ;
    NS_ENSURE_SUCCESS(retCode, retCode) ;
    if (hasCard) {
        PRINTF(("Has card.\n")) ;
        NS_IF_ADDREF(*addedCard = aData);
        return NS_OK ; 
    }
    retCode = CreateCard(aData, addedCard) ;
    NS_ENSURE_SUCCESS(retCode, retCode) ;
    
    mCardList.Put(*addedCard, *addedCard);

    if (!m_AddressList)
    {
        m_AddressList = do_CreateInstance(NS_ARRAY_CONTRACTID, &retCode);
        NS_ENSURE_SUCCESS(retCode, retCode);
    }

    if (m_IsMailList)
        m_AddressList->AppendElement(*addedCard, PR_FALSE);
    NotifyItemAddition(*addedCard) ;
    return retCode ;
}

NS_IMETHODIMP nsAbOutlookDirectory::DropCard(nsIAbCard *aData, PRBool needToCopyCard)
{
    nsCOMPtr <nsIAbCard> addedCard;
    return AddCard(aData, getter_AddRefs(addedCard));
}

NS_IMETHODIMP nsAbOutlookDirectory::AddMailList(nsIAbDirectory *aMailList)
{
    if (mIsQueryURI) { return NS_ERROR_NOT_IMPLEMENTED ; }
    if (!aMailList) { return NS_ERROR_NULL_POINTER ; }
    if (m_IsMailList) { return NS_OK ; }
    nsresult retCode = NS_OK ;
    nsAbWinHelperGuard mapiAddBook (mAbWinType) ;
    nsCAutoString entryString ;
    nsMapiEntry newEntry ;
    PRBool didCopy = PR_FALSE ;

    if (!mapiAddBook->IsOK()) { return NS_ERROR_FAILURE ; }
    retCode = ExtractDirectoryEntry(aMailList, entryString) ;
    if (NS_SUCCEEDED(retCode) && !entryString.IsEmpty()) {
        nsMapiEntry sourceEntry ;

        sourceEntry.Assign(entryString) ;
        mapiAddBook->CopyEntry(*mMapiData, sourceEntry, newEntry) ;
    }
    if (newEntry.mByteCount == 0) {
        if (!mapiAddBook->CreateDistList(*mMapiData, newEntry)) {
            return NS_ERROR_FAILURE ; 
        }
    }
    else { didCopy = PR_TRUE ; }
    newEntry.ToString(entryString) ;
    nsCAutoString uri ;

    buildAbWinUri(kOutlookDirectoryScheme, mAbWinType, uri) ;
    uri.Append(entryString) ;
    nsCOMPtr<nsIRDFResource> resource ;
    retCode = gRDFService->GetResource(uri, getter_AddRefs(resource)) ;
    NS_ENSURE_SUCCESS(retCode, retCode) ;
    nsCOMPtr<nsIAbDirectory> newList(do_QueryInterface(resource, &retCode)) ;
    
    NS_ENSURE_SUCCESS(retCode, retCode) ;
    if (!didCopy) {
        retCode = newList->CopyMailList(aMailList) ;
        NS_ENSURE_SUCCESS(retCode, retCode) ;
        retCode = newList->EditMailListToDatabase(nsnull);
        NS_ENSURE_SUCCESS(retCode, retCode) ;
    }

    if (!m_AddressList)
    {
      m_AddressList = do_CreateInstance(NS_ARRAY_CONTRACTID, &retCode);
      NS_ENSURE_SUCCESS(retCode, retCode);
    }
    m_AddressList->AppendElement(newList, PR_FALSE);
    NotifyItemAddition(newList) ;
    return retCode ;
}

NS_IMETHODIMP nsAbOutlookDirectory::EditMailListToDatabase(nsIAbCard *listCard)
{
  if (mIsQueryURI)
    return NS_ERROR_NOT_IMPLEMENTED;

  nsresult rv;
  nsString name;
  nsAbWinHelperGuard mapiAddBook(mAbWinType);

  if (!mapiAddBook->IsOK())
    return NS_ERROR_FAILURE;

  rv = GetDirName(name);
  NS_ENSURE_SUCCESS(rv, rv);

  if (!mapiAddBook->SetPropertyUString(*mMapiData, PR_DISPLAY_NAME_W,
                                       name.get()))
    return NS_ERROR_FAILURE;

  return CommitAddressList();
}

struct OutlookTableAttr
{
    const char *mOuterName ;
    ULONG mMapiProp ;
} ;

// Here, we are forced to use the Ascii versions of the properties
// instead of the widechar ones, because the content restriction
// operators do not work on unicode strings in mapi.
static const OutlookTableAttr OutlookTableStringToProp [] = 
{
    {kFirstNameProperty, PR_GIVEN_NAME_A},
    {kLastNameProperty, PR_SURNAME_A},
    {kDisplayNameProperty, PR_DISPLAY_NAME_A},
    {kNicknameProperty, PR_NICKNAME_A},
    {kPriEmailProperty, PR_EMAIL_ADDRESS_A},
    {kWorkPhoneProperty, PR_BUSINESS_TELEPHONE_NUMBER_A},
    {kHomePhoneProperty, PR_HOME_TELEPHONE_NUMBER_A},
    {kFaxProperty, PR_BUSINESS_FAX_NUMBER_A},
    {kPagerProperty, PR_PAGER_TELEPHONE_NUMBER_A},
    {kCellularProperty, PR_MOBILE_TELEPHONE_NUMBER_A},
    {kHomeAddressProperty, PR_HOME_ADDRESS_STREET_A},
    {kHomeCityProperty, PR_HOME_ADDRESS_CITY_A},
    {kHomeStateProperty, PR_HOME_ADDRESS_STATE_OR_PROVINCE_A},
    {kHomeZipCodeProperty, PR_HOME_ADDRESS_POSTAL_CODE_A},
    {kHomeCountryProperty, PR_HOME_ADDRESS_COUNTRY_A},
    {kWorkAddressProperty, PR_BUSINESS_ADDRESS_STREET_A}, 
    {kWorkCityProperty, PR_BUSINESS_ADDRESS_CITY_A},
    {kWorkStateProperty, PR_BUSINESS_ADDRESS_STATE_OR_PROVINCE_A},
    {kWorkZipCodeProperty, PR_BUSINESS_ADDRESS_POSTAL_CODE_A},
    {kWorkCountryProperty, PR_BUSINESS_ADDRESS_COUNTRY_A},
    {kJobTitleProperty, PR_TITLE_A},
    {kDepartmentProperty, PR_DEPARTMENT_NAME_A},
    {kCompanyProperty, PR_COMPANY_NAME_A},
    {kWorkWebPageProperty, PR_BUSINESS_HOME_PAGE_A},
    {kHomeWebPageProperty, PR_PERSONAL_HOME_PAGE_A},
    // For the moment, we don't support querying on the birthday
    // sub-elements.
#if 0
    {kBirthYearProperty, PR_BIRTHDAY},
    {kBirthMonthProperty, PR_BIRTHDAY}, 
    {kBirthDayProperty, PR_BIRTHDAY},
#endif // 0
    {kNotesProperty, PR_COMMENT_A}
} ;

static const PRUint32 OutlookTableNbProps = sizeof(OutlookTableStringToProp) /
                                            sizeof(OutlookTableStringToProp [0]) ;

static ULONG findPropertyTag(const char *aName) {
    PRUint32 i = 0 ;
    
    for (i = 0 ; i < OutlookTableNbProps ; ++ i) {
        if (strcmp(aName, OutlookTableStringToProp [i].mOuterName) == 0) {
            return OutlookTableStringToProp [i].mMapiProp ;
        }
    }
    return 0 ;
}

static nsresult BuildRestriction(nsIAbBooleanConditionString *aCondition, 
                                 SRestriction& aRestriction,
                                 PRBool& aSkipItem)
{
    if (!aCondition) { return NS_ERROR_NULL_POINTER ; }
    aSkipItem = PR_FALSE ;
    nsAbBooleanConditionType conditionType = 0 ;
    nsresult retCode = NS_OK ;
    nsCString name;
    nsString value;
    ULONG propertyTag = 0 ;
    nsCAutoString valueAscii ;
    
    retCode = aCondition->GetCondition(&conditionType) ;
    NS_ENSURE_SUCCESS(retCode, retCode) ;
    retCode = aCondition->GetName(getter_Copies(name)) ;
    NS_ENSURE_SUCCESS(retCode, retCode) ;
    retCode = aCondition->GetValue(getter_Copies(value)) ;
    NS_ENSURE_SUCCESS(retCode, retCode) ;
    LossyCopyUTF16toASCII(value, valueAscii);
    propertyTag = findPropertyTag(name.get()) ;
    if (propertyTag == 0) {
        aSkipItem = PR_TRUE ;
        return retCode ;
    }
    switch (conditionType) {
    case nsIAbBooleanConditionTypes::Exists :
        aRestriction.rt = RES_EXIST ;
        aRestriction.res.resExist.ulPropTag = propertyTag ;
        break ;
    case nsIAbBooleanConditionTypes::DoesNotExist :
        aRestriction.rt = RES_NOT ;
        aRestriction.res.resNot.lpRes = new SRestriction ;
        aRestriction.res.resNot.lpRes->rt = RES_EXIST ;
        aRestriction.res.resNot.lpRes->res.resExist.ulPropTag = propertyTag ;
        break ;
    case nsIAbBooleanConditionTypes::Contains :
        aRestriction.rt = RES_CONTENT ;
        aRestriction.res.resContent.ulFuzzyLevel = FL_SUBSTRING | FL_LOOSE ;
        aRestriction.res.resContent.ulPropTag = propertyTag ;
        aRestriction.res.resContent.lpProp = new SPropValue ;
        aRestriction.res.resContent.lpProp->ulPropTag = propertyTag ;
        aRestriction.res.resContent.lpProp->Value.lpszA = strdup(valueAscii.get()) ;
        break ;
    case nsIAbBooleanConditionTypes::DoesNotContain :
        aRestriction.rt = RES_NOT ;
        aRestriction.res.resNot.lpRes = new SRestriction ;
        aRestriction.res.resNot.lpRes->rt = RES_CONTENT ;
        aRestriction.res.resNot.lpRes->res.resContent.ulFuzzyLevel = FL_SUBSTRING | FL_LOOSE ;
        aRestriction.res.resNot.lpRes->res.resContent.ulPropTag = propertyTag ;
        aRestriction.res.resNot.lpRes->res.resContent.lpProp = new SPropValue ;
        aRestriction.res.resNot.lpRes->res.resContent.lpProp->ulPropTag = propertyTag ;
        aRestriction.res.resNot.lpRes->res.resContent.lpProp->Value.lpszA = strdup(valueAscii.get()) ;
        break ;
    case nsIAbBooleanConditionTypes::Is :
        aRestriction.rt = RES_CONTENT ;
        aRestriction.res.resContent.ulFuzzyLevel = FL_FULLSTRING | FL_LOOSE ;
        aRestriction.res.resContent.ulPropTag = propertyTag ;
        aRestriction.res.resContent.lpProp = new SPropValue ;
        aRestriction.res.resContent.lpProp->ulPropTag = propertyTag ;
        aRestriction.res.resContent.lpProp->Value.lpszA = strdup(valueAscii.get()) ;
        break ;
    case nsIAbBooleanConditionTypes::IsNot :
        aRestriction.rt = RES_NOT ;
        aRestriction.res.resNot.lpRes = new SRestriction ;
        aRestriction.res.resNot.lpRes->rt = RES_CONTENT ;
        aRestriction.res.resNot.lpRes->res.resContent.ulFuzzyLevel = FL_FULLSTRING | FL_LOOSE ;
        aRestriction.res.resNot.lpRes->res.resContent.ulPropTag = propertyTag ;
        aRestriction.res.resNot.lpRes->res.resContent.lpProp = new SPropValue ;
        aRestriction.res.resNot.lpRes->res.resContent.lpProp->ulPropTag = propertyTag ;
        aRestriction.res.resNot.lpRes->res.resContent.lpProp->Value.lpszA = strdup(valueAscii.get()) ;
        break ;
    case nsIAbBooleanConditionTypes::BeginsWith :
        aRestriction.rt = RES_CONTENT ;
        aRestriction.res.resContent.ulFuzzyLevel = FL_PREFIX | FL_LOOSE ;
        aRestriction.res.resContent.ulPropTag = propertyTag ;
        aRestriction.res.resContent.lpProp = new SPropValue ;
        aRestriction.res.resContent.lpProp->ulPropTag = propertyTag ;
        aRestriction.res.resContent.lpProp->Value.lpszA = strdup(valueAscii.get()) ;
        break ;
    case nsIAbBooleanConditionTypes::EndsWith :
        // This condition should be implemented through regular expressions,
        // but MAPI doesn't match them correctly.
#if 0
        aRestriction.rt = RES_PROPERTY ;
        aRestriction.res.resProperty.relop = RELOP_RE ;
        aRestriction.res.resProperty.ulPropTag = propertyTag ;
        aRestriction.res.resProperty.lpProp = new SPropValue ;
        aRestriction.res.resProperty.lpProp->ulPropTag = propertyTag ;
        aRestriction.res.resProperty.lpProp->Value.lpszA = strdup(valueAscii.get()) ;
#else
        aSkipItem = PR_TRUE ;
#endif // 0
        break ;
    case nsIAbBooleanConditionTypes::SoundsLike :
        // This condition cannot be implemented in MAPI.
        aSkipItem = PR_TRUE ;
        break ;
    case nsIAbBooleanConditionTypes::RegExp :
        // This condition should be implemented this way, but the following
        // code will never match (through MAPI's fault).
#if 0
        aRestriction.rt = RES_PROPERTY ;
        aRestriction.res.resProperty.relop = RELOP_RE ;
        aRestriction.res.resProperty.ulPropTag = propertyTag ;
        aRestriction.res.resProperty.lpProp = new SPropValue ;
        aRestriction.res.resProperty.lpProp->ulPropTag = propertyTag ;
        aRestriction.res.resProperty.lpProp->Value.lpszA = strdup(valueAscii.get()) ;
#else
        aSkipItem = PR_TRUE ;
#endif // 0
        break ;
    case nsIAbBooleanConditionTypes::LessThan :
        aRestriction.rt = RES_PROPERTY ;
        aRestriction.res.resProperty.relop = RELOP_LT ;
        aRestriction.res.resProperty.ulPropTag = propertyTag ;
        aRestriction.res.resProperty.lpProp = new SPropValue ;
        aRestriction.res.resProperty.lpProp->ulPropTag = propertyTag ;
        aRestriction.res.resProperty.lpProp->Value.lpszA = strdup(valueAscii.get()) ;
        break ;
    case nsIAbBooleanConditionTypes::GreaterThan :
        aRestriction.rt = RES_PROPERTY ;
        aRestriction.res.resProperty.relop = RELOP_GT ;
        aRestriction.res.resProperty.ulPropTag = propertyTag ;
        aRestriction.res.resProperty.lpProp = new SPropValue ;
        aRestriction.res.resProperty.lpProp->ulPropTag = propertyTag ;
        aRestriction.res.resProperty.lpProp->Value.lpszA = strdup(valueAscii.get()) ;
        break ;
    default :
        aSkipItem = PR_TRUE ;
        break ;
    }
    return retCode ;
}

static nsresult BuildRestriction(nsIAbBooleanExpression *aLevel, 
                                 SRestriction& aRestriction)
{
    if (!aLevel) { return NS_ERROR_NULL_POINTER ; }
    aRestriction.rt = RES_COMMENT ;
    nsresult retCode = NS_OK ;
    nsAbBooleanOperationType operationType = 0 ;
    PRUint32 nbExpressions = 0 ;
    nsCOMPtr<nsIArray> expressions;

    retCode = aLevel->GetOperation(&operationType);
    NS_ENSURE_SUCCESS(retCode, retCode);
    retCode = aLevel->GetExpressions(getter_AddRefs(expressions));
    NS_ENSURE_SUCCESS(retCode, retCode);
    retCode = expressions->GetLength(&nbExpressions);
    NS_ENSURE_SUCCESS(retCode, retCode);
    if (nbExpressions == 0) { 
        PRINTF(("Error, no expressions.\n")) ;
        return NS_OK ;
    }
    if (operationType == nsIAbBooleanOperationTypes::NOT && nbExpressions != 1) {
        PRINTF(("Error, unary operation NOT with multiple operands.\n")) ;
        return NS_OK ;
    }
    LPSRestriction restrictionArray = new SRestriction [nbExpressions] ;
    PRUint32 realNbExpressions = 0 ;
    PRBool skipItem = PR_FALSE ;
    PRUint32 i = 0 ;

    nsCOMPtr<nsIAbBooleanConditionString> condition;
    nsCOMPtr<nsIAbBooleanExpression> subExpression;

    for (i = 0; i < nbExpressions; ++i) {
      condition = do_QueryElementAt(expressions, i, &retCode);

      if (NS_SUCCEEDED(retCode)) {
        retCode = BuildRestriction(condition, *restrictionArray, skipItem);
        if (NS_SUCCEEDED(retCode)) {
          if (!skipItem) {
            ++restrictionArray;
            ++realNbExpressions;
          }
        }
        else
          PRINTF(("Cannot build restriction for item %d %08x.\n", i, retCode));
      }
      else { 
        subExpression = do_QueryElementAt(expressions, i, &retCode);

        if (NS_SUCCEEDED(retCode)) {
          retCode = BuildRestriction(subExpression, *restrictionArray);
          if (NS_SUCCEEDED(retCode)) {
            if (restrictionArray->rt != RES_COMMENT) {
              ++restrictionArray;
              ++realNbExpressions;
            }
          }
        }
        else
          PRINTF(("Cannot get interface for item %d %08x.\n", i, retCode));
      }
    }

    restrictionArray -= realNbExpressions ;
    if (realNbExpressions > 1) {
        if (operationType == nsIAbBooleanOperationTypes::OR) {
            aRestriction.rt = RES_OR ;
            aRestriction.res.resOr.lpRes = restrictionArray ;
            aRestriction.res.resOr.cRes = realNbExpressions ;
        }
        else if (operationType == nsIAbBooleanOperationTypes::AND) {
            aRestriction.rt = RES_AND ;
            aRestriction.res.resAnd.lpRes = restrictionArray ;
            aRestriction.res.resAnd.cRes = realNbExpressions ;
        }
        else {
            PRINTF(("Unsupported operation %d.\n", operationType)) ;
        }
    }
    else if (realNbExpressions == 1) {
        if (operationType == nsIAbBooleanOperationTypes::NOT) {
            aRestriction.rt = RES_NOT ;
            // This copy is to ensure that every NOT restriction is being 
            // allocated by new and not new[] (see destruction of restriction)
            aRestriction.res.resNot.lpRes = new SRestriction ;
            memcpy(aRestriction.res.resNot.lpRes, restrictionArray, sizeof(SRestriction)) ;
        }
        else {
            // Case where the restriction array is redundant,
            // we need to fill the restriction directly.
            memcpy(&aRestriction, restrictionArray, sizeof(SRestriction)) ;
        }
        delete [] restrictionArray ;
    }
    if (aRestriction.rt == RES_COMMENT) {
        // This means we haven't really built any useful expression
        delete [] restrictionArray ;
    }
    return NS_OK ;
}

static nsresult BuildRestriction(nsIAbDirectoryQueryArguments *aArguments, 
                                 SRestriction& aRestriction)
{
    if (!aArguments) { return NS_ERROR_NULL_POINTER ; }
    nsresult retCode = NS_OK ;
    nsCOMPtr<nsIAbBooleanExpression> booleanQuery ;

    retCode = aArguments->GetExpression(getter_AddRefs(booleanQuery)) ;
    NS_ENSURE_SUCCESS(retCode, retCode) ;
    retCode = BuildRestriction(booleanQuery, aRestriction) ;
    return retCode ;
}

static void DestroyRestriction(SRestriction& aRestriction)
{
    switch(aRestriction.rt) {
    case RES_AND :
    case RES_OR :
        {
            for (ULONG i = 0 ; i < aRestriction.res.resAnd.cRes ; ++ i) {
                DestroyRestriction(aRestriction.res.resAnd.lpRes [i]) ;
            }
            delete [] aRestriction.res.resAnd.lpRes ;
        }
        break ;
    case RES_COMMENT :
        break ;
    case RES_CONTENT :
        if (PROP_TYPE(aRestriction.res.resContent.ulPropTag) == PT_UNICODE) {
            NS_Free(aRestriction.res.resContent.lpProp->Value.lpszW) ;
        }
        else if (PROP_TYPE(aRestriction.res.resContent.ulPropTag) == PT_STRING8) {
            NS_Free(aRestriction.res.resContent.lpProp->Value.lpszA) ;
        }
        delete aRestriction.res.resContent.lpProp ;
        break ;
    case RES_EXIST :
        break ;
    case RES_NOT :
        DestroyRestriction(*aRestriction.res.resNot.lpRes) ;
        delete aRestriction.res.resNot.lpRes ;
        break ;
    case RES_BITMASK :
    case RES_COMPAREPROPS :
        break ;
    case RES_PROPERTY :
        if (PROP_TYPE(aRestriction.res.resProperty.ulPropTag) == PT_UNICODE) {
            NS_Free(aRestriction.res.resProperty.lpProp->Value.lpszW) ;
        }
        else if (PROP_TYPE(aRestriction.res.resProperty.ulPropTag) == PT_STRING8) {
            NS_Free(aRestriction.res.resProperty.lpProp->Value.lpszA) ;
        }
        delete aRestriction.res.resProperty.lpProp ;
    case RES_SIZE :
    case RES_SUBRESTRICTION :
        break ;
    }
}

struct QueryThreadArgs 
{
    nsAbOutlookDirectory *mThis ;
    SRestriction mRestriction ;
    nsCOMPtr<nsIAbDirSearchListener> mListener ;
    PRInt32 mResultLimit ;
    PRInt32 mTimeout ;
    PRInt32 mThreadId ;
} ;

static void QueryThreadFunc(void *aArguments)
{
    QueryThreadArgs *arguments = reinterpret_cast<QueryThreadArgs *>(aArguments) ;

    if (!aArguments) { return ; }
    arguments->mThis->ExecuteQuery(arguments->mRestriction, arguments->mListener,
                                   arguments->mResultLimit, arguments->mTimeout,
                                   arguments->mThreadId) ;
    DestroyRestriction(arguments->mRestriction) ;
    delete arguments ;
}

NS_IMETHODIMP nsAbOutlookDirectory::DoQuery(nsIAbDirectory *aDirectory,
                                            nsIAbDirectoryQueryArguments *aArguments,
                                            nsIAbDirSearchListener *aListener,
                                            PRInt32 aResultLimit, PRInt32 aTimeout,
                                            PRInt32 *aReturnValue)
{
  if (!aArguments || !aListener || !aReturnValue)  { 
    return NS_ERROR_NULL_POINTER;
  }
  *aReturnValue = -1;
    
  QueryThreadArgs *threadArgs = new QueryThreadArgs;
  PRThread *newThread = nsnull;

  if (!threadArgs)
    return NS_ERROR_OUT_OF_MEMORY;

  nsresult rv = BuildRestriction(aArguments, threadArgs->mRestriction);
  NS_ENSURE_SUCCESS(rv, rv);

  threadArgs->mThis = this;
  threadArgs->mListener = aListener;
  threadArgs->mResultLimit = aResultLimit;
  threadArgs->mTimeout = aTimeout;

  PR_Lock(mProtector);
  *aReturnValue = ++mCurrentQueryId;
  PR_Unlock(mProtector);

  threadArgs->mThreadId = *aReturnValue;
  newThread = PR_CreateThread(PR_USER_THREAD,
                              QueryThreadFunc,
                              threadArgs,
                              PR_PRIORITY_NORMAL,
                              PR_GLOBAL_THREAD,
                              PR_UNJOINABLE_THREAD,
                              0);

  if (!newThread ) {
    DestroyRestriction(threadArgs->mRestriction);
    delete threadArgs;
    return NS_ERROR_OUT_OF_MEMORY;
  }

  mQueryThreads.Put(*aReturnValue, newThread);
  return NS_OK;
}

NS_IMETHODIMP nsAbOutlookDirectory::StopQuery(PRInt32 aContext)
{
    PRThread *queryThread;
    if (mQueryThreads.Get(aContext, &queryThread)) {
        PR_Interrupt(queryThread);
        mQueryThreads.Remove(aContext);
    }
    return NS_OK;
}

// nsIAbDirectorySearch methods
NS_IMETHODIMP nsAbOutlookDirectory::StartSearch(void)
{
    if (!mIsQueryURI) { return NS_ERROR_NOT_IMPLEMENTED ; }
    nsresult retCode = NS_OK ;
    
    retCode = StopSearch() ;
    NS_ENSURE_SUCCESS(retCode, retCode) ;
    mCardList.Clear();

    nsCOMPtr<nsIAbBooleanExpression> expression ;

    nsCOMPtr<nsIAbDirectoryQueryArguments> arguments = do_CreateInstance(NS_ABDIRECTORYQUERYARGUMENTS_CONTRACTID,&retCode);
    NS_ENSURE_SUCCESS(retCode, retCode);

    retCode = nsAbQueryStringToExpression::Convert(mQueryString.get (), getter_AddRefs(expression)) ;
    NS_ENSURE_SUCCESS(retCode, retCode) ;
    retCode = arguments->SetExpression(expression) ;
    NS_ENSURE_SUCCESS(retCode, retCode) ;

    retCode = arguments->SetQuerySubDirectories(PR_TRUE) ;
    NS_ENSURE_SUCCESS(retCode, retCode) ;
    nsCOMPtr<nsIAbDirSearchListener> proxyListener;

    retCode = NS_GetProxyForObject(NS_PROXY_TO_MAIN_THREAD,
                     NS_GET_IID(nsIAbDirSearchListener),
                     static_cast<nsIAbDirSearchListener *>(this),
                     NS_PROXY_SYNC | NS_PROXY_ALWAYS,
                     getter_AddRefs(proxyListener));
    NS_ENSURE_SUCCESS(retCode, retCode);

    return DoQuery(this, arguments, proxyListener, -1, 0, &mSearchContext);
}

NS_IMETHODIMP nsAbOutlookDirectory::StopSearch(void) 
{
    if (!mIsQueryURI) { return NS_ERROR_NOT_IMPLEMENTED ; }
    return StopQuery(mSearchContext) ;
}

// nsIAbDirSearchListener
NS_IMETHODIMP nsAbOutlookDirectory::OnSearchFinished(PRInt32 aResult,
                                                     const nsAString &aErrorMsg)
{
  return NS_OK;
}

NS_IMETHODIMP nsAbOutlookDirectory::OnSearchFoundCard(nsIAbCard *aCard) 
{
  mCardList.Put(aCard, aCard);
  nsresult rv;
  nsCOMPtr<nsIAbManager> abManager(do_GetService(NS_ABMANAGER_CONTRACTID, &rv));
  if (NS_SUCCEEDED(rv))
    rv = abManager->NotifyDirectoryItemAdded(this, aCard);

  return rv;
}

nsresult nsAbOutlookDirectory::ExecuteQuery(SRestriction &aRestriction,
                                            nsIAbDirSearchListener *aListener,
                                            PRInt32 aResultLimit, PRInt32 aTimeout,
                                            PRInt32 aThreadId) 

{
  if (!aListener)
    return NS_ERROR_NULL_POINTER;

  nsresult retCode = NS_OK;

  nsCOMPtr<nsIMutableArray> resultsArray(do_CreateInstance(NS_ARRAY_CONTRACTID,
                                                           &retCode));
  NS_ENSURE_SUCCESS(retCode, retCode);

  retCode = GetChildCards(resultsArray,
                          aRestriction.rt == RES_COMMENT ? nsnull : &aRestriction);
  NS_ENSURE_SUCCESS(retCode, retCode);

  PRUint32 nbResults = 0;
  retCode = resultsArray->GetLength(&nbResults);
  NS_ENSURE_SUCCESS(retCode, retCode);

  if (aResultLimit > 0 && nbResults > static_cast<PRUint32>(aResultLimit)) { 
    nbResults = static_cast<PRUint32>(aResultLimit) ; 
  }

  PRUint32 i = 0;
  nsCOMPtr<nsIAbCard> card;
    
  for (i = 0 ; i < nbResults ; ++ i) {
    card = do_QueryElementAt(resultsArray, i, &retCode);
    NS_ENSURE_SUCCESS(retCode, retCode);

    aListener->OnSearchFoundCard(card);
  }

  mQueryThreads.Remove(aThreadId);

  aListener->OnSearchFinished(nsIAbDirectoryQueryResultListener::queryResultComplete,
                              EmptyString());
  return retCode;
}

// This function expects the aCards array to already be created.
nsresult nsAbOutlookDirectory::GetChildCards(nsIMutableArray *aCards,
                                             void *aRestriction)
{
  nsAbWinHelperGuard mapiAddBook(mAbWinType);

  if (!mapiAddBook->IsOK())
    return NS_ERROR_FAILURE;

  nsMapiEntryArray cardEntries;
  LPSRestriction restriction = (LPSRestriction) aRestriction;

  if (!mapiAddBook->GetCards(*mMapiData, restriction, cardEntries)) {
    PRINTF(("Cannot get cards.\n"));
    return NS_ERROR_FAILURE;
  }

  nsCAutoString entryId;
  nsCAutoString uriName;
  nsCOMPtr<nsIAbCard> childCard;
  nsresult rv;

  for (ULONG card = 0; card < cardEntries.mNbEntries; ++card) {
    cardEntries.mEntries[card].ToString(entryId);
    buildAbWinUri(kOutlookCardScheme, mAbWinType, uriName);
    uriName.Append(entryId);

    rv = OutlookCardForURI(uriName, getter_AddRefs(childCard));
    NS_ENSURE_SUCCESS(rv, rv);

    aCards->AppendElement(childCard, PR_FALSE);
  }
  return rv;
}

nsresult nsAbOutlookDirectory::GetChildNodes(nsIMutableArray* aNodes)
{
    NS_ENSURE_ARG_POINTER(aNodes);

    aNodes->Clear();

    nsAbWinHelperGuard mapiAddBook(mAbWinType);
    nsMapiEntryArray nodeEntries;

    if (!mapiAddBook->IsOK())
        return NS_ERROR_FAILURE;

    if (!mapiAddBook->GetNodes(*mMapiData, nodeEntries)) 
    {
        PRINTF(("Cannot get nodes.\n"));
        return NS_ERROR_FAILURE;
    }

    nsCAutoString entryId;
    nsCAutoString uriName;
    nsCOMPtr<nsIRDFResource> resource;
    nsresult rv = NS_OK;

    for (ULONG node = 0; node < nodeEntries.mNbEntries; ++node) 
        {
        nodeEntries.mEntries[node].ToString(entryId);
        buildAbWinUri(kOutlookDirectoryScheme, mAbWinType, uriName);
        uriName.Append(entryId);

        rv = gRDFService->GetResource(uriName, getter_AddRefs(resource));
        NS_ENSURE_SUCCESS(rv, rv);
        aNodes->AppendElement(resource, PR_FALSE);
    }
    return rv;
}

nsresult nsAbOutlookDirectory::NotifyItemDeletion(nsISupports *aItem) 
{
  nsresult rv;
  nsCOMPtr<nsIAbManager> abManager(do_GetService(NS_ABMANAGER_CONTRACTID, &rv));

  if (NS_SUCCEEDED(rv))
    rv = abManager->NotifyDirectoryItemDeleted(this, aItem);

  return rv;
}

nsresult nsAbOutlookDirectory::NotifyItemAddition(nsISupports *aItem) 
{
  nsresult rv;
  nsCOMPtr<nsIAbManager> abManager = do_GetService(NS_ABMANAGER_CONTRACTID, &rv);
  if (NS_SUCCEEDED(rv))
    rv = abManager->NotifyDirectoryItemAdded(this, aItem);

  return rv;
}

// This is called from EditMailListToDatabase.
// We got m_AddressList containing the list of cards the mailing
// list is supposed to contain at the end.
nsresult nsAbOutlookDirectory::CommitAddressList(void)
{
  if (!m_IsMailList) { 
    PRINTF(("We are not in a mailing list, no commit can be done.\n"));
    return NS_ERROR_UNEXPECTED;
  }

  nsresult rv;
  PRUint32 i = 0;
  nsCOMPtr<nsIMutableArray> oldList(do_CreateInstance(NS_ARRAY_CONTRACTID, &rv));
  NS_ENSURE_SUCCESS(rv, rv);

  rv = GetChildCards(oldList, nsnull);
  NS_ENSURE_SUCCESS(rv, rv);

  if (!m_AddressList)
    return NS_ERROR_NULL_POINTER;

  PRUint32 nbCards = 0;
  rv = m_AddressList->GetLength(&nbCards);
  NS_ENSURE_SUCCESS(rv, rv);

  nsCOMPtr<nsISupports> element;
  nsCOMPtr<nsIAbCard> newCard;
  PRUint32 pos;

  for (i = 0; i < nbCards; ++i) {
    element = do_QueryElementAt(m_AddressList, i, &rv);
    NS_ENSURE_SUCCESS(rv, rv);

    if (NS_SUCCEEDED(oldList->IndexOf(0, element, &pos))) {
        rv = oldList->RemoveElementAt(pos);
        NS_ENSURE_SUCCESS(rv, rv);

        // The entry was not already there
        nsCOMPtr<nsIAbCard> card(do_QueryInterface(element, &rv));
        NS_ENSURE_SUCCESS(rv, rv);

        rv = CreateCard(card, getter_AddRefs(newCard));
        NS_ENSURE_SUCCESS(rv, rv);
        m_AddressList->ReplaceElementAt(newCard, i, PR_FALSE);
    }
  }
  return DeleteCards(oldList);
}

nsresult nsAbOutlookDirectory::UpdateAddressList(void)
{
    if (!m_AddressList)
    {
	nsresult rv;
        m_AddressList = do_CreateInstance(NS_ARRAY_CONTRACTID, &rv);
        NS_ENSURE_SUCCESS(rv, rv);
    }

    return m_IsMailList ? GetChildCards(m_AddressList, nsnull) :
                          GetChildNodes(m_AddressList);
}

nsresult nsAbOutlookDirectory::CreateCard(nsIAbCard *aData, nsIAbCard **aNewCard) 
{
    if (!aData || !aNewCard) { return NS_ERROR_NULL_POINTER ; }
    *aNewCard = nsnull ;
    nsresult retCode = NS_OK ;
    nsAbWinHelperGuard mapiAddBook (mAbWinType) ;
    nsMapiEntry newEntry ;
    nsCAutoString entryString ;
    PRBool didCopy = PR_FALSE ;

    if (!mapiAddBook->IsOK()) { return NS_ERROR_FAILURE ; }
    // If we get a RDF resource and it maps onto an Outlook card uri,
    // we simply copy the contents of the Outlook card.
    retCode = ExtractCardEntry(aData, entryString) ;
    if (NS_SUCCEEDED(retCode) && !entryString.IsEmpty()) {
        nsMapiEntry sourceEntry ;
        
        
        sourceEntry.Assign(entryString) ;
        if (m_IsMailList) {
            // In the case of a mailing list, we can use the address
            // as a direct template to build the new one (which is done
            // by CopyEntry).
            mapiAddBook->CopyEntry(*mMapiData, sourceEntry, newEntry) ;
            didCopy = PR_TRUE ;
        }
        else {
            // Else, we have to create a temporary address and copy the
            // source into it. Yes it's silly.
            mapiAddBook->CreateEntry(*mMapiData, newEntry) ;
        }
    }
    // If this approach doesn't work, well we're back to creating and copying.
    if (newEntry.mByteCount == 0) {
        // In the case of a mailing list, we cannot directly create a new card,
        // we have to create a temporary one in a real folder (to be able to use
        // templates) and then copy it to the mailing list.
        if (m_IsMailList) {
            nsMapiEntry parentEntry ;
            nsMapiEntry temporaryEntry ;

            if (!mapiAddBook->GetDefaultContainer(parentEntry)) {
                return NS_ERROR_FAILURE ;
            }
            if (!mapiAddBook->CreateEntry(parentEntry, temporaryEntry)) {
                return NS_ERROR_FAILURE ;
            }
            if (!mapiAddBook->CopyEntry(*mMapiData, temporaryEntry, newEntry)) {
                return NS_ERROR_FAILURE ;
            }
            if (!mapiAddBook->DeleteEntry(parentEntry, temporaryEntry)) {
                return NS_ERROR_FAILURE ;
            }
        }
        // If we're on a real address book folder, we can directly create an
        // empty card.
        else if (!mapiAddBook->CreateEntry(*mMapiData, newEntry)) {
            return NS_ERROR_FAILURE ;
        }
    }
    newEntry.ToString(entryString) ;
    nsCAutoString uri ;

    buildAbWinUri(kOutlookCardScheme, mAbWinType, uri) ;
    uri.Append(entryString) ;
    
    nsCOMPtr<nsIAbCard> newCard;
    retCode = OutlookCardForURI(uri, getter_AddRefs(newCard));
    NS_ENSURE_SUCCESS(retCode, retCode);

    if (!didCopy) {
        retCode = newCard->Copy(aData) ;
        NS_ENSURE_SUCCESS(retCode, retCode) ;
        retCode = ModifyCard(newCard) ;
        NS_ENSURE_SUCCESS(retCode, retCode) ;
    }
    *aNewCard = newCard ;
    NS_ADDREF(*aNewCard) ;
    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 = static_cast<WORD>(unichar.ToInteger(&errorCode)) ;
    if (errorCode != 0) {
        PRINTF(("Error conversion string %S: %08x.\n", unichar.get(), errorCode)) ;
    }
}

#define PREF_MAIL_ADDR_BOOK_LASTNAMEFIRST "mail.addr_book.lastnamefirst"


NS_IMETHODIMP nsAbOutlookDirectory::ModifyCard(nsIAbCard *aModifiedCard)
{
  NS_ENSURE_ARG_POINTER(aModifiedCard);

  nsString *properties = nsnull;
  nsAutoString utility;
  nsAbWinHelperGuard mapiAddBook(mAbWinType);

  if (!mapiAddBook->IsOK())
    return NS_ERROR_FAILURE;

  nsCString entry;
  nsresult retCode = ExtractCardEntry(aModifiedCard, entry);
  NS_ENSURE_SUCCESS(retCode, retCode);
  // If we don't have the card entry, we can't work.
  if (entry.IsEmpty())
    return NS_ERROR_FAILURE;

  nsMapiEntry mapiData;
  mapiData.Assign(entry);

  // First, all the standard properties in one go
  properties = new nsString[index_LastProp];
  if (!properties) {
    return NS_ERROR_OUT_OF_MEMORY;
  }
  aModifiedCard->GetFirstName(properties[index_FirstName]);
  aModifiedCard->GetLastName(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.
  aModifiedCard->GetDisplayName(properties[index_DisplayName]);
  if (*properties[index_DisplayName].get() == 0) {
    nsresult rv;
    nsCOMPtr<nsIPrefBranch> prefBranch =
      do_GetService(NS_PREFSERVICE_CONTRACTID, &rv);
    NS_ENSURE_SUCCESS(rv,rv);

    PRInt32 format;
    rv = prefBranch->GetIntPref(PREF_MAIL_ADDR_BOOK_LASTNAMEFIRST, &format);
    NS_ENSURE_SUCCESS(rv,rv);

    rv = aModifiedCard->GenerateName(format, nsnull,
                                     properties[index_DisplayName]);
    NS_ENSURE_SUCCESS(rv,rv);

    if (*properties[index_DisplayName].get() == 0) {
      aModifiedCard->GetPrimaryEmail(properties[index_DisplayName]);
    }
  }
  aModifiedCard->SetDisplayName(properties[index_DisplayName]);
  aModifiedCard->GetPrimaryEmail(properties[index_EmailAddress]);
  aModifiedCard->GetPropertyAsAString(kNicknameProperty, properties[index_NickName]);
  aModifiedCard->GetPropertyAsAString(kWorkPhoneProperty, properties[index_WorkPhoneNumber]);
  aModifiedCard->GetPropertyAsAString(kHomePhoneProperty, properties[index_HomePhoneNumber]);
  aModifiedCard->GetPropertyAsAString(kFaxProperty, properties[index_WorkFaxNumber]);
  aModifiedCard->GetPropertyAsAString(kPagerProperty, properties[index_PagerNumber]);
  aModifiedCard->GetPropertyAsAString(kCellularProperty, properties[index_MobileNumber]);
  aModifiedCard->GetPropertyAsAString(kHomeCityProperty, properties[index_HomeCity]);
  aModifiedCard->GetPropertyAsAString(kHomeStateProperty, properties[index_HomeState]);
  aModifiedCard->GetPropertyAsAString(kHomeZipCodeProperty, properties[index_HomeZip]);
  aModifiedCard->GetPropertyAsAString(kHomeCountryProperty, properties[index_HomeCountry]);
  aModifiedCard->GetPropertyAsAString(kWorkCityProperty, properties[index_WorkCity]);
  aModifiedCard->GetPropertyAsAString(kWorkStateProperty, properties[index_WorkState]);
  aModifiedCard->GetPropertyAsAString(kWorkZipCodeProperty, properties[index_WorkZip]);
  aModifiedCard->GetPropertyAsAString(kWorkCountryProperty, properties[index_WorkCountry]);
  aModifiedCard->GetPropertyAsAString(kJobTitleProperty, properties[index_JobTitle]);
  aModifiedCard->GetPropertyAsAString(kDepartmentProperty, properties[index_Department]);
  aModifiedCard->GetPropertyAsAString(kCompanyProperty, properties[index_Company]);
  aModifiedCard->GetPropertyAsAString(kWorkWebPageProperty, properties[index_WorkWebPage]);
  aModifiedCard->GetPropertyAsAString(kHomeWebPageProperty, properties[index_HomeWebPage]);
  aModifiedCard->GetPropertyAsAString(kNotesProperty, properties[index_Comments]);
  if (!mapiAddBook->SetPropertiesUString(mapiData, OutlookCardMAPIProps,
                                         index_LastProp, properties)) {
    PRINTF(("Cannot set general properties.\n")) ;
  }

  delete [] properties;
  nsString unichar;
  nsString unichar2;
  WORD year = 0;
  WORD month = 0;
  WORD day = 0;

  aModifiedCard->GetPropertyAsAString(kHomeAddressProperty, unichar);
  aModifiedCard->GetPropertyAsAString(kHomeAddress2Property, unichar2);

  utility.Assign(unichar.get());
  if (!utility.IsEmpty())
    utility.AppendLiteral("\r\n");

  utility.Append(unichar2.get());
  if (!mapiAddBook->SetPropertyUString(mapiData, PR_HOME_ADDRESS_STREET_W, utility.get())) {
    PRINTF(("Cannot set home address.\n")) ;
  }

  unichar.Truncate();
  aModifiedCard->GetPropertyAsAString(kWorkAddressProperty, unichar);
  unichar2.Truncate();
  aModifiedCard->GetPropertyAsAString(kWorkAddress2Property, unichar2);

  utility.Assign(unichar.get());
  if (!utility.IsEmpty())
    utility.AppendLiteral("\r\n");

  utility.Append(unichar2.get());
  if (!mapiAddBook->SetPropertyUString(mapiData, PR_BUSINESS_ADDRESS_STREET_W, utility.get())) {
    PRINTF(("Cannot set work address.\n")) ;
  }

  unichar.Truncate();
  aModifiedCard->GetPropertyAsAString(kBirthYearProperty, unichar);
  UnicodeToWord(unichar.get(), year);
  unichar.Truncate();
  aModifiedCard->GetPropertyAsAString(kBirthMonthProperty, unichar);
  UnicodeToWord(unichar.get(), month);
  unichar.Truncate();
  aModifiedCard->GetPropertyAsAString(kBirthDayProperty, unichar);
  UnicodeToWord(unichar.get(), day);
  if (!mapiAddBook->SetPropertyDate(mapiData, PR_BIRTHDAY, year, month, day)) {
    PRINTF(("Cannot set date.\n")) ;
  }

  return retCode;
}

NS_IMETHODIMP nsAbOutlookDirectory::OnQueryFoundCard(nsIAbCard *aCard)
{
  return OnSearchFoundCard(aCard);
}

NS_IMETHODIMP nsAbOutlookDirectory::OnQueryResult(PRInt32 aResult,
                                                  PRInt32 aErrorCode)
{
  return OnSearchFinished(aResult, EmptyString());
}

NS_IMETHODIMP nsAbOutlookDirectory::UseForAutocomplete(const nsACString &aIdentityKey, PRBool *aResult)
{
  NS_ENSURE_ARG_POINTER(aResult);
  *aResult = PR_FALSE;
  return NS_OK;
}

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.Append(PRUnichar(' '));
      else
        aTarget.Append(*source);
      ++source;
    }
    aSource.SetLength(offset);
  }
}

nsresult OutlookCardForURI(const nsACString &aUri, nsIAbCard **newCard)
{
  NS_ENSURE_ARG_POINTER(newCard);

  nsCAutoString entry;
  nsCAutoString stub;
  PRUint32 abWinType = getAbWinType(kOutlookCardScheme,
    PromiseFlatCString(aUri).get(), stub, entry);
  if (abWinType == nsAbWinType_Unknown)
  {
    PRINTF(("Huge problem URI=%s.\n", PromiseFlatCString(aUri).get()));
    return NS_ERROR_INVALID_ARG;
  }

  nsAbWinHelperGuard mapiAddBook(abWinType);
  if (!mapiAddBook->IsOK())
    return NS_ERROR_FAILURE;

  nsresult rv;
  nsCOMPtr<nsIAbCard> card = do_CreateInstance(NS_ABCARDPROPERTY_CONTRACTID, &rv);
  NS_ENSURE_SUCCESS(rv, rv);

  card->SetPropertyAsAUTF8String("OutlookEntryURI", aUri);

  nsMapiEntry mapiData;
  mapiData.Assign(entry);

  nsStringArray unichars;
  if (mapiAddBook->GetPropertiesUString(mapiData, OutlookCardMAPIProps,
                                        index_LastProp, unichars))
  {
    card->SetFirstName(*unichars[index_FirstName]);
    card->SetLastName(*unichars[index_LastName]);
    card->SetDisplayName(*unichars[index_DisplayName]);
    card->SetPrimaryEmail(*unichars[index_EmailAddress]);
    card->SetPropertyAsAString(kNicknameProperty, *unichars[index_NickName]);
    card->SetPropertyAsAString(kWorkPhoneProperty, *unichars[index_WorkPhoneNumber]);
    card->SetPropertyAsAString(kHomePhoneProperty, *unichars[index_HomePhoneNumber]);
    card->SetPropertyAsAString(kFaxProperty, *unichars[index_WorkFaxNumber]);
    card->SetPropertyAsAString(kPagerProperty, *unichars[index_PagerNumber]);
    card->SetPropertyAsAString(kCellularProperty, *unichars[index_MobileNumber]);
    card->SetPropertyAsAString(kHomeCityProperty, *unichars[index_HomeCity]);
    card->SetPropertyAsAString(kHomeStateProperty, *unichars[index_HomeState]);
    card->SetPropertyAsAString(kHomeZipCodeProperty, *unichars[index_HomeZip]);
    card->SetPropertyAsAString(kHomeCountryProperty, *unichars[index_HomeCountry]);
    card->SetPropertyAsAString(kWorkCityProperty, *unichars[index_WorkCity]);
    card->SetPropertyAsAString(kWorkStateProperty, *unichars[index_WorkState]);
    card->SetPropertyAsAString(kWorkZipCodeProperty, *unichars[index_WorkZip]);
    card->SetPropertyAsAString(kWorkCountryProperty, *unichars[index_WorkCountry]);
    card->SetPropertyAsAString(kJobTitleProperty, *unichars[index_JobTitle]);
    card->SetPropertyAsAString(kDepartmentProperty, *unichars[index_Department]);
    card->SetPropertyAsAString(kCompanyProperty, *unichars[index_Company]);
    card->SetPropertyAsAString(kWorkWebPageProperty, *unichars[index_WorkWebPage]);
    card->SetPropertyAsAString(kHomeWebPageProperty, *unichars[index_HomeWebPage]);
    card->SetPropertyAsAString(kNotesProperty, *unichars[index_Comments]);
  }

  ULONG cardType = 0;
  if (mapiAddBook->GetPropertyLong(mapiData, PR_OBJECT_TYPE, cardType))
  {
    card->SetIsMailList(cardType == MAPI_DISTLIST);
    if (cardType == MAPI_DISTLIST)
    {
      nsCAutoString normalChars;
      buildAbWinUri(kOutlookDirectoryScheme, abWinType, normalChars);
      normalChars.Append(entry);
      card->SetMailListURI(normalChars.get());
    }
  }

  nsAutoString unichar;
  nsAutoString unicharBis;
  if (mapiAddBook->GetPropertyUString(mapiData, PR_HOME_ADDRESS_STREET_W, unichar))
  {
    splitString(unichar, unicharBis);
    card->SetPropertyAsAString(kHomeAddressProperty, unichar);
    card->SetPropertyAsAString(kHomeAddress2Property, unicharBis);
  }
  if (mapiAddBook->GetPropertyUString(mapiData, PR_BUSINESS_ADDRESS_STREET_W,
                                      unichar))
  {
    splitString(unichar, unicharBis);
    card->SetPropertyAsAString(kWorkAddressProperty, unichar);
    card->SetPropertyAsAString(kWorkAddress2Property, unicharBis);
  }

  WORD year = 0, month = 0, day = 0;
  if (mapiAddBook->GetPropertyDate(mapiData, PR_BIRTHDAY, year, month, day))
  {
    card->SetPropertyAsUint32(kBirthYearProperty, year);
    card->SetPropertyAsUint32(kBirthMonthProperty, month);
    card->SetPropertyAsUint32(kBirthDayProperty, day);
  }

  card.swap(*newCard);
  return NS_OK;
}