File: Kolab.php

package info (click to toggle)
horde3 3.1.3-4etch7
  • links: PTS
  • area: main
  • in suites: etch
  • size: 22,876 kB
  • ctags: 18,071
  • sloc: php: 75,151; xml: 2,979; sql: 1,069; makefile: 79; sh: 64
file content (1838 lines) | stat: -rw-r--r-- 60,165 bytes parent folder | download | duplicates (2)
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
<?php

/** We require the base Horde library. */
require_once 'Horde.php';
require_once 'Horde/Share.php';

/** We need the String & NLS libraries for character set conversions, etc. */
require_once 'Horde/String.php';
require_once 'Horde/NLS.php';

/** We need the Horde MIME library to deal with MIME messages, obviously :-). */
require_once 'Horde/MIME.php';
require_once 'Horde/MIME/Part.php';
require_once 'Horde/MIME/Message.php';
require_once 'Horde/MIME/Headers.php';
require_once 'Horde/MIME/Structure.php';

/**
 * The Horde_Kolab library requires version >= 1.0.3 of Net_IMAP (i.e. a version
 * that includes support for the ANNOTATEMORE IMAP extension). The latest
 * version of Net_IMAP can be obtained from http://pear.php.net/get/Net_IMAP
 */
require_once 'Net/IMAP.php';

/**
 * The character sequence used by a (Kolab) Cyrus IMAP server to separate lines
 * within a message.
 */
define('KOLAB_NEWLINE', "\r\n");

/**
 * The character used to delimit subfolders within a (Kolab) Cyrus folder
 * hierarchy.
 */
define('KOLAB_FOLDER_DELIM', '/');

/**
 * The root of the Kolab annotation hierarchy, used on the various IMAP folder
 * that are used by Kolab clients.
 */
define('KOLAB_ANNOT_ROOT', '/vendor/kolab/');

/**
 * The annotation, as defined by the Kolab format spec, that is used to store
 * information about what groupware format the folder contains.
 */
define('KOLAB_ANNOT_FOLDER_TYPE', KOLAB_ANNOT_ROOT . 'folder-type');

/**
 * A Horde-specific annotation that stores the UID of the Horde share that
 * corresponds to the IMAP folder. This is used in the synchronisation process
 * of the IMAP folder list and the Horde share list.
 */
define('KOLAB_ANNOT_SHARE_UID', KOLAB_ANNOT_ROOT . 'h-share-uid');

/**
 * The X- header used to store a copy of the Kolab object type string for the
 * object type that is contained within the email message.
 */
define('KOLAB_HEADER_TYPE', 'X-Kolab-Type');

/**
 * An index into the $_SESSION array which is used to cache what application
 * was last synchronised; this prevents us from continuously re-synchronising
 * on every page load within a single application.
 */
define('KOLAB_LAST_SYNCHED_APP', 'kolab_last_synched_app');

/**
 * An index into the $_SESSION array which is used to cache a mapping of share
 * UIDs to IMAP folders; this is used by the various application drivers when
 * opening a specific share, in order to know what the corresponding IMAP
 * folder that must be opened is.
 */
define('KOLAB_SHARE_MAP', 'kolab_share_map');

/**
 * The prefix for all Kolab groupware object mime type strings. Each object
 * type has this string in common, with a suffix of e.g. 'note', 'event', etc.
 * to indicate what the specific Kolab groupware format is.
 */
define('KOLAB_MIME_TYPE_PREFIX', 'application/x-vnd.kolab.');

/**
 * The string used to identify the Horde/Kolab integration engine in various
 * places (e.g. in Kolab objects generated by the library).
 */
define('KOLAB_PRODUCT_ID', 'horde/kolab/1.0');

/**
 * The Horde_Kolab library is both an object used by application drivers to
 * communicate with a Kolab server, as well as a utility library providing
 * several functions to help in the IMAP folder <-> Horde Share synchronisation
 * process.
 *
 * $Horde: framework/Kolab/Kolab.php,v 1.26.10.16 2006/07/17 09:30:50 jan Exp $
 *
 * Copyright 2004-2006 Horde Project (http://horde.org/)
 *
 * See the enclosed file COPYING for license information (LGPL). If you
 * did not receive this file, see http://www.fsf.org/copyleft/lgpl.html.
 *
 * @author  Stuart Binge <omicron@mighty.co.za>
 * @package Horde_Kolab
 */
class Kolab {

// Class interface

    /**
     * The current application that this Kolab object instance is catering to.
     *
     * @var string
     */
    var $_app;

    /**
     * Our Net_IMAP object, used to communicate with the Cyrus server.
     *
     * @var Net_IMAP
     */
    var $_imap = null;

    /**
     * A cached version of Kolab::getAppConsts($this->_app) that is used in
     * several of the Kolab:: functions.
     *
     * @var array
     */
    var $_app_consts;

    /**
     * A shortcut to $this->_app_consts['mime_type_suffix']
     *
     * @var string
     */
    var $_object_type;

    /**
     * The full mime type string of the current Kolab object format we're
     * dealing with.
     *
     * @var string
     */
    var $_mime_type;

    /**
     * The (encoded) name of the IMAP folder that corresponds to the current
     * share.
     *
     * @var string
     */
    var $_folder;

    /**
     * The MIME_Message object that contains the currently loaded message. This
     * is used when updating an object, in order to preserve everything else
     * within the message that we don't know how to handle.
     *
     * @var MIME_Message
     */
    var $_message;

    /**
     * An array containing $_message's headers.
     *
     * @var array
     */
    var $_headers;

    /**
     * The MIME identifier of the Kolab groupware object within $this->_message.
     *
     * @var string
     */
    var $_mime_id;

    /**
     * The (Kolab) UID of $this->_message.
     *
     * @var string
     */
    var $_uid;

    /**
     * The DomDocument object that contains the XML DOM tree of the currently
     * loaded groupware object. We cache this here to ensure preservation of
     * unknown fields when re-saving the object.
     *
     * @var DomDocument
     */
    var $_xml;

    /**
     * The IMAP message number of $this->_message.
     *
     * @var integer
     */
    var $_msg_no;

    function getUID()
    {
        return $this->_uid;
    }

    function getMimeType()
    {
        return $this->_mime_type;
    }

    function Kolab()
    {
        global $registry;

        $this->_app = $registry->getApp();
    }

    function open($share_uid)
    {
        global $conf;

        if (!Util::extensionExists('domxml')) {
            return PEAR::raiseError(_("Horde/Kolab: The integration engine requires the 'domxml' PHP extension"));
        }

        $this->_app_consts = Kolab::getAppConsts($this->_app);
        if (is_a($this->_app_consts, 'PEAR_Error')) {
            return $this->_app_consts;
        }

        $this->_object_type = $this->_app_consts['mime_type_suffix'];
        $this->_mime_type = KOLAB_MIME_TYPE_PREFIX . $this->_object_type;

        $current_user = Auth::getAuth();
        $ndx = strpos($current_user, '@');
        $user = $ndx === false ? $current_user : substr($current_user, 0, $ndx);
        $domain = strstr($current_user, '@');

        $share_map = Kolab::getShareMap();
        if (empty($share_map[$share_uid])) {
            return false;
        }
        $folder = $share_map[$share_uid];

        // Translate remote-syntax folders that we own to local-syntax so that
        // we can open them properly
        preg_match(";user/([^/]+)/([^@]+)(@.*)?;", $folder, $matches);

        $user_domain = isset($matches[3]) ? $matches[3] : $domain;
        if ($matches[1] == $user && $user_domain == $domain) {
            $folder = "INBOX/$matches[2]";
        } else {
            $folder = "user/$matches[1]/$matches[2]";
            if ($user_domain != $domain) {
                $folder .= $user_domain;
            }
        }

        $this->_folder = $folder;

        $this->_imap = new Net_IMAP($conf['kolab']['imap']['server'], $conf['kolab']['imap']['port']);

        $result = $this->_imap->login($current_user, Auth::getCredential('password'), false, false);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        $result = $this->_imap->selectMailbox($this->_folder);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        return true;
    }

    function close()
    {
        if (!empty($this->_imap)) {
            $this->_imap->disconnect();
            $this->_imap = null;
        }
    }

    function findObject($uid)
    {
        if (empty($this->_imap)) {
            return false;
        }

        $result = $this->_imap->search("SUBJECT \"$uid\"");
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        if (empty($result)) {
            return PEAR::raiseError(sprintf(_("Horde/Kolab: No message corresponds to object %s"), $uid));
        }

        return $result[0];
    }

    function listObjects()
    {
        if (empty($this->_imap)) {
            return false;
        }

        return $this->_imap->search('HEADER "' . KOLAB_HEADER_TYPE . '" "' . $this->_mime_type . '"');
    }

    function findObjects($criteria)
    {
        if (empty($this->_imap)) {
            return false;
        }

        return $this->_imap->search($criteria);
    }

    function listObjectsInFolder($folder)
    {
        global $conf;

        // Connect to the IMAP server
        $imap = new Net_IMAP($conf['kolab']['imap']['server'], $conf['kolab']['imap']['port']);

        // Login using the current Horde credentials
        $result = $imap->login(Auth::getAuth(), Auth::getCredential('password'), false, false);
        if (is_a($result, 'PEAR_Error')) {
            Horde::logMessage('Unable to authenticate with the Kolab IMAP server', __FILE__, __LINE__, PEAR_LOG_ERR);
            $imap->disconnect();
            return false;
        }

        // Select mailbox to search in
        $result = $imap->selectMailbox($folder);
        if (is_a($result, 'PEAR_Error')) {
            $imap->disconnect();
            return false;
        }

        $result = $this->_imap->search('HEADER "' . KOLAB_HEADER_TYPE . '" "' . $this->_mime_type . '"');
        $imap->disconnect();

        return $result;
    }

    // TODO: write a function that is able to look through all folders
    // of the type we're interested in, looking for an object with a
    // specific UID. This is needed for the getByGUID() functions in
    // the various application drivers.

    function moveObject($uid, $new_share)
    {
        if (empty($this->_imap)) {
            return false;
        }

        $msg_no = $this->findObject($uid);
        if (is_a($msg_no, 'PEAR_Error')) {
            return $msg_no;
        }

        $share_map = Kolab::getShareMap();
        if (empty($share_map[$new_share])) {
            return PEAR::raiseError(sprintf(_("Horde/Kolab: Unknown share \"%s\""), $new_share));
        }

        $new_folder = $share_map[$new_share];

        $result = $this->_imap->copyMessages($new_folder, $msg_no);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        $result = $this->_imap->deleteMessages($msg_no);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        return $this->_imap->expunge();
    }

    function removeObjects($objects, $is_msgno = false)
    {
        if (empty($this->_imap)) {
            return false;
        }

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

        if ($is_msgno === false) {
            $new_objects = array();

            foreach ($objects as $object) {
                $result = $this->findObject($object);
                if (is_a($result, 'PEAR_Error')) {
                    return $result;
                }

                $new_objects[] = $result;
            }

            $objects = $new_objects;
        }

        $result = $this->_imap->deleteMessages($objects);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        $result = $this->_imap->expunge();
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        return true;
    }

    function removeAllObjects()
    {
        if (empty($this->_imap)) {
            return false;
        }

        $result = $this->_imap->deleteMessages($this->listObjects());
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        return true;
    }

    function &loadObject($uid, $is_msgno = false)
    {
        if (empty($this->_imap)) {
            return false;
        }

        if ($is_msgno === false) {
            $uid = $this->findObject($uid);
            if (is_a($uid, 'PEAR_Error')) {
                return $uid;
            }
        }

        $this->_headers = $this->_imap->getParsedHeaders($uid);
        if (is_a($this->_headers, 'PEAR_Error')) {
            return $result;
        }

        $message_text = $this->_imap->getMessages($uid);
        if (is_a($message_text, 'PEAR_Error')) {
            return $message_text;
        }

        if (is_array($message_text)) {
            $message_text = array_shift($message_text);
        }

        $this->_msg_no = $uid;
        $this->_message = &MIME_Structure::parseTextMIMEMessage($message_text);

        $parts = $this->_message->contentTypeMap();
        if (($this->_mime_id = array_search($this->_mime_type, $parts)) !== false) {
            $part = $this->_message->getPart($this->_mime_id);
            $text = $part->transferDecode();
        } else {
            return PEAR::raiseError(sprintf(_("Horde/Kolab: No object of type %s found in message %s"), $this->_mime_type, $uid));
        }

        $this->_xml = @domxml_open_mem($text, DOMXML_LOAD_PARSING |
            DOMXML_LOAD_COMPLETE_ATTRS | DOMXML_LOAD_SUBSTITUTE_ENTITIES |
            DOMXML_LOAD_DONT_KEEP_BLANKS, $error);
        if (!empty($error)) {
            return PEAR::raiseError(sprintf(_("Horde/Kolab: Invalid %s XML data encountered in message %s"), $this->_object_type, $uid));
        }

        $this->_uid = $this->getVal('uid');
        return $this->_xml->document_element();
    }

    function &newObject($uid)
    {
        if (empty($this->_imap)) {
            return false;
        }

        $this->_msg_no = -1;

        $this->_message = new MIME_Message();

        $kolab_text = sprintf(_("This is a Kolab Groupware object. To view this object you will need an email client that understands the Kolab Groupware format. For a list of such email clients please visit %s"),
                              'http://www.kolab.org/kolab2-clients.html');

        $part = new MIME_Part('text/plain', String::wrap($kolab_text, 76, KOLAB_NEWLINE, NLS::getCharset()),
                              NLS::getCharset());
        $part->setTransferEncoding('quoted-printable');
        $this->_message->addPart($part);

        $part = new MIME_Part($this->_mime_type, '', NLS::getCharset());
        $part->setTransferEncoding('quoted-printable');
        $this->_message->addPart($part);

        $parts = $this->_message->contentTypeMap();
        if (($this->_mime_id = array_search($this->_mime_type, $parts)) === false) {
            return PEAR::raiseError(sprintf(_("Horde/Kolab: Unable to retrieve MIME ID for the part of type %s"), $this->_mime_type));
        }

        $headers = new MIME_Headers();
        $headers->addHeader('From', Auth::getAuth());
        $headers->addHeader('To', Auth::getAuth());
        $headers->addHeader('Subject', $uid);
        $headers->addHeader('User-Agent', KOLAB_PRODUCT_ID);
        $headers->addHeader('Reply-To', '');
        $headers->addHeader('Date', date('r'));
        $headers->addHeader(KOLAB_HEADER_TYPE, $this->_mime_type);
        $headers->addMIMEHeaders($this->_message);

        $this->_headers = $headers->toArray();

        $this->_xml = domxml_open_mem(
            '<?xml version="1.0" encoding="UTF-8"?>' .
            '<' . $this->_object_type . ' version="1.0">' .
            '<uid>' . $uid . '</uid>' .
            '<body></body>' .
            '<categories></categories>' .
            '<creation-date>' . Kolab::encodeDateTime() . '</creation-date>' .
            '<sensitivity>public</sensitivity>' .
            '</' . $this->_object_type . '>',
            DOMXML_LOAD_PARSING | DOMXML_LOAD_COMPLETE_ATTRS |
            DOMXML_LOAD_SUBSTITUTE_ENTITIES | DOMXML_LOAD_DONT_KEEP_BLANKS,
            $error
        );
        if (!empty($error)) {
            return PEAR::raiseError(sprintf(_("Horde/Kolab: Unable to create new XML tree for object %s"), $uid));
        }

        $this->_uid = $uid;

        return $this->_xml->document_element();
    }

    function saveObject()
    {
        if (empty($this->_imap)) {
            return false;
        }

        $this->setVal('last-modification-date', Kolab::encodeDateTime());
        $this->setVal('product-id', KOLAB_PRODUCT_ID);

        $part = new MIME_Part($this->_mime_type, $this->_xml->dump_mem(true),
                              NLS::getCharset());
        $part->setTransferEncoding('quoted-printable');
        $this->_message->alterPart($this->_mime_id, $part);

        if ($this->_msg_no != -1) {
            $this->removeObjects($this->_msg_no, true);
        }

        $headers = new MIME_Headers();
        foreach ($this->_headers as $key => $val) {
            $headers->addHeader($key, $val);
        }

        $message = Kolab::kolabNewlines($headers->toString() .
                                        $this->_message->toString(false));

        $result = $this->_imap->appendMessage($message);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        $this->_msg_no = $this->findObject($this->_uid);
        if (is_a($this->_msg_no, 'PEAR_Error')) {
            return $this->_msg_no;
        }

        return true;
    }

    function &getCurrentObject()
    {
        return $this->_xml->document_element();
    }

    function &getElem($name, &$parent)
    {
        $elements = &$this->getAllElems($name, $parent);

        if (empty($elements)) {
            return false;
        }

        return $elements[0];
    }

    function &getAllElems($name, &$parent)
    {
        return $parent->get_elements_by_tagname($name);
    }

    function &getRootElem($name)
    {
        return $this->getElem($name, $this->getCurrentObject());
    }

    function &getAllRootElems($name)
    {
        return $this->getAllElems($name, $this->getCurrentObject());
    }

    function delElem($name, &$parent)
    {
        $element = &$this->getElem($name, $parent);
        if ($element === false) {
            return;
        }

        return $parent->remove_child($element);
    }

    function delAllElems($name, &$parent)
    {
        $elements = &$this->getAllElems($name, $parent);
        for ($i = 0, $j = count($elements); $i < $j; $i++) {
            $parent->remove_child($elements[$i]);
        }
        return true;
    }

    function delAllRootElems($name)
    {
        return $this->delAllElems($name, $this->getCurrentObject());
    }

    function delRootElem(&$element)
    {
        if ($element === false) {
            return;
        }

        $root = &$this->getCurrentObject();
        return $root->remove_child($element);
    }

    function getElemVal(&$parent, $name, $default = 0)
    {
        if ($parent === false) {
            return $default;
        }

        $element = &$this->getElem($name, $parent);
        if ($element === false) {
            return $default;
        }

        return $element->get_content();
    }

    function getElemStr(&$parent, $name, $default = '')
    {
        if ($parent === false) {
            return $default;
        }

        $element = &$this->getElem($name, $parent);
        if ($element === false) {
            return $default;
        }

        return String::convertCharset($element->get_content(), 'utf-8');
    }

    function getVal($name, $default = 0)
    {
        return $this->getElemVal($this->getCurrentObject(), $name, $default);
    }

    function getStr($name, $default = '')
    {
        return $this->getElemStr($this->getCurrentObject(), $name, $default);
    }

    function &initElem($name, &$parent)
    {
        if ($parent === false) {
            $parent = $this->getCurrentObject();
        }

        $element = $this->getElem($name, $parent);

        if ($element === false) {
            $element = $parent->append_child($this->_xml->create_element($name));
        }

        $children = $element->child_nodes();
        foreach ($children as $child) {
            if ($child->node_type() == XML_TEXT_NODE) {
                $element->remove_child($child);
            }
        }

        return $element;
    }

    function &initRootElem($name)
    {
        return $this->initElem($name, $this->getCurrentObject());
    }

    function &appendElem($name, &$parent)
    {
        return $parent->append_child($this->_xml->create_element($name));
    }

    function &appendRootElem($name)
    {
        return $this->appendElem($name, $this->getCurrentObject());
    }

    function &setElemVal(&$parent, $name, $value = '')
    {
        $element = &$this->initElem($name, $parent);
        $element->set_content($value);

        return $element;
    }

    function &setElemStr(&$parent, $name, $value = '')
    {
        return $this->setElemVal($parent, $name, String::convertCharset($value, NLS::getCharset(), 'utf-8'));
    }

    function &setVal($name, $value = '')
    {
        return $this->setElemVal($this->getCurrentObject(), $name, $value);
    }

    function &setStr($name, $value = '')
    {
        return $this->setElemStr($this->getCurrentObject(), $name, $value);
    }

// Utility library interface

    /**
     * Returns a string containing the current UTC date in the format
     * prescribed by the Kolab Format Specification.
     *
     * @return string  The current UTC date in the format 'YYYY-MM-DD'.
     */
    function encodeDate($date = false)
    {
        if ($date === 0) {
            return 0;
        }
        return strftime('%Y-%m-%d', $date === false ? time() : $date);
    }

    /**
     * Returns a UNIX timestamp corresponding the given date string which is in
     * the format prescribed by the Kolab Format Specification.
     *
     * @param string $date  The string representation of the date.
     *
     * @return integer  The unix timestamp corresponding to $date.
     */
    function decodeDate($date)
    {
        if (empty($date)) {
            return 0;
        }

        list($year, $month, $day) = explode('-', $date);
        return mktime(0, 0, 0, $month, $day, $year);
    }

    /**
     * Returns a string containing the current UTC date and time in the format
     * prescribed by the Kolab Format Specification.
     *
     * @return string    The current UTC date and time in the format
     *                   'YYYY-MM-DDThh:mm:ssZ', where the T and Z are literal
     *                   characters.
     */
    function encodeDateTime($datetime = false)
    {
        if ($datetime === 0) {
            return 0;
        }
        return gmstrftime('%Y-%m-%dT%H:%M:%SZ', $datetime === false ? time() : $datetime);
    }

    /**
     * Returns a UNIX timestamp corresponding the given date-time string which
     * is in the format prescribed by the Kolab Format Specification.
     *
     * @param string $datetime  The string representation of the date & time.
     *
     * @return integer  The unix timestamp corresponding to $datetime.
     */
    function decodeDateTime($datetime)
    {
        if (empty($datetime)) {
            return 0;
        }

        list($year, $month, $day, $hour, $minute, $second)
            = sscanf($datetime, '%d-%d-%dT%d:%d:%dZ');
        return gmmktime($hour, $minute, $second, $month, $day, $year);
    }

    /**
     * Returns a UNIX timestamp corresponding the given date or date-time
     * string which is in either format prescribed by the Kolab Format
     * Specification.
     *
     * @param string $date  The string representation of the date (& time).
     *
     * @return integer  The unix timestamp corresponding to $date.
     */
    function decodeDateOrDateTime($date)
    {
        if (empty($date)) {
            return 0;
        }

        return (strlen($date) == 10 ? Kolab::decodeDate($date) : Kolab::decodeDateTime($date));
    }

    function decodeFullDayDate($date)
    {
        if (empty($date)) {
            return 0;
        }

        return (strlen($date) == 10 ? Kolab::decodeDate($date)+24*60*60 : Kolab::decodeDateTime($date));
    }

    function percentageToBoolean($percentage)
    {
        return $percentage == 100 ? '1' : '0';
    }

    function booleanToPercentage($boolean)
    {
        return $boolean ? '100' : '0';
    }

    /**
     * Converts a string in the current character set to an IMAP UTF-7 string,
     * suitable for use as the name of an IMAP folder.
     *
     * @param string $name  The text in the current character set to convert.
     *
     * @return string    $name encoded in the IMAP variation of UTF-7.
     */
    function encodeImapFolderName($name)
    {
        return String::convertCharset($name, NLS::getCharset(), 'UTF7-IMAP');
    }

    /**
     * Converts a string in the IMAP variation of UTF-7 into a string in the
     * current character set.
     *
     * @param string $name  The text in IMAP UTF-7 to convert.
     *
     * @return string    $name encoded in the current character set.
     */
    function decodeImapFolderName($name)
    {
        return String::convertCharset($name, 'UTF7-IMAP');
    }

    /**
     * Converts all newlines (in DOS, MAC & UNIX format) in the specified text
     * to unix-style (LF) format.
     *
     * @param string $text  The text to convert.
     *
     * @return string  $text with all newlines replaced by LF.
     */
    function unixNewlines($text)
    {
        return preg_replace("/\r\n|\n|\r/s", "\n", $text);
    }

    /**
     * Converts all newlines (in DOS, MAC & UNIX format) in the specified text
     * to Kolab (Cyrus) format.
     *
     * @param string $text  The text to convert.
     *
     * @return string  $text with all newlines replaced by KOLAB_NEWLINE.
     */
    function kolabNewlines($text)
    {
        return preg_replace("/\r\n|\n|\r/s", KOLAB_NEWLINE, $text);
    }

    /**
     * Returns the unfolded representation of the given text.
     *
     * @param string $text  The text to unfold.
     *
     * @return string  The unfolded representation of $text.
     */
    function unfoldText($text)
    {
        return preg_replace("/\r\n[ \t]+/", "", $text);
    }

    /**
     * Returns an array of application-specific constants, that are used in
     * a generic manner throughout the library.
     *
     * @param string $app  The application whose constants to query.
     *
     * @return mixed  An array of application-specific constants if $app is a
     *                supported application, or a PEAR_Error object if $app is
     *                not supported.
     */
    function getAppConsts($app)
    {
        switch ($app) {
        case 'mnemo':
            return array(
                'mime_type_suffix'      => 'note',
                'default_folder_name'   => _("Notes"),
                'share_name'            => _("notepad"),
                'default_share_name'    => _("%s's Notepad"),
            );

        case 'kronolith':
            return array(
                'mime_type_suffix'      => 'event',
                'default_folder_name'   => _("Calendar"),
                'share_name'            => _("calendar"),
                'default_share_name'    => _("%s's Calendar"),
            );

        case 'turba':
            return array(
                'mime_type_suffix'      => 'contact',
                'default_folder_name'   => _("Contacts"),
                'share_name'            => _("address book"),
                'default_share_name'    => _("%s's Address Book"),
            );

        case 'nag':
            return array(
                'mime_type_suffix'      => 'task',
                'default_folder_name'   => _("Tasks"),
                'share_name'            => _("task list"),
                'default_share_name'    => _("%s's Tasklist"),
            );

        default:
            return PEAR::raiseError(sprintf(_("The Horde/Kolab integration engine does not support \"%s\""), $app));
        }
    }

    /**
     * Returns an IMAP ACL string corresponding to the given Horde permissions
     * value.
     *
     * @param integer $perms  The Horde permissions value.
     * @param boolean $owner  Will the ACL string be used for the folder owner?
     *                        This includes the 'a' rights in the ACL string.
     *
     * @return string  The IMAP ACL string corresponding to $perms and $owner.
     */
    function permsToACL($perms, $owner = true)
    {
        $result = $owner ? 'a' : '';
        if ($perms & PERMS_SHOW) {
            $result .= 'l';
        }
        if ($perms & PERMS_READ) {
            $result .= 'r';
        }
        if ($perms & PERMS_EDIT) {
            $result .= 'iswc';
        }
        if ($perms & PERMS_DELETE) {
            $result .= 'd';
        }

        return $result;
    }

    /**
     * Returns a Horde permissions value corresponding to the given IMAP ACL
     * string.
     *
     * @param string $acl_string  The IMAP ACL string.
     *
     * @return integer  The Horde permissions value corresponding to
     *                  $acl_string.
     */
    function aclToPerms($acl_string)
    {
        $result = 0;

        for ($i = 0, $j = strlen($acl_string); $i < $j; $i++) {
            switch ($acl_string[$i]) {
            case 'l':
                $result |= PERMS_SHOW;
                break;

            case 'r':
                $result |= PERMS_READ;
                break;

            case 'i':
                $result |= PERMS_EDIT;
                break;

            case 'd':
                $result |= PERMS_DELETE;
                break;
            }
        }

        return $result;
    }

    /**
     * Creates an associative array out of an IMAP ACL list as returned by the
     * Net_IMAP object.
     *
     * @param array $acl  The IMAP ACL array.
     *
     * @return array  An associative array, where the keys are individual users
     *                and the values the ACL string for the specific user.
     */
    function aclToArray($acl)
    {
        if (is_a($acl, 'PEAR_Error')) {
            return $acl;
        }

        $result = array();
        foreach ($acl as $user) {
            if (preg_match('/group:(.+)/', $user['USER'], $matches)) {
                /* Look up and expand groups. */
                require_once 'Horde/Group.php';
                $group = &Group::singleton();
                $gid = $group->getGroupId($matches[1]);
                $users = $group->listUsers($gid);
                foreach ($users as $u) {
                    $result[$u] = $user['RIGHTS'];
                }
            } else {
                $result[$user['USER']] = $user['RIGHTS'];
            }
        }

        return $result;
    }

    function getShareMap()
    {
        return empty($_SESSION[KOLAB_SHARE_MAP])
          ? array()
          : unserialize($_SESSION[KOLAB_SHARE_MAP]);
    }

    function setShareMap($share_map)
    {
        $_SESSION[KOLAB_SHARE_MAP] = serialize($share_map);
    }

    function updateMappedShare(&$share_map, $share_uid, $imap_folder)
    {
        $share_map[$share_uid] = $imap_folder;
    }

    function getShareMapping(&$share_map, $share_uid, $dne_result = '')
    {
        return empty($share_map[$share_uid]) ? $dne_result : $share_map[$share_uid];
    }

    function removeMappedShare(&$share_map, $share_uid)
    {
        if (isset($share_map[$share_uid])) {
            unset($share_map[$share_uid]);
        }
    }

    /**
     * Synchronises the Perms of a Horde share to the ACL of an IMAP folder,
     * creating the folder if necessary. It also sets the necessary annotations
     * indicating what groupware format type is contained within the folder,
     * and what Horde share it corresponds to.
     *
     * @param object $imap   A reference to a Net_IMAP object that is already
     *                       connected and authenticated to the correct server.
     * @param object $share  A reference to the Horde share object that we are
     *                       interested in.
     * @param string $app_consts  A reference to the result of a getAppConsts()
     *                            call for the current Horde application.
     *                       Horde/Kolab integration-supported app.
     *
     * @return mixed  True on success, a PEAR_Error object on failure.
     */
    function synchroniseShare(&$imap, &$share, &$app_consts)
    {
        global $conf;

        if (empty($share)) {
            return PEAR::raiseError(_("Invalid share object"));
        }

        $share_uid = $share->getName();
        $owner = $share->get('owner');
        $default = $share_uid == $owner;

        $ndx = strpos($owner, '@');
        $user = $ndx === false ? $owner : substr($owner, 0, $ndx);
        $domain = strstr($owner, '@');

        $folder_type = $app_consts['mime_type_suffix'] . ($default ? '.default' : '');
        $folder_name = "user/$user/" . ($default ? $app_consts['default_folder_name'] : $share->get('name')) . $domain;
        //Kolab::encodeImapFolderName($default ? $app_consts['default_folder_name'] : $share->get('name'));
        if (is_a($folder_name, 'PEAR_Error')) {
            return $folder_name;
        }

        $share_map = Kolab::getShareMap();

        $old_folder = Kolab::getShareMapping($share_map, $share_uid);

        $result = $imap->mailboxExist($folder_name);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        if ($folder_name != $old_folder) {
            if ($result && $old_folder) {
                return PEAR::raiseError(sprintf(_("Unable to rename %s to %s: destination folder already exists"), $folder_name, $old_folder));
            }

            if ($old_folder) {
                $result = $imap->renameMailbox($old_folder, $folder_name);
                if (is_a($result, 'PEAR_Error')) {
                    return $result;
                }
            } elseif ($result === false) {
                $result = $imap->createMailbox($folder_name);
                if (is_a($result, 'PEAR_Error')) {
                    return $result;
                }
            }
        }

        // Grant the Cyrus Administrator create & delete access (needed
        // for the adminuser to delete the mailbox when removing shares)
        $result = $imap->setACL($folder_name, $conf['kolab']['imap']['adminuser'], 'cd');
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        $acl = Kolab::aclToArray($imap->getACL($folder_name));
        if (is_a($acl, 'PEAR_Error')) {
            return $acl;
        }

        $perm = &$share->getPermission();
        $perm_list = $perm->getUserPermissions();

        foreach ($perm_list as $user => $user_perms) {
            $result = $imap->setACL($folder_name, $user, Kolab::permsToAcl($user_perms, $user == $owner));
            if (is_a($result, 'PEAR_Error')) {
                return $result;
            }

            unset($acl[$user]);
        }

        // Make sure we don't delete the current user or the Cyrus
        // Administrator from the folder's ACL, or else we'll be locked out
        unset($acl[$owner]);
        unset($acl[$conf['kolab']['imap']['adminuser']]);

        foreach ($acl as $user => $user_acl) {
            $result = $imap->deleteACL($folder_name, $user);
            if (is_a($result, 'PEAR_Error')) {
                return $result;
            }
        }

        $result = $imap->setAnnotation(KOLAB_ANNOT_FOLDER_TYPE, array('value.shared' => $folder_type), $folder_name);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        $result = $imap->setAnnotation(KOLAB_ANNOT_SHARE_UID, array('value.shared' => $share_uid), $folder_name);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        Kolab::updateMappedShare($share_map, $share_uid, $folder_name);
        Kolab::setShareMap($share_map);

        return true;
    }

    function updateShare(&$share)
    {
        global $registry, $notification;

        $app = $registry->getApp();
        if (array_search($app, array('mnemo', 'nag', 'turba', 'kronolith')) === false) {
            if (empty($_SESSION[KOLAB_LAST_SYNCHED_APP])) {
                return false;
            }
            $app = $_SESSION[KOLAB_LAST_SYNCHED_APP];
        }

        $app_consts = Kolab::getAppConsts($app);
        if (is_a($app_consts, 'PEAR_Error')) {
            return false;
        }

        $result = Kolab::_updateShare($share, $app_consts);
        $id = $share->get('name');
        if (is_a($result, 'PEAR_Error')) {
            $notification->push(sprintf(_("Horde/Kolab: Unable to synchronise %s \"%s\": %s"),
                                        $app_consts['share_name'], $id, $result->getMessage()), 'horde.error');
        }

        return true;
    }

    function _updateShare(&$share, &$app_consts)
    {
        global $conf;

        $imap = new Net_IMAP($conf['kolab']['imap']['server'], $conf['kolab']['imap']['port']);

        $result = $imap->login($conf['kolab']['imap']['adminuser'], $conf['kolab']['imap']['adminpw'], false, false);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        $result = Kolab::synchroniseShare($imap, $share, $app_consts);

        $imap->disconnect();

        return $result;
    }

    function removeShare(&$share)
    {
        global $registry, $notification;

        $app = $registry->getApp();

        // We only remove shares if Kolab integration is enabled, and if we've
        // previously synchronised the shares list (i.e. we know what IMAP
        // folder corresponds to the given share).
        if (empty($GLOBALS['conf']['kolab']['enabled']) ||
            (!empty($_SESSION[KOLAB_LAST_SYNCHED_APP]) &&
             $_SESSION[KOLAB_LAST_SYNCHED_APP] != $app)) {
            return false;
        }

        $app_consts = Kolab::getAppConsts($app);
        if (is_a($app_consts, 'PEAR_Error')) {
            return false;
        }

        $result = Kolab::_removeShare($share);
        $id = $share->get('name');
        if (is_a($result, 'PEAR_Error')) {
            $notification->push(sprintf(_("Horde/Kolab: Unable to remove %s \"%s\": %s"),
                                        $app_consts['share_name'], $id, $result->getMessage()), 'horde.error');
        } elseif ($result === true) {
            $notification->push(sprintf(_("Horde/Kolab: Successfully removed %s \"%s\""),
                                        $app_consts['share_name'], $id), 'horde.success');
        }

        return true;
    }

    function _removeShare(&$share)
    {
        global $conf;

        if (empty($share)) {
            return PEAR::raiseError(_("Invalid share object"));
        }

        $share_uid = $share->getName();

        $share_map = Kolab::getShareMap();

        $folder = Kolab::getShareMapping($share_map, $share_uid);
        if (empty($folder)) {
            return true;
        }

        $imap = new Net_IMAP($conf['kolab']['imap']['server'], $conf['kolab']['imap']['port']);

        $result = $imap->login($conf['kolab']['imap']['adminuser'], $conf['kolab']['imap']['adminpw'], false, false);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        $result = $imap->deleteMailbox($folder);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        $imap->disconnect();

        Kolab::removeMappedShare($share_map, $share_uid);

        Kolab::setShareMap($share_map);

        return true;
    }

    function synchroniseShares(&$shares, $app)
    {
        if (empty($GLOBALS['conf']['kolab']['enabled']) ||
            array_search($app, array('mnemo', 'nag', 'turba', 'kronolith')) === false) {
            return;
        }

        // Turba doesn't use shares, so we just create a dummy share list &
        // default share here to make sure the following code works.
        if (empty($shares) && $app == 'turba') {
            $shares = &Horde_Share::singleton($app);

            $app_consts = Kolab::getAppConsts($app);

            require_once 'Horde/Identity.php';
            $identity = &Identity::singleton();
            $name = $identity->getValue('fullname');
            if (trim($name) == '') {
                $name = Auth::removeHook(Auth::getAuth());
            }
            $share = &$shares->newShare(Auth::getAuth());
            $share->set('name', sprintf($app_consts['default_share_name'], $name));
            $shares->addShare($share);
        }

        // Check if we've already synchronised the IMAP folder list; if we have
        // then exit early. Folder synchronisation is done on application
        // startup - this includes switching between applications as well as
        // upon initial login.
        if (!empty($_SESSION[KOLAB_LAST_SYNCHED_APP]) &&
            $_SESSION[KOLAB_LAST_SYNCHED_APP] == $app) {
            return;
        }

        global $notification;

        $result = Kolab::_synchShares($shares);
        if (is_a($result, 'PEAR_Error')) {
            $notification->push(sprintf(_("Horde/Kolab: Unable to synchronise shares: %s"), $result->getMessage()), 'horde.error');
        }
    }

    /**
     * Synchronises the IMAP folder list and the Horde share list.
     *
     * @return mixed  True on a successful synchronisation, false when a
     *                synchronisation is not required (i.e. multiple page loads
     *                in a single application), or a PEAR_Error object on
     *                failure.
     */
    function _synchShares(&$shares)
    {
        global $registry, $conf;

        $app = $registry->getApp();

        // Otherwise we need to map the current IMAP folder list to the
        // applications share list.

        // Make sure this is being called from a known application
        $app_consts = Kolab::getAppConsts($app);
        if (is_a($app_consts, 'PEAR_Error')) {
            return $app_consts;
        }

        // Connect to the IMAP server
        $imap = new Net_IMAP($conf['kolab']['imap']['server'], $conf['kolab']['imap']['port']);

        // Login using the current Horde credentials
        $current_user = Auth::getAuth();
        $ndx = strpos($current_user, '@');
        $user = $ndx === false ? $current_user : substr($current_user, 0, $ndx);
        $domain = strstr($current_user, '@');
        $result = $imap->login($current_user, Auth::getCredential('password'), false, false);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        // Obtain a list of all folders the current user has access to
        $folder_list = $imap->getMailboxes();
        if (is_a($folder_list, 'PEAR_Error')) {
            return $folder_list;
        }

        // We're only interested in the folders of the specific resource type
        // for the current application, so filter out the rest
        $local_folders = array();
        $remote_folders = array();
        foreach ($folder_list as $folder) {
            $annotation = $imap->getAnnotation(KOLAB_ANNOT_FOLDER_TYPE, 'value.shared', $folder);
            if (is_a($annotation, 'PEAR_Error')) {
                return $annotation;
            }

            // If there is no annotation then we treat it as a standard mail
            // folder (i.e. we ignore it).
            if (empty($annotation)) {
                continue;
            }

            // If the folder is of the correct type then we add it to our list
            // of folders that should correspond to a share. Here we get any
            // other additional information we may need, such as whether the
            // folder was previously mapped to a share, its ACL, its owner (if
            // it is a shared folder) and its display name.
            $type = explode('.', $annotation);
            if ($type[0] == $app_consts['mime_type_suffix']) {
                $acl = Kolab::aclToArray($imap->getACL($folder));
                if (is_a($acl, 'PEAR_Error')) {
                    return $acl;
                }

                // Skip the Cyrus Administrator
                unset($acl[$conf['kolab']['imap']['adminuser']]);

                $share_uid = $imap->getAnnotation(KOLAB_ANNOT_SHARE_UID, 'value.shared', $folder);
                if (is_a($share_uid, 'PEAR_Error')) {
                    return $share_uid;
                }

                preg_match(";(INBOX|user/([^/]+))/([^@]+)(@.*)?;", $folder, $matches);

                $default = (!empty($type[1]) && $type[1] == 'default');

                if ($matches[1] == 'INBOX') {
                    if ($default) {
                        require_once 'Horde/Identity.php';
                        $identity = &Identity::singleton();
                        $name = $identity->getValue('fullname');
                        if (trim($name) == '') {
                            $name = Auth::removeHook($current_user);
                        }
                        $name = sprintf($app_consts['default_share_name'], $name);
                        $folder = $app_consts['default_folder_name'];
                    } else {
                        $name = $folder = Kolab::decodeImapFolderName($matches[3]);
                    }

                    $folder = "user/$user/$folder$domain";

                    $local_folders[$folder] = array(
                        'share_uid'     => $share_uid,
                        'acl'           => $acl,
                        'name'          => $name,
                        'default'       => $default,
                    );
                } else {
                    $user_domain = isset($matches[4]) ? $matches[4] : $domain;
                    $folder = isset($matches[4]) ? $folder : $folder . $user_domain;
                    $owner = $matches[2] . $user_domain;
                    if ($default) {
                        require_once 'Horde/Identity.php';
                        $identity = &Identity::singleton('none', $owner);
                        $name = $identity->getValue('fullname');
                        if (trim($name) == '') {
                            $name = Auth::removeHook($owner);
                        }
                        $name = sprintf($app_consts['default_share_name'], $name);
                    } else {
                        $name = Kolab::decodeImapFolderName($matches[3]);
                    }

                    $remote_folders[$folder] = array(
                        'share_uid'     => $share_uid,
                        'acl'           => $acl,
                        'name'          => $name,
                        'default'       => $default,
                        'owner'         => $owner,
                    );
                }
            }
        }

        // We now map the remaining folder list to the current applications
        // share list, to synch Horde with other Kolab clients that may have
        // previously modified the groupware folders

        $imap->disconnect();
        $imap = new Net_IMAP($conf['kolab']['imap']['server'], $conf['kolab']['imap']['port']);

        $result = $imap->login($conf['kolab']['imap']['adminuser'], $conf['kolab']['imap']['adminpw'], false, false);
        if (is_a($result, 'PEAR_Error')) {
            return $result;
        }

        // TODO: see if there is a more accurate way of listing all shares that
        // are accessible, regardless of what permissions the user has (i.e. if
        // the user has at least one permission level to the share, the share
        // should be in one of these lists).
        $local_shares = $shares->listShares($current_user, PERMS_SHOW, $current_user);
        $all_shares = $shares->listShares($current_user, PERMS_SHOW);
        $remote_shares = array_diff_assoc($all_shares, $local_shares);
        Kolab::setShareMap(array());
        $share_map = array();

        // Now synchronise the folder list with the share list
        foreach ($local_folders as $folder => $attrs) {
            if (empty($attrs['share_uid'])) {
                // No share corresponds to this folder, so create one
                $uid = empty($attrs['default']) ? md5(microtime()) : $current_user;
                $share = &$shares->newShare($uid);
                $share->set('name', $attrs['name']);
                $shares->addShare($share);

                $result = $imap->setAnnotation(KOLAB_ANNOT_SHARE_UID, array('value.shared' => $uid), $folder);
                if (is_a($result, 'PEAR_Error')) {
                    return $result;
                }

                Kolab::updateMappedShare($share_map, $uid, $folder);
            } else {
                // Otherwise there is a share corresponding to this folder
                if (!$shares->exists($attrs['share_uid'])) {
                    // If it's not present for whatever reason, create it
                    $share = &$shares->newShare($attrs['share_uid']);
                    $share->set('name', $attrs['name']);
                    $shares->addShare($share);
                } else {
                    // Otherwise check that it is named correctly
                    $share = &$local_shares[$attrs['share_uid']];
                    if ($share->get('name') != $attrs['name']) {
                        $share->set('name', $attrs['name']);
                    }
                }

                Kolab::updateMappedShare($share_map, $attrs['share_uid'], $folder);
            }

            $current_users = $share->listUsers();

            $perm = &$share->getPermission();
            $must_save = false;

            foreach ($attrs['acl'] as $user => $acl) {
                $perms = Kolab::aclToPerms($acl);
                if ($perms != $GLOBALS['perms']->getPermissions($perm, $user)) {
                    $perm->addUserPermission($user, $perms, false);
                    $must_save = true;
                }
                $ndx = array_search($user, $current_users);
                if ($ndx !== false) {
                    unset($current_users[$ndx]);
                }
            }

            foreach ($current_users as $user) {
                if ($GLOBALS['perms']->getPermissions($perm, $user) !== false) {
                    $perm->removeUserPermission($user, PERMS_ALL, false);
                    $must_save = true;
                }
            }

            if ($must_save) {
                $share->setPermission($perm, false);
                $share->save();
            }

            if (!empty($attrs['share_uid'])) {
                unset($local_shares[$attrs['share_uid']]);
            }
        }
        unset($local_shares[$current_user]);

        // Update shares that are not owned by the current user (only if there
        // are shared folders accessible to the current user)
        if (!empty($remote_folders)) {
            foreach ($remote_folders as $folder => $attrs) {
                if (empty($attrs['share_uid'])) {
                    $uid = empty($attrs['default']) ? md5(microtime()) : $attrs['owner'];
                    $share = &$shares->newShare($uid);
                    $share->set('owner', $attrs['owner']);
                    $share->set('name', $attrs['name']);
                    $shares->addShare($share);

                    $result = $imap->setAnnotation(KOLAB_ANNOT_SHARE_UID, array('value.shared' => $uid), $folder);
                    if (is_a($result, 'PEAR_Error')) {
                        return $result;
                    }

                    Kolab::updateMappedShare($share_map, $uid, $folder);
                } else {
                    if (!$shares->exists($attrs['share_uid'])) {
                        $share = &$shares->newShare($attrs['share_uid']);
                        $share->set('owner', $attrs['owner']);
                        $share->set('name', $attrs['name']);
                        $shares->addShare($share);
                    } else {
                        // The share exists globally, but may not yet be listed
                        if (empty($remote_shares[$attrs['share_uid']])) {
                            $share = &$shares->getShare($attrs['share_uid']);
                        } else {
                            $share = &$remote_shares[$attrs['share_uid']];
                        }
                        if ($share->get('name') != $attrs['name']) {
                            $share->set('name', $attrs['name']);
                        }
                    }

                    Kolab::updateMappedShare($share_map, $attrs['share_uid'], $folder);
                }

                $current_users = $share->listUsers();

                $perm = &$share->getPermission();
                $must_save = false;

                foreach ($attrs['acl'] as $user => $acl) {
                    $perms = Kolab::aclToPerms($acl);
                    if ($perms != $GLOBALS['perms']->getPermissions($perm, $user)) {
                        $perm->addUserPermission($user, $perms, false);
                        $must_save = true;
                    }
                    $ndx = array_search($user, $current_users);
                    if ($ndx !== false) {
                        unset($current_users[$ndx]);
                    }
                }

                foreach ($current_users as $user) {
                    if ($GLOBALS['perms']->getPermissions($perm, $user) !== false) {
                        $perm->removeUserPermission($user, PERMS_ALL, false);
                        $must_save = true;
                    }
                }

                if ($must_save) {
                    $share->setPermission($perm, false);
                    $share->save();
                }

                if (!empty($attrs['share_uid'])) {
                    unset($remote_shares[$attrs['share_uid']]);
                }
            }
        }

        // Finally, remove any extra shares we may have (these were once folders
        // that were subsequently deleted by another Kolab client). This is only
        // done for shares that the current user owns, i.e. shares that were
        // subfolders of the current users' INBOX.
        foreach ($local_shares as $share) {
            $result = $shares->removeShare($share);
            if (is_a($result, 'PEAR_Error')) {
                return $result;
            }
        }

        // For remote shares, we simply remove the current user from the shares
        // permissions list.
        foreach ($remote_shares as $uid => $share) {
            $perm = &$share->getPermission();
            $perm->removeUserPermission($current_user, PERMS_ALL, false);
            $share->setPermission($perm, false);
            $share->save();
        }

        // And we're done! Disconnect from IMAP, set the last synch'ed app
        // flag to the current application, and update the share map.
        $imap->disconnect();

        $_SESSION[KOLAB_LAST_SYNCHED_APP] = $app;
        Kolab::setShareMap($share_map);

        return true;
    }

    /**
     * Returns the groupware type of the given IMAP folder.
     *
     * @param object $mailbox  The mailbox of interest.
     *
     * @return mixed  A string indicating the groupware type of $mailbox or
     *                boolean "false" on error.
     */
    function getMailboxType($mailbox)
    {
        global $conf;

        $type = false;

        // Connect to the IMAP server
        $imap = new Net_IMAP($conf['kolab']['imap']['server'], $conf['kolab']['imap']['port']);

        // Login using the current Horde credentials
        $result = $imap->login(Auth::getAuth(), Auth::getCredential('password'), false, false);
        if (is_a($result, 'PEAR_Error')) {
            Horde::logMessage('Unable to authenticate with the Kolab IMAP server', __FILE__, __LINE__, PEAR_LOG_ERR);
            $imap->disconnect();
            return $type;
        }

        // Obtain the groupware annotation of $mailbox
        $annotation = $imap->getAnnotation(KOLAB_ANNOT_FOLDER_TYPE, 'value.shared', $mailbox);
        if (!is_a($annotation, 'PEAR_Error') && !empty($annotation)) {
            $type = explode('.', $annotation);
            if ((!empty($type[1]) && $type[1] == 'default') || (empty($type[1]))) {
                $type = $type[0];
            }
        }

        $imap->disconnect();

        return $type;
    }

    /**
     * Return a list of all IMAP folders (including their groupware type) that
     * the current user has acccess to.
     *
     * @return array  An array of array($foldername, $foldertype) items (empty
     *                on error).
     */
    function listFolders()
    {
        global $conf;

        $folders = array();

        // Connect to the IMAP server
        $imap = new Net_IMAP($conf['kolab']['imap']['server'], $conf['kolab']['imap']['port']);

        // Login using the current Horde credentials
        $result = $imap->login(Auth::getAuth(), Auth::getCredential('password'), false, false);
        if (is_a($result, 'PEAR_Error')) {
            Horde::logMessage('Unable to authenticate with the Kolab IMAP server', __FILE__, __LINE__, PEAR_LOG_ERR);
            $imap->disconnect();
            return $folders;
        }

        // Obtain a list of all folders the current user has access to
        $folder_list = $imap->getMailboxes();
        if (is_a($folder_list, 'PEAR_Error')) {
            Horde::logMessage('Unable to obtain IMAP folder list', __FILE__, __LINE__, PEAR_LOG_ERR);
            $imap->disconnect();
            return $folders;
        }

        // Iterate over all the folders obtaining their groupware types
        foreach ($folder_list as $folder) {
            $foldertype = 'mail';

            $annotation = $imap->getAnnotation(KOLAB_ANNOT_FOLDER_TYPE, 'value.shared', $folder);
            if (!is_a($annotation, 'PEAR_Error') && !empty($annotation)) {
                $type = explode('.', $annotation);
                if ((!empty($type[1]) && $type[1] == 'default') || (empty($type[1]))) {
                    $foldertype = $type[0];
                }
            }

            $folders[] = array($folder, $foldertype);
        }

        $imap->disconnect();

        return $folders;
    }

    /**
     * Triggers the freebusy update for the given share uid.
     *
     * @return boolean True if update was successfull, false otherwise.
     */
    function triggerFreeBusyUpdate($share_uid)
    {
        $share_map = Kolab::getShareMap();
        if (empty($share_map[$share_uid])) {
            return false;
        }

        $folder_path = $share_map[$share_uid];

        // IMAP path is either /INBOX/<path>@domain or /user/someone/<path>@domain
        // strip domain
        $end = strrpos($folder_path, '@');
        $folder = substr($folder_path, 0, $end);

        if (!$folder[0] == '/') {
            return false;
        }
        $second_slash = strpos($folder, '/', 1);
        if ($second_slash === false) {
            return false;
        }

        if (strncmp($folder, '/INBOX/', 7) == 0) {
            $folder = Auth::getAuth().substr($folder, $second_slash);
        } else {
            $folder = substr($folder, $second_slash + 1);
        }
        $url = 'https://' . $GLOBALS['conf']['kolab']['imap']['server'] . '/freebusy/trigger/' . $folder . '.pfb';

        // now start the request
        require_once 'HTTP/Request.php';
        $http = new HTTP_Request($url,
                                 array('method' => 'GET',
                                       'timeout' => 5,
                                       'allowRedirects' => true));
        $http->setBasicAuth(Auth::getAuth(), Auth::getCredential('password'));

        @$http->sendRequest();
        if ($http->getResponseCode() != 200) {
            return PEAR::raiseError(sprintf(_("Unable to trigger free/busy update for %s"),
                                    $email));
        }

        return true;
    }

}