This file is indexed.

/usr/share/horde/turba/lib/Driver.php is in php-horde-turba 4.2.2-3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

   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
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
<?php
/**
 * Copyright 2000-2014 Horde LLC (http://www.horde.org/)
 *
 * See the enclosed file LICENSE for license information (ASL).  If you did
 * did not receive this file, see http://www.horde.org/licenses/apache.
 *
 * @category  Horde
 * @copyright 2000-2014 Horde LLC
 * @license   http://www.horde.org/licenses/apache ASL
 * @package   Turba
 */

/**
 * Provides a common abstracted interface to the various directory search
 * drivers.  It includes functions for searching, adding, removing, and
 * modifying directory entries.
 *
 * @author    Chuck Hagenbuch <chuck@horde.org>
 * @author    Jon Parise <jon@csh.rit.edu>
 * @category  Horde
 * @copyright 2000-2014 Horde LLC
 * @license   http://www.horde.org/licenses/apache ASL
 * @package   Turba
 */
class Turba_Driver implements Countable
{
    /**
     * The symbolic title of this source.
     *
     * @var string
     */
    public $title;

    /**
     * Hash describing the mapping between Turba attributes and
     * driver-specific fields.
     *
     * @var array
     */
    public $map = array();

    /**
     * Hash with all tabs and their fields.
     *
     * @var array
     */
    public $tabs = array();

    /**
     * List of all fields that can be accessed in the backend (excludes
     * composite attributes, etc.).
     *
     * @var array
     */
    public $fields = array();

    /**
     * Array of fields that must match exactly.
     *
     * @var array
     */
    public $strict = array();

    /**
     * Array of fields to search "approximately" (@see
     * config/backends.php).
     *
     * @var array
     */
    public $approximate = array();

    /**
     * The name of a field to store contact list names in if not the default.
     *
     * @var string
     */
    public $listNameField = null;

    /**
     * The name of a field to use as an alternative to the name field if that
     * one is empty.
     *
     * @var string
     */
    public $alternativeName = null;

    /**
     * The internal name of this source.
     *
     * @var string
     */
    protected $_name;

    /**
     * Hash holding the driver's additional parameters.
     *
     * @var array
     */
    protected $_params = array();

    /**
     * What can this backend do?
     *
     * @var array
     */
    protected $_capabilities = array();

    /**
     * Any additional options passed to Turba_Object constructors.
     *
     * @var array
     */
    protected $_objectOptions = array();

    /**
     * Number of contacts in this source.
     *
     * @var integer
     */
    protected $_count = null;

    /**
     * Hold the value for the owner of this address book.
     *
     * @var string
     */
    protected $_contact_owner = '';

    /**
     * Mapping of Turba attributes to ActiveSync fields.
     *
     * @var array
     */
    static protected $_asMap = array(
        'name' => 'fileas',
        'lastname' => 'lastname',
        'firstname' => 'firstname',
        'middlenames' => 'middlename',
        'alias' => 'nickname',
        'nickname' => 'nickname',
        'namePrefix' => 'title',
        'nameSuffix' => 'suffix',
        'homeStreet' => 'homestreet',
        'homeCity' => 'homecity',
        'homeProvince' => 'homestate',
        'homePostalCode' => 'homepostalcode',
        'homeCountryFree' => 'homecountry',
        'otherStreet' => 'otherstreet',
        'otherCity' => 'othercity',
        'otherProvince' => 'otherstate',
        'otherPostalCode' => 'otherpostalcode',
        'otherCountryFree' => 'othercountry',
        'workStreet' => 'businessstreet',
        'workCity' => 'businesscity',
        'workProvince' => 'businessstate',
        'workPostalCode' => 'businesspostalcode',
        'workCountryFree' => 'businesscountry',
        'title' => 'jobtitle',
        'company' => 'companyname',
        'department' => 'department',
        'office' => 'officelocation',
        'spouse' => 'spouse',
        'website' => 'webpage',
        'assistant' => 'assistantname',
        'manager' => 'managername',
        'yomifirstname' => 'yomifirstname',
        'yomilastname' => 'yomilastname',
        'imaddress' => 'imaddress',
        'imaddress2' => 'imaddress2',
        'imaddress3' => 'imaddress3',
        'homePhone' => 'homephonenumber',
        'homePhone2' => 'home2phonenumber',
        'workPhone' => 'businessphonenumber',
        'workPhone2' => 'business2phonenumber',
        'fax' => 'businessfaxnumber',
        'homeFax' => 'homefaxnumber',
        'pager' => 'pagernumber',
        'cellPhone' => 'mobilephonenumber',
        'carPhone' => 'carphonenumber',
        'assistPhone' => 'assistnamephonenumber',
        'companyPhone' => 'companymainphone',
        'radioPhone' => 'radiophonenumber'
    );

    /**
     * Constructs a new Turba_Driver object.
     *
     * @param string $name   Source name
     * @param array $params  Hash containing additional configuration
     *                       parameters.
     */
    public function __construct($name = '', array $params = array())
    {
        $this->_name = $name;
        $this->_params = $params;
    }

    /**
     * Returns the current driver's additional parameters.
     *
     * @return array  Hash containing the driver's additional parameters.
     */
    public function getParams()
    {
        return $this->_params;
    }

    /**
     * Checks if this backend has a certain capability.
     *
     * @param string $capability  The capability to check for.
     *
     * @return boolean  Supported or not.
     */
    public function hasCapability($capability)
    {
        return !empty($this->_capabilities[$capability]);
    }

    /**
     * Returns the attributes that are blob types.
     *
     * @return array  List of blob attributes in the array keys.
     */
    public function getBlobs()
    {
        global $attributes;

        $blobs = array();
        foreach (array_keys($this->fields) as $attribute) {
            if (isset($attributes[$attribute]) &&
                $attributes[$attribute]['type'] == 'image') {
                $blobs[$attribute] = true;
            }
        }

        return $blobs;
    }

    /**
     *  Returns the attributes that represent dates.
     *
     * @return array List of date attributes in the array keys.
     * @since 4.2.0
     */
    public function getDateFields()
    {
        global $attributes;

        $dates = array();
        foreach (array_keys($this->fields) as $attribute) {
            if (isset($attributes[$attribute]) &&
                $attributes[$attribute]['type'] == 'monthdayyear') {
                $dates[$attribute] = '0000-00-00';
            }
        }

        return $dates;
    }

    /**
     * Translates the keys of the first hash from the generalized Turba
     * attributes to the driver-specific fields. The translation is based on
     * the contents of $this->map.
     *
     * @param array $hash  Hash using Turba keys.
     *
     * @return array  Translated version of $hash.
     */
    public function toDriverKeys(array $hash)
    {
        if (!empty($hash['name']) &&
            !empty($this->listNameField) &&
            !empty($hash['__type']) &&
            is_array($this->map['name']) &&
            ($hash['__type'] == 'Group')) {
            $hash[$this->listNameField] = $hash['name'];
            unset($hash['name']);
        }

        // Add composite fields to $hash if at least one field part exists
        // and the composite field will be saved to storage.
        // Otherwise composite fields won't be computed during an import.
        foreach ($this->map as $key => $val) {
            if (!is_array($val) ||
                empty($this->map[$key]['attribute']) ||
                array_key_exists($key, $hash)) {
                continue;
            }

            foreach ($this->map[$key]['fields'] as $mapfields) {
                if (isset($hash[$mapfields])) {
                    // Add composite field
                    $hash[$key] = null;
                    break;
                }
            }
        }

        $fields = array();
        foreach ($hash as $key => $val) {
            if (!isset($this->map[$key])) {
                continue;
            }
            if (!is_array($this->map[$key])) {
                $fields[$this->map[$key]] = $val;
            } elseif (!empty($this->map[$key]['attribute'])) {
                $fieldarray = array();
                foreach ($this->map[$key]['fields'] as $mapfields) {
                    $fieldarray[] = isset($hash[$mapfields])
                        ? $hash[$mapfields]
                        : '';
                }
                $fields[$this->map[$key]['attribute']] = Turba::formatCompositeField($this->map[$key]['format'], $fieldarray);
            } else {
                // If 'parse' is not specified, use 'format' and 'fields'.
                if (!isset($this->map[$key]['parse'])) {
                    $this->map[$key]['parse'] = array(
                        array(
                            'format' => $this->map[$key]['format'],
                            'fields' => $this->map[$key]['fields']
                        )
                    );
                }
                foreach ($this->map[$key]['parse'] as $parse) {
                    $splitval = sscanf($val, $parse['format']);
                    $count = 0;
                    $tmp_fields = array();
                    foreach ($parse['fields'] as $mapfield) {
                        if (isset($hash[$mapfield])) {
                            // If the compositing fields are set
                            // individually, then don't set them at all.
                            break 2;
                        }
                        $tmp_fields[$this->map[$mapfield]] = $splitval[$count++];
                    }
                    // Exit if we found the best match.
                    if ($splitval[$count - 1] !== null) {
                        break;
                    }
                }
                $fields = array_merge($fields, $tmp_fields);
            }
        }

        return $fields;
    }

    /**
     * Takes a hash of Turba key => search value and return a (possibly
     * nested) array, using backend attribute names, that can be turned into a
     * search by the driver. The translation is based on the contents of
     * $this->map, and includes nested OR searches for composite fields.
     *
     * @param array  $criteria      Hash of criteria using Turba keys.
     * @param string $search_type   OR search or AND search?
     * @param array  $strict        Fields that must be matched exactly.
     * @param boolean $match_begin  Whether to match only at beginning of
     *                              words.
     *
     * @return array  An array of search criteria.
     */
    public function makeSearch($criteria, $search_type, array $strict,
                               $match_begin = false)
    {
        $search = $search_terms = $subsearch = $strict_search = array();
        $glue = $temp = '';
        $lastChar = '\"';
        $blobs = $this->getBlobs();

        foreach ($criteria as $key => $val) {
            if (!isset($this->map[$key])) {
                continue;
            }
            if (is_array($this->map[$key])) {
                /* Composite field, break out the search terms. */
                $parts = explode(' ', $val);
                if (count($parts) > 1) {
                    /* Only parse if there was more than 1 search term and
                     * 'AND' the cumulative subsearches. */
                    for ($i = 0; $i < count($parts); ++$i) {
                        $term = $parts[$i];
                        $firstChar = substr($term, 0, 1);
                        if ($firstChar == '"') {
                            $temp = substr($term, 1, strlen($term) - 1);
                            $done = false;
                            while (!$done && $i < count($parts) - 1) {
                                $lastChar = substr($parts[$i + 1], -1);
                                if ($lastChar == '"') {
                                    $temp .= ' ' . substr($parts[$i + 1], 0, -1);
                                    $done = true;
                                } else {
                                    $temp .= ' ' . $parts[$i + 1];
                                }
                                ++$i;
                            }
                            $search_terms[] = $temp;
                        } else {
                            $search_terms[] = $term;
                        }
                    }
                    $glue = 'AND';
                } else {
                    /* If only one search term, use original input and
                       'OR' the searces since we're only looking for 1
                       term in any of the composite fields. */
                    $search_terms[0] = $val;
                    $glue = 'OR';
                }

                foreach ($this->map[$key]['fields'] as $field) {
                    if (!empty($blobs[$field])) {
                        continue;
                    }
                    $field = $this->toDriver($field);
                    if (!empty($strict[$field])) {
                        /* For strict matches, use the original search
                         * vals. */
                        $strict_search[] = array(
                            'field' => $field,
                            'op' => '=',
                            'test' => $val,
                        );
                    } else {
                        /* Create a subsearch for each individual search
                         * term. */
                        if (count($search_terms) > 1) {
                            /* Build the 'OR' search for each search term
                             * on this field. */
                            $atomsearch = array();
                            for ($i = 0; $i < count($search_terms); ++$i) {
                                $atomsearch[] = array(
                                    'field' => $field,
                                    'op' => 'LIKE',
                                    'test' => $search_terms[$i],
                                    'begin' => $match_begin,
                                    'approximate' => !empty($this->approximate[$field]),
                                );
                            }
                            $atomsearch[] = array(
                                'field' => $field,
                                'op' => '=',
                                'test' => '',
                                'begin' => $match_begin,
                                'approximate' => !empty($this->approximate[$field])
                            );

                            $subsearch[] = array('OR' => $atomsearch);
                            unset($atomsearch);
                            $glue = 'AND';
                        } else {
                            /* $parts may have more than one element, but
                             * if they are all quoted we will only have 1
                             * $subsearch. */
                            $subsearch[] = array(
                                'field' => $field,
                                'op' => 'LIKE',
                                'test' => $search_terms[0],
                                'begin' => $match_begin,
                                'approximate' => !empty($this->approximate[$field]),
                            );
                            $glue = 'OR';
                        }
                    }
                }
                if (count($subsearch)) {
                    $search[] = array($glue => $subsearch);
                }
            } else {
                /* Not a composite field. */
                if (!empty($blobs[$key])) {
                    continue;
                }
                if (!empty($strict[$this->map[$key]])) {
                    $strict_search[] = array(
                        'field' => $this->map[$key],
                        'op' => '=',
                        'test' => $val,
                    );
                } else {
                    $search[] = array(
                        'field' => $this->map[$key],
                        'op' => 'LIKE',
                        'test' => $val,
                        'begin' => $match_begin,
                        'approximate' => !empty($this->approximate[$this->map[$key]]),
                    );
                }
            }
        }

        if (count($strict_search) && count($search)) {
            return array(
                'AND' => array(
                    $search_type => $strict_search,
                    array(
                        $search_type => $search
                    )
                )
            );
        } elseif (count($strict_search)) {
            return array(
                'AND' => $strict_search
            );
        } elseif (count($search)) {
            return array(
                $search_type => $search
            );
        }

        return array();
    }

    /**
     * Translates a single Turba attribute to the driver-specific
     * counterpart. The translation is based on the contents of
     * $this->map. This ignores composite fields.
     *
     * @param string $attribute  The Turba attribute to translate.
     *
     * @return string  The driver name for this attribute.
     */
    public function toDriver($attribute)
    {
        if (!isset($this->map[$attribute])) {
            return null;
        }

        return is_array($this->map[$attribute])
            ? $this->map[$attribute]['fields']
            : $this->map[$attribute];
    }

    /**
     * Translates a hash from being keyed on driver-specific fields to being
     * keyed on the generalized Turba attributes. The translation is based on
     * the contents of $this->map.
     *
     * @param array $entry  A hash using driver-specific keys.
     *
     * @return array  Translated version of $entry.
     */
    public function toTurbaKeys(array $entry)
    {
        $new_entry = array();
        foreach ($this->map as $key => $val) {
            if (!is_array($val)) {
                $new_entry[$key] = (isset($entry[$val]) && (!empty($entry[$val]) || (is_string($entry[$val]) && strlen($entry[$val]))))
                    ? trim($entry[$val])
                    : null;
            }
        }

        return $new_entry;
    }

    /**
     * Searches the source based on the provided criteria.
     *
     * @todo Allow $criteria to contain the comparison operator (<, =, >,
     *       'like') and modify the drivers accordingly.
     *
     * @param array $search_criteria  Hash containing the search criteria.
     * @param string $sort_order      The requested sort order which is passed
     *                                to Turba_List::sort().
     * @param string $search_type     Do an AND or an OR search (defaults to
     *                                AND).
     * @param array $return_fields    A list of fields to return; defaults to
     *                                all fields.
     * @param array $custom_strict    A list of fields that must match exactly.
     * @param boolean $match_begin    Whether to match only at beginning of
     *                                words.
     * @param boolean $count_only   Only return the count of matching entries,
     *                              not the entries themselves.
     *
     * @return mixed Turba_List|integer  The sorted, filtered list of search
     *                                   results or the number of matching
     *                                   entries (if $count_only is true).
     * @throws Turba_Exception
     */
    public function search(array $search_criteria, $sort_order = null,
                           $search_type = 'AND', array $return_fields = array(),
                           array $custom_strict = array(), $match_begin = false,
                           $count_only = false)
    {
        /* If we are not using Horde_Share, enforce the requirement that the
         * current user must be the owner of the addressbook. */
        $search_criteria['__owner'] = $this->getContactOwner();
        $strict_fields = array($this->toDriver('__owner') => true);

        /* Add any fields that must match exactly for this source to the
         * $strict_fields array. */
        foreach ($this->strict as $strict_field) {
            $strict_fields[$strict_field] = true;
        }
        foreach ($custom_strict as $strict_field) {
            if (isset($this->map[$strict_field])) {
                $strict_fields[$this->map[$strict_field]] = true;
            }
        }

        /* Translate the Turba attributes to driver-specific attributes. */
        $fields = $this->makeSearch($search_criteria, $search_type,
                                    $strict_fields, $match_begin);

        if (in_array('email', $return_fields) &&
            !in_array('emails', $return_fields)) {
            $return_fields[] = 'emails';
        }
        if (count($return_fields)) {
            $return_fields_pre = array_unique(array_merge(array('__key', '__type', '__owner', '__members', 'name'), $return_fields));
            $return_fields = array();
            foreach ($return_fields_pre as $field) {
                $result = $this->toDriver($field);
                if (is_array($result)) {
                    foreach ($result as $composite_field) {
                        $composite_result = $this->toDriver($composite_field);
                        if ($composite_result) {
                            $return_fields[] = $composite_result;
                        }
                    }
                } elseif ($result) {
                    $return_fields[] = $result;
                }
            }
        } else {
            /* Need to force the array to be re-keyed for the (fringe) case
             * where we might have 1 DB field mapped to 2 or more Turba
             * fields */
            $return_fields = array_values(
                array_unique(array_values($this->fields)));
        }

        /* Retrieve the search results from the driver. */
        $objects = $this->_search($fields, $return_fields, $this->toDriverKeys($this->getBlobs()), $count_only);
        if ($count_only) {
            return $objects;
        }
        return $this->_toTurbaObjects($objects, $sort_order);
    }

    /**
     * Searches the current address book for duplicate entries.
     *
     * Duplicates are determined by comparing email and name or last name and
     * first name values.
     *
     * @return array  A hash with the following format:
     * <code>
     * array('name' => array('John Doe' => Turba_List, ...), ...)
     * </code>
     * @throws Turba_Exception
     */
    public function searchDuplicates()
    {
        return array();
    }

    /**
     * Takes an array of object hashes and returns a Turba_List
     * containing the correct Turba_Objects
     *
     * @param array $objects     An array of object hashes (keyed to backend).
     * @param array $sort_order  Array of hashes describing sort fields.  Each
     *                           hash has the following fields:
     * <pre>
     * ascending - (boolean) Indicating sort direction.
     * field - (string) Sort field.
     * </pre>
     *
     * @return Turba_List  A list object.
     */
    protected function _toTurbaObjects(array $objects, array $sort_order = null)
    {
        $list = new Turba_List();

        foreach ($objects as $object) {
            /* Translate the driver-specific fields in the result back to the
             * more generalized common Turba attributes using the map. */
            $object = $this->toTurbaKeys($object);

            $done = false;
            if (!empty($object['__type']) &&
                ucwords($object['__type']) != 'Object') {
                $class = 'Turba_Object_' . ucwords($object['__type']);
                if (class_exists($class)) {
                    $list->insert(new $class($this, $object, $this->_objectOptions));
                    $done = true;
                }
            }
            if (!$done) {
                $list->insert(new Turba_Object($this, $object, $this->_objectOptions));
            }
        }

        $list->sort($sort_order);

        /* Return the filtered (sorted) results. */
        return $list;
    }

    /**
     * Returns a list of birthday or anniversary hashes from this source for a
     * certain period.
     *
     * @param Horde_Date $start  The start date of the valid period.
     * @param Horde_Date $end    The end date of the valid period.
     * @param string $category   The timeObjects category to return.
     *
     * @return array  A list of timeObject hashes.
     * @throws Turba Exception
     */
    public function listTimeObjects(Horde_Date $start, Horde_Date $end, $category)
    {
        try {
            $res = $this->getTimeObjectTurbaList($start, $end, $category);
        } catch (Turba_Exception $e) {
            /* Try the default implementation before returning an error */
            $res = $this->_getTimeObjectTurbaListFallback($start, $end, $category);
        }

        $t_objects = array();
        while ($ob = $res->next()) {
            $t_object = $ob->getValue($category);
            if (empty($t_object)) {
                continue;
            }

            try {
                $t_object = new Horde_Date($t_object);
            } catch (Horde_Date_Exception $e) {
                continue;
            }

            if ($t_object->compareDate($end) > 0) {
                continue;
            }

            $t_object_end = new Horde_Date($t_object);
            ++$t_object_end->mday;
            $key = $ob->getValue('__key');

            // Calculate the age of the time object
            if ($start->year == $end->year ||
                $end->year == 9999) {
                $age = $start->year - $t_object->year;
            } elseif ($t_object->month <= $end->month) {
                // t_object must be in later year
                $age = $end->year - $t_object->year;
            } else {
                // t_object must be in earlier year
                $age = $start->year - $t_object->year;
            }

            $title = sprintf(_("%d. %s of %s"),
                             $age,
                             $GLOBALS['attributes'][$category]['label'],
                             $ob->getValue('name'));

            $t_objects[] = array(
                'id' => $key,
                'title' => $title,
                'start' => sprintf('%d-%02d-%02dT00:00:00',
                                   $t_object->year,
                                   $t_object->month,
                                   $t_object->mday),
                'end' => sprintf('%d-%02d-%02dT00:00:00',
                                 $t_object_end->year,
                                 $t_object_end->month,
                                 $t_object_end->mday),
                'recurrence' => array('type' => Horde_Date_Recurrence::RECUR_YEARLY_DATE,
                                      'interval' => 1),
                'params' => array('source' => $this->_name, 'key' => $key),
                'link' => Horde::url('contact.php', true)->add(array('source' => $this->_name, 'key' => $key))->setRaw(true)
            );
        }

        return $t_objects;
    }

    /**
     * Default implementation for obtaining a Turba_List to get TimeObjects
     * out of.
     *
     * @param Horde_Date $start  The starting date.
     * @param Horde_Date $end    The ending date.
     * @param string $field      The address book field containing the
     *                           timeObject information (birthday,
     *                           anniversary).
     *
     * @return Turba_List  A list of objects.
     * @throws Turba_Exception
     */
    public function getTimeObjectTurbaList(Horde_Date $start, Horde_Date $end, $field)
    {
        return $this->_getTimeObjectTurbaListFallback($start, $end, $field);
    }

    /**
     * Default implementation for obtaining a Turba_List to get TimeObjects
     * out of.
     *
     * @param Horde_Date $start  The starting date.
     * @param Horde_Date $end    The ending date.
     * @param string $field      The address book field containing the
     *                           timeObject information (birthday,
     *                           anniversary).
     *
     * @return Turba_List  A list of objects.
     * @throws Turba_Exception
     */
    protected function _getTimeObjectTurbaListFallback(Horde_Date $start, Horde_Date $end, $field)
    {
        return $this->search(array(), null, 'AND', array('name', $field));
    }

    /**
     * Retrieves a set of objects from the source.
     *
     * @param array $objectIds  The unique ids of the objects to retrieve.
     *
     * @return array  The array of retrieved objects (Turba_Objects).
     * @throws Turba_Exception
     * @throws Horde_Exception_NotFound
     */
    public function getObjects(array $objectIds)
    {
        $objects = $this->_read($this->map['__key'], $objectIds,
                                $this->getContactOwner(),
                                array_values($this->fields),
                                $this->toDriverKeys($this->getBlobs()),
                                $this->toDriverKeys($this->getDateFields()));
        if (!is_array($objects)) {
            throw new Horde_Exception_NotFound();
        }

        $results = array();
        foreach ($objects as $object) {
            $object = $this->toTurbaKeys($object);
            $done = false;
            if (!empty($object['__type']) &&
                ucwords($object['__type']) != 'Object') {
                $class = 'Turba_Object_' . ucwords($object['__type']);
                if (class_exists($class)) {
                    $results[] = new $class($this, $object, $this->_objectOptions);
                    $done = true;
                }
            }
            if (!$done) {
                $results[] = new Turba_Object($this, $object, $this->_objectOptions);
            }
        }

        return $results;
    }

    /**
     * Retrieves one object from the source.
     *
     * @param string $objectId  The unique id of the object to retrieve.
     *
     * @return Turba_Object  The retrieved object.
     * @throws Turba_Exception
     * @throws Horde_Exception_NotFound
     */
    public function getObject($objectId)
    {
        $result = $this->getObjects(array($objectId));

        if (empty($result[0])) {
            throw new Horde_Exception_NotFound();
        }

        $result = $result[0];
        if (!isset($this->map['__owner'])) {
            $result->attributes['__owner'] = $this->getContactOwner();
        }

        return $result;
    }

    /**
     * Adds a new entry to the contact source.
     *
     * @param array $attributes  The attributes of the new object to add.
     *
     * @return string  The new __key value on success.
     * @throws Turba_Exception
     */
    public function add(array $attributes)
    {
        /* Only set __type and __owner if they are not already set. */
        if (!isset($attributes['__type'])) {
            $attributes['__type'] = 'Object';
        }
        if (isset($this->map['__owner']) && !isset($attributes['__owner'])) {
            $attributes['__owner'] = $this->getContactOwner();
        }

        if (!isset($attributes['__uid'])) {
            $attributes['__uid'] = $this->_makeUid();
        }

        $key = $attributes['__key'] = $this->_makeKey($this->toDriverKeys($attributes));
        $uid = $attributes['__uid'];

        $attributes = $this->toDriverKeys($attributes);

        $this->_add($attributes, $this->toDriverKeys($this->getBlobs()), $this->toDriverKeys($this->getDateFields()));

        /* Add tags. */
        if (isset($attributes['__tags'])) {
            $GLOBALS['injector']->getInstance('Turba_Tagger')->tag(
                $uid,
                $attributes['__tags'],
                $GLOBALS['registry']->getAuth(),
                'contact'
            );
        }

        /* Log the creation of this item in the history log. */
        try {
            $GLOBALS['injector']->getInstance('Horde_History')
                ->log('turba:' . $this->getName() . ':' . $uid,
                      array('action' => 'add'), true);
        } catch (Exception $e) {
            Horde::log($e, 'ERR');
        }

        return $key;
    }

    /**
     * Returns ability of the backend to add new contacts.
     *
     * @return boolean  Can backend add?
     */
    public function canAdd()
    {
        return $this->_canAdd();
    }

    /**
     * Returns ability of the backend to add new contacts.
     *
     * @return boolean  Can backend add?
     */
    protected function _canAdd()
    {
        return false;
    }

    /**
     * Deletes the specified entry from the contact source.
     *
     * @param string $object_id  The ID of the object to delete.
     *
     * @throws Turba_Exception
     * @throws Horde_Exception_NotFound
     */
    public function delete($object_id)
    {
        $object = $this->getObject($object_id);

        if (!$object->hasPermission(Horde_Perms::DELETE)) {
            throw new Turba_Exception(_("Permission denied"));
        }

        $this->_delete($this->toDriver('__key'), $object_id);

        $own_contact = $GLOBALS['prefs']->getValue('own_contact');
        if (!empty($own_contact)) {
            @list(,$id) = explode(';', $own_contact);
            if ($id == $object_id) {
                $GLOBALS['prefs']->setValue('own_contact', '');
            }
        }

        /* Log the deletion of this item in the history log. */
        if ($object->getValue('__uid')) {
            try {
                $GLOBALS['injector']->getInstance('Horde_History')->log($object->getGuid(),
                                                array('action' => 'delete'),
                                                true);
            } catch (Exception $e) {
                Horde::log($e, 'ERR');
            }
        }

        /* Remove any CalDAV mappings. */
        try {
            $GLOBALS['injector']
                ->getInstance('Horde_Dav_Storage')
                ->deleteInternalObjectId($object_id, $this->_name);
        } catch (Horde_Exception $e) {
            Horde::log($e);
        }
    }

    /**
     * Deletes all contacts from an address book.
     *
     * @param string $sourceName  The identifier of the address book to
     *                            delete.  If omitted, will clear the current
     *                            user's 'default' address book for this
     *                            source type.
     *
     * @throws Turba_Exception
     */
    public function deleteAll($sourceName = null)
    {
        if (!$this->hasCapability('delete_all')) {
            throw new Turba_Exception('Not supported');
        }

        $ids = $this->_deleteAll($sourceName);

        // Update Horde_History
        $history = $GLOBALS['injector']->getInstance('Horde_History');
        try {
            foreach ($ids as $id) {
                // This is slightly hackish, but it saves us from having to
                // create and save an array of Turba_Objects before we delete
                // them, just to be able to calculate this using
                // Turba_Object#getGuid
                $guid = 'turba:' . $this->getName() . ':' . $id;
                $history->log($guid, array('action' => 'delete'), true);
            }
        } catch (Exception $e) {
            Horde::log($e, 'ERR');
        }
    }

    /**
     * Deletes all contacts from an address book.
     *
     * @param string $sourceName  The source to remove all contacts from.
     *
     * @return array  An array of UIDs that have been deleted.
     * @throws Turba_Exception
     */
    protected function _deleteAll()
    {
        return array();
    }

    /**
     * Modifies an existing entry in the contact source.
     *
     * @param Turba_Object $object  The object to update.
     *
     * @return string  The object id, possibly updated.
     * @throws Turba_Exception
     */
    public function save(Turba_Object $object)
    {
        $object_id = $this->_save($object);

        if ($uid = $object->getValue('__uid')) {
            /* Update tags. */
            if (!is_null($tags = $object->getValue('__tags'))) {
                $GLOBALS['injector']->getInstance('Turba_Tagger')->replaceTags(
                    $uid,
                    $tags,
                    $this->getContactOwner(),
                    'contact'
                );
            }

            /* Log the modification of this item in the history log. */
            try {
                $GLOBALS['injector']->getInstance('Horde_History')->log($object->getGuid(),
                                                array('action' => 'modify'),
                                                true);
            } catch (Exception $e) {
                Horde::log($e, 'ERR');
            }
        }

        return $object_id;
    }

    /**
     * Returns the criteria available for this source except '__key'.
     *
     * @return array  An array containing the criteria.
     */
    public function getCriteria()
    {
        return array_diff_key($this->map, array('__key' => true));
    }

    /**
     * Returns all non-composite fields for this source. Useful for importing
     * and exporting data, etc.
     *
     * @return array  The field list.
     */
    public function getFields()
    {
        return array_flip($this->fields);
    }

    /**
     * Exports a given Turba_Object as an iCalendar vCard.
     *
     * @param Turba_Object $object  Turba_Object.
     * @param string $version       The vcard version to produce.
     * @param array $fields         Hash of field names and
     *                              Horde_SyncMl_Property properties with the
     *                              requested fields.
     * @param boolean $skipEmpty    Whether to skip empty fields.
     *
     * @return Horde_Icalendar_Vcard  A vcard object.
     */
    public function tovCard(Turba_Object $object, $version = '2.1',
                            array $fields = null, $skipEmpty = false)
    {
        global $injector;

        $hash = $object->getAttributes();
        $attributes = array_keys($this->map);
        $vcard = new Horde_Icalendar_Vcard($version);
        $formattedname = false;
        $charset = ($version == '2.1')
            ? array('CHARSET' => 'UTF-8')
            : array();

        $hooks = $injector->getInstance('Horde_Core_Hooks');
        $decode_hook = $hooks->hookExists('decode_attribute', 'turba');

        // Tags are stored externally to Turba, so they don't appear in the
        // source map.
        $attributes[] = '__tags';

        foreach ($attributes as $key) {
            $val = $object->getValue($key);
            if ($skipEmpty && !is_array($val) && !strlen($val)) {
                continue;
            }
            if ($decode_hook) {
                try {
                    $val = $hooks->callHook(
                        'decode_attribute',
                        'turba',
                        array($key, $val, $object)
                    );
                } catch (Turba_Exception $e) {}
            }
            switch ($key) {
            case '__uid':
                $vcard->setAttribute('UID', $val);
                break;

            case 'name':
                if ($fields && !isset($fields['FN'])) {
                    break;
                }
                $vcard->setAttribute('FN', $val, Horde_Mime::is8bit($val) ? $charset : array());
                $formattedname = true;
                break;

            case 'nickname':
            case 'alias':
                $params = Horde_Mime::is8bit($val) ? $charset : array();
                if (!$fields || isset($fields['NICKNAME'])) {
                    $vcard->setAttribute('NICKNAME', $val, $params);
                }
                if (!$fields || isset($fields['X-EPOCSECONDNAME'])) {
                    $vcard->setAttribute('X-EPOCSECONDNAME', $val, $params);
                }
                break;

            case 'homeAddress':
                if ($fields &&
                    (!isset($fields['LABEL']) ||
                     (isset($fields['LABEL']->Params['TYPE']) &&
                      !$this->_hasValEnum($fields['LABEL']->Params['TYPE']->ValEnum, 'HOME')))) {
                    break;
                }
                if ($version == '2.1') {
                    $vcard->setAttribute('LABEL', $val, array('HOME' => null));
                } else {
                    $vcard->setAttribute('LABEL', $val, array('TYPE' => 'HOME'));
                }
                break;

            case 'workAddress':
                if ($fields &&
                    (!isset($fields['LABEL']) ||
                     (isset($fields['LABEL']->Params['TYPE']) &&
                      !$this->_hasValEnum($fields['LABEL']->Params['TYPE']->ValEnum, 'WORK')))) {
                    break;
                }
                if ($version == '2.1') {
                    $vcard->setAttribute('LABEL', $val, array('WORK' => null));
                } else {
                    $vcard->setAttribute('LABEL', $val, array('TYPE' => 'WORK'));
                }
                break;

            case 'otherAddress':
                if ($fields && !isset($fields['LABEL'])) {
                    break;
                }
                $vcard->setAttribute('LABEL', $val);
                break;

            case 'phone':
                if ($fields && !isset($fields['TEL'])) {
                    break;
                }
                $vcard->setAttribute('TEL', $val);
                break;

            case 'homePhone':
                if ($fields &&
                    (!isset($fields['TEL']) ||
                     (isset($fields['TEL']->Params['TYPE']) &&
                      !$this->_hasValEnum($fields['TEL']->Params['TYPE']->ValEnum, 'HOME')))) {
                    break;
                }
                if ($version == '2.1') {
                    $vcard->setAttribute('TEL', $val, array('HOME' => null, 'VOICE' => null));
                } else {
                    $vcard->setAttribute('TEL', $val, array('TYPE' => array('HOME', 'VOICE')));
                }
                break;

            case 'workPhone':
                if ($fields &&
                    (!isset($fields['TEL']) ||
                     (isset($fields['TEL']->Params['TYPE']) &&
                      !$this->_hasValEnum($fields['TEL']->Params['TYPE']->ValEnum, 'WORK')))) {
                    break;
                }
                if ($version == '2.1') {
                    $vcard->setAttribute('TEL', $val, array('WORK' => null, 'VOICE' => null));
                } else {
                    $vcard->setAttribute('TEL', $val, array('TYPE' => array('WORK', 'VOICE')));
                }
                break;

            case 'cellPhone':
                if ($fields &&
                    (!isset($fields['TEL']) ||
                     (isset($fields['TEL']->Params['TYPE']) &&
                      !$this->_hasValEnum($fields['TEL']->Params['TYPE']->ValEnum, 'CELL')))) {
                    break;
                }
                if ($version == '2.1') {
                    $vcard->setAttribute('TEL', $val, array('CELL' => null, 'VOICE' => null));
                } else {
                    $vcard->setAttribute('TEL', $val, array('TYPE' => array('CELL', 'VOICE')));
                }
                break;

            case 'homeCellPhone':
                $parameters = array();
                if ($fields) {
                    if (!isset($fields['TEL'])) {
                        break;
                    }
                    if (!isset($fields['TEL']->Params['TYPE']) ||
                        $this->_hasValEnum($fields['TEL']->Params['TYPE']->ValEnum, 'CELL')) {
                        if ($version == '2.1') {
                            $parameters['CELL'] = null;
                            $parameters['VOICE'] = null;
                        } else {
                            $parameters['TYPE'] = array('CELL', 'VOICE');
                        }
                    }
                    if (!isset($fields['TEL']->Params['TYPE']) ||
                        $this->_hasValEnum($fields['TEL']->Params['TYPE']->ValEnum, 'HOME')) {
                        if ($version == '2.1') {
                            $parameters['HOME'] = null;
                            $parameters['VOICE'] = null;
                        } else {
                            $parameters['TYPE'] = array('HOME', 'VOICE');
                        }
                    }
                    if (empty($parameters)) {
                        break;
                    }
                } else {
                    if ($version == '2.1') {
                        $parameters = array('CELL' => null, 'HOME' => null, 'VOICE' => null);
                    } else {
                        $parameters = array('TYPE' => array('CELL', 'HOME', 'VOICE'));
                    }
                }
                $vcard->setAttribute('TEL', $val, $parameters);
                break;

            case 'workCellPhone':
                $parameters = array();
                if ($fields) {
                    if (!isset($fields['TEL'])) {
                        break;
                    }
                    if (!isset($fields['TEL']->Params['TYPE']) ||
                        $this->_hasValEnum($fields['TEL']->Params['TYPE']->ValEnum, 'CELL')) {
                        if ($version == '2.1') {
                            $parameters['CELL'] = null;
                            $parameters['VOICE'] = null;
                        } else {
                            $parameters['TYPE'] = array('CELL', 'VOICE');
                        }
                    }
                    if (!isset($fields['TEL']->Params['TYPE']) ||
                        $this->_hasValEnum($fields['TEL']->Params['TYPE']->ValEnum, 'WORK')) {
                        if ($version == '2.1') {
                            $parameters['WORK'] = null;
                            $parameters['VOICE'] = null;
                        } else {
                            $parameters['TYPE'] = array('WORK', 'VOICE');
                        }
                    }
                    if (empty($parameters)) {
                        break;
                    }
                } else {
                    if ($version == '2.1') {
                        $parameters = array('CELL' => null, 'WORK' => null, 'VOICE' => null);
                    } else {
                        $parameters = array('TYPE' => array('CELL', 'WORK', 'VOICE'));
                    }
                }
                $vcard->setAttribute('TEL', $val, $parameters);
                break;

            case 'videoCall':
                if ($fields &&
                    (!isset($fields['TEL']) ||
                     (isset($fields['TEL']->Params['TYPE']) &&
                      !$this->_hasValEnum($fields['TEL']->Params['TYPE']->ValEnum, 'VIDEO')))) {
                    break;
                }
                if ($version == '2.1') {
                    $vcard->setAttribute('TEL', $val, array('VIDEO' => null));
                } else {
                    $vcard->setAttribute('TEL', $val, array('TYPE' => 'VIDEO'));
                }
                break;

            case 'homeVideoCall':
                $parameters = array();
                if ($fields) {
                    if (!isset($fields['TEL'])) {
                        break;
                    }
                    if (!isset($fields['TEL']->Params['TYPE']) ||
                        $this->_hasValEnum($fields['TEL']->Params['TYPE']->ValEnum, 'VIDEO')) {
                        if ($version == '2.1') {
                            $parameters['VIDEO'] = null;
                        } else {
                            $parameters['TYPE'] = 'VIDEO';
                        }
                    }
                    if (!isset($fields['TEL']->Params['TYPE']) ||
                        $this->_hasValEnum($fields['TEL']->Params['TYPE']->ValEnum, 'HOME')) {
                        if ($version == '2.1') {
                            $parameters['HOME'] = null;
                        } else {
                            $parameters['TYPE'] = 'HOME';
                        }
                    }
                    if (empty($parameters)) {
                        break;
                    }
                } else {
                    if ($version == '2.1') {
                        $parameters = array('VIDEO' => null, 'HOME' => null);
                    } else {
                        $parameters = array('TYPE' => array('VIDEO', 'HOME'));
                    }
                }
                $vcard->setAttribute('TEL', $val, $parameters);
                break;

            case 'workVideoCall':
                $parameters = array();
                if ($fields) {
                    if (!isset($fields['TEL'])) {
                        break;
                    }
                    if (!isset($fields['TEL']->Params['TYPE']) ||
                        $this->_hasValEnum($fields['TEL']->Params['TYPE']->ValEnum, 'VIDEO')) {
                        if ($version == '2.1') {
                            $parameters['VIDEO'] = null;
                        } else {
                            $parameters['TYPE'] = 'VIDEO';
                        }
                    }
                    if (!isset($fields['TEL']->Params['TYPE']) ||
                        $this->_hasValEnum($fields['TEL']->Params['TYPE']->ValEnum, 'WORK')) {
                        if ($version == '2.1') {
                            $parameters['WORK'] = null;
                        } else {
                            $parameters['TYPE'] = 'WORK';
                        }
                    }
                    if (empty($parameters)) {
                        break;
                    }
                } else {
                    if ($version == '2.1') {
                        $parameters = array('VIDEO' => null, 'WORK' => null);
                    } else {
                        $parameters = array('TYPE' => array('VIDEO', 'WORK'));
                    }
                }
                $vcard->setAttribute('TEL', $val, $parameters);
                break;

            case 'sip':
                if ($fields && !isset($fields['X-SIP'])) {
                    break;
                }
                $vcard->setAttribute('X-SIP', $val);
                break;
            case 'ptt':
                if ($fields &&
                    (!isset($fields['X-SIP']) ||
                     (isset($fields['X-SIP']->Params['TYPE']) &&
                      !$this->_hasValEnum($fields['X-SIP']->Params['TYPE']->ValEnum, 'POC')))) {
                    break;
                }
                if ($version == '2.1') {
                    $vcard->setAttribute('X-SIP', $val, array('POC' => null));
                } else {
                    $vcard->setAttribute('X-SIP', $val, array('TYPE' => 'POC'));
                }
                break;

            case 'voip':
                if ($fields &&
                    (!isset($fields['X-SIP']) ||
                     (isset($fields['X-SIP']->Params['TYPE']) &&
                      !$this->_hasValEnum($fields['X-SIP']->Params['TYPE']->ValEnum, 'VOIP')))) {
                    break;
                }
                if ($version == '2.1') {
                    $vcard->setAttribute('X-SIP', $val, array('VOIP' => null));
                } else {
                    $vcard->setAttribute('X-SIP', $val, array('TYPE' => 'VOIP'));
                }
                break;

            case 'shareView':
                if ($fields &&
                    (!isset($fields['X-SIP']) ||
                     (isset($fields['X-SIP']->Params['TYPE']) &&
                      !$this->_hasValEnum($fields['X-SIP']->Params['TYPE']->ValEnum, 'SWIS')))) {
                    break;
                }
                if ($version == '2.1') {
                    $vcard->setAttribute('X-SIP', $val, array('SWIS' => null));
                } else {
                    $vcard->setAttribute('X-SIP', $val, array('TYPE' => 'SWIS'));
                }
                break;

            case 'imaddress':
                if ($fields && !isset($fields['X-WV-ID'])) {
                    break;
                }
                $vcard->setAttribute('X-WV-ID', $val);
                break;

            case 'fax':
                if ($fields &&
                    (!isset($fields['TEL']) ||
                     (isset($fields['TEL']->Params['TYPE']) &&
                      !$this->_hasValEnum($fields['TEL']->Params['TYPE']->ValEnum, 'FAX')))) {
                    break;
                }
                if ($version == '2.1') {
                    $vcard->setAttribute('TEL', $val, array('FAX' => null));
                } else {
                    $vcard->setAttribute('TEL', $val, array('TYPE' => 'FAX'));
                }
                break;

            case 'homeFax':
                $parameters = array();
                if ($fields) {
                    if (!isset($fields['TEL'])) {
                        break;
                    }
                    if (!isset($fields['TEL']->Params['TYPE']) ||
                        $this->_hasValEnum($fields['TEL']->Params['TYPE']->ValEnum, 'FAX')) {
                        if ($version == '2.1') {
                            $parameters['FAX'] = null;
                        } else {
                            $parameters['TYPE'] = 'FAX';
                        }
                    }
                    if (!isset($fields['TEL']->Params['TYPE']) ||
                        $this->_hasValEnum($fields['TEL']->Params['TYPE']->ValEnum, 'HOME')) {
                        if ($version == '2.1') {
                            $parameters['HOME'] = null;
                        } else {
                            $parameters['TYPE'] = 'HOME';
                        }
                    }
                    if (empty($parameters)) {
                        break;
                    }
                } else {
                    if ($version == '2.1') {
                        $parameters = array('FAX' => null, 'HOME' => null);
                    } else {
                        $parameters = array('TYPE' => array('FAX', 'HOME'));
                    }
                }
                $vcard->setAttribute('TEL', $val, $parameters);
                break;

            case 'workFax':
                $parameters = array();
                if ($fields) {
                    if (!isset($fields['TEL'])) {
                        break;
                    }
                    if (!isset($fields['TEL']->Params['TYPE']) ||
                        $this->_hasValEnum($fields['TEL']->Params['TYPE']->ValEnum, 'FAX')) {
                        if ($version == '2.1') {
                            $parameters['FAX'] = null;
                        } else {
                            $parameters['TYPE'] = 'FAX';
                        }
                    }
                    if (!isset($fields['TEL']->Params['TYPE']) ||
                        $this->_hasValEnum($fields['TEL']->Params['TYPE']->ValEnum, 'WORK')) {
                        if ($version == '2.1') {
                            $parameters['WORK'] = null;
                        } else {
                            $parameters['TYPE'] = 'WORK';
                        }
                    }
                    if (empty($parameters)) {
                        break;
                    }
                } else {
                    if ($version == '2.1') {
                        $parameters = array('FAX' => null, 'WORK' => null);
                    } else {
                        $parameters = array('TYPE' => array('FAX', 'WORK'));
                    }
                }
                $vcard->setAttribute('TEL', $val, $parameters);
                if ($version == '2.1') {
                    $vcard->setAttribute('TEL', $val, array('FAX' => null, 'WORK' => null));
                } else {
                    $vcard->setAttribute('TEL', $val, array('TYPE' => array('FAX', 'WORK')));
                }
                break;

            case 'pager':
                if ($fields &&
                    (!isset($fields['TEL']) ||
                     (isset($fields['TEL']->Params['TYPE']) &&
                      !$this->_hasValEnum($fields['TEL']->Params['TYPE']->ValEnum, 'PAGER')))) {
                    break;
                }
                if ($version == '2.1') {
                    $vcard->setAttribute('TEL', $val, array('PAGER' => null));
                } else {
                    $vcard->setAttribute('TEL', $val, array('TYPE' => 'PAGER'));
                }
                break;

            case 'email':
                if ($fields && !isset($fields['EMAIL'])) {
                    break;
                }
                if ($version == '2.1') {
                    $vcard->setAttribute(
                        'EMAIL',
                        Horde_Icalendar_Vcard::getBareEmail($val),
                        array('INTERNET' => null));
                } else {
                    $vcard->setAttribute(
                        'EMAIL',
                        Horde_Icalendar_Vcard::getBareEmail($val),
                        array('TYPE' => 'INTERNET'));
                }
                break;

            case 'homeEmail':
                if ($fields &&
                    (!isset($fields['EMAIL']) ||
                     (isset($fields['EMAIL']->Params['TYPE']) &&
                      !$this->_hasValEnum($fields['EMAIL']->Params['TYPE']->ValEnum, 'HOME')))) {
                    break;
                }
                if ($version == '2.1') {
                    $vcard->setAttribute('EMAIL',
                                         Horde_Icalendar_Vcard::getBareEmail($val),
                                         array('HOME' => null));
                } else {
                    $vcard->setAttribute('EMAIL',
                                         Horde_Icalendar_Vcard::getBareEmail($val),
                                         array('TYPE' => 'HOME'));
                }
                break;

            case 'workEmail':
                if ($fields &&
                    (!isset($fields['EMAIL']) ||
                     (isset($fields['EMAIL']->Params['TYPE']) &&
                      !$this->_hasValEnum($fields['EMAIL']->Params['TYPE']->ValEnum, 'WORK')))) {
                    break;
                }
                if ($version == '2.1') {
                    $vcard->setAttribute('EMAIL',
                                         Horde_Icalendar_Vcard::getBareEmail($val),
                                         array('WORK' => null));
                } else {
                    $vcard->setAttribute('EMAIL',
                                         Horde_Icalendar_Vcard::getBareEmail($val),
                                         array('TYPE' => 'WORK'));
                }
                break;

            case 'emails':
                if ($fields && !isset($fields['EMAIL'])) {
                    break;
                }
                $emails = explode(',', $val);
                foreach ($emails as $email) {
                    $vcard->setAttribute('EMAIL', Horde_Icalendar_Vcard::getBareEmail($email));
                }
                break;

            case 'title':
                if ($fields && !isset($fields['TITLE'])) {
                    break;
                }
                $vcard->setAttribute('TITLE', $val, Horde_Mime::is8bit($val) ? $charset : array());
                break;

            case 'role':
                if ($fields && !isset($fields['ROLE'])) {
                    break;
                }
                $vcard->setAttribute('ROLE', $val, Horde_Mime::is8bit($val) ? $charset : array());
                break;

            case 'notes':
                if ($fields && !isset($fields['NOTE'])) {
                    break;
                }
                $vcard->setAttribute('NOTE', $val, Horde_Mime::is8bit($val) ? $charset : array());
                break;
            case '__tags':
                $val = explode(',', $val);
            case 'businessCategory':
                // No CATEGORIES in vCard 2.1
                if ($version == '2.1' ||
                    ($fields && !isset($fields['CATEGORIES']))) {
                    break;
                }
                $vcard->setAttribute('CATEGORIES', null, array(), true, $val);
                break;

            case 'anniversary':
                if (!$fields || isset($fields['X-ANNIVERSARY'])) {
                    $vcard->setAttribute('X-ANNIVERSARY', $val);
                }
                break;

            case 'spouse':
                if (!$fields || isset($fields['X-SPOUSE'])) {
                    $vcard->setAttribute('X-SPOUSE', $val);
                }
                break;

            case 'children':
                if (!$fields || isset($fields['X-CHILDREN'])) {
                    $vcard->setAttribute('X-CHILDREN', $val);
                }
                break;

            case 'website':
                if ($fields && !isset($fields['URL'])) {
                    break;
                }
                $vcard->setAttribute('URL', $val);
                break;

            case 'homeWebsite':
                if ($fields &&
                    (!isset($fields['URL']) ||
                     (isset($fields['URL']->Params['TYPE']) &&
                      !$this->_hasValEnum($fields['URL']->Params['TYPE']->ValEnum, 'HOME')))) {
                    break;
                }
                if ($version == '2.1') {
                    $vcard->setAttribute('URL', $val, array('HOME' => null));
                } else {
                    $vcard->setAttribute('URL', $val, array('TYPE' => 'HOME'));
                }
                break;

            case 'workWebsite':
                if ($fields &&
                    (!isset($fields['URL']) ||
                     (isset($fields['URL']->Params['TYPE']) &&
                      !$this->_hasValEnum($fields['URL']->Params['TYPE']->ValEnum, 'WORK')))) {
                    break;
                }
                if ($version == '2.1') {
                    $vcard->setAttribute('URL', $val, array('WORK' => null));
                } else {
                    $vcard->setAttribute('URL', $val, array('TYPE' => 'WORK'));
                }
                break;

            case 'freebusyUrl':
                if ($version == '2.1' ||
                    ($fields && !isset($fields['FBURL']))) {
                    break;
                }
                $vcard->setAttribute('FBURL', $val);
                break;

            case 'birthday':
                if ($fields && !isset($fields['BDAY'])) {
                    break;
                }
                $vcard->setAttribute('BDAY', $val);
                break;

            case 'timezone':
                if ($fields && !isset($fields['TZ'])) {
                    break;
                }
                $vcard->setAttribute('TZ', $val, array('VALUE' => 'text'));
                break;

            case 'latitude':
                if ($fields && !isset($fields['GEO'])) {
                    break;
                }
                if (isset($hash['longitude'])) {
                    $vcard->setAttribute('GEO',
                                         array('latitude' => $val,
                                               'longitude' => $hash['longitude']));
                }
                break;

            case 'homeLatitude':
                if ($fields &&
                    (!isset($fields['GEO']) ||
                     (isset($fields['GEO']->Params['TYPE']) &&
                      !$this->_hasValEnum($fields['GEO']->Params['TYPE']->ValEnum, 'HOME')))) {
                    break;
                }
                if (isset($hash['homeLongitude'])) {
                    if ($version == '2.1') {
                        $vcard->setAttribute('GEO',
                                             array('latitude' => $val,
                                                   'longitude' => $hash['homeLongitude']),
                                             array('HOME' => null));
                   } else {
                        $vcard->setAttribute('GEO',
                                             array('latitude' => $val,
                                                   'longitude' => $hash['homeLongitude']),
                                             array('TYPE' => 'HOME'));
                   }
                }
                break;

            case 'workLatitude':
                if ($fields &&
                    (!isset($fields['GEO']) ||
                     (isset($fields['GEO']->Params['TYPE']) &&
                      !$this->_hasValEnum($fields['GEO']->Params['TYPE']->ValEnum, 'HOME')))) {
                    break;
                }
                if (isset($hash['workLongitude'])) {
                    if ($version == '2.1') {
                        $vcard->setAttribute('GEO',
                                             array('latitude' => $val,
                                                   'longitude' => $hash['workLongitude']),
                                             array('WORK' => null));
                   } else {
                        $vcard->setAttribute('GEO',
                                             array('latitude' => $val,
                                                   'longitude' => $hash['workLongitude']),
                                             array('TYPE' => 'WORK'));
                   }
                }
                break;

            case 'photo':
            case 'logo':
                $name = Horde_String::upper($key);
                $params = array();
                if (strlen($hash[$key])) {
                    $params['ENCODING'] = 'b';
                }
                if (isset($hash[$key . 'type'])) {
                    $params['TYPE'] = $hash[$key . 'type'];
                }
                if ($fields &&
                    (!isset($fields[$name]) ||
                     (isset($params['TYPE']) &&
                      isset($fields[$name]->Params['TYPE']) &&
                      !$this->_hasValEnum($fields[$name]->Params['TYPE']->ValEnum, $params['TYPE'])))) {
                    break;
                }
                $vcard->setAttribute($name,
                                     base64_encode($hash[$key]),
                                     $params);
                break;
            }
        }

        // No explicit firstname/lastname in data source: we have to guess.
        if (!isset($hash['lastname']) && isset($hash['name'])) {
            $this->_guessName($hash);
        }

        $a = array(
            Horde_Icalendar_Vcard::N_FAMILY => isset($hash['lastname']) ? $hash['lastname'] : '',
            Horde_Icalendar_Vcard::N_GIVEN  => isset($hash['firstname']) ? $hash['firstname'] : '',
            Horde_Icalendar_Vcard::N_ADDL   => isset($hash['middlenames']) ? $hash['middlenames'] : '',
            Horde_Icalendar_Vcard::N_PREFIX => isset($hash['namePrefix']) ? $hash['namePrefix'] : '',
            Horde_Icalendar_Vcard::N_SUFFIX => isset($hash['nameSuffix']) ? $hash['nameSuffix'] : '',
        );
        $val = implode(';', $a);
        if (!$fields || isset($fields['N'])) {
            $vcard->setAttribute('N', $val, Horde_Mime::is8bit($val) ? $charset : array(), false, $a);
        }

        if (!$formattedname && (!$fields || isset($fields['FN']))) {
            if ($object->getValue('name')) {
                $val = $object->getValue('name');
            } elseif (!empty($this->alternativeName) &&
                isset($hash[$this->alternativeName])) {
                $val = $hash[$this->alternativeName];
            } else {
                $val = '';
            }
            $vcard->setAttribute('FN', $val, Horde_Mime::is8bit($val) ? $charset : array());
        }

        $org = array();
        if (!empty($hash['company']) ||
            (!$skipEmpty && array_key_exists('company', $hash))) {
            $org[] = $hash['company'];
        }
        if (!empty($hash['department']) ||
            (!$skipEmpty && array_key_exists('department', $hash))) {
            $org[] = $hash['department'];
        }
        if (count($org) && (!$fields || isset($fields['ORG']))) {
            $val = implode(';', $org);
            $vcard->setAttribute('ORG', $val, Horde_Mime::is8bit($val) ? $charset : array(), false, $org);
        }

        if ((!$fields || isset($fields['ADR'])) &&
            (!empty($hash['commonAddress']) ||
             !empty($hash['commonStreet']) ||
             !empty($hash['commonPOBox']) ||
             !empty($hash['commonExtended']) ||
             !empty($hash['commonCity']) ||
             !empty($hash['commonProvince']) ||
             !empty($hash['commonPostalCode']) ||
             !empty($hash['commonCountry']) ||
             (!$skipEmpty &&
              (array_key_exists('commonAddress', $hash) ||
               array_key_exists('commonStreet', $hash) ||
               array_key_exists('commonPOBox', $hash) ||
               array_key_exists('commonExtended', $hash) ||
               array_key_exists('commonCity', $hash) ||
               array_key_exists('commonProvince', $hash) ||
               array_key_exists('commonPostalCode', $hash) ||
               array_key_exists('commonCountry', $hash))))) {
            /* We can't know if this particular Turba source uses a single
             * address field or multiple for
             * street/city/province/postcode/country. Try to deal with
             * both. */
            if (isset($hash['commonAddress']) &&
                !isset($hash['commonStreet'])) {
                $hash['commonStreet'] = $hash['commonAddress'];
            }
            $a = array(
                Horde_Icalendar_Vcard::ADR_POB      => isset($hash['commonPOBox'])
                    ? $hash['commonPOBox'] : '',
                Horde_Icalendar_Vcard::ADR_EXTEND   => isset($hash['commonExtended'])
                    ? $hash['commonExtended'] : '',
                Horde_Icalendar_Vcard::ADR_STREET   => isset($hash['commonStreet'])
                    ? $hash['commonStreet'] : '',
                Horde_Icalendar_Vcard::ADR_LOCALITY => isset($hash['commonCity'])
                    ? $hash['commonCity'] : '',
                Horde_Icalendar_Vcard::ADR_REGION   => isset($hash['commonProvince'])
                    ? $hash['commonProvince'] : '',
                Horde_Icalendar_Vcard::ADR_POSTCODE => isset($hash['commonPostalCode'])
                    ? $hash['commonPostalCode'] : '',
                Horde_Icalendar_Vcard::ADR_COUNTRY  => isset($hash['commonCountry'])
                    ? Horde_Nls::getCountryISO($hash['commonCountry']) : '',
            );

            $val = implode(';', $a);
            if ($version == '2.1') {
                $params = array();
                if (Horde_Mime::is8bit($val)) {
                    $params['CHARSET'] = 'UTF-8';
                }
            } else {
                $params = array('TYPE' => '');
            }
            $vcard->setAttribute('ADR', $val, $params, true, $a);
        }

        if ((!$fields ||
             (isset($fields['ADR']) &&
              (!isset($fields['ADR']->Params['TYPE']) ||
               $this->_hasValEnum($fields['ADR']->Params['TYPE']->ValEnum, 'HOME')))) &&
            (!empty($hash['homeAddress']) ||
             !empty($hash['homeStreet']) ||
             !empty($hash['homePOBox']) ||
             !empty($hash['homeExtended']) ||
             !empty($hash['homeCity']) ||
             !empty($hash['homeProvince']) ||
             !empty($hash['homePostalCode']) ||
             !empty($hash['homeCountry']) ||
             (!$skipEmpty &&
              (array_key_exists('homeAddress', $hash) ||
               array_key_exists('homeStreet', $hash) ||
               array_key_exists('homePOBox', $hash) ||
               array_key_exists('homeExtended', $hash) ||
               array_key_exists('homeCity', $hash) ||
               array_key_exists('homeProvince', $hash) ||
               array_key_exists('homePostalCode', $hash) ||
               array_key_exists('homeCountry', $hash))))) {
            if (isset($hash['homeAddress']) && !isset($hash['homeStreet'])) {
                $hash['homeStreet'] = $hash['homeAddress'];
            }
            $a = array(
                Horde_Icalendar_Vcard::ADR_POB      => isset($hash['homePOBox'])
                    ? $hash['homePOBox'] : '',
                Horde_Icalendar_Vcard::ADR_EXTEND   => isset($hash['homeExtended'])
                    ? $hash['homeExtended'] : '',
                Horde_Icalendar_Vcard::ADR_STREET   => isset($hash['homeStreet'])
                    ? $hash['homeStreet'] : '',
                Horde_Icalendar_Vcard::ADR_LOCALITY => isset($hash['homeCity'])
                    ? $hash['homeCity'] : '',
                Horde_Icalendar_Vcard::ADR_REGION   => isset($hash['homeProvince'])
                    ? $hash['homeProvince'] : '',
                Horde_Icalendar_Vcard::ADR_POSTCODE => isset($hash['homePostalCode'])
                    ? $hash['homePostalCode'] : '',
                Horde_Icalendar_Vcard::ADR_COUNTRY  => isset($hash['homeCountry'])
                    ? Horde_Nls::getCountryISO($hash['homeCountry']) : '',
            );

            $val = implode(';', $a);
            if ($version == '2.1') {
                $params = array('HOME' => null);
                if (Horde_Mime::is8bit($val)) {
                    $params['CHARSET'] = 'UTF-8';
                }
            } else {
                $params = array('TYPE' => 'HOME');
            }
            $vcard->setAttribute('ADR', $val, $params, true, $a);
        }

        if ((!$fields ||
             (isset($fields['ADR']) &&
              (!isset($fields['ADR']->Params['TYPE']) ||
               $this->_hasValEnum($fields['ADR']->Params['TYPE']->ValEnum, 'WORK')))) &&
            (!empty($hash['workAddress']) ||
             !empty($hash['workStreet']) ||
             !empty($hash['workPOBox']) ||
             !empty($hash['workExtended']) ||
             !empty($hash['workCity']) ||
             !empty($hash['workProvince']) ||
             !empty($hash['workPostalCode']) ||
             !empty($hash['workCountry']) ||
             (!$skipEmpty &&
              (array_key_exists('workAddress', $hash) ||
               array_key_exists('workStreet', $hash) ||
               array_key_exists('workPOBox', $hash) ||
               array_key_exists('workExtended', $hash) ||
               array_key_exists('workCity', $hash) ||
               array_key_exists('workProvince', $hash) ||
               array_key_exists('workPostalCode', $hash) ||
               array_key_exists('workCountry', $hash))))) {
            if (isset($hash['workAddress']) && !isset($hash['workStreet'])) {
                $hash['workStreet'] = $hash['workAddress'];
            }
            $a = array(
                Horde_Icalendar_Vcard::ADR_POB      => isset($hash['workPOBox'])
                    ? $hash['workPOBox'] : '',
                Horde_Icalendar_Vcard::ADR_EXTEND   => isset($hash['workExtended'])
                    ? $hash['workExtended'] : '',
                Horde_Icalendar_Vcard::ADR_STREET   => isset($hash['workStreet'])
                    ? $hash['workStreet'] : '',
                Horde_Icalendar_Vcard::ADR_LOCALITY => isset($hash['workCity'])
                    ? $hash['workCity'] : '',
                Horde_Icalendar_Vcard::ADR_REGION   => isset($hash['workProvince'])
                    ? $hash['workProvince'] : '',
                Horde_Icalendar_Vcard::ADR_POSTCODE => isset($hash['workPostalCode'])
                    ? $hash['workPostalCode'] : '',
                Horde_Icalendar_Vcard::ADR_COUNTRY  => isset($hash['workCountry'])
                    ? Horde_Nls::getCountryISO($hash['workCountry']) : '',
            );

            $val = implode(';', $a);
            if ($version == '2.1') {
                $params = array('WORK' => null);
                if (Horde_Mime::is8bit($val)) {
                    $params['CHARSET'] = 'UTF-8';
                }
            } else {
                $params = array('TYPE' => 'WORK');
            }
            $vcard->setAttribute('ADR', $val, $params, true, $a);
        }

        return $vcard;
    }

    /**
     * Returns whether a ValEnum entry from a DevInf object contains a certain
     * type.
     *
     * @param array $valEnum  A ValEnum hash.
     * @param string $type    A requested attribute type.
     *
     * @return boolean  True if $type exists in $valEnum.
     */
    protected function _hasValEnum($valEnum, $type)
    {
        foreach (array_keys($valEnum) as $key) {
            if (in_array($type, explode(',', $key))) {
                return true;
            }
        }
        return false;
    }

    /**
     * Function to convert a Horde_Icalendar_Vcard object into a Turba
     * Object Hash with Turba attributes suitable as a parameter for add().
     *
     * @see add()
     *
     * @param Horde_Icalendar_Vcard $vcard  The Horde_Icalendar_Vcard object
     *                                      to parse.
     *
     * @return array  A Turba attribute hash.
     */
    public function toHash(Horde_Icalendar_Vcard $vcard)
    {
        $hash = array();
        $attr = $vcard->getAllAttributes();
        foreach ($attr as $item) {
            switch ($item['name']) {
            case 'UID':
                $hash['__uid'] = $item['value'];
                break;

            case 'FN':
                $hash['name'] = $item['value'];
                break;

            case 'N':
                $name = $item['values'];
                if (!empty($name[Horde_Icalendar_Vcard::N_FAMILY])) {
                    $hash['lastname'] = $name[Horde_Icalendar_Vcard::N_FAMILY];
                }
                if (!empty($name[Horde_Icalendar_Vcard::N_GIVEN])) {
                    $hash['firstname'] = $name[Horde_Icalendar_Vcard::N_GIVEN];
                }
                if (!empty($name[Horde_Icalendar_Vcard::N_ADDL])) {
                    $hash['middlenames'] = $name[Horde_Icalendar_Vcard::N_ADDL];
                }
                if (!empty($name[Horde_Icalendar_Vcard::N_PREFIX])) {
                    $hash['namePrefix'] = $name[Horde_Icalendar_Vcard::N_PREFIX];
                }
                if (!empty($name[Horde_Icalendar_Vcard::N_SUFFIX])) {
                    $hash['nameSuffix'] = $name[Horde_Icalendar_Vcard::N_SUFFIX];
                }
                break;

            case 'NICKNAME':
            case 'X-EPOCSECONDNAME':
                $hash['nickname'] = $item['value'];
                $hash['alias'] = $item['value'];
                break;

            // We use LABEL but also support ADR.
            case 'LABEL':
                if (isset($item['params']['HOME']) && !isset($hash['homeAddress'])) {
                    $hash['homeAddress'] = $item['value'];
                } elseif (isset($item['params']['WORK']) && !isset($hash['workAddress'])) {
                    $hash['workAddress'] = $item['value'];
                } elseif (!isset($hash['commonAddress'])) {
                    $hash['commonAddress'] = $item['value'];
                }
                break;

            case 'ADR':
                if (isset($item['params']['TYPE'])) {
                    if (!is_array($item['params']['TYPE'])) {
                        $item['params']['TYPE'] = array($item['params']['TYPE']);
                    }
                } else {
                    $item['params']['TYPE'] = array();
                    if (isset($item['params']['WORK'])) {
                        $item['params']['TYPE'][] = 'WORK';
                    }
                    if (isset($item['params']['HOME'])) {
                        $item['params']['TYPE'][] = 'HOME';
                    }
                    if (count($item['params']['TYPE']) == 0) {
                        $item['params']['TYPE'][] = 'COMMON';
                    }
                }

                $address = $item['values'];
                foreach ($item['params']['TYPE'] as $adr) {
                    switch (Horde_String::upper($adr)) {
                    case 'HOME':
                        $prefix = 'home';
                        break;

                    case 'WORK':
                        $prefix = 'work';
                        break;

                    default:
                        $prefix = 'common';
                    }

                    if (isset($hash[$prefix . 'Address'])) {
                        continue;
                    }

                    $hash[$prefix . 'Address'] = '';

                    if (!empty($address[Horde_Icalendar_Vcard::ADR_STREET])) {
                        $hash[$prefix . 'Street'] = $address[Horde_Icalendar_Vcard::ADR_STREET];
                        $hash[$prefix . 'Address'] .= $hash[$prefix . 'Street'] . "\n";
                    }
                    if (!empty($address[Horde_Icalendar_Vcard::ADR_EXTEND])) {
                        $hash[$prefix . 'Extended'] = $address[Horde_Icalendar_Vcard::ADR_EXTEND];
                        $hash[$prefix . 'Address'] .= $hash[$prefix . 'Extended'] . "\n";
                    }
                    if (!empty($address[Horde_Icalendar_Vcard::ADR_POB])) {
                        $hash[$prefix . 'POBox'] = $address[Horde_Icalendar_Vcard::ADR_POB];
                        $hash[$prefix . 'Address'] .= $hash[$prefix . 'POBox'] . "\n";
                    }
                    if (!empty($address[Horde_Icalendar_Vcard::ADR_LOCALITY])) {
                        $hash[$prefix . 'City'] = $address[Horde_Icalendar_Vcard::ADR_LOCALITY];
                        $hash[$prefix . 'Address'] .= $hash[$prefix . 'City'];
                    }
                    if (!empty($address[Horde_Icalendar_Vcard::ADR_REGION])) {
                        $hash[$prefix . 'Province'] = $address[Horde_Icalendar_Vcard::ADR_REGION];
                        $hash[$prefix . 'Address'] .= ', ' . $hash[$prefix . 'Province'];
                    }
                    if (!empty($address[Horde_Icalendar_Vcard::ADR_POSTCODE])) {
                        $hash[$prefix . 'PostalCode'] = $address[Horde_Icalendar_Vcard::ADR_POSTCODE];
                        $hash[$prefix . 'Address'] .= ' ' . $hash[$prefix . 'PostalCode'];
                    }
                    if (!empty($address[Horde_Icalendar_Vcard::ADR_COUNTRY])) {
                        include 'Horde/Nls/Countries.php';
                        $country = array_search($address[Horde_Icalendar_Vcard::ADR_COUNTRY], $countries);
                        if ($country === false) {
                            $country = $address[Horde_Icalendar_Vcard::ADR_COUNTRY];
                        }
                        $hash[$prefix . 'Country'] = $country;
                        $hash[$prefix . 'Address'] .= "\n" . $address[Horde_Icalendar_Vcard::ADR_COUNTRY];
                    }

                    $hash[$prefix . 'Address'] = trim($hash[$prefix . 'Address']);
                }
                break;

            case 'TZ':
                // We only support textual timezones.
                if (!isset($item['params']['VALUE']) ||
                    Horde_String::lower($item['params']['VALUE']) != 'text') {
                    break;
                }
                $timezones = explode(';', $item['value']);
                $available_timezones = Horde_Nls::getTimezones();
                foreach ($timezones as $timezone) {
                    $timezone = trim($timezone);
                    if (isset($available_timezones[$timezone])) {
                        $hash['timezone'] = $timezone;
                        break 2;
                    }
                }
                break;

            case 'GEO':
                if (isset($item['params']['HOME'])) {
                    $hash['homeLatitude'] = $item['value']['latitude'];
                    $hash['homeLongitude'] = $item['value']['longitude'];
                } elseif (isset($item['params']['WORK'])) {
                    $hash['workLatitude'] = $item['value']['latitude'];
                    $hash['workLongitude'] = $item['value']['longitude'];
                } else {
                    $hash['latitude'] = $item['value']['latitude'];
                    $hash['longitude'] = $item['value']['longitude'];
                }
                break;

            case 'TEL':
                if (isset($item['params']['FAX'])) {
                    if (isset($item['params']['WORK']) &&
                        !isset($hash['workFax'])) {
                        $hash['workFax'] = $item['value'];
                    } elseif (isset($item['params']['HOME']) &&
                              !isset($hash['homeFax'])) {
                        $hash['homeFax'] = $item['value'];
                    } elseif (!isset($hash['fax'])) {
                        $hash['fax'] = $item['value'];
                    }
                } elseif (isset($item['params']['PAGER']) &&
                          !isset($hash['pager'])) {
                    $hash['pager'] = $item['value'];
                } elseif (isset($item['params']['TYPE'])) {
                    if (!is_array($item['params']['TYPE'])) {
                        $item['params']['TYPE'] = array($item['params']['TYPE']);
                    }
                    foreach ($item['params']['TYPE'] as &$type) {
                        $type = Horde_String::upper($type);
                    }
                    // For vCard 3.0.
                    if (in_array('CELL', $item['params']['TYPE'])) {
                        if (in_array('HOME', $item['params']['TYPE']) &&
                            !isset($hash['homeCellPhone'])) {
                            $hash['homeCellPhone'] = $item['value'];
                        } elseif (in_array('WORK', $item['params']['TYPE']) &&
                                  !isset($hash['workCellPhone'])) {
                            $hash['workCellPhone'] = $item['value'];
                        } elseif (!isset($hash['cellPhone'])) {
                            $hash['cellPhone'] = $item['value'];
                        }
                    } elseif (in_array('FAX', $item['params']['TYPE'])) {
                        if (in_array('HOME', $item['params']['TYPE']) &&
                            !isset($hash['homeFax'])) {
                            $hash['homeFax'] = $item['value'];
                        } elseif (in_array('WORK', $item['params']['TYPE']) &&
                                  !isset($hash['workFax'])) {
                            $hash['workFax'] = $item['value'];
                        } elseif (!isset($hash['fax'])) {
                            $hash['fax'] = $item['value'];
                        }
                    } elseif (in_array('VIDEO', $item['params']['TYPE'])) {
                        if (in_array('HOME', $item['params']['TYPE']) &&
                            !isset($hash['homeVideoCall'])) {
                            $hash['homeVideoCall'] = $item['value'];
                        } elseif (in_array('WORK', $item['params']['TYPE']) &&
                                  !isset($hash['workVideoCall'])) {
                            $hash['workVideoCall'] = $item['value'];
                        } elseif (!isset($hash['videoCall'])) {
                            $hash['videoCall'] = $item['value'];
                        }
                    } elseif (in_array('PAGER', $item['params']['TYPE']) &&
                              !isset($hash['pager'])) {
                        $hash['pager'] = $item['value'];
                    } elseif (in_array('WORK', $item['params']['TYPE']) &&
                              !isset($hash['workPhone'])) {
                        $hash['workPhone'] = $item['value'];
                    } elseif (in_array('HOME', $item['params']['TYPE']) &&
                              !isset($hash['homePhone'])) {
                        $hash['homePhone'] = $item['value'];
                    } elseif (!isset($hash['phone'])) {
                        $hash['phone'] = $item['value'];
                    }
                } elseif (isset($item['params']['CELL'])) {
                    if (isset($item['params']['WORK']) &&
                        !isset($hash['workCellPhone'])) {
                        $hash['workCellPhone'] = $item['value'];
                    } elseif (isset($item['params']['HOME']) &&
                              !isset($hash['homeCellPhone'])) {
                        $hash['homeCellPhone'] = $item['value'];
                    } elseif (!isset($hash['cellPhone'])) {
                        $hash['cellPhone'] = $item['value'];
                    }
                } elseif (isset($item['params']['VIDEO'])) {
                    if (isset($item['params']['WORK']) &&
                        !isset($hash['workVideoCall'])) {
                        $hash['workVideoCall'] = $item['value'];
                    } elseif (isset($item['params']['HOME']) &&
                              !isset($hash['homeVideoCall'])) {
                        $hash['homeVideoCall'] = $item['value'];
                    } elseif (!isset($hash['videoCall'])) {
                        $hash['videoCall'] = $item['value'];
                    }
                } else {
                    if (isset($item['params']['WORK']) &&
                        !isset($hash['workPhone'])) {
                        $hash['workPhone'] = $item['value'];
                    } elseif (isset($item['params']['HOME']) &&
                              !isset($hash['homePhone'])) {
                        $hash['homePhone'] = $item['value'];
                    } else {
                        $hash['phone'] = $item['value'];
                    }
                }
                break;

            case 'EMAIL':
                $email_set = false;
                if (isset($item['params']['HOME']) &&
                    (!isset($hash['homeEmail']) ||
                     isset($item['params']['PREF']))) {
                    $e = Horde_Icalendar_Vcard::getBareEmail($item['value']);
                    $hash['homeEmail'] = $e ? $e : '';
                    $email_set = true;
                } elseif (isset($item['params']['WORK']) &&
                          (!isset($hash['workEmail']) ||
                           isset($item['params']['PREF']))) {
                    $e = Horde_Icalendar_Vcard::getBareEmail($item['value']);
                    $hash['workEmail'] = $e ? $e : '';
                    $email_set = true;
                } elseif (isset($item['params']['TYPE'])) {
                    if (!is_array($item['params']['TYPE'])) {
                        $item['params']['TYPE'] = array($item['params']['TYPE']);
                    }
                    foreach ($item['params']['TYPE'] as &$type) {
                        $type = Horde_String::upper($type);
                    }
                    if (in_array('HOME', $item['params']['TYPE']) &&
                        (!isset($hash['homeEmail']) ||
                         in_array('PREF', $item['params']['TYPE']))) {
                        $e = Horde_Icalendar_Vcard::getBareEmail($item['value']);
                        $hash['homeEmail'] = $e ? $e : '';
                        $email_set = true;
                    } elseif (in_array('WORK', $item['params']['TYPE']) &&
                              (!isset($hash['workEmail']) ||
                         in_array('PREF', $item['params']['TYPE']))) {
                        $e = Horde_Icalendar_Vcard::getBareEmail($item['value']);
                        $hash['workEmail'] = $e ? $e : '';
                        $email_set = true;
                    }
                }
                if (!$email_set &&
                    (!isset($hash['email']) ||
                     isset($item['params']['PREF']))) {
                    $e = Horde_Icalendar_Vcard::getBareEmail($item['value']);
                    $hash['email'] = $e ? $e : '';
                }

                if (!isset($hash['emails'])) {
                    $hash['emails'] = '';
                }
                if ($e = Horde_Icalendar_Vcard::getBareEmail($item['value'])) {
                    if (strlen($hash['emails'])) {
                        $hash['emails'] .= ',';
                    }
                    $hash['emails'] .= $e;
                }
                break;

            case 'TITLE':
                $hash['title'] = $item['value'];
                break;

            case 'ROLE':
                $hash['role'] = $item['value'];
                break;

            case 'ORG':
                // The VCARD 2.1 specification requires the presence of two
                // SEMI-COLON separated fields: Organizational Name and
                // Organizational Unit. Additional fields are optional.
                $hash['company'] = !empty($item['values'][0]) ? $item['values'][0] : '';
                $hash['department'] = !empty($item['values'][1]) ? $item['values'][1] : '';
                break;

            case 'NOTE':
                $hash['notes'] = $item['value'];
                break;

            case 'CATEGORIES':
                $hash['businessCategory'] = $item['value'];
                $hash['__tags'] = $item['values'];
                break;

            case 'URL':
                if (isset($item['params']['HOME']) &&
                    !isset($hash['homeWebsite'])) {
                    $hash['homeWebsite'] = $item['value'];
                } elseif (isset($item['params']['WORK']) &&
                          !isset($hash['workWebsite'])) {
                    $hash['workWebsite'] = $item['value'];
                } elseif (!isset($hash['website'])) {
                    $hash['website'] = $item['value'];
                }
                break;

            case 'BDAY':
                if (empty($item['value'])) {
                    $hash['birthday'] = '';
                } else {
                    $hash['birthday'] = $item['value']['year'] . '-' . $item['value']['month'] . '-' .  $item['value']['mday'];
                }
                break;

            case 'PHOTO':
            case 'LOGO':
                if (isset($item['params']['VALUE']) &&
                    Horde_String::lower($item['params']['VALUE']) == 'uri') {
                    // No support for URIs yet.
                    break;
                }
                if (!isset($item['params']['ENCODING']) ||
                    (Horde_String::lower($item['params']['ENCODING']) != 'b' &&
                     Horde_String::upper($item['params']['ENCODING']) != 'BASE64')) {
                    // Invalid property.
                    break;
                }
                $type = Horde_String::lower($item['name']);
                $hash[$type] = base64_decode($item['value']);
                if (isset($item['params']['TYPE'])) {
                    $hash[$type . 'type'] = $item['params']['TYPE'];
                }
                break;

            case 'X-SIP':
                if (isset($item['params']['POC']) &&
                    !isset($hash['ptt'])) {
                    $hash['ptt'] = $item['value'];
                } elseif (isset($item['params']['VOIP']) &&
                          !isset($hash['voip'])) {
                    $hash['voip'] = $item['value'];
                } elseif (isset($item['params']['SWIS']) &&
                          !isset($hash['shareView'])) {
                    $hash['shareView'] = $item['value'];
                } elseif (!isset($hash['sip'])) {
                    $hash['sip'] = $item['value'];
                }
                break;

            case 'X-WV-ID':
                $hash['imaddress'] = $item['value'];
                break;

            case 'X-ANNIVERSARY':
                if (empty($item['value'])) {
                    $hash['anniversary'] = '';
                } else {
                    $hash['anniversary'] = $item['value']['year'] . '-' . $item['value']['month'] . '-' . $item['value']['mday'];
                }
                break;

            case 'X-CHILDREN':
                $hash['children'] = $item['value'];
                break;

            case 'X-SPOUSE':
                $hash['spouse'] = $item['value'];
                break;
            }
        }

        /* Ensure we have a valid name field. */
        if (empty($hash['name'])) {
            /* If name is a composite field, it won't be present in the
             * $this->fields array, so check for that as well. */
            if (isset($this->map['name']) &&
                is_array($this->map['name']) &&
                !empty($this->map['name']['attribute'])) {
                $fieldarray = array();
                foreach ($this->map['name']['fields'] as $mapfields) {
                    $fieldarray[] = isset($hash[$mapfields]) ?
                        $hash[$mapfields] : '';
                }
                $hash['name'] = Turba::formatCompositeField($this->map['name']['format'], $fieldarray);
            } else {
                $hash['name'] = isset($hash['firstname']) ? $hash['firstname'] : '';
                if (!empty($hash['lastname'])) {
                    $hash['name'] .= ' ' . $hash['lastname'];
                }
                $hash['name'] = trim($hash['name']);
            }
        }

        // Ensure we have an 'email' field since we don't know for sure what
        // the source is, therefore we don't know the mappings available. Fixes
        // importing vCards that have all EMAIL properties with a TYPE
        // attribute.
        // See Bug: 12955
        if (!isset($hash['email'])) {
            if (!empty($hash['homeEmail'])) {
                $hash['email'] = Horde_Icalendar_Vcard::getBareEmail($hash['homeEmail']);
            } else if (!empty($hash['workEmail'])) {
                $hash['email'] = Horde_Icalendar_Vcard::getBareEmail($hash['workEmail']);
            }
        }

        return $hash;
    }

    /**
     * Convert the contact to an ActiveSync contact message
     *
     * @param Turba_Object $object  The turba object to convert
     * @param array $options        Options:
     *   - protocolversion: (float)  The EAS version to support
     *                      DEFAULT: 2.5
     *   - bodyprefs: (array)  A BODYPREFERENCE array.
     *                DEFAULT: none (No body prefs enforced).
     *   - truncation: (integer)  Truncate event body to this length
     *                 DEFAULT: none (No truncation).
     *   - device: (Horde_ActiveSync_Device) The device object.
     *
     * @return Horde_ActiveSync_Message_Contact
     */
    public function toASContact(Turba_Object $object, array $options = array())
    {
        global $injector;

        $message = new Horde_ActiveSync_Message_Contact(array(
            'logger' => $injector->getInstance('Horde_Log_Logger'),
            'protocolversion' => $options['protocolversion'],
            'device' => !empty($options['device']) ? $options['device'] : null
        ));
        $hash = $object->getAttributes();
        if (!isset($hash['lastname']) && isset($hash['name'])) {
            $this->_guessName($hash);
        }

        // Ensure we have at least a good guess as to separate address fields.
        // Not ideal, but EAS does not have a single "address" field so we must
        // map "common" to either home or work. I choose home since
        // work/non-personal installs will be more likely to have separated
        // address fields.
        if (!empty($hash['commonAddress'])) {
            if (!isset($hash['commonStreet'])) {
                $hash['commonStreet'] = $hash['commonHome'];
            }
            foreach (array('Address', 'Street', 'POBox', 'Extended', 'City', 'Province', 'PostalCode', 'Country') as $field) {
                $hash['home' . $field] = $hash['common' . $field];
            }
        } else {
            if (isset($hash['homeAddress']) && !isset($hash['homeStreet'])) {
                $hash['homeStreet'] = $hash['homeAddress'];
            }
            if (isset($hash['workAddress']) && !isset($hash['workStreet'])) {
                $hash['workStreet'] = $hash['workAddress'];
            }
        }

        $hooks = $injector->getInstance('Horde_Core_Hooks');
        $decode_hook = $hooks->hookExists('decode_attribute', 'turba');

        foreach ($hash as $field => $value) {
            if ($decode_hook) {
                try {
                    $value = $hooks->callHook(
                        'decode_attribute',
                        'turba',
                        array($field, $value, $object)
                    );
                } catch (Turba_Exception $e) {
                    Horde::log($e);
                }
            }
            if (isset(self::$_asMap[$field])) {
                try {
                    $message->{self::$_asMap[$field]} = $value;
                } catch (InvalidArgumentException $e) {
                }
                continue;
            }

            switch ($field) {
            case 'photo':
                $message->picture = base64_encode($value);
                break;

            case 'homeCountry':
                $message->homecountry = !empty($hash['homeCountryFree'])
                    ? $hash['homeCountryFree']
                    : !empty($hash['homeCountry'])
                        ? Horde_Nls::getCountryISO($hash['homeCountry'])
                        : null;
                break;

            case 'otherCountry':
                $message->othercountry = !empty($hash['otherCountryFree'])
                    ? $hash['otherCountryFree']
                    : !empty($hash['otherCountry'])
                        ? Horde_Nls::getCountryISO($hash['otherCountry'])
                        : null;
                break;

            case 'workCountry':
                $message->businesscountry = !empty($hash['workCountryFree'])
                    ? $hash['workCountryFree']
                    : !empty($hash['workCountry'])
                        ? Horde_Nls::getCountryISO($hash['workCountry'])
                        : null;
                break;

            case 'email':
                $message->email1address = $value;
                break;

            case 'homeEmail':
                $message->email2address = $value;
                break;

            case 'workEmail':
                $message->email3address = $value;
                break;

            case 'emails':
                $address = 1;
                foreach (explode(',', $value) as $email) {
                    while ($address <= 3 &&
                           $message->{'email' . $address . 'address'}) {
                        $address++;
                    }
                    if ($address > 3) {
                        break;
                    }
                    $message->{'email' . $address . 'address'} = $email;
                    $address++;
                }
                break;

            case 'children':
                // Children FROM horde are a simple string value. Even though EAS
                // uses an array stucture to pass them, we pass as a single
                // string since we can't assure what delimter the user will
                // use and (at least in some languages) a comma can be used
                // within a full name.
                $message->children = array($value);
                break;

            case 'notes':
                if ($options['protocolversion'] > Horde_ActiveSync::VERSION_TWOFIVE) {
                    $bp = $options['bodyprefs'];
                    $note = new Horde_ActiveSync_Message_AirSyncBaseBody();
                    // No HTML supported in Turba's notes. Always use plaintext.
                    $note->type = Horde_ActiveSync::BODYPREF_TYPE_PLAIN;
                    if (isset($bp[Horde_ActiveSync::BODYPREF_TYPE_PLAIN]['truncationsize'])) {
                        if (Horde_String::length($value) > $bp[Horde_ActiveSync::BODYPREF_TYPE_PLAIN]['truncationsize']) {
                            $note->data = Horde_String::substr($value, 0, $bp[Horde_ActiveSync::BODYPREF_TYPE_PLAIN]['truncationsize']);
                            $note->truncated = 1;
                        } else {
                            $note->data = $value;
                        }
                        $note->estimateddatasize = Horde_String::length($value);
                    }
                    $message->airsyncbasebody = $note;
                } else {
                    // EAS 2.5
                    $message->body = $value;
                    $message->bodysize = strlen($message->body);
                    $message->bodytruncated = 0;
                }
                break;

            case 'birthday':
            case 'anniversary':
                if (!empty($value) && $value != '0000-00-00') {
                    try {
                        $date = new Horde_Date($value);
                    } catch (Horde_Date_Exception $e) {
                        $message->$field = null;
                    }
                    // Some sanity checking to make sure the date was
                    // successfully parsed.
                    if ($date->month != 0) {
                        $message->$field = $date;
                    } else {
                        $message->$field = null;
                    }
                } else {
                    $message->$field = null;
                }
                break;
            }
        }

        /* Get tags. */
        $message->categories = $object->getValue('__tags');

        if (empty($this->fileas)) {
            $message->fileas = Turba::formatName($object);
        }

        return $message;
    }

    /**
     * Convert an ActiveSync contact message into a hash suitable for
     * importing via self::add().
     *
     * @param Horde_ActiveSync_Message_Contact $message  The contact message
     *                                                   object.
     *
     * @return array  A contact hash.
     */
    public function fromASContact(Horde_ActiveSync_Message_Contact $message)
    {
        $hash = array();

        foreach (self::$_asMap as $turbaField => $asField) {
            if (!$message->isGhosted($asField)) {
                try {
                    $hash[$turbaField] = $message->{$asField};
                } catch (InvalidArgumentException $e) {
                }
            }
        }

        /* Requires special handling */

        try {
            if ($message->getProtocolVersion() >= Horde_ActiveSync::VERSION_TWELVE) {
                if (!empty($message->airsyncbasebody)) {
                    $hash['notes'] = $message->airsyncbasebody->data;
                }
            } else {
                $hash['notes'] = $message->body;
            }
        } catch (InvalidArgumentException $e) {}

        // picture ($message->picture *should* already be base64 encdoed)
        if (!$message->isGhosted('picture')) {
            $hash['photo'] = base64_decode($message->picture);
        }

        /* Email addresses */
        $hash['emails'] = array();
        if (!$message->isGhosted('email1address')) {
            $e = Horde_Icalendar_Vcard::getBareEmail($message->email1address);
            $hash['emails'][] = $hash['email'] = $e ? $e : '';

        }
        if (!$message->isGhosted('email2address')) {
            $e = Horde_Icalendar_Vcard::getBareEmail($message->email2address);
            $hash['emails'][] = $hash['homeEmail'] = $e ? $e : '';
        }
        if (!$message->isGhosted('email3address')) {
            $e = Horde_Icalendar_Vcard::getBareEmail($message->email3address);
            $hash['emails'][] = $hash['workEmail'] = $e ? $e : '';
        }
        $hash['emails'] = implode(',', $hash['emails']);

        /* Categories */
        if (is_array($message->categories) && count($message->categories)) {
            $hash['__tags'] = $message->categories;
        }

        /* Children */
        if (is_array($message->children) && count($message->children)) {
            // We use a comma as incoming delimiter as it's the most
            // common even though it might be used withing a name string.
            $hash['children'] = implode(', ', $message->children);
        } elseif (!$message->isGhosted('children')) {
            $hash['children'] = '';
        }

        /* Birthday and Anniversary */
        if (!empty($message->birthday)) {
            $bday = new Horde_Date($message->birthday);
            $bday->setTimezone(date_default_timezone_get());
            $hash['birthday'] = $bday->format('Y-m-d');
        } elseif (!$message->isGhosted('birthday')) {
            $hash['birthday'] = '';
        }
        if (!empty($message->anniversary)) {
            $anniversary = new Horde_Date($message->anniversary);
            $anniversary->setTimezone(date_default_timezone_get());
            $hash['anniversary'] = $anniversary->format('Y-m-d');
        } elseif (!$message->isGhosted('anniversary')) {
            $hash['anniversary'] = '';
        }

        /* Countries */
        include 'Horde/Nls/Countries.php';
        if (!empty($message->homecountry)) {
            if (!empty($this->map['homeCountryFree'])) {
                $hash['homeCountryFree'] = $message->homecountry;
            } else {
                $country = array_search($message->homecountry, $countries);
                if ($country === false) {
                    $country = $message->homecountry;
                }
                $hash['homeCountry'] = $country;
            }
        } elseif (!$message->isGhosted('homecountry')) {
            $hash['homeCountry'] = '';
        }

        if (!empty($message->businesscountry)) {
            if (!empty($this->map['workCountryFree'])) {
                $hash['workCountryFree'] = $message->businesscountry;
            } else {
                $country = array_search($message->businesscountry, $countries);
                if ($country === false) {
                    $country = $message->businesscountry;
                }
                $hash['workCountry'] = $country;
            }
        } elseif (!$message->isGhosted('businesscountry')) {
            $hash['workCountry'] = '';
        }

        if (!empty($message->othercountry)) {
            if (!empty($this->map['otherCountryFree'])) {
                $hash['otherCountryFree'] = $message->othercountry;
            } else {
                $country = array_search($message->othercountry, $countries);
                if ($country === false) {
                    $country = $message->othercountry;
                }
                $hash['otherCountry'] = $country;
            }
        } elseif (!$message->isGhosted('othercountry')) {
            $hash['otherCountry'] = '';
        }

        return $hash;
    }

    /**
     * Checks if the current user has the requested permissions on this
     * address book.
     *
     * @param integer $perm  The permission to check for.
     *
     * @return boolean  True if the user has permission, otherwise false.
     */
    public function hasPermission($perm)
    {
        $perms = $GLOBALS['injector']->getInstance('Horde_Perms');
        return $perms->exists('turba:sources:' . $this->_name)
            ? $perms->hasPermission('turba:sources:' . $this->_name, $GLOBALS['registry']->getAuth(), $perm)
            // Assume we have permissions if they're not explicitly set.
            : true;
    }

    /**
     * Return the name of this address book.
     * (This is the key into the cfgSources array)
     *
     * @string Address book name
     */
    public function getName()
    {
        return $this->_name;
    }

    /**
     * Return the owner to use when searching or creating contacts in
     * this address book.
     *
     * @return string  Contact owner.
     */
    public function getContactOwner()
    {
        return empty($this->_contact_owner)
            ? $this->_getContactOwner()
            : $this->_contact_owner;
    }

    /**
     * Override the contactOwner setting for this driver.
     *
     * @param string $owner  The contact owner.
     */
    public function setContactOwner($owner)
    {
        $this->_contact_owner = $owner;
    }

    /**
     * Override the name setting for this driver.
     *
     * @param string $name  The source name. This is the key into the
     *                      $cfgSources array.
     */
    public function setSourceName($name)
    {
        $this->_name = $name;
    }

    /**
     * Return the owner to use when searching or creating contacts in
     * this address book.
     *
     * @return string  Contact owner.
     */
    protected function _getContactOwner()
    {
        return $GLOBALS['registry']->getAuth();
    }

    /**
     * Creates a new Horde_Share for this source type.
     *
     * @param string $share_name  The share name
     * @param array  $params      The params for the share.
     *
     * @return Horde_Share  The share object.
     */
    public function createShare($share_name, array $params)
    {
        // If the raw address book name is not set, use the share name
        if (empty($params['params']['name'])) {
            $params['params']['name'] = $share_name;
        }

        return Turba::createShare($share_name, $params);
    }

    /**
     * Runs any actions after setting a new default tasklist.
     *
     * @param string $share  The default share ID.
     */
    public function setDefaultShare($share)
    {
    }

    /**
     * Creates an object key for a new object.
     *
     * @param array $attributes  The attributes (in driver keys) of the
     *                           object being added.
     *
     * @return string  A unique ID for the new object.
     */
    protected function _makeKey(array $attributes)
    {
        return hash('md5', mt_rand());
    }

    /**
     * Creates an object UID for a new object.
     *
     * @return string  A unique ID for the new object.
     */
    protected function _makeUid()
    {
        return strval(new Horde_Support_Guid());
    }

    /**
     * Initialize the driver.
     *
     * @throws Turba_Exception
     */
    protected function _init()
    {
    }

    /**
     * Searches the address book with the given criteria and returns a
     * filtered list of results. If the criteria parameter is an empty array,
     * all records will be returned.
     *
     * @param array $criteria       Array containing the search criteria.
     * @param array $fields         List of fields to return.
     * @param array $blobFields     Array of fields containing binary data.
     * @param boolean $count_only   Only return the count of matching entries,
     *                              not the entries themselves.
     *
     * @return array  Hash containing the search results.
     * @throws Turba_Exception
     */
    protected function _search(array $criteria, array $fields, array $blobFields = array(), $count_only = false)
    {
        throw new Turba_Exception(_("Searching is not available."));
    }

    /**
     * Reads the given data from the address book and returns the results.
     *
     * @param string $key        The primary key field to use.
     * @param mixed $ids         The ids of the contacts to load.
     * @param string $owner      Only return contacts owned by this user.
     * @param array $fields      List of fields to return.
     * @param array $blobFields  Array of fields containing binary data.
     * @param array $dateFields  Array of fields containing date data.
     *                           @since 4.2.0
     *
     * @return array  Hash containing the search results.
     * @throws Turba_Exception
     */
    protected function _read($key, $ids, $owner, array $fields,
                             array $blobFields = array(),
                             array $dateFields = array())
    {
        throw new Turba_Exception(_("Reading contacts is not available."));
    }

    /**
     * Adds the specified contact to the addressbook.
     *
     * @param array $attributes  The attribute values of the contact.
     * @param array $blob_fields  Fields that represent binary data.
     * @param array $date_fields  Fields that represent dates. @since 4.2.0
     *
     * @throws Turba_Exception
     */
    protected function _add(array $attributes, array $blob_fields = array(), array $date_fields = array())
    {
        throw new Turba_Exception(_("Adding contacts is not available."));
    }

    /**
     * Deletes the specified contact from the addressbook.
     *
     * @param string $object_key TODO
     * @param string $object_id  TODO
     *
     * @throws Turba_Exception
     */
    protected function _delete($object_key, $object_id)
    {
        throw new Turba_Exception(_("Deleting contacts is not available."));
    }

    /**
     * Saves the specified object in the SQL database.
     *
     * @param Turba_Object $object  The object to save
     *
     * @return string  The object id, possibly updated.
     * @throws Turba_Exception
     */
    protected function _save(Turba_Object $object)
    {
        throw new Turba_Exception(_("Saving contacts is not available."));
    }

    /**
     * Remove all entries owned by the specified user.
     *
     * @param string $user  The user's data to remove.
     *
     * @throws Turba_Exception
     */
    public function removeUserData($user)
    {
        throw new Turba_Exception_NotSupported(_("Removing user data is not supported in the current address book storage driver."));
    }

    /**
     * Check if the passed in share is the default share for this source.
     *
     * @param Horde_Share_Object $share  The share object.
     * @param array $srcconfig           The cfgSource entry for the share.
     *
     * @return boolean TODO
     */
    public function checkDefaultShare(Horde_Share_Object $share, array $srcconfig)
    {
        $params = @unserialize($share->get('params'));
        if (!isset($params['default'])) {
            $params['default'] = ($params['name'] == $GLOBALS['registry']->getAuth());
            $share->set('params', serialize($params));
            $share->save();
        }

        return $params['default'];
    }

    /* Countable methods. */

    /**
     * Returns the number of contacts of the current user in this address book.
     *
     * @return integer  The number of contacts that the user owns.
     * @throws Turba_Exception
     */
    public function count()
    {
        if (is_null($this->_count)) {
            $this->_count = count(
                $this->_search(array('AND' => array(
                                   array('field' => $this->toDriver('__owner'),
                                         'op' => '=',
                                         'test' => $this->getContactOwner()))),
                               array($this->toDriver('__key')))
            );
        }

        return $this->_count;
    }

    /**
     * Helper function for guessing name parts from a single name string.
     *
     * @param array $hash  The attributes array.
     */
    protected function _guessName(&$hash)
    {
        if (($pos = strpos($hash['name'], ',')) !== false) {
            // Assume Last, First
            $hash['lastname'] = Horde_String::substr($hash['name'], 0, $pos);
            $hash['firstname'] = trim(Horde_String::substr($hash['name'], $pos + 1));
        } elseif (($pos = Horde_String::rpos($hash['name'], ' ')) !== false) {
            // Assume everything after last space as lastname
            $hash['lastname'] = trim(Horde_String::substr($hash['name'], $pos + 1));
            $hash['firstname'] = Horde_String::substr($hash['name'], 0, $pos);
        } else {
            $hash['lastname'] = $hash['name'];
            $hash['firstname'] = '';
        }
    }

}