This file is indexed.

/usr/share/horde/turba/lib/Api.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
<?php
/**
 * Turba external API interface.
 *
 * This file defines Turba's external API interface. Other applications can
 * interact with Turba through this API.
 *
 * Copyright 2009-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.
 *
 * @author   Michael Slusarz <slusarz@horde.org>
 * @category Horde
 * @license  http://www.horde.org/licenses/apache ASL
 * @package  Turba
 */
class Turba_Api extends Horde_Registry_Api
{
    /**
     * Links.
     *
     * @var array
     */
    protected $_links = array(
        'show' => '%application%/contact.php?source=|source|&key=|key|&uid=|uid|',
        'smartmobile_browse' => '%application%/smartmobile.php#browse'
    );

    /**
     * The listing of API calls that do not require permissions checking.
     *
     * @var array
     */
    protected $_noPerms = array(
        'getClientSource', 'getClient', 'getClients', 'searchClients'
    );

    /**
     * Callback for comment API.
     *
     * @param integer $id  Internal data identifier.
     *
     * @return mixed  Name of object on success, false on failure.
     */
    public function commentCallback($id)
    {
        if (!$GLOBALS['conf']['comments']['allow']) {
            return false;
        }

        @list($source, $key) = explode('.', $id, 2);
        if (isset($GLOBALS['cfgSources'][$source]) && $key) {
            try {
                return $GLOBALS['injector']->getInstance('Turba_Factory_Driver')->create($source)->getObject($key)->getValue('name');
            } catch (Horde_Exception $e) {
            }
        }

        return false;
    }

    /**
     * Does this API allow comments?
     *
     * @return boolean  True if API allows comments.
     */
    public function hasComments()
    {
        return !empty($GLOBALS['conf']['comments']['allow']);
    }

    /**
     * Returns a list of available sources.
     *
     * @param boolean $writeable  If true, limits to writeable sources.
     * @param boolean $sync_only  Only include synchable address books.
     *
     * @return array  An array of the available sources. Keys are source IDs,
     *                values are source titles.
     */
    public function sources($writeable = false, $sync_only = false)
    {
        $out = array();

        foreach (Turba::getAddressBooks($writeable ? Horde_Perms::EDIT : Horde_Perms::READ) as $key => $val) {
            $out[$key] = $val['title'];
        }

        if ($sync_only) {
            $syncable = unserialize($GLOBALS['prefs']->getValue('sync_books'));
            $out = array_intersect_key($out, array_flip($syncable));
        }

        return $out;
    }

    /**
     * Returns a list of fields avaiable in a source.
     *
     * @param string $source  The source name.
     *
     * @return array  An array describing the fields. Keys are the field name,
     *                values are arrays with these keys:
     *   - name: (string) Field name.
     *   - label: (string) Field label.
     *   - search: (boolean) Can this field be searched?
     *   - type: (string) See turba/config/attributes.php.
     *
     * @throws Turba_Exception
     */
    public function fields($source = null)
    {
        global $attributes, $cfgSources;

        if (is_null($source) || !isset($cfgSources[$source])) {
            throw new Turba_Exception(_("Invalid address book."));
        }

        $fields = array();

        foreach (array_keys($cfgSources[$source]['map']) as $name) {
            if (substr($name, 0, 2) != '__') {
                $fields[$name] = array(
                    'label' => $attributes[$name]['label'],
                    'name' => $name,
                    'search' => in_array($name, $cfgSources[$source]['search']),
                    'type' => $attributes[$name]['type']
                );
            }
        }

        return $fields;
    }

    /**
     * Retrieve the UID for the current user's default Turba share.
     *
     * @return string  UID.
     */
    public function getDefaultShare()
    {
        global $injector, $prefs, $session;

        // Bring in a clean copy of sources.
        $cfgSources = Turba::availableSources();

        if ($session->get('turba', 'has_share')) {
            $driver = $injector->getInstance('Turba_Factory_Driver');

            foreach (Turba::listShares(true) as $uid => $share) {
                $params = @unserialize($share->get('params'));
                if (!empty($params['source'])) {
                    try {
                        if ($driver->create($uid)->checkDefaultShare($share, $cfgSources[$params['source']])) {
                            return $uid;
                        }
                    } catch (Turba_Exception $e) {}
                }
            }
        }

        // Return Turba's default_dir as default.
        return $prefs->getValue('default_dir');
    }

    /**
     * Retrieve the UID for the Global Address List source.
     *
     * @return string|boolean  The UID or false if none configured.
     */
    public function getGalUid()
    {
        return empty($GLOBALS['conf']['gal']['addressbook'])
            ? false
            : $GLOBALS['conf']['gal']['addressbook'];
    }

    /**
     * Browses through Turba's object tree.
     *
     * @param string $path       The path of the tree to browse.
     * @param array $properties  The item properties to return. Defaults to
     *                           'name', 'icon', and 'browseable'.
     *
     * @return array  Content of the specified path.
     * @throws Turba_Exception
     * @throws Horde_Exception_NotFound
     */
    public function browse($path = '',
                          $properties = array('name', 'icon', 'browseable'))
    {
        global $injector, $registry, $session;

        // Strip off the application name if present
        if (substr($path, 0, 5) == 'turba') {
            $path = substr($path, 5);
        }
        $path = trim($path, '/');

        $results = array();

        if (empty($path)) {
            /* We always provide the "global" folder which contains address
             * book sources that are shared among all users.  Per-user shares
             * are shown in a folder for each respective user. */
            $owners = array(
                'global' => true
            );

            foreach (Turba::listShares() as $share) {
                $owners[$share->get('owner') ? $share->get('owner') : '-system-'] = true;
            }

            $now = time();

            foreach (array_keys($owners) as $owner) {
                if (in_array('name', $properties)) {
                    $results['turba/' . $owner]['name'] = $owner;
                }
                if (in_array('icon', $properties)) {
                    $results['turba/' . $owner]['icon'] = Horde_Themes::img('turba.png');
                }
                if (in_array('browseable', $properties)) {
                    $results['turba/' . $owner]['browseable'] = true;
                }
                if (in_array('contenttype', $properties)) {
                    $results['turba/' . $owner]['contenttype'] = 'httpd/unix-directory';
                }
                if (in_array('contentlength', $properties)) {
                    $results['turba/' . $owner]['contentlength'] = 0;
                }
                if (in_array('modified', $properties)) {
                    // @TODO: Get a real modification date
                    $results['turba/' . $owner]['modified'] = $now;
                }
                if (in_array('created', $properties)) {
                    // @TODO Get a real creation date
                    $results['turba/' . $owner]['created'] = 0;
                }
            }

            return $results;
        }

        $parts = explode('/', $path);

        if (count($parts) == 1) {
            /* We should either have the username that is a valid share owner
             * or 'global'. */
            if (empty($parts[0])) {
                // We need either 'global' or a valid username with shares.
                return array();
            }

            if ($parts[0] == 'global') {
                // The client is requesting a list of global address books.
                $addressbooks = Turba::getAddressBooks();
                foreach ($addressbooks as $addressbook => $info) {
                    if ($info['type'] == 'share') {
                        // Ignore address book shares in the 'global' folder
                        unset($addressbooks[$addressbook]);
                    }
                }
            } else {
                /* Assume $parts[0] is a valid username and we need to list
                 * their shared addressbooks. */
                if (!$session->get('turba', 'has_share')) {
                    // No backends are configured to provide shares
                    return array();
                }
                $addressbooks = $injector->getInstance('Turba_Shares')
                    ->listShares(
                        $registry->getAuth(),
                        array(
                            'attributes' => $parts[0],
                            'perm' => Horde_Perms::READ
                        )
                    );
            }

            $curpath = 'turba/' . $parts[0] . '/';
            $now = time();

            foreach ($addressbooks as $addressbook => $info) {
                if (in_array('name', $properties)) {
                    $results[$curpath . $addressbook]['name'] =
                        sprintf(
                            _("Contacts from %s"),
                            ($info instanceof Horde_Share_Object)
                                ? $info->get('name')
                                : $info['title']
                        );
                }
                if (in_array('icon', $properties)) {
                    $results[$curpath . $addressbook]['icon'] = Horde_Themes::img('turba.png');
                }
                if (in_array('browseable', $properties)) {
                    $results[$curpath . $addressbook]['browseable'] = true;
                }
                if (in_array('contenttype', $properties)) {
                    $results[$curpath . $addressbook]['contenttype'] = 'httpd/unix-directory';
                }
                if (in_array('contentlength', $properties)) {
                    $results[$curpath . $addressbook]['contentlength'] = 0;
                }
                if (in_array('modified', $properties)) {
                    // @TODO: Get a real modification date
                    $results[$curpath . $addressbook]['modified'] = $now;
                }
                if (in_array('created', $properties)) {
                    // @TODO Get a real creation date
                    $results[$curpath . $addressbook]['created'] = 0;
                }
            }

            return $results;
        }

        if (count($parts) == 2) {
            /* The client is requesting all contacts from a given
             * addressbook. */
            if (empty($parts[0]) || empty($parts[1])) {
                /* $parts[0] must be either 'global' or a valid user with
                 * shares; $parts[1] must be an addressbook ID. */
                return array();
            }

            $addressbooks = Turba::getAddressBooks();
            if (!isset($addressbooks[$parts[1]])) {
                // We must have a valid addressbook to continue.
                return array();
            }

            $contacts = $injector->getInstance('Turba_Factory_Driver')->create($parts[1])->search(array());
            $contacts->reset();

            $curpath = 'turba/' . $parts[0] . '/' . $parts[1] . '/';

            while ($contact = $contacts->next()) {
                $key = $curpath . $contact->getValue('__key');
                if (in_array('name', $properties)) {
                    $results[$key]['name'] = Turba::formatName($contact);
                }
                if (in_array('icon', $properties)) {
                    $results[$key]['icon'] = Horde_Themes::img('mime/vcard.png');
                }
                if (in_array('browseable', $properties)) {
                    $results[$key]['browseable'] = false;
                }
                if (in_array('contenttype', $properties)) {
                    $results[$key]['contenttype'] = 'text/x-vcard';
                }
                if (in_array('contentlength', $properties)) {
                    try {
                        $data = $this->export($contact->getValue('__uid'), 'text/x-vcard', $contact->getSource(), null, array('skip_empty' => true));
                    } catch (Turba_Exception $e) {
                        $data = '';
                    }
                    $results[$key]['contentlength'] = strlen($data);
                }
                if (in_array('modified', $properties)) {
                    $results[$key]['modified'] = $this->_modified($contact->getValue('__uid'), $parts[1]);
                }
                if (in_array('created', $properties)) {
                    $results[$key]['created'] = $this->getActionTimestamp($contact->getValue('__uid'), 'add', $parts[1]);
                }
            }

            return $results;
        }

        if (count($parts) == 3) {
            /* The client is requesting an individual contact. */
            $addressbooks = Turba::getAddressBooks();
            if (!isset($addressbooks[$parts[1]])) {
                // We must have a valid addressbook to continue.
                return array();
            }

            // Load the Turba driver.
            $driver = $injector->getInstance('Turba_Factory_Driver')->create($parts[1]);

            $contact = $driver->getObject($parts[2]);

            $result = array(
                'data' => $this->export($contact->getValue('__uid'), 'text/x-vcard', $contact->getSource(), null, array('skip_empty' => true)),
                'mimetype' => 'text/x-vcard'
            );
            $modified = $this->_modified($contact->getValue('__uid'), $parts[1]);
            if (!empty($modified)) {
                $result['mtime'] = $modified;
            }
            return $result;
        }

        throw new Turba_Exception(_("Malformed request."));
    }

    /**
     * Deletes a file from the Turba tree.
     *
     * @param string $path  The path to the file.
     *
     * @return string  The event's UID.
     * @throws Turba_Exception
     */
    public function path_delete($path)
    {
        // Strip off the application name if present
        if (substr($path, 0, 5) == 'turba') {
            $path = substr($path, 5);
        }

        $parts = explode('/', trim($path, '/'));

        if (count($parts) < 3) {
            // Deletes must be on individual contacts.
            throw new Turba_Exception(_("Delete denied."));
        }

        if (!array_key_exists($parts[1], Turba::getAddressBooks())) {
            throw new Turba_Exception(_("Address book does not exist"));
        }

        return $GLOBALS['injector']->getInstance('Turba_Factory_Driver')->create($parts[1])->delete($parts[2]);
    }

    /**
     * Returns an array of UIDs for all contacts that the current user is
     * authorized to see.
     *
     * @param string|array $sources  The name(s) of the source(s) to return
     *                               contacts of. If empty, the current user's
     *                               sync sources or default source are used.
     *
     * @return array  An array of UIDs for all contacts the user can access.
     * @throws Turba_Exception
     */
    public function listUids($sources = null)
    {
        $driver = $GLOBALS['injector']->getInstance('Turba_Factory_Driver');
        $uids = array();

        foreach ($this->_getSources($sources) as $source) {
            try {
                $results = $driver->create($source)->search(array());
            } catch (Turba_Exception $e) {
                throw new Turba_Exception(sprintf(_("Error searching the address book: %s"), $e->getMessage()));
            }

            foreach ($results->objects as $o) {
                if (!$o->isGroup()) {
                    $uids[] = $o->getValue('__uid');
                }
            }
        }

        return $uids;
    }

    /**
     * Returns an array of UIDs for contacts that have had a given action
     * since a certain time.
     *
     * @param string $action         The action to check for - add, modify, or
     *                               delete.
     * @param integer $timestamp     The time to start the search.
     * @param string|array $sources  The source(s) for which to retrieve the
     *                               history.
     * @param integer $end           The optional ending timestamp.
     * @param boolean $isModSeq      If true, $timestamp and $end are
     *                               modification sequences and not timestamps.
     *                               @since 4.1.1
     *
     * @return array  An array of UIDs matching the action and time criteria.
     *
     * @throws Turba_Exception
     */
    public function listBy($action, $timestamp, $sources = null, $end = null, $isModSeq = false)
    {
        $driver = $GLOBALS['injector']->getInstance('Turba_Factory_Driver');
        $history = $GLOBALS['injector']->getInstance('Horde_History');
        $filter = array(
            array(
                'field' => 'action',
                'op' => '=',
                'value' => $action
            )
        );
        $uids = array();

        if (!empty($end) && !$isModSeq) {
            $filter[] = array(
                'field' => 'ts',
                'op' => '<',
                'value' => $end
            );
        }

        foreach ($this->_getSources($sources) as $source) {
            $sdriver = $driver->create($source);
            if (!$isModSeq) {
                $histories = $history->getByTimestamp(
                    '>', $timestamp, $filter,
                    'turba:' . $sdriver->getName()
                );
            } else {
                $histories = $history->getByModSeq(
                    $timestamp, $end, $filter, 'turba:' . $sdriver->getName());
            }

            // Filter out groups
            $nguids = str_replace(
                'turba:' . $sdriver->getName() . ':',
                '',
                array_keys($histories)
            );

            $include = array();
            foreach ($nguids as $uid) {
                if ($action != 'delete') {
                    $list = $sdriver->search(array('__uid' => $uid));
                    if ($list->count()) {
                        $object = $list->next();
                        if ($object->isGroup()) {
                            continue;
                        }
                    }
                }
                $include[] = $uid;
            }

            // Strip leading turba:addressbook:.
            $uids = array_merge($uids, $include);
        }

        return $uids;
    }

    /**
     * Method for obtaining all server changes between two timestamps.
     * Essentially a wrapper around listBy(), but returns an array containing
     * all adds, edits, and deletions.
     *
     * @param integer $start         The starting timestamp
     * @param integer $end           The ending timestamp.
     * @param boolean $isModSeq      If true, $start and $end are modification
     *                               sequences and not timestamps. @since 4.1.1
     * @param string|array $sources  The sources to check. @since 4.2.0
     *
     * @return array  A hash with 'add', 'modify' and 'delete' arrays.
     */
    public function getChanges($start, $end, $isModSeq = false, $sources = null)
    {
        return array(
            'add' => $this->listBy('add', $start, $sources, $end, $isModSeq),
            'modify' => $this->listBy('modify', $start, $sources, $end, $isModSeq),
            'delete' => $this->listBy('delete', $start, $sources, $end, $isModSeq)
        );
    }

    /**
     * Return all changes occuring between the specified modification
     * sequences.
     *
     * @param integer $start         The starting modseq.
     * @param integer $end           The ending modseq.
     * @param string|array $sources  The sources to check. @since 4.2.0
     *
     * @return array  The changes @see getChanges()
     * @since 4.1.1
     */
    public function getChangesByModSeq($start, $end, $sources = null)
    {
        return $this->getChanges($start, $end, true, $sources);
    }

    /**
     * Returns the timestamp of an operation for a given UID and action.
     *
     * @param string $uid            The UID to look for.
     * @param string $action         The action to check for - add, modify, or
     *                               delete.
     * @param string|array $sources  The source(s) for which to retrieve the
     *                               history.
     * @param boolean $modSeq        Request a modification sequence instead of
     *                               timestamp. @since 4.1.1
     *
     * @return integer  The timestamp for this action.
     *
     * @throws Turba_Exception
     */
    public function getActionTimestamp($uid, $action, $sources = null, $modSeq = false)
    {
        $driver = $GLOBALS['injector']->getInstance('Turba_Factory_Driver');
        $history = $GLOBALS['injector']->getInstance('Horde_History');
        $last = 0;

        foreach ($this->_getSources($sources) as $source) {
            if (!$modSeq) {
                $ts = $history->getActionTimestamp(
                    'turba:' . $driver->create($source)->getName() . ':' . $uid,
                    $action);
            } else {
                $ts = $history->getActionModSeq(
                    'turba:' . $driver->create($source)->getName() . ':' . $uid,
                    $action);
            }
            if (!empty($ts) && $ts > $last) {
                $last = $ts;
            }
        }

        return $last;
    }

    /**
     * Return the largest modification sequence from the history backend.
     *
     * @param string $id  Addressbook id to return highest MODSEQ for. If
     *                    null, the highest MODSEQ across all addressbooks is
     *                    returned. @since 4.2.0
     *
     * @return integer  The modseq.
     * @since 4.1.1
     */
    public function getHighestModSeq($id = null)
    {
        $parent = 'turba';
        if (!empty($id)) {
            $parent .= ':' . $id;
        }
        return $GLOBALS['injector']->getInstance('Horde_History')->getHighestModSeq($parent);
    }

    /**
     * Import a contact represented in the specified contentType.
     *
     * @param string $content      The content of the contact.
     * @param string $contentType  What format is the data in? Currently
     *                             supports array, text/directory, text/vcard,
     *                             text/x-vcard, and activesync.
     * @param string $source       The source into which the contact will be
     *                             imported.
     *
     * @return string  The new UID.
     *
     * @throws Turba_Exception
     * @throws Turba_Exception_ObjectExists
     */
    public function import($content, $contentType = 'array', $source = null)
    {
        global $cfgSources, $injector, $prefs;

        /* Get default address book from user preferences. */
        if (empty($source) &&
            !($source = $prefs->getValue('default_dir'))) {
            // On new installations default_dir is not set. Try default
            // addressbook if it's editable. Otherwise use first editable
            // addressbook.
            $edit_sources = Turba::getAddressBooks(Horde_Perms::EDIT);
            $default_source = Turba::getDefaultAddressbook();
            if (isset($edit_sources[$default_source])) {
                // use default addressbook
                $source = $default_source;
            } else {
                // Use first writable source
                $source = reset($edit_sources);
            }
        }

        // Check existence of and permissions on the specified source.
        if (!isset($cfgSources[$source])) {
            throw new Turba_Exception(sprintf(_("Invalid address book: %s"), $source));
        }

        $driver = $injector
            ->getInstance('Turba_Factory_Driver')
            ->create($source);

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

        if (!($content instanceof Horde_Icalendar_Vcard)) {
            switch ($contentType) {
            case 'activesync':
                $content = $driver->fromASContact($content);
                break;

            case 'array':
                if (!isset($content['emails']) && isset($content['email'])) {
                    $content['emails'] = $content['email'];
                }
                break;

            case 'text/x-vcard':
            case 'text/vcard':
            case 'text/directory':
                $iCal = new Horde_Icalendar();
                if (!$iCal->parsevCalendar($content)) {
                    throw new Turba_Exception(_("There was an error importing the iCalendar data."));
                }

                switch ($iCal->getComponentCount()) {
                case 0:
                    throw new Turba_Exception(_("No vCard data was found."));

                case 1:
                    $content = $iCal->getComponent(0);
                    break;

                default:
                    $ids = array();

                    foreach ($iCal->getComponents() as $c) {
                        if ($c instanceof Horde_Icalendar_Vcard) {
                            $content = $driver->toHash($c);
                            $result = $driver->search($content);
                            if (count($result)) {
                                continue;
                            }

                            $ids[] = $driver->add($content);
                        }
                    }

                    return $ids;
                }
                break;

            default:
                throw new Turba_Exception(sprintf(_("Unsupported Content-Type: %s"), $contentType));
            }
        }

        if ($content instanceof Horde_Icalendar_Vcard) {
            $content = $driver->toHash($content);
        }

        // Check if the entry already exists in the data source.
        $result = $driver->search($content);
        if (count($result)) {
            throw new Turba_Exception_ObjectExists(_("Already Exists"));
        }

        // We can't use $object->setValue() here since that cannot be used
        // with composite fields.
        $hooks = $injector->getInstance('Horde_Core_Hooks');
        if ($hooks->hookExists('encode_attribute', 'turba')) {
            foreach ($content as $attribute => &$value) {
                try {
                    $value = $hooks->callHook(
                        'encode_attribute',
                        'turba',
                        array($attribute, $value, null, null)
                    );
                } catch (Turba_Exception $e) {}
            }
        }
        $result = $driver->add($content);

        return $driver->getObject($result)->getValue('__uid');
    }

    /**
     * Export a contact, identified by UID, in the requested contentType.
     *
     * @param string $uid            Identify the contact to export.
     * @param mixed $contentType     What format should the data be in?
     *   - text/directory: Returns RFC2426 vcard3.0
     *   - text/vcard:     Returns RFC2426 vcard3.0
     *   - text/x-vcard:   Returns imc.org vcard 2.1 format.
     *   - array:          Returns a raw array
     *   - activesync:     Returns a Horde_ActiveSync_Message_Contact:: object
     * @param string|array $sources  The source(s) from which the contact will
     *                               be exported.
     * @param array $fields          Hash of field names and
     *                               Horde_SyncMl_Property properties with the
     *                               requested fields.
     * @param array $options         Any additional options to be passed to the
     *                               exporter. Currently supported:
     *   - skip_empty:       (boolean) {text/vcard or text/x-vcard} Set to
     *                       true to not output empty properties.
     *                       DEFAULT: false.
     *   - protocolversion:  (float) {activesync} The EAS version to support
     *                       DEFAULT: 2.5
     *   - bodyprefs:        (array) {activesync} A BODYPREFERENCE array.
     *                       DEFAULT: none (No body prefs enforced).
     *   - truncation:       (integer) {activesync} Truncate event body to this
     *                       length.
     *                       DEFAULT: none (No truncation).
     *
     *
     * @return mixed  The requested data.
     * @throws Turba_Exception
     */
    public function export($uid, $contentType, $sources = null, $fields = null, array $options = array())
    {
        if (empty($uid)) {
            throw new Turba_Exception(_("Invalid ID"));
        }

        $driver = $GLOBALS['injector']->getInstance('Turba_Factory_Driver');

        foreach ($this->_getSources($sources) as $source) {
            $sdriver = $driver->create($source);

            if (!$sdriver->hasPermission(Horde_Perms::READ)) {
                continue;
            }

            $result = $sdriver->search(array('__uid' => $uid));
            if (count($result) == 0) {
                continue;
            } elseif (count($result) > 1) {
                throw new Turba_Exception(sprintf("Internal Horde Error: multiple Turba objects with same objectId %s.", $uid));
            }

            $version = '3.0';
            list($contentType,) = explode(';', $contentType);

            switch ($contentType) {
            case 'text/x-vcard':
                $version = '2.1';
                // Fall-through

            case 'text/vcard':
            case 'text/directory':
                $export = '';
                foreach ($result->objects as $obj) {
                    $vcard = $sdriver->tovCard($obj, $version, $fields, !empty($options['skip_empty']));
                    /* vCards are not enclosed in
                     * BEGIN:VCALENDAR..END:VCALENDAR.  Export the individual
                     * cards instead. */
                    $export .= $vcard->exportvCalendar();
                }
                return $export;

            case 'array':
                $attributes = array();
                foreach ($result->objects as $object) {
                    foreach (array_keys($GLOBALS['cfgSources'][$source]['map']) as $field) {
                        $attributes[$field] = $object->getValue($field);
                    }
                }
                return $attributes;

            case 'activesync':
                foreach ($result->objects as $object) {
                    $return = $object;
                }
                return $sdriver->toASContact($return, $options);

            default:
                throw new Turba_Exception(sprintf(_("Unsupported Content-Type: %s"), $contentType));
            }
        }

        throw new Turba_Exception(sprintf(_("Object %s not found."), $uid));
    }

    /**
     * Exports the user's own contact as a vCard string.
     *
     * @return string  The requested vCard data.
     * @throws Turba_Exception
     */
    public function ownVCard()
    {
        $contact = $this->getOwnContactObject();

        $vcard = $GLOBALS['injector']->getInstance('Turba_Factory_Driver')->create($contact['source'])->tovCard($contact['contact'], '3.0', null, true);
        $vcard->setAttribute('VERSION', '3.0');

        return $vcard->exportvCalendar();
    }

    /**
     * Export the user's own contact as a hash.
     *
     * @return array  The contact hash.
     * @throws Turba_Exception
     */
    public function ownContact()
    {
        $contact = $this->getOwnContactObject();
        return $contact['contact']->getAttributes();
    }

    /**
     * Helper function to return the user's own contact object
     *
     * @return array  An array containing the following keys:
     *   - contact: (Turba_Object) Object representing the user's own contact.
     *   - source: (string) The source of the user's own contact.
     * @throws Turba_Exception
     */
    public function getOwnContactObject()
    {
        $own_contact = $GLOBALS['prefs']->getValue('own_contact');
        if (empty($own_contact)) {
            throw new Turba_Exception(_("You didn't mark a contact as your own yet."));
        }
        @list($source, $id) = explode(';', $own_contact);

        if (!isset($GLOBALS['cfgSources'][$source])) {
            throw new Turba_Exception(_("The address book with your own contact doesn't exist anymore."));
        }

        $driver = $GLOBALS['injector']->getInstance('Turba_Factory_Driver')->create($source);

        if (!$driver->hasPermission(Horde_Perms::READ)) {
            throw new Turba_Exception(_("You don't have sufficient permissions to read the address book that contains your own contact."));
        }

        try {
            $contact = $driver->getObject($id);
        } catch (Horde_Exception_NotFound $e) {
            throw new Turba_Exception(_("Your own contact cannot be found in the address book."));
        }

        return array(
            'contact' => $contact,
            'source'=> $source
        );
    }

    /**
     * Deletes a contact identified by UID.
     *
     * @param string|array $uid      Identify the contact to delete, either a
     *                               single UID or an array.
     * @param string|array $sources  The source(s) from which the contact will
     *                               be deleted.
     *
     * @return boolean  Success or failure.
     * @throws Turba_Exception
     */
    public function delete($uid, $sources = null)
    {
        if (empty($uid)) {
            throw new Turba_Exception(_("Invalid ID"));
        }

        // Handle an array of UIDs for convenience of deleting multiple
        // contacts at once.
        if (is_array($uid)) {
            foreach ($uid as $g) {
                if (!$this->delete($g, $sources)) {
                    return false;
                }
            }

            return true;
        }

        $driver = $GLOBALS['injector']->getInstance('Turba_Factory_Driver');

        foreach ($this->_getSources($sources) as $source) {
            $sdriver = $driver->create($source);

            if (!$GLOBALS['registry']->isAdmin() &&
                !$sdriver->hasPermission(Horde_Perms::DELETE)) {
                continue;
            }

            // If the objectId isn't in $source in the first place, just
            // return true. Otherwise, try to delete it and return success or
            // failure.
            $result = $sdriver->search(array('__uid' => $uid));
            if (count($result) != 0) {
                $r = $result->objects[0];
                try {
                    $sdriver->delete($r->getValue('__key'));
                } catch (Turba_Exception $e) {
                    return false;
                }
            }
        }

        return true;
    }

    /**
     * Replaces the contact identified by UID with the content represented in
     * the specified contentType.
     *
     * @param string $uid            Idenfity the contact to replace.
     * @param mixed  $content        The content of the contact.
     * @param string $contentType    What format is the data in? Currently
     *                               supports array, text/directory,
     *                               text/vcard, text/x-vcard and activesync.
     * @param string|array $sources  The source(s) where the contact will be
     *                               replaced.
     *
     * @return boolean  Success or failure.
     * @throws Turba_Exception
     */
    public function replace($uid, $content, $contentType, $sources = null)
    {
        if (empty($uid)) {
            throw new Turba_Exception(_("Invalid contact unique ID"));
        }

        $driver = $GLOBALS['injector']->getInstance('Turba_Factory_Driver');

        foreach ($this->_getSources($sources) as $source) {
            $sdriver = $driver->create($source);

            // Check permissions.
            if (!$sdriver->hasPermission(Horde_Perms::EDIT)) {
                continue;
            }

            $result = $sdriver->search(array('__uid' => $uid));
            if (!count($result)) {
                continue;
            } elseif (count($result) > 1) {
                throw new Turba_Exception(sprintf(_("Multiple contacts found with same unique ID %s."), $uid));
            }

            $object = $result->objects[0];

            switch ($contentType) {
            case 'activesync':
                $content = $sdriver->fromASContact($content);
                foreach ($content as $attribute => $value) {
                    if ($attribute != '__key') {
                        $object->setValue($attribute, $value);
                    }
                }
                return $object->store();

            case 'array':
                break;

            case 'text/x-vcard':
            case 'text/vcard':
            case 'text/directory':
                $iCal = new Horde_Icalendar();
                if (!$iCal->parsevCalendar($content)) {
                    throw new Turba_Exception(_("There was an error importing the iCalendar data."));
                }

                switch ($iCal->getComponentCount()) {
                case 0:
                    throw new Turba_Exception(_("No vCard data was found."));

                case 1:
                    $content = $sdriver->toHash($iCal->getComponent(0));
                    break;

                default:
                    throw new Turba_Exception(_("Only one vcard supported."));
                }
                break;

            default:
                throw new Turba_Exception(sprintf(_("Unsupported Content-Type: %s"), $contentType));
            }

            foreach ($content as $attribute => $value) {
                if ($attribute != '__key') {
                    $object->setValue($attribute, $value);
                }
            }

            return $object->store();
        }

        throw new Turba_Exception(sprintf(_("Object %s not found."), $uid));
    }

    /**
     * Returns a contact search result.
     *
     * @param mixed $names  The search filter values.
     * @param array $opts   Optional parameters:
     *   - customStrict: (array) An array of fields that must match exactly.
     *                   DEFAULT: None
     *   - fields: (array) The fields to search on.
     *             DEFAULT: All fields
     *   - forceSource: (boolean) Whether to use the specified sources, even
     *                  if they have been disabled in the preferences?
     *                  DEFAULT: false
     *   - matchBegin: (boolean) Match word boundaries only?
     *                 DEFAULT: false
     *   - returnFields: Only return these fields.
     *                   DEFAULT: Return all fields.
     *   - rfc822Return: Return a Horde_Mail_Rfc822_List object.
     *                   DEFAULT: Returns an array of search results.
     *   - sources: (array) The sources to search in.
     *              DEFAULT: Search the user's default address book
     *   - count_only: (boolean) If true, only return the count of matching
     *                           results.
     *                 DEFAULT: false (Return the full data set).
     *
     * @return mixed  Either a hash containing the search results or a
     *                Rfc822 List object (if 'rfc822Return' is true).
     * @throws Turba_Exception
     */
    public function search($names = null, array $opts = array())
    {
        global $attributes, $cfgSources, $injector;

        $opts = array_merge(array(
            'fields' => array(),
            'forceSource' => false,
            'matchBegin' => false,
            'returnFields' => array(),
            'rfc822Return' => false,
            'sources' => array(),
            'customStrict' => array(),
            'count_only' => false,
        ), $opts);

        $results = !empty($opts['count_only'])
            ? 0
            : (empty($opts['rfc822Return'])
                ? array()
                : new Horde_Mail_Rfc822_List());

        if (!isset($cfgSources) ||
            !is_array($cfgSources) ||
            !count($cfgSources) ||
            is_null($names)) {
            return $results;
        }

        if (!is_array($names)) {
            $names = array($names);
        }

        if (!$opts['forceSource']) {
            // Make sure the selected source is activated in Turba.
            $addressbooks = array_keys(Turba::getAddressBooks());
            foreach (array_keys($opts['sources']) as $id) {
                if (!in_array($opts['sources'][$id], $addressbooks)) {
                    unset($opts['sources'][$id]);
                }
            }
        }

        // ...and ensure the default source is used as a default.
        if (!count($opts['sources'])) {
            $opts['sources'] = array(Turba::getDefaultAddressbook());
        }

        $driver = $injector->getInstance('Turba_Factory_Driver');
        foreach ($opts['sources'] as $source) {
            // Skip invalid sources -or-
            // skip sources that aren't browseable if the search is empty.
            if (!isset($cfgSources[$source]) ||
                (empty($cfgSources[$source]['browse']) &&
                 (!count($names) ||
                  ((count($names) == 1) && empty($names[0]))))) {

                continue;
            }

            $sdriver = $driver->create($source);

            foreach ($names as $name) {
                $trimname = trim($name);
                $out = $criteria = array();
                unset($tname);

                if (strlen($trimname)) {
                    if (isset($opts['fields'][$source])) {
                        foreach ($opts['fields'][$source] as $field) {
                            $criteria[$field] = $trimname;
                        }
                    }
                    if (!count($criteria)) {
                        $criteria['name'] = $trimname;
                    }
                }

                try {
                    $search = $sdriver->search(
                        $criteria,
                        Turba::getPreferredSortOrder(),
                        'OR',
                        $opts['returnFields'],
                        $opts['customStrict'],
                        $opts['matchBegin'],
                        $opts['count_only']
                    );
                } catch (Exception $e) {
                    continue;
                }

                if ($opts['count_only']) {
                    $results += $search;

                    continue;
                } elseif (!($search instanceof Turba_List)) {
                    continue;
                }

                $rfc822 = new Horde_Mail_Rfc822();

                while ($ob = $search->next()) {
                    $emails = $seen = array();

                    if ($ob->isGroup()) {
                        /* Is a distribution list. */
                        $members = $ob->listMembers();
                        if (!($members instanceof Turba_List) ||
                            !count($members)) {
                            continue;
                        }

                        $listatt = $ob->getAttributes();
                        $listName = $ob->getValue('name');

                        while ($ob = $members->next()) {
                            foreach (array_keys($ob->getAttributes()) as $key) {
                                $value = $ob->getValue($key);
                                if (empty($value)) {
                                    continue;
                                }

                                $seen_key = trim(Horde_String::lower($ob->getValue('name'))) . trim(Horde_String::lower(is_array($value) ? $value['load']['file'] : $value));

                                if (isset($attributes[$key]) &&
                                    ($attributes[$key]['type'] == 'email') &&
                                    empty($seen[$seen_key])) {
                                    $emails[] = $value;
                                    $seen[$seen_key] = true;
                                }
                            }
                        }

                        if (empty($opts['rfc822Return'])) {
                            $out[] = array(
                                'email' => implode(', ', $emails),
                                'id' => $listatt['__key'],
                                'name' => $listName,
                                'source' => $source
                            );
                        } else {
                            $results->add(new Horde_Mail_Rfc822_Group($listName, $emails));
                        }
                    } else {
                        /* Not a group. */
                        $att = array(
                            '__key' => $ob->getValue('__key')
                        );

                        foreach (array_keys($ob->driver->getCriteria()) as $key) {
                            $att[$key] = $ob->getValue($key);
                        }

                        $email = new Horde_Mail_Rfc822_List();

                        $display_name = ($ob->hasValue('name') || !isset($ob->driver->alternativeName))
                            ? Turba::formatName($ob)
                            : $ob->getValue($ob->driver->alternativeName);
                        unset($tdisplay_name);

                        foreach (array_keys($att) as $key) {
                            if ($ob->getValue($key) &&
                                isset($attributes[$key]) &&
                                ($attributes[$key]['type'] == 'email')) {
                                $e_val = $ob->getValue($key);

                                if (strlen($trimname)) {
                                    /* Ticket #12480: Don't return email if it
                                     * doesn't contain the search string, since
                                     * an entry can contain multiple e-mail
                                     * fields. Return all e-mails if it
                                     * occurs in the name. */
                                    if (!isset($tname)) {
                                        $tname = Horde_String_Transliterate::toAscii($name);
                                    }
                                    if (!isset($tdisplay_name)) {
                                        $tdisplay_name = Horde_String_Transliterate::toAscii($display_name);
                                    }

                                    $add = ((Horde_String::ipos(Horde_String_Transliterate::toAscii($e_val), $tname) !== false) ||
                                            (Horde_String::ipos($tdisplay_name, $tname) !== false));
                                } else {
                                    $add = true;
                                }

                                if ($add) {
                                    // Multiple addresses support
                                    $email->add($rfc822->parseAddressList($e_val, array(
                                        'limit' => (isset($attributes[$key]['params']) && is_array($attributes[$key]['params']) && !empty($attributes[$key]['params']['allow_multi'])) ? 0 : 1
                                    )));
                                }
                            }
                        }

                        if (count($email)) {
                            foreach ($email as $val) {
                                $seen_key = trim(Horde_String::lower($display_name)) . '/' . Horde_String::lower($val->bare_address);
                                if (empty($seen[$seen_key])) {
                                    $seen[$seen_key] = true;
                                    if (empty($opts['rfc822Return'])) {
                                        $emails[] = $val->bare_address;
                                    } else {
                                        $val->personal = $display_name;
                                        $results->add($val);
                                    }
                                }
                            }
                        } elseif (empty($opts['rfc822Return'])) {
                            $emails[] = null;
                        }

                        if (empty($opts['rfc822Return'])) {
                            foreach ($emails as $val) {
                                $out[] = array_merge($att, array(
                                    '__type' => 'Object',
                                    'email' => $val,
                                    'id' => $att['__key'],
                                    'name' => $display_name,
                                    'source' => $source
                                ));
                            }
                        }
                    }
                }

                if (!empty($out)) {
                    $results[$name] = $out;
                }
            }
        }

        return $results;
    }

    /**
     * Retrieves a contact.
     *
     * @param string $source    The source name where the contact is stored
     * @param string $objectId  The unique id of the contact to retrieve
     *
     * @return array  The retrieved contact.
     * @throws Turba_Exception
     * @throws Horde_Exception_NotFound
     */
    public function getContact($source = null, $objectId = '')
    {
        global $cfgSources;

        if (!isset($cfgSources) ||
            !is_array($cfgSources) ||
            !isset($cfgSources[$source])) {
            return array();
        }

        $attributes = array();
        $object = $GLOBALS['injector']->getInstance('Turba_Factory_Driver')->create($source)->getObject($objectId);

        foreach (array_keys($cfgSources[$source]['map']) as $field) {
            $attributes[$field] = $object->getValue($field);
        }

        return $attributes;
    }

    /**
     * Retrieves a set of contacts from a single source.
     *
     * @param string $source    The source name where the contact is stored
     * @param array $objectIds  The unique ids of the contact to retrieve.
     *
     * @return array  The retrieved contact.
     * @throws Turba_Exception
     * @throws Horde_Exception_NotFound
     */
    public function getContacts($source = '', array $objectIds = array())
    {
        global $cfgSources;

        if (!isset($cfgSources) ||
            !is_array($cfgSources) ||
            !isset($cfgSources[$source])) {
            return array();
        }

        if (!is_array($objectIds)) {
            $objectIds = array($objectIds);
        }

        $objects = $GLOBALS['injector']->getInstance('Turba_Factory_Driver')->create($source)->getObjects($objectIds);
        $results = array();

        foreach ($objects as $object) {
            $attributes = array();
            foreach (array_keys($cfgSources[$source]['map']) as $field) {
                $attributes[$field] = $object->getValue($field);
            }
            $results[] = $attributes;
        }

        return $results;
    }

    /**
     * Retrieves a list of all possible values of a field in specified
     * source(s).
     *
     * @param string $field   Field name to check.
     * @param array $sources  Array containing the sources to look in.
     *
     * @return array  An array of fields and possible values.
     * @throws Turba_Exception
     */
    public function getAllAttributeValues($field = '',
                                          array $sources = array())
    {
        global $cfgSources;

        if (!isset($cfgSources) || !is_array($cfgSources)) {
            return array();
        }

        if (!count($sources)) {
            $sources = array(Turba::getDefaultAddressbook());
        }

        $driver = $GLOBALS['injector']->getInstance('Turba_Factory_Driver');
        $results = array();

        foreach ($sources as $source) {
            if (isset($cfgSources[$source])) {
                $res = $driver->create($source)->search(array());
                if (!($res instanceof Turba_List)) {
                    throw new Turba_Exception(_("Search failed"));
                }

                while ($ob = $res->next()) {
                    if ($ob->hasValue($field)) {
                        $results[$source . ':' . $ob->getValue('__key')] = array(
                            'email' => $ob->getValue('email'),
                            'name' => $ob->getValue('name'),
                            $field => $ob->getValue($field)
                        );
                    }
                }
            }
        }

        return $results;
    }

    /**
     * Retrieves a list of available time objects categories.
     *
     * @return array  An array of all configured time object categories.
     */
    public function listTimeObjectCategories()
    {
        $categories = array();

        foreach ($GLOBALS['attributes'] as $key => $attribute) {
            if (($attribute['type'] == 'monthdayyear') &&
                !empty($attribute['time_object_label'])) {
                foreach ($GLOBALS['cfgSources'] as $srcKey => $source) {
                    if (!empty($source['map'][$key])) {
                        $categories[$key . '/'. $srcKey] =array(
                            'title' => sprintf(_("%s in %s"), $attribute['time_object_label'], $source['title']),
                            'type' => 'share');
                    }
                }
            }
        }

        return $categories;
    }

    /**
     * Lists birthdays and/or anniversaries as time objects.
     *
     * @param array $time_categories  The time categories (from
     *                                listTimeObjectCategories) to list.
     * @param mixed $start            The start date of the period.
     * @param mixed $end              The end date of the period.
     *
     * @return array  An array of timeObject results.
     * @throws Turba_Exception
     */
    public function listTimeObjects($time_categories, $start, $end)
    {
        $start = new Horde_Date($start);
        $end = new Horde_Date($end);

        $driver = $GLOBALS['injector']->getInstance('Turba_Factory_Driver');
        $objects = array();

        foreach ($time_categories as $category) {
            list($category, $source) = explode('/', $category, 2);
            $objects = array_merge($objects, $driver->create($source)->listTimeObjects($start, $end, $category));
        }

        return $objects;
    }

    /**
     * Returns the client source name.
     *
     * @return string  The name of the source to use with the clients api.
     */
    public function getClientSource()
    {
        return empty($GLOBALS['conf']['client']['addressbook'])
            ? false
            : $GLOBALS['conf']['client']['addressbook'];
    }

    /**
     * Returns the available client fields.
     *
     * @return array  An array describing the fields.
     */
    public function clientFields()
    {
        return $this->fields($GLOBALS['conf']['client']['addressbook']);
    }

    /**
     * Returns a contact from the client source.
     *
     * @param string $objectId  Client unique ID.
     *
     * @return array  Array of client data.
     * @throws Turba_Exception
     */
    public function getClient($objectId = '')
    {
        return $this->getContact($GLOBALS['conf']['client']['addressbook'], $objectId);
    }

    /**
     * Returns mulitple contacts from the client source.
     *
     * @param array $objectIds  client unique ids.
     *
     * @return array  An array of clients data.
     * @throws Turba_Exception
     */
    public function getClients($objectIds = array())
    {
        return $this->getContacts($GLOBALS['conf']['client']['addressbook'], $objectIds);
    }

    /**
     * Adds a client to the client source.
     *
     * @param array $attributes  Array containing the client attributes.
     *
     * @return boolean
     */
    public function addClient(array $attributes = array())
    {
        return $this->import($attributes, 'array', $this->getClientSource());
    }

    /**
     * Updates client data.
     *
     * @param string $objectId   The unique id of the client.
     * @param array $attributes  An array of client attributes.
     *
     * @return boolean
     */
    public function updateClient($objectId = '', array $attributes = array())
    {
        return $this->replace($this->getClientSource() . ':' . $objectId, $attributes, 'array');
    }

    /**
     * Deletes a client
     *
     * @param string $objectId  The unique id of the client
     *
     * @return boolean
     */
    public function deleteClient($objectId = '')
    {
        return $this->delete($this->getClientSource() . ':' . $objectId);
    }

    /**
     * Search for clients.
     *
     * @param array $names         The search filter values.
     * @param array $fields        The fields to search in.
     * @param boolean $matchBegin  Match word boundaries only.
     *
     * @return array  A hash containing the search results.
     * @throws Turba_Exception
     */
    public function searchClients(array $names = array(),
                                  array $fields = array(),
                                  $matchBegin = false)
    {
        $abook = $this->getClientSource();
        return $this->search(
            $names,
            array('sources' => array($abook),
                  'fields' => array($abook => $fields),
                  'matchBegin' => $matchBegin,
                  'forceSource' => true)
        );
    }

    /**
     * Sets the value of the specified attribute of a contact
     *
     * @param string|array $address  Contact email address(es).
     * @param string $name           Contact name.
     * @param string $field          Field to update.
     * @param string $value          Field value to set.
     * @param string $source         Contact source.
     *
     * @throws Turba_Exception
     */
    public function addField($address = '', $name = '', $field = '',
                             $value = '', $source = '')
    {
        if (is_array($address)) {
            $e = null;
            $success = 0;

            foreach ($address as $tmp) {
                try {
                    $this->addField($tmp, $name, $field, $value, $source);
                    ++$success;
                } catch (Exception $e) {}
            }

            if ($e) {
                if ($success) {
                    throw new Turba_Exception(sprintf(ngettext("Added or updated %d contact, but at least one contact failed:", "Added or updated %d contacts, but at least one contact failed:", $success), $success) . ' ' . $e->getMessage());
                } else {
                    throw $e;
                }
            }
        }

        global $cfgSources;

        if (empty($source) || !isset($cfgSources[$source])) {
            throw new Turba_Exception(sprintf(_("Invalid address book: %s"), $source));
        }

        if (empty($address)) {
            throw new Turba_Exception(_("Invalid email"));
        }

        if (empty($name)) {
            throw new Turba_Exception(_("Invalid name"));
        }

        if (empty($value)) {
            throw new Turba_Exception(_("Invalid entry"));
        }

        $driver = $GLOBALS['injector']->getInstance('Turba_Factory_Driver')->create($source);

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

        try {
            $res = $driver->search(array('email' => trim($address)), null, 'AND');
        } catch (Turba_Exception $e) {
            throw new Turba_Exception(sprintf(_("Search failed: %s"), $res->getMessage()));
        }

        if (count($res) > 1) {
            try {
                $res2 = $driver->search(array('email' => trim($address), 'name' => trim($name)), null, 'AND');
            } catch (Turba_Exception $e) {
                throw new Turba_Exception(sprintf(_("Search failed: %s"), $e->getMessage()));
            }

            if (!count($res2)) {
                throw new Turba_Exception(sprintf(_("Multiple persons with address [%s], but none with name [%s] already exist"), trim($address), trim($name)));
            }

            try {
                $res3 = $driver->search(array('email' => $address, 'name' => $name, $field => $value));
            } catch (Turba_Exception $e) {
                throw new Turba_Exception(sprintf(_("Search failed: %s"), $e->getMessage()));
            }

            if (count($res3)) {
                throw new Turba_Exception(sprintf(_("This person already has a %s entry in the address book"), $field));
            }

            $ob = $res2->next();
            $ob->setValue($field, $value);
            $ob->store();
        } elseif (count($res) == 1) {
            try {
                $res4 = $driver->search(array('email' => $address, $field => $value));
            } catch (Turba_Exception $e) {
                throw new Turba_Exception(sprintf(_("Search failed: %s"), $e->getMessage()));
            }

            if (count($res4)) {
                throw new Turba_Exception(sprintf(_("This person already has a %s entry in the address book"), $field));
            }

            $ob = $res->next();
            $ob->setValue($field, $value);
            $ob->store();
        } else {
            $driver->add(array('email' => $address, 'name' => $name, $field => $value, '__owner' => $GLOBALS['registry']->getAuth()));
        }
    }

    /**
     * Returns a field value.
     *
     * @param string $address    Contact email address.
     * @param string $field      Field to get.
     * @param array $sources     Sources to check.
     * @param boolean $strict    Match the email address strictly.
     * @param boolean $multiple  Return more than one entry if found and true,
     *                           return an error if this is false.
     *
     * @return array  An array of field value(s).
     * @throws Turba_Exception
     */
    public function getField($address = '', $field = '', $sources = array(),
                             $strict = false, $multiple = false)
    {
        global $cfgSources;

        if (empty($address)) {
            throw new Turba_Exception(_("Invalid email"));
        }

        if (!isset($cfgSources) || !is_array($cfgSources)) {
            return array();
        }

        if (!count($sources)) {
            $sources = array(Turba::getDefaultAddressbook());
        }

        $driver = $GLOBALS['injector']->getInstance('Turba_Factory_Driver');
        $result = array();

        foreach ($sources as $source) {
            if (!isset($cfgSources[$source])) {
                continue;
            }

            $sdriver = $driver->create($source);
            $criterium = array('email' => $address);
            if (!isset($sdriver->map['email'])) {
                if (isset($sdriver->map['emails'])) {
                    $criterium = array('emails' => $address);
                } else {
                    continue;
                }
            }

            try {
                $list = $sdriver->search($criterium, null, 'AND', array(), $strict ? array('email') : array());
            } catch (Turba_Exception $e) {
                Horde::log($e, 'ERR');
            }

            if ($list instanceof Turba_List) {
                while ($ob = $list->next()) {
                    if ($ob->hasValue($field)) {
                        $result[] = $ob->getValue($field);
                    }
                }
            }
        }

        if (count($result) > 1) {
            if ($multiple) {
                return $result;
            } else {
                throw new Turba_Exception(_("More than 1 entry found"));
            }
        } elseif (empty($result)) {
            throw new Turba_Exception(sprintf(_("No %s entry found for %s"), $field, $address));
        }

        return reset($result);
    }

    /**
     * Deletes a field value.
     *
     * @param string $address  Contact email address.
     * @param string $field    Field to delete value for.
     * @param array $sources   Sources to delete value from.
     *
     * @throws Turba_Exception
     */
    public function deleteField($address = '', $field = '', $sources = array())
    {
        global $cfgSources;

        if (!strlen($address)) {
            throw new Turba_Exception(_("Invalid email"));
        }

        if (!isset($cfgSources) || !is_array($cfgSources)) {
            return;
        }

        if (count($sources) == 0) {
            $sources = array(Turba::getDefaultAddressbook());
        }

        $driver = $GLOBALS['injector']->getInstance('Turba_Factory_Driver');
        $success = false;

        foreach ($sources as $source) {
            if (isset($cfgSources[$source])) {
                $sdriver = $driver->create($source);
                if (!$sdriver->hasPermission(Horde_Perms::EDIT)) {
                    continue;
                }

                $res = $sdriver->search(array('email' => $address));
                if ($res instanceof Turba_List) {
                    if (count($res) == 1) {
                        $ob = $res->next();
                        if (is_object($ob) && $ob->hasValue($field)) {
                            $ob->setValue($field, '');
                            $ob->store();
                            $success = true;
                        }
                    }
                }
            }
        }

        if (!$success) {
            throw new Turba_Exception(sprintf(_("No %s entry found for %s"), $field, $address));
        }
    }

    /**
     * Obtain an array of $cfgSource entries matching the filter criteria.
     *
     * @param type $filter  A single key -> value hash to filter the sources.
     *
     * @return array
     */
    public function getSourcesConfig($filter = array())
    {
        $results = array();

        if (!empty($filter)) {
            foreach (Turba::availableSources() as $key => $source) {
                $curr = current(array_keys($filter));
                if (!empty($source[$curr]) &&
                    ($source[$curr] == current($filter))) {
                    $results[$key] = $source;
                }
            }
        }

        return $results;
    }

    /**
     * Lists all shares the current user has access to.
     *
     * @param integer $perms
     *
     * @return  array of Turba_Share objects.
     */
    public function listShares($perms = Horde_Perms::READ)
    {
        return Turba::listShares(true, $perms);
    }

    /**
     * GroupObject API - Lists all turba lists for the current user that can
     * be treated as Horde_Group objects.
     *
     * @return array  A hash of all visible groups in the form of
     *                group_id => group_name
     * @throws Horde_Exception
     */
    public function listUserGroupObjects()
    {
        $groups = $owners = array();

        // Only turba's SQL based sources can act as Horde_Groups
        $sources = $this->getSourcesConfig(array('type' => 'sql'));

        foreach ($sources as $key => $source) {
            // Each source could have a different database connection
            $db[$key] = empty($source['params']['sql'])
                    ? $GLOBALS['injector']->getInstance('Horde_Db_Adapter')
                    : $GLOBALS['injector']->getInstance('Horde_Core_Factory_Db')->create('turba', $source['params']['sql']);

            if ($source['use_shares']) {
                if (empty($contact_shares)) {
                    $contact_shares = $this->listShares(Horde_Perms::SHOW);
                }
                foreach ($contact_shares as $id => $share) {
                    $params = @unserialize($share->get('params'));
                    if ($params['source'] == $key) {
                        $owners[] = $params['name'];
                    }
                }
                if (!$owners) {
                    return array();
                }
            } else {
                $owners = array($GLOBALS['registry']->getAuth());
            }

            $owner_ids = array();
            foreach ($owners as $owner) {
                $owner_ids[] = $db[$key]->quoteString($owner);
            }

            $sql = 'SELECT ' . $source['map']['__key'] . ', ' . $source['map'][$source['list_name_field']]
                . '  FROM ' . $source['params']['table'] . ' WHERE '
                . $source['map']['__type'] . ' = \'Group\' AND '
                . $source['map']['__owner'] . ' IN (' . implode(',', $owner_ids ) . ')';

            try {
                $results = $db[$key]->selectAssoc($sql);
            } catch (Horde_Db_Exception $e) {
                throw new Horde_Exception(_("Server error when performing search."));
            }

            foreach ($results as $id => $name) {
                $groups[$key . ':' . $id] = $name;
            }
        }

        return $groups;
    }

    /**
     * Returns all contact groups.
     *
     * @return array  A list of group hashes.
     * @throws Turba_Exception
     */
    public function getGroupObjects()
    {
        $ret = array();

        foreach ($this->getSourcesConfig(array('type' => 'sql')) as $key => $source) {
            if (empty($source['map']['__type'])) {
                continue;
            }

            list($db, $sql) = $this->_getGroupObject($source, 'Group');

            try {
                $results = $db->selectAll($sql);
            } catch (Horde_Db_Exception $e) {
                throw new Horde_Exception(_("Server error when performing search."));
            }

            foreach ($results as $row) {
                /* name is a reserved word in Postgresql (at a minimum). */
                $row['name'] = $row['lname'];
                unset($row['lname']);
                $ret[$key . ':' . $row['id']] = $row;
            }
        }

        return $ret;
    }

    /**
     * Returns all contact groups that the specified user is a member of.
     *
     * @param string $user           The user.
     * @param boolean $parentGroups  Include user as a member of the any
     *                               parent group as well.
     *
     * @return array  An array of group identifiers that the specified user is
     *                a member of.
     * @throws Horde_Exception
     */
    public function getGroupMemberships($user, $parentGroups = false)
    {
        $memberships = array();

        foreach ($this->getGroupObjects() as $id => $list) {
            if (in_array($user, $this->getGroupMembers($id, $parentGroups))) {
                $memberships[$id] = $list['name'];
            }
        }

        return $memberships;
    }

    /**
     * Returns a contact group hash.
     *
     * @param string $gid  The group identifier.
     *
     * @return array  A hash defining the group.
     * @throws Turba_Exception
     */
    public function getGroupObject($gid)
    {
        if (empty($gid) || (strpos($gid, ':') === false)) {
            throw new Turba_Exception(sprintf('Unsupported group id: %s', $gid));
        }

        $sources = $this->getSourcesConfig(array('type' => 'sql'));
        list($source, $id) = explode(':', $gid);
        if (empty($sources[$source])) {
            return array();
        }

        list($db, $sql) = $this->_getGroupObject($sources[$source], $id);

        try {
            $ret = $db->selectOne($sql);
            $ret['name'] = $ret['lname'];
            unset($ret['lname']);
            return $ret;
        } catch (Horde_Db_Exception $e) {
            throw new Horde_Exception(_("Server error when performing search."));
        }
    }

    /**
     */
    protected function _getGroupObject($source, $key)
    {
        $db = empty($source['params']['sql'])
            ? $GLOBALS['injector']->getInstance('Horde_Db_Adapter')
            : $GLOBALS['injector']->getInstance('Horde_Core_Factory_Db')->create('turba', $source['params']['sql']);

        $sql = 'SELECT ' . $source['map']['__members'] . ' members,'
            . $source['map']['email'] . ' email,'
            . $source['map'][$source['list_name_field']]
            . ' lname FROM ' . $source['params']['table'] . ' WHERE '
            . $source['map']['__key'] . ' = ' . $db->quoteString($key);

        return array($db, $sql);
    }

    /**
     * Returns a list of all members belonging to a contact group.
     *
     * @param string $gid         The group identifier
     * @param boolean $subGroups  Also include members of any subgroups?
     *
     * @return array An array of group members (identified by email address).
     * @throws Horde_Exception
     */
    public function getGroupMembers($gid, $subGroups = false)
    {
        $contact_shares = $this->listShares(Horde_Perms::SHOW);
        $sources = $this->getSourcesConfig(array('type' => 'sql'));

        $entry = $this->getGroupObject($gid);
        if (!$entry) {
            return array();
        }
        list($source,) = explode(':', $gid);
        $members = @unserialize($entry['members']);
        if (!is_array($members)) {
            return array();
        }

        $db[$source] = empty($sources[$source]['params']['sql'])
            ? $GLOBALS['injector']->getInstance('Horde_Db_Adapter')
            : $GLOBALS['injector']->getInstance('Horde_Core_Factory_Db')->create('turba', $sources[$source]['params']['sql']);

        $users = array();
        foreach ($members as $member) {
            // Is this member from the same source or a different one?
            if (strpos($member, ':') !== false) {
                list($newSource, $uid) = explode(':', $member);
                if (!empty($contact_shares[$newSource])) {
                    $params = @unserialize($contact_shares[$newSource]->get('params'));
                    $newSource = $params['source'];
                    $member = $uid;
                    $db[$newSource] = empty($sources[$newSource]['params']['sql'])
                        ? $GLOBALS['injector']->getInstance('Horde_Db_Adapter')
                        : $GLOBALS['injector']->getInstance('Horde_Core_Factory_Db')->create('turba', $sources[$newSource]['params']['sql']);

                } elseif (empty($sources[$newSource])) {
                    // Last chance, it's not in one of our non-share sources
                    continue;
                }
            } else {
                // Same source
                $newSource = $source;
            }

            $type = $sources[$newSource]['map']['__type'];
            $email = $sources[$newSource]['map']['email'];
            $sql = 'SELECT ' . $email . ', ' . $type
                . ' FROM ' . $sources[$newSource]['params']['table']
                . ' WHERE ' . $sources[$newSource]['map']['__key']
                . ' = ' . $db[$newSource]->quoteString($member);

            try {
                $results = $db[$newSource]->selectOne($sql);
            } catch (Horde_Db_Exception $e) {
                throw new Horde_Exception(_("Server error when performing search."));
            }

            // Sub-Lists are treated as sub groups the best that we can...
            if ($subGroups && $results[$type] == 'Group') {
                $users = array_merge($users, $this->getGroupMembers($newSource . ':' . $member));
            }
            if (strlen($results[$email])) {
                // use a key to dump dups
                $users[$results[$email]] = true;
            }
        }

        ksort($users);
        return array_keys($users);
    }

    /**
     * Create a new addressbook
     *
     * @param string $name   The display name for the addressbook.
     * @param array  $params Any addtional parameters needed.
     *     - synchronize:   (boolean) If true, add address book to the list of
     *                                address books to syncronize.
     *                      DEFAULT: false (do not add to the list).
     *                      @since 4.2.1
     *
     * @return string  The new addressbook's id (share name).
     * @since 4.2.0
     */
    public function addAddressbook($name, array $params = array())
    {
        $share_name = strval(new Horde_Support_Randomid());
        $share = Turba::createShare($share_name, array('name' => $name));
        $name = $share->getName();
        if (!empty($params['synchronize'])) {
            $sync = @unserialize($prefs->getValue('sync_books'));
            $sync[] = $name;
            $prefs->setValue('sync_books', serialize($sync));
        }

        return $name;
    }

    /**
     * Delete the specified addressbook.
     *
     * @param string $id  The addressbook id.
     * @since 4.2.0
     */
    public function deleteAddressbook($id)
    {
        $share = $GLOBALS['injector']
            ->getInstance('Turba_Factory_Driver')
            ->create($id);

        $GLOBALS['injector']
            ->getInstance('Turba_Shares')
            ->removeShare($share);
    }

    /**
     * Update an existing addressbook's name or description.
     *
     * @param string $id    The addressbook id.
     * @param array  $info  The info to change:
     *   - name: The addressbook's display name.
     *   - desc: The addressbook's description.
     *
     * @since 4.2.0
     */
    public function updateAddressbook($id, array $info)
    {
        $share = $GLOBALS['injector']->getInstance('Turba_Factory_Driver')->create($id);
        if (!empty($info['name'])) {
            $share->set('name', $info['name']);
        }
        if (!empty($info['desc'])) {
            $share->set('desc', $info['desc']);
        }

        $share->save();
    }

    /* Helper methods. */

    /**
     */
    private function _modified($uid, $sources)
    {
        $modified = $this->getActionTimestamp($uid, 'modify', $sources);
        if (empty($modified)) {
            $modified = $this->getActionTimestamp($uid, 'add', $sources);
        }
        return $modified;
    }

    /**
     * @throws Turba_Exception
     */
    private function _getSources($sources)
    {
        /* Get default address book from user preferences. */
        if (empty($sources)) {
            $sources = @unserialize($GLOBALS['prefs']->getValue('sync_books'));
        } elseif (!is_array($sources)) {
            $sources = array($sources);
        }

        if (empty($sources)) {
            $sources = array(Turba::getDefaultAddressbook());
            if (empty($sources)) {
                throw new Turba_Exception(_("No address book specified"));
            }
        }

        foreach ($sources as $val) {
            if (!strlen($val) || !isset($GLOBALS['cfgSources'][$val])) {
                throw new Turba_Exception(sprintf(_("Invalid address book: %s"), $val));
            }
        }

        return $sources;
    }

    /**
     * Retrieve the list of used tag_names, tag_ids and the total number
     * of resources that are linked to that tag.
     *
     * @param array $tags  An optional array of tag_ids. If omitted, all tags
     *                     will be included.
     *
     * @return array  An array containing tag_name, and total
     */
    public function listTagInfo($tags = null, $user = null)
    {
        return $GLOBALS['injector']->getInstance('Turba_Tagger')
            ->getTagInfo($tags, 500, null, $user);
    }

    /**
     * SearchTags API:
     * Returns an application-agnostic array (useful for when doing a tag search
     * across multiple applications)
     *
     * The 'raw' results array can be returned instead by setting $raw = true.
     *
     * @param array $names           An array of tag_names to search for.
     * @param integer $max           The maximum number of resources to return.
     * @param integer $from          The number of the resource to start with.
     * @param string $resource_type  The resource type [bookmark, '']
     * @param string $user           Restrict results to resources owned by $user.
     * @param boolean $raw           Return the raw data?
     *
     * @return array An array of results:
     * <pre>
     *  'title'    - The title for this resource.
     *  'desc'     - A terse description of this resource.
     *  'view_url' - The URL to view this resource.
     *  'app'      - The Horde application this resource belongs to.
     *  'icon'     - URL to an image.
     * </pre>
     */
    public function searchTags($names, $max = 10, $from = 0,
                               $resource_type = '', $user = null, $raw = false)
    {
        global $injector, $registry;

        $results = $injector
            ->getInstance('Turba_Tagger')
            ->search(
                $names,
                array('user' => $user));

        // Check for error or if we requested the raw data array.
        if ($raw) {
            return $results;
        }
        $return = array();
        foreach ($results as $contact_uid) {
            try {
                $driver = $injector->getInstance('Turba_Factory_Driver');
                foreach ($this->_getSources($sources) as $source) {
                    $sdriver = $driver->create($source);
                    if (!$sdriver->hasPermission(Horde_Perms::READ)) {
                        continue;
                    }
                    $result = $sdriver->search(array('__uid' => $contact_uid));
                    if (count($result) == 0) {
                        continue;
                    } elseif (count($result) > 1) {
                        throw new Turba_Exception(sprintf("Internal Horde Error: multiple Turba objects with same objectId %s.", $uid));
                    }
                    foreach ($result->objects as $obj) {
                        $return[] = array(
                            'title' => $obj->getValue('name'),
                            'desc' => $obj->getValue('name'),
                            'view_url' => $obj->url,
                            'app' => 'turba',
                            'icon' => $this->_getContactImageUrl($obj)
                        );
                    }
                }
            } catch (Exception $e) {
            }
        }

        return $return;
    }


    protected function _getContactImageUrl($obj)
    {
        if ($photo = $obj->getValue('photo')) {
            try {
                $img = $GLOBALS['injector']->getInstance('Horde_Core_Factory_Image')->create();
                $img->loadString($photo['load']['data']);
                $img->resize(50, 50, true);
                $data = $img->raw(true);
                $type = $img->getContentType();
            } catch (Horde_Image_Exception $e) {
                $data = $photo['load']['data'];
                $type = $obj->getValue('phototype');
            }

            return Horde_Url_Data::create($type, $data);
        }
    }

}