summaryrefslogtreecommitdiffstats
path: root/plugins/contacts/symbian/contactsmodel/cntmodel/src/ccontactdatabase.cpp
blob: a64556cd5712a32d37c379058e98dd92a25f71ec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
/*
* Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
* Contact: http://www.qt-project.org/legal
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description: 
*
*/


#include <cntitem.h>
#include <f32file.h>
#include <cntfldst.h>   //for ccontactfieldstorage used in setfieldasspeeddiall
#include <phbksync.h>
#include <cntdb.h>

#include "cntstd.h"
#include "rcntmodel.h"
#include "ccontactprivate.h"

#include "clplproxyfactory.h"
#ifdef SYMBIAN_ENABLE_SPLIT_HEADERS
#include "cntdb_internal.h"
#include "cntsyncecom.h"

const TInt KMajorVersion=1;

const TInt KMinorVersion=0;

const TInt KBuildNumber=40;
#endif

CContactDatabase::CContactDatabase():
		iDbConnectionState(EDbConnectionNotReady),
		iTablesOpen(EFalse),
		iDbViewContactType(KUidContactItem),
		iContactSynchroniser(NULL)
	{
	// Needed to ensure unicode sorting / inserting into sorted lists works the
	// same as er5 i.e. that it encludes all spaces and punctuation.
	iCollateMethod = *Mem::CollationMethodByIndex(0);
	iCollateMethod.iFlags|=TCollationMethod::EIgnoreNone;
	}


/**
Frees all resources owned by the contact database, prior to its destruction.
*/
EXPORT_C CContactDatabase::~CContactDatabase()
	{
	delete iConv;
	delete iProxyFactory;
	delete iView;
	delete iAllFieldsView;
	delete iCardTemplateIds;
	delete iGroupIds;
	delete iTemplateCache;
	delete iTextDef;
	if (iCntSvr)
		{
		iCntSvr->RemoveObserver(*iDataBaseObserver);
		iCntSvr->Close();
		}
	if (iContactSynchroniser)
		{
		iContactSynchroniser->Release();
		iContactSynchroniser = NULL;
		}
	delete iDataBaseObserver;
	delete iCntSvr;
	delete iIdleSorter;
	delete iSortedItems;
	delete iSortOrder;
	REComSession::FinalClose();
	}


/**
Create a new CContactDatabase object 
*/
CContactDatabase* CContactDatabase::NewLC()
	{
	CContactDatabase* db =new(ELeave) CContactDatabase();
	CleanupStack::PushL(db);
	db->ConstructL();
	return db;
	}


void CContactDatabase::ConstructL()
	{
	iCntSvr = new (ELeave) RCntModel;
	iCntSvr->ConnectL();
	iProxyFactory = CProxyFactory::NewL(*this);
	CreateViewDefL();
	iTemplateCache = CCntTemplateCache::NewL(*iCntSvr);
	iDataBaseObserver = CDataBaseChangeObserver::NewL(*this);
	iCntSvr->AddObserverL(*iDataBaseObserver);
	iIdleSorter = CCntIdleSorter::NewL(*this);
	}


void CContactDatabase::CreateViewDefL()
	{
	// The exact same object is created in the Session on the server. If
	// it is changed here it must also be changed in the server code.
	CContactItemViewDef* itemDef = CContactItemViewDef::NewLC(CContactItemViewDef::EIncludeFields,CContactItemViewDef::EMaskHiddenFields);
	itemDef->AddL(KUidContactFieldMatchAll);
	iView = CContactViewDef::NewL(itemDef);
	CleanupStack::Pop(itemDef);

	// iAllFieldView is not created on the server code - an exported getter method
	// allows the user to modify this member and so it cannot be mirrored on the
	// server
	iAllFieldsView = CContactItemViewDef::NewL(CContactItemViewDef::EMaskFields,CContactItemViewDef::EIncludeHiddenFields);
	}


/**
For BC.

@internalComponent
*/
EXPORT_C CContactDatabase* CContactDatabase::LockServerConnectL(const TDesC& /*aFileName*/)
	{
	return NULL;
	}


/**
For BC.

@internalComponent
*/
EXPORT_C CContactDatabase* CContactDatabase::LockServerConnectL(const TDesC& /*aFileName*/, TInt /*aOperation*/)
	{
	return NULL;
	}


/**
For BC.

@internalComponent
*/
EXPORT_C TInt CContactDatabase::LockServerCallBackL(TUint /*aServerOperation*/)
	{
	return NULL;
	}


/**
For BC.

@internalComponent
*/
EXPORT_C void CContactDatabase::LockServerCleanup()
	{
	}


/**
Gets the file name of the default contact database.

By default it is on drive C: but this can be changed using SetDatabaseDriveL().

@capability None

@param aDes On return, contains the drive and filename of the default 
contact database. From v9.0 onwards, this has the form driveletter:filename, 
in other words, it does not include a path.

@see CContactDatabase::SetDatabaseDriveL()
@see CContactDatabase::DatabaseDrive()
@see CContactDatabase::DefaultContactDatabaseExistsL()
*/
EXPORT_C void CContactDatabase::GetDefaultNameL(TDes& aDes)
	{
	CContactDatabase* db = NewLC();
	User::LeaveIfError(db->iCntSvr->DefaultDatabase(aDes));
	CleanupStack::PopAndDestroy(db);	
	}


/**
Deletes the default contact database.

@capability WriteUserData

@leave	KErrInUse Another client has the database open.
@leave	KErrNotFound The database file was not found or it did not have the correct UIDs.

@see CContactDatabase::DeleteDatabaseL()
@see CContactDatabase::GetDefaultNameL()
@see CContactDatabase::DefaultContactDatabaseExistsL()
*/
EXPORT_C void CContactDatabase::DeleteDefaultFileL()
	{
	CContactDatabase* db = NewLC();
	User::LeaveIfError(db->iCntSvr->DeleteDatabase(KNullDesC));
	CleanupStack::PopAndDestroy(db);
	}


/**
Gets the current database drive. The database drive is the drive on which 
the default contact database is located. Note: this function can leave.

@capability None

@param aDriveUnit On return, contains the database drive.

@return ETrue if the database drive has been set using SetDatabaseDriveL(). 
Otherwise EFalse and in this case, the function returns drive c: in aDriveUnit 
as the current drive.

@leave KErrNoMemory Out of memory.

@see CContactDatabase::SetDatabaseDrive()
@see CContactDatabase::GetDefaultNameL()
*/
EXPORT_C TBool CContactDatabase::DatabaseDrive(TDriveUnit& aDriveUnit)
	{
	CContactDatabase* db = NewLC(); // this can leave
	TBool ret = db->iCntSvr->DatabaseDrive(aDriveUnit);
	CleanupStack::PopAndDestroy(db);
	return ret;
	}


/**
Sets the contact database drive and optionally moves the default contact database 
from its current location to the new drive. This function guarantees an all 
or nothing operation. If the database is not successfully moved, the drive 
setting is not updated to reflect the change.

In v8.1 when copying the file is moved to \\system\\data on the specified 
drive, and if the destination file already exists it is replaced.

From v9.0 onwards the file copying goes to the correct data caged directory
on the destination drive. If the destination file already exists the copy 
fails.

@capability WriteUserData

@param	aDriveUnit
		The drive to which to move the database.
@param	aCopy
		ETrue moves the existing file to the specified drive. Deletion of
		the source file will fail if it is in use.
		EFalse does not move the file.

@leave KErrNotReady There is no media present in the drive.
@leave KErrInUse The destination file for the copy is already open.
@leave KErrNotFound The source file for the copy was not found.
@leave KErrAlreadyExists The destination file for the copy already exists, (v9.0).

@see CContactdatabase::DatabaseDrive()
@see CContactDatabase::GetDefaultNameL()
@see CContactDatabase::DefaultContactDatabaseExistsL()
*/
EXPORT_C void CContactDatabase::SetDatabaseDriveL(TDriveUnit aDriveUnit, TBool aCopy)
	{
	CContactDatabase* db = NewLC();
	db->iCntSvr->SetDatabaseDriveL(aDriveUnit, aCopy);
	CleanupStack::PopAndDestroy(db); 
	}


/**
Opens the default contact database.

Note: clients should not assume any knowledge of the default database name or location 
because they may be changed in future releases.

@capability ReadUserData

@param  aAccess The default (ESingleThread) allows access to the session with the 
database server from a single client thread only (as in v5 and v5.1). EMultiThread 
allows multiple client threads to share the same session with the server. As 
multi-threaded programs are uncommon in Symbian OS, this argument can be ignored 
by most C++ developers

@return Pointer to the open contact database. 

@leave	KErrNotFound The database file was not found or it did not have the correct UIDs.
@leave	KErrLocked Another client is writing to the database. 
@leave	KErrDiskFull The disk does not have enough free space to perform the operation.
*/
EXPORT_C CContactDatabase* CContactDatabase::OpenL(TThreadAccess aAccess)
	{
	CContactDatabase* db = NewLC();
	User::LeaveIfError(db->iCntSvr->OpenDatabase(KNullDesC));
	if( aAccess == EMultiThread )
		{
		db->iCntSvr->ShareAuto();
		} 
	db->FetchGroupAndTemplateListsL();
	CleanupStack::Pop(db);
	return db;
	}

EXPORT_C CContactDatabase* CContactDatabase::OpenV2L(TThreadAccess aAccess)
	{
    CContactDatabase* db = NewLC();
	User::LeaveIfError(db->iCntSvr->OpenDatabase(KNullDesC));
	if( aAccess == EMultiThread )
		{
		db->iCntSvr->ShareAuto();
		} 
	CleanupStack::Pop(db);
	return db;
	}

/**
Opens a named contact database.

From v9.0 onwards, contact databases can only be located in the correct data caged 
subdirectory. The filenames must have no path, for example c:contacts.cdb.
The maximum length for the drive, filename and extension is 190 characters, and empty
string is not accepted.

@capability ReadUserData

@param	aFileName The filename of the database to open.
@param  aAccess The default (ESingleThread) allows access to the session with the 
database server from a single client thread only (as in v5 and v5.1). EMultiThread 
allows multiple client threads to share the same session with the server. As 
multi-threaded programs are uncommon in Symbian OS, this argument can be ignored 
by most C++ developers

@leave	KErrNotFound The database file was not found or it did not have the correct UIDs.
@leave	KErrLocked Another client is writing to the database.
@leave	KErrBadName The filename is invalid; for example it contains 
wildcard characters or the drive is missing.
@leave	KErrDiskFull The disk does not have enough free space to perform the operation.
@leave  KErrArgument if the given descriptor contains more than the maximum length 
        of 190 characters.

@return A pointer to the open contact database.
*/
EXPORT_C CContactDatabase* CContactDatabase::OpenL(const TDesC& aFileName, TThreadAccess aAccess)
	{
	__ASSERT_ALWAYS(aFileName.Length() != 0, User::Leave(KErrBadName) );
	CContactDatabase* db = NewLC();
	User::LeaveIfError(db->iCntSvr->OpenDatabase(aFileName));
	if( aAccess == EMultiThread )
		{
		db->iCntSvr->ShareAuto();
		} 
	db->FetchGroupAndTemplateListsL();
	CleanupStack::Pop(db);
	return db;
	}


/** 
Creates and opens an empty contact database, replacing the existing default 
database. 

@capability WriteUserData

@param  aAccess The default (ESingleThread) allows access to the session with the 
database server from a single client thread only (as in v5 and v5.1). EMultiThread 
allows multiple client threads to share the same session with the server. As 
multi-threaded programs are uncommon in Symbian OS, this argument can be ignored 
by most C++ developers

@return Pointer to the new contact database.

@leave	KErrInUse Another client has an open connection to the database.
@leave	KErrDiskFull The disk does not have enough free space to perform the operation.
@leave	KErrNoMemory There is no memory to perform the operation.
*/
EXPORT_C CContactDatabase* CContactDatabase::ReplaceL(TThreadAccess aAccess)
	{
	CContactDatabase* db = NewLC();
	User::LeaveIfError(db->iCntSvr->ReplaceDatabase(KNullDesC));
	if( aAccess == EMultiThread )
		{
		db->iCntSvr->ShareAuto();
		} 
	db->FetchGroupAndTemplateListsL();
	CleanupStack::Pop(db);
	return db;
	}
	
	
/**
Creates and opens an empty contact database, replacing any existing file with 
the same name.

From v9.0 onwards, contact databases can only be located in the correct data caged 
subdirectory. The filenames must have no path, for example c:contacts.cdb.
The maximum length for the drive, filename and extension is 190 characters.

@capability WriteUserData

@param	aFileName The filename of the database to replace.
@param  aAccess The default (ESingleThread) allows access to the session with the 
database server from a single client thread only (as in v5 and v5.1). EMultiThread 
allows multiple client threads to share the same session with the server. As 
multi-threaded programs are uncommon in Symbian OS, this argument can be ignored 
by most C++ developers

@leave	KErrBadName The filename is invalid; for example it contains wildcard characters 
or the drive letter is missing.
@leave	KErrInUse Another client has an open connection to the database.
@leave	KErrDiskFull The disk does not have enough free space to perform the operation.
@leave	KErrNoMemory There is no memory to perform the operation.
@leave  KErrArgument if the given descriptor contains more than the maximum length 
        of 190 characters.

@return A pointer to the new contact database.
*/				
EXPORT_C CContactDatabase* CContactDatabase::ReplaceL(const TDesC& aFileName, TThreadAccess aAccess)
	{
	__ASSERT_ALWAYS(aFileName.Length() != 0, User::Leave(KErrBadName) );
	CContactDatabase* db = NewLC();
	User::LeaveIfError(db->iCntSvr->ReplaceDatabase(aFileName)); 
	if( aAccess == EMultiThread )
		{
		db->iCntSvr->ShareAuto();
		} 
	db->FetchGroupAndTemplateListsL();
	CleanupStack::Pop(db);
	return db;
	}


/** 
Creates and opens an empty contact database using the default database name. 

@capability WriteUserData

@param  aAccess The default (ESingleThread) allows access to the session with the 
database server from a single client thread only (as in v5 and v5.1). EMultiThread 
allows multiple client threads to share the same session with the server. As 
multi-threaded programs are uncommon in Symbian OS, this argument can be ignored 
by most C++ developers

@return A pointer to the new contact database. 

@leave	KErrAlreadyExists The database already exists.
@leave	KErrDiskFull The disk does not have enough free space to perform the operation.
*/
EXPORT_C CContactDatabase* CContactDatabase::CreateL(TThreadAccess aAccess)
	{
	CContactDatabase* db = NewLC();
	User::LeaveIfError(db->iCntSvr->CreateDatabase(KNullDesC)); 
	if( aAccess == EMultiThread )
		{
		db->iCntSvr->ShareAuto();
		} 
	db->FetchGroupAndTemplateListsL();
	CleanupStack::Pop  (db);
	return db;	
	}

EXPORT_C CContactDatabase* CContactDatabase::CreateV2L(TThreadAccess aAccess)
	{
	CContactDatabase* db = NewLC();
	User::LeaveIfError(db->iCntSvr->CreateDatabase(KNullDesC)); 
	if( aAccess == EMultiThread )
		{
		db->iCntSvr->ShareAuto();
		} 
	CleanupStack::Pop  (db);
	return db;	
	}


/**
Creates and opens a named contact database. 

From v9.0 onwards, contact databases can only be located in the correct data caged 
subdirectory. The filenames must have no path, for example c:contacts.cdb.
The maximum length for the drive, filename and extension is 190 characters.

@capability WriteUserData

@param	aFileName The filename of the database to create. 
@param  aAccess The default (ESingleThread) allows access to the session with the 
database server from a single client thread only (as in v5 and v5.1). EMultiThread 
allows multiple client threads to share the same session with the server. As 
multi-threaded programs are uncommon in Symbian OS, this argument can be ignored 
by most C++ developers

@leave	KErrAlreadyExists The database already exists. 
@leave	KErrBadName The filename is invalid; for example it contains wildcard characters 
or the drive letter is missing.
@leave	KErrDiskFull The disk does not have enough free space to perform the operation.
@leave  KErrArgument if the given descriptor contains more than the maximum length 
        of 190 characters.

@return A pointer to the new contact database.
*/
EXPORT_C CContactDatabase* CContactDatabase::CreateL(const TDesC& aFileName,TThreadAccess aAccess)
	{
	__ASSERT_ALWAYS(aFileName.Length() != 0, User::Leave(KErrBadName) );
	CContactDatabase* db = NewLC();
	User::LeaveIfError(db->iCntSvr->CreateDatabase(aFileName)); 
	if( aAccess == EMultiThread )
		{
		db->iCntSvr->ShareAuto();
		} 
	db->FetchGroupAndTemplateListsL();
	CleanupStack::Pop  (db);
	return db;	
	}


/**
This method is no longer required and should not be called.

Closes all database tables. After a rollback and recover all tables need to 
be closed and re-opened before the database can be accessed again.

@capability WriteUserData
@deprecated
*/
EXPORT_C void CContactDatabase::CloseTables()
	{  	
	TRAP_IGNORE( iCntSvr->CloseTablesL() );   
	}


/** 
This method is no longer required and should not be called.

Opens all database tables. After a rollback and recover all tables need to 
be closed and re-opened before the database can be accessed again.

@capability ReadUserData
@deprecated
*/
EXPORT_C void CContactDatabase::OpenTablesL()
	{
	iCntSvr->OpenTablesL();	
	}


/**
A static method to recreate the system template. 

From v9.0 onwards, contact databases can only be located in the correct data caged 
subdirectory. The filenames must have no path, for example c:contacts.cdb. 
The maximum length for the drive, filename and extension is 190 characters.

@publishedPartner
@released
@capability ReadUserData 
@capability WriteUserData

@param aFileName The contact database filename.

@leave KErrBadName The filename is invalid; for example it contains wildcard characters 
or the drive letter is missing.
@leave  KErrArgument if the given descriptor contains more than the maximum length 
        of 190 characters.
*/
EXPORT_C void CContactDatabase::RecreateSystemTemplateL(const TDesC& aFileName)
	{
	// Workaround for dynamic language switching because the system template may need to be recreated in a different language.
	CContactDatabase* db = NewLC();
	User::LeaveIfError(db->iCntSvr->OpenDatabase(aFileName)); 
	User::LeaveIfError(db->iCntSvr->ReCreateTemplate());
	CleanupStack::PopAndDestroy(db); 
	}

	
/**
Sets the default view definition. The contact database takes ownership of the 
view definition specified. The default view definition is used in calls to 
ReadContactL(), ReadContactLC() and ReadContactAndAgentL() when no view definition 
is explicitly specified.

@capability WriteUserData

@param aView The view definition. This method does nothing if this is null.
*/
EXPORT_C void CContactDatabase::SetViewDefinitionL(CContactViewDef* aView)
	{
    if (aView)
        {
    	iCntSvr->SetViewDefinitionL(*aView);
    	// We also need to hold the ViewDef here - it is used in merging
    	delete iView;
    	iView = aView;
        }
	}

	
/**
Sets the text definition. The contact database takes ownership of the 
text definition specified.

@param aTextDef The new text definition. 
*/
EXPORT_C void CContactDatabase::SetTextDefinitionL(CContactTextDef* aTextDef)
	{
	delete iTextDef;
	iTextDef = aTextDef;
	}

	
/**
Gets a pointer to the text definition.

@return A pointer to the text definition. 
*/
EXPORT_C const CContactTextDef* CContactDatabase::TextDefinition() const
	{
	return iTextDef;
	}


void CContactDatabase::CleanupDatabaseRollback(TAny *aDatabase)
	{
	ASSERT(aDatabase);
	CContactDatabase* db = static_cast<CContactDatabase*>(aDatabase);
	db->DatabaseRollback();
	}


/**
Starts a new transaction. Places and leaves a cleanup item to rollback
the database on the cleanupstack. 

@publishedPartner
@released

@param aIsInTransaction Used to determine whether or not to start the transaction depending on if a transaction is currently in progress.
@leave KErrDiskFull There is insufficient disk space.
*/
EXPORT_C void CContactDatabase::DatabaseBeginLC(TBool aIsInTransaction)
	{
	if (!aIsInTransaction)
		{
		User::LeaveIfError(iCntSvr->BeginDbTransaction());	
		CleanupStack::PushL(TCleanupItem(CleanupDatabaseRollback, this));
		}
	}


/**
Commits an existing transaction, pops the rollback cleanup item off the CleanupStack.
Closes the database if the connection state is EDbConnectionNeedToCloseForRestore.

@publishedPartner
@released

@param aIsInTransaction Used to determine whether or not to commit the transaction depending on whether a transaction is currently in progress.
*/
EXPORT_C void CContactDatabase::DatabaseCommitLP(TBool aIsInTransaction)
	{
	if (!aIsInTransaction)
		{
		User::LeaveIfError(iCntSvr->CommitDbTransaction());
		CleanupStack::Pop(); // CleanupDatabaseRollback
		}
	}


/**
This function is not currently supported.
@deprecated
*/
EXPORT_C void CContactDatabase::StoreSortOrderL()
	{
	// Does nothing in the new architecture.
	}


/**
This function is not currently supported.
@deprecated
*/
EXPORT_C void CContactDatabase::RestoreSortOrderL()
	{
	//Does nothing in the new architecture
	}


/** 
 Gets the array of sort preferences.
 
 Note: This method can leave.
 
 @deprecated
 @capability None
 @return A pointer to an array of sort preferences of the contact database.
*/
EXPORT_C const CArrayFix<CContactDatabase::TSortPref>* CContactDatabase::SortOrder() const
	{
    CArrayFix<CContactDatabase::TSortPref>* prefs = NULL;
    TRAPD( err, prefs = iCntSvr->GetSortPreferenceL() );
    if ( err != KErrNone )
        {
	prefs = NULL; // return NULL if have some error
	}
    return prefs;
	}


/** 
Adds a new contact item to the database and returns its ID.

@capability WriteUserData

@param aContact The contact item to add to the database.

@leave KErrDiskFull The disk does not have enough free space to perform the operation.

@return The ID of the new contact item. 
*/
EXPORT_C TContactItemId CContactDatabase::AddNewContactL(CContactItem& aContact)
	{
	return doAddNewContactL(aContact, EFalse, EFalse);
	}


/** 
Adds a new contact item to the database and returns its ID.

@capability WriteUserData

@param aContact The contact item to add to the database.
@param aIsTemplate This argument should be ignored by developers.
@param aIsInTransaction This argument should be ignored by developers.

@leave KErrDiskFull The disk does not have enough free space to perform the operation.

@return The ID of the new contact item. 
*/
EXPORT_C TContactItemId CContactDatabase::doAddNewContactL(CContactItem& aContact,TBool /*aIsTemplate*/,TBool /*aIsInTransaction*/)
	{
	if (aContact.Type() == KUidContactICCEntry)
	    {
		LoadSyncPluginL();
	    }
	
	aContact.iId = iCntSvr->CreateContactL(aContact);

	if (CheckType(aContact.Type()))
		{
		InsertInSortArray(aContact);
		}

	return aContact.iId;
	}


CContactItem* CContactDatabase::doCreateContactGroupLC(const TDesC& aGroupLabel)
	{
	CContactItem* newGroup = CContactGroup::NewLC();
	newGroup->AddLabelFieldL();
	if (aGroupLabel != KNullDesC)
		STATIC_CAST(CContactGroup*, newGroup)->SetGroupLabelL(aGroupLabel);

	newGroup->iId = AddNewContactL(*newGroup);
	RespondToEventL(EContactDbObserverEventGroupAdded, newGroup->iId);
	return newGroup;
	}

	
/**
Creates a new contact group with a default label of 'Group Label' and 
adds it to the database. 

The caller takes ownership of the returned object.

@capability WriteUserData

@param aInTransaction This argument should be ignored by developers.

@return Pointer to the newly created contact group. 
*/
EXPORT_C CContactItem* CContactDatabase::CreateContactGroupL(TBool aInTransaction)
	{
	CContactItem* newGroup = CContactDatabase::CreateContactGroupLC(aInTransaction);
	CleanupStack::Pop(newGroup);
	return newGroup;
	}


/**
Creates a new contact group with a default label of 'Group Label' and 
adds it to the database. 

The caller takes ownership of the returned object.

@capability WriteUserData

@param aInTransaction This argument should be ignored by developers.

@return Pointer to the newly created contact group. 
*/
EXPORT_C CContactItem* CContactDatabase::CreateContactGroupLC(TBool /*aInTransaction*/)
	{
	return doCreateContactGroupLC();
	}

	
/** 
Creates a new contact group with a specified label and adds it to the database. 

The pointer to the group is left on the cleanup stack. The caller takes 
ownership of the returned object.

@capability WriteUserData

@param aGroupLabel The string to set as the group label.
@param aInTransaction This argument should be ignored by developers.

@leave KErrDiskFull The disk does not have enough free space to perform the operation.

@return Pointer to the newly created contact group. 
*/
EXPORT_C CContactItem* CContactDatabase::CreateContactGroupLC(const TDesC& aGroupLabel, TBool /*aInTransaction*/)
	{
	return doCreateContactGroupLC(aGroupLabel);
	}


/** 
Creates a new contact group with a specified label and adds it to the database. 

The caller takes ownership of the returned object.

@capability WriteUserData

@param aGroupLabel The string to set as the group label.
@param aInTransaction This argument should be ignored by developers.

@return Pointer to the newly created contact group. 
*/
EXPORT_C CContactItem* CContactDatabase::CreateContactGroupL(const TDesC& aGroupLabel,TBool aInTransaction)
	{
	CContactItem* newGroup = CContactDatabase::CreateContactGroupLC(aGroupLabel, aInTransaction);
	CleanupStack::Pop(newGroup);
	return newGroup;
	}

	
/** 
Creates a contact card template based on the system template and adds it to the database.

A template label must be specifed. This can be changed later using CContactCardTemplate::SetTemplateLabelL(). 

The pointer to the template is left on the cleanup stack. The caller takes ownership of the returned object.

@capability WriteUserData

@param aTempLabel The string to set as the template label. 
@param aInTransaction This argument should be ignored by developers.

@leave KErrDiskFull The disk does not have enough free space to perform the operation.

@return Pointer to the contact card template. 
*/
EXPORT_C CContactItem* CContactDatabase::CreateContactCardTemplateLC(const TDesC& aTempLabel, TBool aInTransaction)
	{
	return CreateContactCardTemplateLC(&iTemplateCache->SystemTemplateL(), aTempLabel, aInTransaction);
	}


/** 
Creates a contact card template based on the system template and adds it to the database.

A template label must be specifed. This can be changed later using CContactCardTemplate::SetTemplateLabelL(). 

The caller takes ownership of the returned object.

@capability WriteUserData

@param aTempLabel The string to set as the template label. 
@param aInTransaction This argument should be ignored by developers.

@return Pointer to the contact card template. 
*/
EXPORT_C CContactItem* CContactDatabase::CreateContactCardTemplateL(const TDesC& aTempLabel, TBool aInTransaction)
	{
	CContactItem *cntItem = CreateContactCardTemplateLC(&iTemplateCache->SystemTemplateL(), aTempLabel, aInTransaction);
	CleanupStack::Pop(cntItem);
	return cntItem;
	}

	
/** 
Creates a contact card template and adds it to the database.
 
The new template's field set is based on the specified contact item. This could be a 
contact card, an own card, another template or even a group. Note that no field data 
is copied into the new template. All of the new template's fields are marked as template 
fields.

A template label must be specifed. This can be changed later using CContactCardTemplate::SetTemplateLabelL(). 

The caller takes ownership of the returned object.

@capability WriteUserData

@param aTemplate Pointer to an instance of a CContactItem-derived class. This 
is used to initialise the new template's field set.
@param aTemplateLabel The string to set as the template label.
@param aInTransaction This argument should be ignored by developers.

@return Pointer to the contact card template. 
*/
EXPORT_C CContactItem* CContactDatabase::CreateContactCardTemplateL(const CContactItem* aTemplate,const TDesC& aTempLabel,TBool aInTransaction)
	{
	CContactItem *cntItem = CreateContactCardTemplateLC(aTemplate, aTempLabel, aInTransaction);
	CleanupStack::Pop(cntItem);
	return cntItem;
	}


/** 
Creates a contact card template and adds it to the database.
 
The new template's field set is based on the specified contact item. This could be a 
contact card, an own card, another template or even a group. Note that no field data 
is copied into the new template. All of the new template's fields are marked as template 
fields.

A template label must be specifed. This can be changed later using CContactCardTemplate::SetTemplateLabelL(). 

The pointer to the object is left on the cleanup stack. The caller takes ownership of it.

@capability WriteUserData

@param aTemplate Pointer to an instance of a CContactItem-derived class. This 
is used to initialise the new template's field set.
@param aTemplateLabel The string to set as the template label.
@param aInTransaction This argument should be ignored by developers.

@leave KErrDiskFull The disk does not have enough free space to perform the operation.

@return Pointer to the contact card template. 
*/
EXPORT_C CContactItem* CContactDatabase::CreateContactCardTemplateLC(const CContactItem* aTemplate, const TDesC& aLabel, TBool /*aInTransaction*/)
	{
	CContactItem* newTemplate = CContactCardTemplate::NewLC(aTemplate); 
	// Clear all data from the new template
	newTemplate->ClearFieldContent();

	// Add label field
	newTemplate->AddLabelFieldL();
	static_cast<CContactCardTemplate*>(newTemplate)->SetTemplateLabelL(aLabel);

	// Create the contact in the database	
	newTemplate->iId = AddNewContactL(*newTemplate);
	AddToTemplateListL(newTemplate->Id());
	return newTemplate;
	}


void CContactDatabase::AddToTemplateListL(const TContactItemId aNewTemplateId)
	{
	if (!iCardTemplateIds)
		{
		iCardTemplateIds = CContactIdArray::NewL();
		}
	RespondToEventL(EContactDbObserverEventTemplateAdded, aNewTemplateId);
	}


void CContactDatabase::RemoveFromTemplateList(const TContactItemId aTemplateId)
	{	
	if (iCardTemplateIds)
 		{
		TInt templatePos =	iCardTemplateIds->Find(aTemplateId);
		if (templatePos != KErrNotFound)
			{
			iCardTemplateIds->Remove(templatePos);
			}
 		}	
	}


/**
Gets a copy of the database's template ID list. This is a list of the IDs 
of all contact card templates which have been added to the database. The caller 
takes ownership of the returned object.

@return Pointer to a copy of the database's template ID list. This does 
not include the system template. NULL if there are no templates in the database. 
*/
EXPORT_C CContactIdArray* CContactDatabase::GetCardTemplateIdListL() const
	{
	if (iCardTemplateIds)
		{
		CContactIdArray* copyArray = CContactIdArray::NewL(iCardTemplateIds);
		return copyArray;
		}
	else
		return NULL;
	}


void CContactDatabase::ReadTemplateIdsL()
	{
	const_cast<CContactDatabase*>(this)->FetchGroupAndTemplateListsL();
	}
	

/** Determines if the System template fields are valid.  Valid means that no
fields contain data.
@internalTechnology
@released
@capability None
@param aContact Contact item representing the System template.
@return ETrue if the System template fields are valid, EFalse otherwise.
*/
TBool CContactDatabase::SystemTemplateFieldsValid( const CContactItem& aContact )
	{
	// Precondition: aContact's ID must match the System template's ID.
	__ASSERT_ALWAYS( aContact.Id() == TemplateId(), Panic(ECntPanicSystemTemplate) );

	TBool fieldsValid = ETrue;
	CContactItemFieldSet& fieldSet = aContact.CardFields();

	for( TInt ii = 0; ii < fieldSet.Count(); ii++ )
		{
		CContactItemField& field = fieldSet[ii];
		CContactFieldStorage* fieldStorage = field.Storage();
		//
		// If the field contains data (is "full") then the System template
		// fields are not valid.
		//
		if( fieldStorage->IsFull() )
			{
			fieldsValid = EFalse;
			break;
			}
		}
	
	return fieldsValid;
	}


/**
Returns a copy of the database's group ID list. This is a list which contains 
the contact item IDs for each group in the database. The caller takes ownership 
of the returned object.

@return Pointer to an array containing the contact item IDs for each group 
in the database. NULL if there are no groups in the database. 
*/
EXPORT_C CContactIdArray* CContactDatabase::GetGroupIdListL() const
	{
	const_cast<CContactDatabase*>(this)->FetchGroupAndTemplateListsL();
	CContactIdArray* copyArray = CContactIdArray::NewL(iGroupIds);
	return copyArray;
	}

/** 
Sets a list of contact items in the database to be members of a contact group.

The items and the group are identified by their IDs. 

@capability WriteUserData

@param aItemIdList The list of IDs of the items to add to the group.
@param aGroupId  The ID of the group to which the items should be added. 

@leave KErrNotFound Either the group or the item does not exist.
@leave KErrNotSupported The group is not of type KUidContactGroup. 
@leave KErrDiskFull The disk does not have enough free space to perform the operation.
*/
EXPORT_C void CContactDatabase::AddContactsToGroupL(RArray<TContactItemId>& aItemIdList, TContactItemId aGroupId)
	{
	//Remember if the group was already opened, if so open it at the end of the method
	TBool isAlreadyOpened = iCntSvr->CloseContact(aGroupId);
	CContactItem* cntGroup = OpenNoMergeLCX(aGroupId); //double push

	if (cntGroup->Type() != KUidContactGroup)
		User::Leave(KErrNotSupported);

	CContactGroup* group = static_cast<CContactGroup*>(cntGroup);

    TBool isGroupModified = EFalse;
    TInt itemCount = aItemIdList.Count();
    for (TInt i = 0; i < itemCount; ++i)
        {
    	TContactItemId itemId = aItemIdList[i];
    	if (!group->ContainsItem(itemId))
		    {
		    group->AddContactL(itemId);
		    isGroupModified = ETrue;
		    }
        }

    if (isGroupModified)
        {
	    iCntSvr->CommitContactL(*cntGroup);
		}
	else
		{
		iCntSvr->CloseContact(cntGroup->Id());
		}

	CleanupStack::PopAndDestroy(cntGroup);	// cntGroup
	CleanupStack::Pop(); // Pop the lock
	cntGroup = NULL;
	if (isAlreadyOpened)
		{
		CContactItem* dummy = OpenContactL(aGroupId);
		delete dummy;				
		}
	}

/** 
Sets a contact item in the database to be a member of a contact group.

The item and group are identified by their IDs. 

@capability WriteUserData

@param aItemId The ID of the item to add to the group.
@param aGroupId  The ID of the group to which the item should be added. 

@leave KErrNotFound Either the group or the item does not exist.
@leave KErrNotSupported The group is not of type KUidContactGroup. 
@leave KErrDiskFull The disk does not have enough free space to perform the operation.
*/
EXPORT_C void CContactDatabase::AddContactToGroupL(TContactItemId aItemId, TContactItemId aGroupId)
	{
	//Remember if the group was already opened, if so open it at the end of the method
	TBool isAlreadyOpened = iCntSvr->CloseContact(aGroupId);

	CContactItem* cntGroup = OpenNoMergeLCX(aGroupId); //double push
	
	if (cntGroup->Type() != KUidContactGroup)
		User::Leave(KErrNotSupported);
	AddCntToOpenedGroupL(aItemId, *cntGroup);

	CleanupStack::PopAndDestroy(cntGroup);	// cntGroup
	CleanupStack::Pop(); // Pop the lock
	cntGroup = NULL;
	if (isAlreadyOpened)
		{
		CContactItem* dummy = OpenContactL(aGroupId);
		delete dummy;				
		}
	}


/** 
Sets a contact item in the database to be a member of a contact group.

The item and group are identified by their IDs. 

@capability WriteUserData

@param aItemId The ID of the item to add to the group.
@param aGroupId  The ID of the group to which the item should be added. 
@param aInTransaction This argument should be ignored by developers.

@leave KErrNotFound Either the group or the item does not exist.
@leave KErrNotSupported The group is not of type KUidContactGroup. 
@leave KErrDiskFull The disk does not have enough free space to perform the operation.
*/
EXPORT_C void CContactDatabase::AddContactToGroupL(TContactItemId aItemId, TContactItemId aGroupId, TBool /*aInTransaction*/)
	{
	AddContactToGroupL(aItemId, aGroupId);	
	}

	
/** 
Sets a contact item in the database to be a member of a contact group. 

@capability WriteUserData

@param aItem The item to add to the group.
@param aGroup  The group to which the item should be added. 

@leave KErrNotFound Either the group or the item does not exist in the database.
@leave KErrNotSupported The group is not of type KUidContactGroup.
@leave KErrDiskFull The disk does not have enough free space to perform the operation.
*/
EXPORT_C void CContactDatabase::AddContactToGroupL(CContactItem& aItem, CContactItem& aGroup)
	{
	if (aGroup.Type() != KUidContactGroup)
		{
		User::Leave(KErrNotSupported);
		}

	AddContactToGroupL(aItem.Id(), aGroup.Id());

	//Update client's group object
	static_cast<CContactGroup&>(aGroup).AddContactL(aItem.Id());

	//Update client's contacts item object
	CContactItemPlusGroup& item = static_cast<CContactItemPlusGroup&>(aItem);
	if (!item.iGroups)
		{
		item.iGroups = CContactIdArray::NewL();
		}
	item.iGroups->AddL(aGroup.Id());
	}


/** 
Removes the association between a contact item and a group.

@capability WriteUserData

@param aItem The item to remove.
@param aGroup The group from which the item should be removed.

@leave KErrDiskFull The disk does not have enough free space to perform the operation. 
*/
EXPORT_C void CContactDatabase::RemoveContactFromGroupL(CContactItem& aItem, CContactItem& aGroup)
	{
	if (aGroup.Type() != KUidContactGroup)
		{
		User::Leave(KErrNotSupported);
		}
	
	RemoveContactFromGroupL(aItem.Id(), aGroup.Id()); //Perform the change in the database

	//Update client's group object
	static_cast<CContactGroup&>(aGroup).RemoveContactL(aItem.Id());

	//Update client's contacts item object
	CContactItemPlusGroup& item = static_cast<CContactItemPlusGroup&>(aItem);
	if (item.iGroups)
		{
		const TInt groupIndex = item.iGroups->Find(aGroup.Id());
		if (groupIndex>=0)
			{
			item.iGroups->Remove(groupIndex);
			}
		}
	}


void CContactDatabase::AddCntToOpenedGroupL(TContactItemId aItemId, CContactItem& aGroup)
	{
	CContactGroup& group = static_cast<CContactGroup&>(aGroup);
	if (!group.ContainsItem(aItemId))
		{
		group.AddContactL(aItemId);
	    iCntSvr->CommitContactL(aGroup);
		}
	else
		{
		iCntSvr->CloseContact(aGroup.Id());
		}
	}


/** 
Removes the association between a contact item and a group.

The item and group are identified by their IDs. 

@capability WriteUserData

@param aItemId The ID of the item to remove.
@param aGroupId The ID of the group from which the item should be removed. 

@leave KErrDiskFull The disk does not have enough free space to perform the operation.
*/
EXPORT_C void CContactDatabase::RemoveContactFromGroupL(TContactItemId aItemId, TContactItemId aGroupId)
	{
	//Remember if the group was already opened, if so open it at the end of the method
	TBool isAlreadyOpened = iCntSvr->CloseContact(aGroupId);
	CContactItem* cntGroup = OpenNoMergeLCX(aGroupId); //double push
	
	if (cntGroup->Type() != KUidContactGroup)
		{
		User::Leave(KErrNotSupported);
		}
	
	CContactGroup* group = static_cast<CContactGroup*>(cntGroup);
	if (group->ContainsItem(aItemId))
		{
		group->RemoveContactL(aItemId);
	    iCntSvr->CommitContactL(*cntGroup);
		}
	else
		{
		iCntSvr->CloseContact(cntGroup->Id());
		}
		
	CleanupStack::PopAndDestroy(2); // cntGroup, CntItemClose
	cntGroup = NULL;
	
	if (isAlreadyOpened)
		{
		CContactItem* dummy = OpenContactL(aGroupId);
		delete dummy;				
		}

	}


/** 
Removes the association between a list of contact items and a group.

The items and the group are identified by their IDs. 

@capability WriteUserData

@param aItemId The list of IDs of the items to remove.
@param aGroupId The ID of the group from which the items should be removed. 

@leave KErrDiskFull The disk does not have enough free space to perform the operation.
*/
EXPORT_C void CContactDatabase::RemoveContactsFromGroupL(RArray<TContactItemId>& aItemIdList, TContactItemId aGroupId)
	{
	//Remember if the group was already opened, if so open it at the end of the method
	TBool isAlreadyOpened = iCntSvr->CloseContact(aGroupId);
	CContactItem* cntGroup = OpenNoMergeLCX(aGroupId); //double push
	
	if (cntGroup->Type() != KUidContactGroup)
		{
		User::Leave(KErrNotSupported);
		}

	CContactGroup* group = static_cast<CContactGroup*>(cntGroup);
	
    TBool isGroupModified = EFalse;
    TInt itemCount = aItemIdList.Count();
    for (TInt i = 0; i < itemCount; ++i)
        {
    	TContactItemId itemId = aItemIdList[i];
    	if (group->ContainsItem(itemId))
		    {
		    group->RemoveContactL(itemId);
		    isGroupModified = ETrue;
		    }
		else
		    {
            User::Leave(KErrNotFound);
            }
        }

    if (isGroupModified)
        {
	    iCntSvr->CommitContactL(*cntGroup);
		}
	else
		{
		iCntSvr->CloseContact(cntGroup->Id());
		}
    
	CleanupStack::PopAndDestroy(2); // cntGroup, CntItemClose
	cntGroup = NULL;
	
	if (isAlreadyOpened)
		{
		CContactItem* dummy = OpenContactL(aGroupId);
		delete dummy;				
		}
	}
	
    
/**
Sets a field containing a telephone number as a speed dial field. The field 
is identified by aFieldIndex within the contact item aItem. It is assigned a 
speed dial position between 1 and 9 inclusive.

The field's speed dial and user added attributes are set and the appropriate 
UID (KUidSpeedDialXxx) is added to the field's content type. The changes are 
committed to the database.

Notes:

If an item's telephone number field has already been assigned to position 
aSpeedDialPosition, that item is updated so that the speed dial attribute 
is removed from its field and the speed dial field type UID is removed from 
the field's content type, before the new speed dial field is set.

The speed dial attribute can be tested for using the CContactItemField::IsSpeedDial() 
function.

The contact item passed to this function (aItem) must have been obtained using 
one of the variants of CContactDatabase::OpenContactL(). This is because it 
is modified and committed to the database by this function - no further 
commits are necessary.

@capability ReadUserData
@capability WriteUserData

@param aItem The contact item containing the field to set as a speed dial 
field.
@param aFieldIndex Index of a field in aItem's field set to set as a speed dial field.
@param aSpeedDialPosition The speed dial position. This is an integer in the 
range 1 to 9 inclusive. If outside this range, the function leaves with KErrArgument. 

@leave KErrDiskFull The disk does not have enough free space to perform the operation.
*/
EXPORT_C void CContactDatabase::SetFieldAsSpeedDialL(CContactItem& aItem, TInt aFieldIndex, TInt aSpeedDialPosition)
	{
	//
	// aItem has been merged with the appropriate template.  On the server when
	// the contact is read it is not merged with the template.  Therefore we
	// need to determine an equivalent field index for the server.  The index
	// on the client's side takes account of the template fields so to compute
	// the equivalent index iterate through the contact fields up to and
	// including aFieldIndex and count the number of non-empty (i.e. non-
	// template) fields.  The total number is the equivalent index.
	//
	CContactItemFieldSet &fieldSet = aItem.CardFields();
	TInt svrFieldIndex = -1;
	if(fieldSet.Count() == 0) 
		{
		User::Leave(KErrArgument);
		}
	for( TInt fieldIndex = 0; fieldIndex <= aFieldIndex; fieldIndex++ )
		{
		CContactItemField& field = fieldSet[fieldIndex];
		if( field.Storage()->IsFull() )
			{
			svrFieldIndex++;
			}
		}
		
	
	CContactItemField& field = fieldSet[aFieldIndex];	
	if (field.StorageType() == KStorageTypeText)
		{
		iCntSvr->SetFieldAsSpeedDialL(aItem.Id(), svrFieldIndex, aSpeedDialPosition);
		}
	else	
		{
		User::Leave(KErrArgument);
		}


	//
	// The contact has been read from the database and modified on the server.
	// These changes have not been made to the CContactItem passed in to this
	// function.  We need to make these changes here for consistency with the
	// old model.  A future BC break will disallow this behaviour by changing
	// the parameter from CContactItem& to const CContactItem& thus forcing the
	// client to pass a constant object.
	//

	// Get the field containing the number to be associated with the
	// speed dial.  Note that we use the original index passed in not the
	// equivalent server index.
	CContactItemField& speedDialField = aItem.CardFields()[aFieldIndex];
	// Add speed dial attributes to the contact item field.
	TUid fieldTypeUid = CContactDatabase::SpeedDialFieldUidFromSpeedDialPosition(aSpeedDialPosition);
	if (!speedDialField.ContentType().ContainsFieldType(fieldTypeUid))
		{
		speedDialField.AddFieldTypeL(fieldTypeUid);
		}
	speedDialField.SetUserAddedField(ETrue);
	speedDialField.SetSpeedDial(ETrue);
	}


/**
Returns the field UID for the given speed dial position.  This method is
copied from CCntServerSpeedDialManager::SpeedDialFieldUidFromSpeedDialPosition()
rather than export this method for use here and on the server.  Once the BC
break referred to in SetFieldAsSpeedDialL() has been made this method should be
removed.

@internalTechnology
@released

@param aSpeedDialPosition The speed dial position for which we want the field
UID.

@return The field UID corresponding to aSpeedDialPosition.
*/
TUid CContactDatabase::SpeedDialFieldUidFromSpeedDialPosition(TInt aSpeedDialPosition)
	{
	__ASSERT_ALWAYS(aSpeedDialPosition >= KCntMinSpeedDialIndex && aSpeedDialPosition <= KCntMaxSpeedDialIndex, Panic(ECntPanicInvalidSpeedDialIndex));

	TUid fieldTypeUid = KNullUid;
	switch (aSpeedDialPosition)
		{
	case 1:
		fieldTypeUid = KUidSpeedDialOne;
		break;
	case 2:
		fieldTypeUid = KUidSpeedDialTwo;
		break;
	case 3:
		fieldTypeUid = KUidSpeedDialThree;
		break;
	case 4:
		fieldTypeUid = KUidSpeedDialFour;
		break;
	case 5:
		fieldTypeUid = KUidSpeedDialFive;
		break;
	case 6:
		fieldTypeUid = KUidSpeedDialSix;
		break;
	case 7:
		fieldTypeUid = KUidSpeedDialSeven;
		break;
	case 8:
		fieldTypeUid = KUidSpeedDialEight;
		break;
	case 9:
		fieldTypeUid = KUidSpeedDialNine;
		break;
		}

	return fieldTypeUid; 
	}


/** 
Returns the ID of the contact item whose telephone number field is mapped to 
the speed dial position specified. This function is provided so that information 
may be displayed about a contact item whose telephone number is being dialled 
using speed dialling.

The function also retrieves the telephone number stored in the field.

@capability ReadUserData

@param aSpeedDialPosition The speed dial position. This is an integer in the 
range 1 to 9 inclusive. If outside this range, the function leaves with KErrArgument.
@param aPhoneNumber On return, contains the telephone number which is mapped 
to the speed dial position specified. Returns KNullDesC if the speed dial 
position requested has not been set.

@return The ID of the contact item for which the speed dial has been set. 
*/
EXPORT_C TContactItemId CContactDatabase::GetSpeedDialFieldL(TInt aSpeedDialPosition, TDes& aPhoneNumber)
	{
	return iCntSvr->GetSpeedDialFieldL(aSpeedDialPosition, aPhoneNumber);
	}


/** 
Removes the mapping between a contact item field and a speed dial position.

Removes the KUidSpeedDialXxx UID from the field's content type, removes the 
field's speed dial attribute and commits the changes to the item.

@capability ReadUserData
@capability WriteUserData

@param aContactId The ID of the contact item containing the speed dial field.
@param aSpeedDialPosition The speed dial position. This is an integer in the 
range 1 to 9 inclusive. If outside this range, the function leaves with KErrArgument. 

@leave KErrDiskFull The disk does not have enough free space to perform the operation.
*/
EXPORT_C void CContactDatabase::RemoveSpeedDialFieldL(TContactItemId aContactId, TInt aSpeedDialPosition)
	{
	iCntSvr->RemoveSpeedDialFieldL(aContactId, aSpeedDialPosition);	
	}

	
/**
Reads a contact item without locking it.

This function uses the default view definition (as set by SetViewDefinitionL()). The 
caller takes ownership of the returned object.

@capability ReadUserData

@param aContactId The ID of the contact item to read.

@return Pointer to the contact item.

@leave KErrNotFound The specified contact item does not exist in the database. */
EXPORT_C CContactItem* CContactDatabase::ReadContactL(TContactItemId aContactId)
	{
	CContactItem* cntItem = ReadContactLC(aContactId);
	CleanupStack::Pop(cntItem);
	return cntItem;
	}


/**
Reads a contact item without locking it.

This function uses the view definition specified. The caller takes ownership 
of the returned object.

@capability ReadUserData

@param aContactId The ID of the contact item to read.
@param aViewDef The view definition to use. 

@return Pointer to the contact item.

@leave KErrNotFound The specified contact item does not exist in the database. */
EXPORT_C CContactItem* CContactDatabase::ReadContactL(TContactItemId aContactId, const CContactItemViewDef& aViewDef)
	{
	CContactItem* cntItem = ReadContactLC(aContactId, aViewDef);
	CleanupStack::Pop(cntItem);
	return cntItem;
	}


/**
Reads a contact item without locking it.

This function uses the default view definition (as set by SetViewDefinitionL()). The 
caller takes ownership of the returned object.

@capability ReadUserData

@param aContactId The ID of the contact item to read.

@return Pointer to the contact item. This is left on the cleanup stack.

@leave KErrNotFound The specified contact item does not exist in the database. 
*/
EXPORT_C CContactItem* CContactDatabase::ReadContactLC(TContactItemId aContactId)
	{
	CContactItem* cntItem = iCntSvr->ReadContactL(&iView->ItemDef(), aContactId);
	CleanupStack::PushL(cntItem);

	iTemplateCache->MergeWithTemplateL(*cntItem, &iView->ItemDef());
	
	return cntItem;
	}


/**
Reads a contact item without locking it.

This function uses the view definition specified. The caller takes ownership 
of the returned object.

@capability ReadUserData

@param aContactId The ID of the contact item to read.
@param aViewDef The view definition to use. 

@return Pointer to the contact item. This is left on the cleanup stack.

@leave KErrNotFound The specified contact item does not exist in the database. 
*/
EXPORT_C CContactItem* CContactDatabase::ReadContactLC(TContactItemId aContactId,const CContactItemViewDef& aViewDef)
	{
	CContactItem* cntItem = iCntSvr->ReadContactL(&aViewDef, aContactId);
	CleanupStack::PushL(cntItem);
	iTemplateCache->MergeWithTemplateL(*cntItem, &aViewDef);
	return cntItem;
	}


/**
Reads a contact item and an agent if the item has an agent field. The item 
and agent (if present) are returned in an array. The function uses the database's 
default view definition (as set by SetViewDefinitionL()). The caller takes 
ownership of the returned object.

@capability ReadUserData

@param aContactId The ID of the contact item to read.
@leave KErrNotFound The specified contact item cannot be found in the database.

@return Pointer to an array containing the contact item and agent, if present.
*/
EXPORT_C CArrayPtr<CContactItem>* CContactDatabase::ReadContactAndAgentL(TContactItemId aContactId)
	{
	CArrayPtr<CContactItem>* cntItemsArray = new (ELeave)CArrayPtrFlat<CContactItem>(4);
	CleanupStack::PushL(cntItemsArray);
	CContactItem* contactItem = ReadContactLC(aContactId);
	cntItemsArray->AppendL(contactItem);
	CleanupStack::Pop(contactItem);	// from ReadContactLC
	
	// Determine whether the contactItem needs an agent
	TInt agentIndex = (*cntItemsArray)[0]->Agent();
	if (agentIndex != KErrNotFound)
  		{
  		CContactItem* contactItemAgent = ReadContactLC(agentIndex);
  		cntItemsArray->AppendL(contactItemAgent); // Will use the Viewdef on the server - no need to marshal ViewDef
		CleanupStack::Pop(contactItemAgent);// from ReadContactLC
  		}
	CleanupStack::Pop(cntItemsArray);	// cntItemsArray
	return cntItemsArray;
	}


/**
Reads a contact item (contact card, own card, template, or contact group), 
but does not read the group or template information. 

This function is identical to the variant of ReadContactL() which uses the database's 
default view definition, except that this function does not read:

- the list of group members and the group label (if the item is a CContactGroup)
- the template label (if the item is a CContactCardTemplate)
- the list of groups to which the item belongs, if any (not applicable to templates)
- any fields inherited from a non-system template, if any (not applicable if 
the item is a CContactCardTemplate)

Notes:

This function is faster than the standard reading function (ReadContactL()), 
which needs to match the template fields and groups etc.

The caller takes ownership of the returned object.

@capability ReadUserData

@param aContactId The ID of the contact to read.

@leave KErrNotFound The specified contact item cannot be found in the database.

@return Pointer to the contact whose ID is aContactId.
*/
EXPORT_C CContactItem* CContactDatabase::ReadMinimalContactL(TContactItemId aContactId)
	{
	return iCntSvr->ReadContactL(NULL, aContactId);
	}


/**
Reads a contact item (contact card, own card, template, or contact group), 
but does not read the group or template information. 

This function is identical to the variant of ReadContactLC() which uses the server's 
default view definition, except that this function does not read:
	
- the list of group members and the group label (if the item is a CContactGroup)
- the template label (if the item is a CContactCardTemplate)
- the list of groups to which the item belongs, if any (not applicable to templates)
- any fields inherited from a non-system template, if any (not applicable if 
the item is a CContactCardTemplate)

Notes:

This function is faster than the standard reading function (ReadContactLC()), 
which needs to match the template fields and groups etc.

The caller takes ownership of the returned object.

@capability ReadUserData

@param aContactId The ID of the contact to read.

@leave KErrNotFound The specified contact item cannot be found in the database.

@return Pointer to the contact whose ID is aContactId. The contact is left 
on the cleanup stack. 
*/
EXPORT_C CContactItem* CContactDatabase::ReadMinimalContactLC(TContactItemId aContactId)
	{
	CContactItem* cntItem = iCntSvr->ReadContactL(NULL, aContactId);
	CleanupStack::PushL(cntItem);
	return cntItem;
	}

	
/**
Gets the content type of the template field which a specified field maps onto. 
If the field does not map onto a field in a template, then its own content 
type is returned.

Note: this function can leave.

@param aField The field of interest. 

@return The content type of the field. 
*/
EXPORT_C const CContentType& CContactDatabase::TemplateContentType(const CContactItemField& aField) const
	{
	return(aField.TemplateContentType(iTemplateCache->SystemTemplateL().CardFields())); // this can leave
	}


//
// Logic cut and paste with minor edit from old CContactTables.
// Create a descriptor with field values separated by the 'separator' from a
// CContactItemFieldSet.
// No database read.
//
void CContactDatabase::DoReadContactTextDefL(const CContactItemFieldSet* aFieldSet,TDes& aResult,CContactTextDef* aTextDef)
	{
	TBool firstText=ETrue;
	if (aTextDef)
		{
		TBuf<KMaxContactTextSeperator> nextSeperator;
		for(TInt loop=0;loop<aTextDef->Count();loop++)
			{
			CContactDatabase::TTextFieldMinimal textFieldMin;
			TContactTextDefItem textDefItem=(*aTextDef)[loop];
			const TInt startOfFieldSet=0;
			aFieldSet->FieldText(textDefItem.iFieldType,textFieldMin,startOfFieldSet);
			if (textFieldMin.Length()>0)
				{
				if (!firstText && aResult.MaxLength()>aResult.Length())
					aResult.Append(nextSeperator.Left(Min(aResult.MaxLength()-aResult.Length(),nextSeperator.Length())));
				aResult.Append(textFieldMin.Left(Min(aResult.MaxLength()-aResult.Length(),textFieldMin.Length())));
				firstText=EFalse;
				}
			nextSeperator=textDefItem.iSeperator;
			}
		}
	if (firstText)
		{
		if(aTextDef && aTextDef->ExactMatchOnly()!=EFalse)
			return;//text def specifies an exact match only
		CContactDatabase::TTextFieldMinimal textFieldMin;
		if (aTextDef)
			{
			TFieldType fieldType=aTextDef->iFallbackFieldType;
			if (fieldType!=KUidContactFieldNone)
				{
				const TInt startOfFieldSet=0;
				aFieldSet->FieldText(fieldType,textFieldMin,startOfFieldSet);
				}
			}
		if (textFieldMin.Length()==0)
			{
			TInt findPos=KContactFieldSetSearchAll;
			do
				{
				findPos=aFieldSet->FindNext(KUidContactFieldMatchAll,findPos+1);
				if (findPos<0)
					break;
				(*aFieldSet)[findPos].GetFieldText(textFieldMin);
				} while(textFieldMin.Length()==0);
		}
		aResult.Append(textFieldMin.Left(Min(aResult.MaxLength(),textFieldMin.Length())));
		}
	}


/**
Reads text into a descriptor from a pre-loaded contact item.

This function uses the database's current text definition (as set using 
CContactDatabase::SetTextDefinitionL()).

@capability ReadUserData

@param aItem The contact item to read.
@param aResult On return, contains the text read from the contact item aItem, 
using the database's current text definition. 
*/
EXPORT_C void CContactDatabase::ReadContactTextDefL(const CContactItem& aItem, TDes& aResult)
	{
	DoReadContactTextDefL(&aItem.CardFields(),aResult,iTextDef);
	}


/**
Reads text into a descriptor from a pre-loaded contact item, using the specified
text definition.

@capability ReadUserData

@param aItem The contact item to read.
@param aResult On return, contains the text read from the contact item aItem, 
using the text definition specified in aTextDef.
@param aTextDef The text definition to use. 
*/
EXPORT_C void CContactDatabase::ReadContactTextDefL(const CContactItem& aItem, TDes& aResult,CContactTextDef* aTextDef)
	{
	DoReadContactTextDefL(&aItem.CardFields(),aResult,aTextDef);
	}


/**
Reads text from a contact item stored in the database into a descriptor.

This function uses the database's currently set text definition (as set using 
CContactDatabase::SetTextDefinitionL()).

@capability ReadUserData

@param aContactId The ID of the contact to read.
@param aResult On return, contains the text read from the contact item identified by aContactId, using 
the database's current text definition.

@leave KErrNotFound The specified contact item cannot be found in the database. 
*/
EXPORT_C void CContactDatabase::ReadContactTextDefL(TContactItemId aContactId, TDes& aResult)
	{
	ReadContactTextDefL(aContactId,aResult,iTextDef);
	}


/**
Reads text from a contact item stored in the database into a descriptor 
using the specified text definition.

@capability ReadUserData

@param aContactId The ID of the contact to read.
@param aResult On return, contains the text read from the contact item identified by aContactId, using 
the text definition specified in aTextDef.
@param aTextDef The text definition to use.

@leave KErrNotFound The specified contact item cannot be found in the database. 
*/
EXPORT_C void CContactDatabase::ReadContactTextDefL(TContactItemId aContactId, TDes& aResult,CContactTextDef* aTextDef)
	{
	CContactTextDef* textDef = NULL;
	if(aTextDef == NULL)
		{
		textDef = CContactTextDef::NewLC();
		}
	else
		{
		textDef = aTextDef;
		}
	MLplViewIteratorManager& manager = FactoryL()->GetViewIteratorManagerL();
	manager.ReadContactTextDefL(aContactId,aResult,*textDef);
	if(aTextDef == NULL)
		{
		CleanupStack::PopAndDestroy(textDef);
		}
	}


CContactIdArray* CContactDatabase::SortLC(const CArrayFix<CContactDatabase::TSortPref>* aSortOrder, const CContactIdArray* aIdArray)
	{
	CContactIdArray* sortedItems=CContactIdArray::NewLC();
	if (aSortOrder->Count()==0)
		{
		TContactItemId currentId(1);
		TContactItemId actualId;
		TUid contactType;
		TBool deleted;
		MLplCollection& collection = FactoryL()->GetCollectorL();
		while(collection.SeekContactL(currentId,actualId,contactType,deleted))
			{
			if(CheckType(contactType) && !deleted)
				{
				sortedItems->AddL(actualId);
				}
			currentId = actualId+1;
			}
		}
	else
		{
		CContactTextDef* textDef;
		TUid fieldType=(*aSortOrder)[0].iFieldType;
		if (fieldType==KUidContactFieldDefinedText)
			{
			textDef=iTextDef;
			}
		else
			{
			//We are sorting on aSortOrder.
			textDef=CContactTextDef::NewLC();
			TInt sortOrderCount=aSortOrder->Count();
			for (TInt sortIndex=0;sortIndex<sortOrderCount;sortIndex++)
				{
				textDef->AppendL(TContactTextDefItem((*aSortOrder)[sortIndex].iFieldType));
				}
			}
		CSortArray* sortedList=new(ELeave) CSortArray;
		CleanupStack::PushL(sortedList);
		TContactItemId currentId(1);
		TInt arrayIndex(0);
		for(;;)
			{
			TUid contactType;
			TContactItemId actualId;
			TBool deleted;
			if(aIdArray)
				{
				if (arrayIndex==aIdArray->Count())
					break;
				MLplCollection& collection = FactoryL()->GetCollectorL();
				if(!collection.SeekContactL((*aIdArray)[arrayIndex],actualId,contactType,deleted) || actualId != (*aIdArray)[arrayIndex])
					{
					User::Leave(KErrNotFound);	
					}
				++arrayIndex;
				}
			else
				{
				MLplCollection& collection = FactoryL()->GetCollectorL();
				if(!collection.SeekContactL(currentId,actualId,contactType,deleted))
					{
					break;	
					}
				currentId = actualId+1;
				}
			if(CheckType(contactType) && !deleted)
				{
				CContactDatabase::TTextFieldMinimal textFieldMin;
				ReadContactTextDefL(actualId,textFieldMin,textDef);
				sortedList->AppendL(textFieldMin,actualId);
				}
			}
		sortedList->SortL((*aSortOrder)[0].iOrder);
		SortDuplicatesL(*aSortOrder,*sortedList,1);
		const TInt count=sortedList->Count();
		for (TInt ii=0;ii<count;ii++)
			sortedItems->AddL(sortedList->Id(ii));
		CleanupStack::PopAndDestroy(); // sortedList ,
		if (fieldType!=KUidContactFieldDefinedText)
			{
			CleanupStack::PopAndDestroy();//textdef
			}
		}
	CContactIdArray* newSortedItems=CContactIdArray::NewL(sortedItems);
	CleanupStack::PopAndDestroy(sortedItems);
	CleanupStack::PushL(newSortedItems);
	User::Heap().Compress();
	return(newSortedItems);		
	}


void CContactDatabase::ReSortL(CArrayFix<TSortPref>* aSortOrder)
	{
	CContactIdArray* sortedItems=SortLC(aSortOrder,NULL);
	delete iSortedItems;
	iSortedItems=sortedItems;
	CleanupStack::Pop(sortedItems);
	}


void CContactDatabase::SortDuplicatesL(const CArrayFix<TSortPref>& aSortOrder,
											CSortArray& aList,TInt aSortIndex)
	{ // is this too heavy on stack usage to be called recursively ???
	__ASSERT_DEBUG(&aSortOrder!=NULL,Panic(ECntPanicNullPointer));
	__ASSERT_DEBUG(&aList!=NULL,Panic(ECntPanicNullPointer));
	if (aSortIndex<aSortOrder.Count())
		{
		const TInt count=aList.Count();
		if (count<=1)
			return;
		TInt ii=0;
		HBufC *text1=aList.Text(ii);
		TInt startPos=KErrNotFound;
		TBool checkedList=EFalse;
		while (!checkedList)
			{
			checkedList=(++ii==count-1);
			HBufC *text2=aList.Text(ii);
			const TInt compare=text1->CompareC(*text2,3,&iCollateMethod);
			if (compare==0)
				{
				if (startPos==KErrNotFound)
					startPos=ii-1;
				}
			else if (startPos!=KErrNotFound)
				{
				SortDuplicatesL(aSortOrder,aList,aSortIndex,startPos,ii);
				startPos=KErrNotFound;
				}
			text1=text2;
			}
		if (startPos!=KErrNotFound)
			SortDuplicatesL(aSortOrder,aList,aSortIndex,startPos,ii+1);
		}
	}


void CContactDatabase::SortDuplicatesL(const CArrayFix<TSortPref>& /*aSortOrder*/,CSortArray& /*aList*/,
											TInt /*aIndex*/,TInt /*aStartPos*/,TInt /*aEndPos*/)
	{ 
	}


TBool CContactDatabase::CheckType(TUid aUid) const
	{
	// checks the view on the db whether the uid supplied complies to the rules below
	if (aUid == KUidContactTemplate)  // do not include golden template;
		return EFalse;
	if (iDbViewContactType == KUidContactItem)  // any type of contact;
		return ETrue;
	if (iDbViewContactType == KUidContactCardOrGroup &&
		(aUid == KUidContactCard || aUid == KUidContactGroup)) // cards and/or groups
		return ETrue;
	if (iDbViewContactType == KUidContactCard && aUid == KUidContactOwnCard)
		// if the card being checked is an own card - allow it to be included
		return ETrue;
	else if (aUid == iDbViewContactType)		// only a specific match
		return ETrue;
	return EFalse;
	}


/**
Sets the template id on the contact item to that of the SystemTemplate
after each update or commit operation.
*/
void CContactDatabase::CheckTemplateField(CContactItem& aCnt)
	{
	if (aCnt.iTemplateRefId == KNoValueSet)	
		{
		aCnt.iTemplateRefId = KGoldenTemplateId;	
		}
	if (aCnt.iAccessCount == (TUint32)KNoValueSet)	
		{
		aCnt.iAccessCount = 0;	
		}
	}


/** 
Opens a contact item for editing using a specified view definition. 

The returned contact item is locked and left open until either CommitContactL() or CloseContactL() 
is called.

Note: care should be taken when specifying a view definition because when committing 
the contact item, any fields not loaded by the view definition are deleted 
from the item.

The caller takes ownership of the returned object.

@deprecated
@capability WriteUserData

@param aContactId The ID of the contact item to open.

@leave KErrInUse The contact item is already open.
@leave KErrNotFound The contact item is not present in the database. 

@return The open, locked contact. 
*/
EXPORT_C CContactItem* CContactDatabase::OpenContactLX(TContactItemId aContactId)
	{
	// Since the AllFieldsView method returns a modifiable ptr to the iAllFieldsView
	// we must always send it across the IPC as it may have changed.
	return OpenContactLX(aContactId, *iAllFieldsView);
	}


/**
Opens a contact item for editing.

The returned contact item is locked and left open until either CommitContactL() 
or CloseContactL() is called.

This function uses a view definition that loads every field. If you need to 
specify your own view definition use the other overload of this function.

The caller takes ownership of the returned object.

@capability WriteUserData

@param aContactId The ID of the contact item to open. 

@return The open, locked contact.

@leave KErrInUse The contact item is already open.
@leave KErrNotFound The contact item is not present in the database. 
*/
EXPORT_C CContactItem* CContactDatabase::OpenContactL(TContactItemId aContactId)
	{
	CContactItem* cntItem = OpenContactLX(aContactId);
	CleanupStack::Pop(); // Pop the lock
	return cntItem;
	}


/** 
Opens a contact item for editing, leaving the lock record on the cleanup stack.

The returned item is locked and left open until either CommitContactL() or 
CloseContactL() is called.

This function uses the specified view definition. Note: Care should be taken 
when specifying a view definition because when committing the contact item 
any fields not loaded by the view definition are deleted from the item.

The caller takes ownership of the returned object.

@deprecated
@capability WriteUserData

@param aContactId The ID of the contact item to open.
@param aViewDef The view definition.

@return The open, locked contact item.

@leave KErrInUse The contact item is already open
@leave KErrNotFound The contact item is not present in the database. 
*/
EXPORT_C CContactItem* CContactDatabase::OpenContactL(TContactItemId aContactId, const CContactItemViewDef& aViewDef)
	{
	CContactItem* cntItem = OpenContactLX(aContactId, aViewDef);
	CleanupStack::Pop();
	return cntItem;
	}


/** 
Opens a contact item for editing, leaving the lock record on the cleanup stack.

The returned item is locked and left open until either CommitContactL() or 
CloseContactL() is called.

This function uses the specified view definition. Note: Care should be taken 
when specifying a view definition because when committing the contact item 
any fields not loaded by the view definition are deleted from the item.

The caller takes ownership of the returned object.

@deprecated
@capability WriteUserData

@param aContactId The ID of the contact item to open.
@param aViewDef The view definition.

@return The open, locked contact item.

@leave KErrInUse The contact item is already open
@leave KErrNotFound The contact item is not present in the database. 
*/
EXPORT_C CContactItem* CContactDatabase::OpenContactLX(TContactItemId aContactId, const CContactItemViewDef& aViewDef)
	{
	CContactItem* cntItem = iCntSvr->OpenContactLX(&aViewDef, aContactId);

	CleanupStack::PushL(cntItem);
	iTemplateCache->MergeWithTemplateL(*cntItem, &aViewDef);

	CleanupStack::Pop(cntItem);	
	return cntItem;
	}


CContactItem* CContactDatabase::OpenNoMergeLCX(TContactItemId aContactId)
	{
	CContactItem* cntItem = iCntSvr->OpenContactLX(NULL, aContactId);
	CleanupStack::PushL(cntItem);
	
	return cntItem;
	}


/** 
Gets the ID of the system template. This can then be read, opened and committed 
like any other contact item.

@return ID of the system template. 
*/
EXPORT_C TContactItemId CContactDatabase::TemplateId() const
	{
	return iTemplateCache->TemplateId();
	}


/** 
Creates a default own card based on the system template and adds it to the 
database. This is set as the database's current own card, replacing any existing 
current own card. The caller takes ownership of the returned object.

@capability WriteUserData

@return Pointer to the new default own card. The pointer is left on the cleanup 
stack.
*/
EXPORT_C CContactItem* CContactDatabase::CreateOwnCardLC()
	{
	CContactCard* ownCard = CContactCard::NewLC(&iTemplateCache->SystemTemplateL());
	TInt cntId = AddNewContactL(*ownCard);
	ownCard->iId = cntId;
	// set and persist newowncard id
	iCntSvr->SetOwnCardL(*ownCard);
	CleanupStack::PopAndDestroy(ownCard);
    return ReadContactLC(cntId);	
	}


/** 
Creates a default own card based on the system template and adds it to the 
database. This is set as the database's current own card, replacing any existing 
current own card. The caller takes ownership of the returned object.

@capability WriteUserData

@return Pointer to the new default own card. 
*/
EXPORT_C CContactItem* CContactDatabase::CreateOwnCardL()
	{
	CContactItem* ownCard = CreateOwnCardLC();
	CleanupStack::Pop(ownCard);
	return ownCard;
	}

	
/**
Returns the ID of the database's current own card. 

Having obtained this ID, the client may then open the own card in the same 
way as an ordinary contact card (using ReadContactL() or OpenContactL()).

@capability None

@return The ID of the database's current own card. KNullContactId if the own 
card has been deleted or has not yet been set.
*/
EXPORT_C TContactItemId CContactDatabase::OwnCardId() const
	{
	return iCntSvr->OwnCard();
	}


/**
Returns the ID of the database's preferred template, as set by SetPrefTemplateL(). 
KNullContactId if not set. The preferred template is for clients who may have 
multiple templates but want to identify one as preferred.

@capability None

@return The ID of the database's current preferred template.
*/
EXPORT_C TContactItemId CContactDatabase::PrefTemplateId() const
	{
	return(iCntSvr->PrefTemplateId());
	}


/** 
Sets an existing contact item to be the database's current own card.

@capability WriteUserData

@param aContact The contact item to set as the database's current own card. 
It must already exist in the database. It cannot be a group or a template.

@leave KErrNotFound aContact does not exist in the database. 
@leave KErrDiskFull The disk does not have enough free space to perform the operation.
*/
EXPORT_C void CContactDatabase::SetOwnCardL(const CContactItem& aContact)
	{
	iCntSvr->SetOwnCardL(aContact);	
	}

	
/**
Sets the time out of operations on the database server.

This API allows the behaviour of the Contacts Model to be tuned for scenarios
where clients either expect to encounter or know they will encounter operations
failing primarily due to the database being locked.

Not all clients will find they need to use this API.  By default the operation
timeout is 1 second.

The timeout only needs to be set once per session.  Multiple clients using the
same database can specify independent values for the operation timeout.

@capability None

@publishedPartner

@released

@param aMicroSeconds The operation timeout in microseconds.  This timeout will
only be applied to requests sent by clients of this database after this point in
time.

@leave KErrArgument If aMicroSeconds is less than 0 or is greater than 300000000
(equivalent to 5 minutes). 
*/	
EXPORT_C void CContactDatabase::SetOperationTimeOutL(const TInt aMicroSeconds) const
	{
	if (aMicroSeconds < 0 || aMicroSeconds > KFiveMins)
		{
		User::Leave(KErrArgument);
		}
	iCntSvr->SetOperationTimeOutL(aMicroSeconds);
	}


/** 
Sets the database's preferred template.

The preferred template's ID persists when the database is opened and closed. 
If the preferred template is subsequently deleted, the preferred template 
ID is set to KNullContactId.

@capability WriteUserData

@param aContact The contact card template to set as the database's preferred 
template.

@leave KErrNotSupported The item is not a template (of type KUidContactCardTemplate).
@leave KErrDiskFull The disk does not have enough free space to perform the operation.
*/
EXPORT_C void CContactDatabase::SetPrefTemplateL(const CContactItem& aContact)
	{
	TUid aContactType = aContact.Type();
	__ASSERT_ALWAYS(aContactType==KUidContactCardTemplate,User::Leave(KErrNotSupported));
	if (aContact.Id()==PrefTemplateId())
		{
		// leave quietly if already set as the preferred template
		return;
		}
	iCntSvr->SetPrefTemplateL(aContact.Id());
	}


/** 
Sets the ID of the current item and persists it in the database. The current 
item is provided for use by clients who want to identify one contact item 
in the database as the currently selected item.

@capability WriteUserData

@param aContactId The ID of the current item. 
*/
EXPORT_C void CContactDatabase::SetCurrentItem(const TContactItemId aContactId)
	{
	iCntSvr->SetCurrentItem(aContactId);	
	}


/** 
Gets the ID of the current item, as set by SetCurrentItem(). The current item 
ID is initialised to KNullContactId when the database is opened.

@capability None

@return The ID of the current item. 
*/	
EXPORT_C TContactItemId CContactDatabase::GetCurrentItem() const
	{	
	return iCntSvr->CurrentItem();
	}


/**
Updates a contact identified by aContactId with the data in aNewContact.
All empty fields are deleted.

@deprecated
@publishedPartner

@capability WriteUserData
@capability ReadUserData 

@param aContactId This argument should be ignored by developers.
@param aNewContact The contact item to replace it with.

@leave KErrDiskFull The disk does not have enough free space to perform the operation.

@return The contact item after the update.
*/
EXPORT_C CContactItem* CContactDatabase::UpdateContactLC(TContactItemId aContactId,CContactItem* aNewContact)
	{
	CContactItemViewDef* viewDef = CContactItemViewDef::NewLC(CContactItemViewDef::EIncludeFields,CContactItemViewDef::EIncludeHiddenFields);
	viewDef->AddL(KUidContactFieldMatchAll);

	CContactItem* cntItem = OpenContactLX(aContactId, *viewDef);
	CleanupStack::PushL(cntItem);

	CContactItemFieldSet& newfieldSet = aNewContact->CardFields();

	TInt count=newfieldSet.Count();
	for (TInt ii=0; ii<count; ++ii)
		{
		//In the case there are duplicate fields in the field Set
		//matchCount need to be increased, so the previous field won't be 
		//overwritten by the later one. 
		TInt matchCount =1;
		for (TInt jj=ii-1; jj>=0; jj--)
			{
			if(newfieldSet[ii].ContentType()==newfieldSet[jj].ContentType())
			matchCount++;
			}
			
		cntItem->CardFields().UpdateFieldL(newfieldSet[ii],matchCount);
		}
		
	doCommitContactL(*cntItem,ETrue,ETrue);
	if (!count)
		{
	    doDeleteContactL(aContactId,ETrue,ETrue);
	    CleanupStack::PopAndDestroy(cntItem); // Pop and destroy cntItem

	    cntItem = NULL;
	    CleanupStack::PushL(cntItem); // push a NULL ptr to cleanup stack
	    }

	if(cntItem != NULL)
	    {
	    CheckTemplateField(*cntItem);
	    }
	CleanupStack::Pop(); // cntItem
	CleanupStack::Pop(); // Pop the lock
	CleanupStack::PopAndDestroy(viewDef);	
	CleanupStack::PushL(cntItem);	
	return(cntItem);
	}


/**
Closes the contact item, allowing other applications to access it. Specifying 
a contact item that is not open, or cannot be found, is harmless. This function 
does not commit any changes made to the item. Despite the trailing L in the 
function's name, this function cannot leave.

@capability None

@param aContactId The ID of the contact to close.
*/
EXPORT_C void CContactDatabase::CloseContactL(TContactItemId aContactId)
	{
	iCntSvr->CloseContact(aContactId);
	}


/**
Overwrites a contact item with the values contained in aContact. The contact 
item is also closed by this call.

@capability ReadUserData
@capability WriteUserData 

@param aContact Contains the new values for the contact item.

@leave KErrAccessDenied The contact item is not locked by the caller.
@leave KErrNotFound The contact item's ID is not present in the database. 
@leave KErrDiskFull The disk does not have enough free space to perform the operation.
@leave KErrNotSupported The contact item cannot be committed because it contains
invalid data.
*/
EXPORT_C void CContactDatabase::CommitContactL(const CContactItem& aContact)
	{
	// If the contact item being committed is the System template then check if
	// the fields are valid.
	if (aContact.Id()==TemplateId())
		{
		if (!SystemTemplateFieldsValid(aContact))
			{
			User::Leave(KErrNotSupported);
			}
		}

	iCntSvr->CommitContactL(aContact);
	RespondToEventL(EContactDbObserverEventTemplateChanged, aContact.Id());
	}

	
/** Updates the existing contact information.
@publishedPartner
@released

@capability ReadUserData
@capability WriteUserData 

@param aContact Contains the new values for the contact item.
@param aIsInTransaction This argument should be ignored by developers.
@param aSendChangedEvent This argument should be ignored by developers.

@leave KErrAccessDenied The contact item is not locked by the caller.
@leave KErrNotFound The contact item's ID is not present in the database. 
@leave KErrNotSupported The contact item cannot be committed because it contains
invalid data.
*/	
EXPORT_C void CContactDatabase::doCommitContactL(const CContactItem& aContact,TBool /*aIsInTransaction*/, TBool aSendChangedEvent)
	{
	// If the contact item being committed is the System template then check if
	// the fields are valid.
	if (aContact.Id()==TemplateId())
		{
		if (!SystemTemplateFieldsValid(aContact))
			{
			User::Leave(KErrNotSupported);
			}
		}

	iCntSvr->CommitContactL(aContact, aSendChangedEvent);
	MoveInSortArray(aContact);
	}


/**
Deletes an array of contacts. 

The function commits the changes for every 32 (for 9.5 onwards it commits after every 50)
contacts deleted, and compresses the database as required. A changed message 
is not sent for every contact deleted, instead a single unknown change event 
message (EContactDbObserverEventUnknownChanges) is sent after all the contacts 
have been deleted and the changes committed.

@capability WriteUserData 
@capability ReadUserData 

@param aContactIds An array of contacts to delete.

@leave KErrNotFound A contact item ID contained in the array is not present 
in the database.
@leave KErrInUse One or more of the contact items is open. 
@leave KErrDiskFull The disk does not have enough free space to perform the operation.
*/
EXPORT_C void CContactDatabase::DeleteContactsL(const CContactIdArray& aContactIds)
	{
  TInt error = KErrNone;
  const TInt KDeleteTransactionGranularity = 50;
  TInt count = aContactIds.Count();
	if (count == 0)
		{
		return;
		}

	// Clone the ContactIdArray so it can be sorted into ascending order
	CContactIdArray* sortedIdArray = CContactIdArray::NewLC(&aContactIds);
	sortedIdArray->Sort();

	TInt deleteError = KErrNone;
    if (count > 1)
	    {	    
	    for(TInt ii = 0; ii < count-1; ++ii)
		    {
		    if ((ii % KDeleteTransactionGranularity) == 0)
			    {
			    if (ii > 0)
				    {
				    DatabaseCommitLP(EFalse);
				    }
			    DatabaseBeginLC(EFalse);			
			    }
		    // Delete the contact but do not trigger any event		
		    deleteError = DeleteContactSendEventAction((*sortedIdArray)[ii], EDeferEvent);
		    
		    // On error, check if possible to continue delete operation
		    if (deleteError == KErrInUse || deleteError == KErrNotFound)
		        {
		        error = deleteError;
		        continue;
		        }
		    else
		        {
		        User::LeaveIfError(deleteError);
		        }
		    }
	    }
	else	 
		{ // edge case
		DatabaseBeginLC(EFalse);	
		}		
		
	// Delete the last item and trigger EContactDbObserverEventUnknownChanges 
    deleteError = DeleteContactSendEventAction((*sortedIdArray)[count-1], ESendUnknownChangesEvent);
    if (deleteError == KErrInUse || deleteError == KErrNotFound)
        {
        error = deleteError;
        }
    else
        {
        User::LeaveIfError(deleteError);
        }
    
	DatabaseCommitLP(EFalse);

	CleanupStack::PopAndDestroy(sortedIdArray);
	
	// Propogate error to client
	User::LeaveIfError(error);
	}

/**
Not supporte anymore.

@leave KErrInNotSupported Always. 
*/
EXPORT_C void CContactDatabase::DeleteContactsV2L(const CContactIdArray& /*aContactIds*/)
    {
    User::LeaveIfError(KErrNotSupported);
    }

/**
Deletes a contact item.

Note: if the contact's access count is greater than zero, the contact is not fully 
deleted from the database. A 'skeleton' of the contact is left, containing only 
basic information, and no field data. The skeleton contact can still be accessed 
if a record of its contact ID has been retained (or call DeletedContactsLC()). 
The skeleton is removed when the access count is zero.

@capability ReadUserData
@capability WriteUserData

@param aContactId The contact item ID of the contact to delete.

@leave KErrNotFound aContactId is not present in the database.
@leave KErrInUse The contact item is open.
@leave KErrDiskFull The disk does not have enough free space to perform the operation.
*/
EXPORT_C void CContactDatabase::DeleteContactL(TContactItemId aContactId)
	{
	iCntSvr->DeleteContactL(aContactId, ESendEvent);	
	//Now we check if the contact belonged to the sort array, if so 
	//remove it from iSortedItems
    RemoveFromSortArray(aContactId);
	//Now we check if the contact belonged to the template list, if so 
	//remove it from iCardTemplateIds
	RemoveFromTemplateList(aContactId);
	//Now we check if the contact belonged to the Group Id list, if so 
	//remove it from iGroupIds	
	RemoveFromGroupIds(aContactId);
	}


/**
Deletes a contact item. 

Note: if the contact's access count is greater than zero, the contact is not fully 
deleted from the database. A 'skeleton' of the contact is left, containing only 
basic information, and no field data. The skeleton contact can still be accessed 
if a record of its contact ID has been retained (or call DeletedContactsLC()). 
The skeleton is removed when the access count is zero.

@publishedPartner
@released

@capability ReadUserData
@capability WriteUserData

@param aContactId The contact item ID of the contact to delete.
@param aIsInTransaction This argument should be ignored by developers.
@param aSendChangedEvent This argument should be ignored by developers.
@param aDecAccessCount This argument should be ignored by developers.

@leave KErrNotSupported An attempt has been made to delete the system template.
@leave KErrNotFound aContactId is not present in the database.
@leave KErrInUse The contact item is open.
*/
EXPORT_C void CContactDatabase::doDeleteContactL(TContactItemId aContactId, TBool /*aIsInTransaction*/, TBool aSendChangedEvent, TBool aDecAccessCount)
	{
	TCntSendEventAction action = aSendChangedEvent ? ESendEvent : EDeferEvent;
	iCntSvr->DeleteContactL(aContactId, action, aDecAccessCount);	
	//Now we check if the contact belonged to the sort array, if so 
	//remove it from iSortedItems
    RemoveFromSortArray(aContactId);
	//Now we check if the contact belonged to the template list, if so 
	//remove it from iCardTemplateIds
	RemoveFromTemplateList(aContactId);
	//Now we check if the contact belonged to the Group Id list, if so 
	//remove it from iGroupIds	
	RemoveFromGroupIds(aContactId);
	}

	
/**
Returns the full view definition, that loads every field,
the returned pointer is owned by the CContactDatabase object.

@publishedPartner
@released

@capability None

@return The definition for a full view with all the contact item fields.
*/	
EXPORT_C CContactItemViewDef* CContactDatabase::AllFieldsView()
	{
	return iAllFieldsView;
	}


/**
Imports one or more vCards from a read stream. The vCards are converted into 
contact items, and added to the database. If at least one contact item was 
successfully imported, aImportSuccessful is set to ETrue. If EImportSingleContact 
is specified in aOption, the read stream marker is left at the next position, 
ready to read the next contact item. The caller takes ownership of the returned 
object.

@capability WriteUserData

@param aFormat Indicates the format for imported and exported contacts. Its 
value must be KUidVCardConvDefaultImpl.
@param aReadStream The stream to read from.
@param aImportSuccessful On return, ETrue if at least one contact was successfully 
imported. EFalse if not.
@param aOption Indicates the options for import and export. See the TOptions 
enum.

@leave KErrNotSupported aFormat.iUid is not KUidVCardConvDefaultImpl.

@return The array of contact items imported.
*/
EXPORT_C CArrayPtr<CContactItem>* CContactDatabase::ImportContactsL(const TUid& aFormat,RReadStream& aReadStream,TBool& aImportSuccessful,TInt aOption)
	{
	const TBool importSingleContact= aOption & EImportSingleContact;
	return ConverterL(aFormat).ImportL(*this,aReadStream,aImportSuccessful,aOption,importSingleContact);
	}


/**
Converts an array of contact items to vCards and exports them to a write stream.

The default character set CVersitParser::EUTF8CharSet is used to convert into. If 
you need a different character set, use the other overload of this function.

@capability ReadUserData

@param aFormat Indicates the format for imported and exported contacts. Must 
have a value of KUidVCardConvDefaultImpl.
@param aSelectedContactIds Array of contact IDs to export.
@param aWriteStream The stream to write to.
@param aOption Indicates the options for import and export. See the TOptions 
enum.
@param aExportPrivateFields ETrue exports fields marked as private. EFalse 
does not export fields marked as private. See CContactItemField::SetPrivate().

@leave KErrNotSupported aFormat.iUid is not KUidVCardConvDefaultImpl.
@leave KErrNotFound One or more of the contact items does not exist in the 
database.
*/
EXPORT_C void CContactDatabase::ExportSelectedContactsL(const TUid& aFormat,const CContactIdArray& aSelectedContactIds, RWriteStream& aWriteStream, TInt aOption, TBool aExportPrivateFields)
	{
	ExportSelectedContactsL(aFormat,aSelectedContactIds,aWriteStream,aOption,Versit::EUTF8CharSet,aExportPrivateFields);
	}


/**
Converts an array of contact items to vCards and exports them to a write 
stream using the specified character set.

@capability ReadUserData

@param aFormat Indicates the format for imported and exported contacts. Must 
have a value of KUidVCardConvDefaultImpl.
@param aSelectedContactIds Array of contact IDs to export.
@param aWriteStream The stream to write to.
@param aOption Indicates the options for import and export. See the TOptions 
enum.
@param aCharSet The character set to convert into.
@param aExportPrivateFields ETrue exports fields marked as private. EFalse 
does not export fields marked as private. See CContactItemField::SetPrivate().

@leave KErrNotSupported aFormat.iUid is not KUidVCardConvDefaultImpl.
@leave KErrNotFound One or more of the contact items does not exist in the 
database.
*/
EXPORT_C void CContactDatabase::ExportSelectedContactsL(const TUid& aFormat,const CContactIdArray& aSelectedContactIds, RWriteStream& aWriteStream,TInt aOption,const Versit::TVersitCharSet aCharSet, TBool aExportPrivateFields)
	{
	ConverterL(aFormat).ExportL(*this,aSelectedContactIds,aWriteStream,aOption,aCharSet,aExportPrivateFields);
	}


/**
Converts an array of contact items to PBAP compliant vCards following vCard2.1 and vCard3.0 specifications and exports them to a write 
stream using UTF-8 as the character set. It also provides support for exporting contacts as standard vCard2.1.

@capability ReadUserData
@internalTechnology
@released 

@param aFormat Indicates the format for imported and exported contacts. It should have a value of KUidPBAPVCardConvImpl if user
wants to export contacts as PBAP specific vCards and KUidVCardConvDefaultImpl for standard vCard2.1.
@param aSelectedContactIds Array of contact IDs to export.
@param aWriteStream The stream to write to.
@param aOption Indicates the options for import and export. See the TOptions 
enum.
@param aContactFieldFilter 64-bit filter,specifies the contact fields to export, argument value not considered for standard vCard2.1 export.
@param aCallback Calls client which has to implement class MConverterCallBack, used to add intra-contact properties,
argument value not considered for standard vCard2.1 export.
@param aVersion TVCardVersion specifies vCard version to which contacts should be exported.
@param aExportTel If TEL property should be exported, it should be set to ETrue, argument value not considered for standard vCard2.1 export.
@param aCharSet The character set to convert into.Must be UTF-8 for PBAP export, provided as default value.
@param aExportPrivateFields ETrue exports fields marked as private. EFalse does not export fields marked as private. See CContactItemField::SetPrivate().

@leave KErrNotSupported aFormat.iUid is not KUidPBAPVCardConvImpl for PBAP export.
@leave KErrNotSupported aFormat.iUid is not KUidVCardConvDefaultImpl for standard vCard2.1 export.
@leave KErrNotSupported aCharSet is other than UTF-8 for PBAP export. 
@leave KErrNotFound One or more of the contact items does not exist in the database.
*/
EXPORT_C void CContactDatabase::ExportSelectedContactsL(const TUid& aFormat, const CContactIdArray& aSelectedContactIds, RWriteStream& aWriteStream, TInt aOption, const TInt64 aContactFieldFilter, MConverterCallBack* aCallback, const TVCardVersion aVersion, const TBool aExportTel, Versit::TVersitCharSet aCharSet, TBool aExportPrivateFields)
	{
	if(aVersion == EVCard21)
		{
		//client wants to export contacts as standard vCard2.1.
		ConverterL(aFormat).ExportL(*this, aSelectedContactIds, aWriteStream, aOption, aCharSet, aExportPrivateFields);		
		}
	else
		{
		if(aCharSet != Versit::EUTF8CharSet)
			{
			User::Leave(KErrNotSupported);	
			}
		ConverterL(aFormat, aContactFieldFilter, aCallback, aVersion, aExportTel).ExportL(*this, aSelectedContactIds, aWriteStream, aOption, aCharSet, aExportPrivateFields);		
		}
	}

CContactConverter& CContactDatabase::ConverterL(const TUid& aFormat, const TInt64 aContactFieldFilter, MConverterCallBack* aCallback, const TVCardVersion aVersion, const TBool aExportTel)
	{
	if(aFormat.iUid != KUidPBAPVCardConvImpl)
		{
		User::Leave(KErrNotSupported);
		}
	//since version, filter and boolean TEL are initialised only when PBAP plug-in is created,
	//if there is any change in these arguments provided by Client, The plugin should be loaded once again.
	if(iConv && (iConv->GetCurrentVersion() != aVersion || iConv->GetPBAPFilter() != aContactFieldFilter || iConv->GetExportTel() != aExportTel) )
		{
		delete iConv;
		iConv = NULL;
		}
	if(!iConv)
		{
		iConv = CPrivConverter::NewL(aFormat, aContactFieldFilter, aCallback, aVersion, aExportTel);	
		}
	return *iConv->Converter();
	}


CContactConverter& CContactDatabase::ConverterL(const TUid& aFormat)
	{
	if(iConv && iConv->GetCurrentVersion() != EVCard21)
		{
		delete iConv;
		iConv = NULL;				
		}

	switch (aFormat.iUid)
		{
		case KVersitEntityUidVCard:
		case KUidVCardConvDefaultImpl:
		if (!iConv)
			{
			if(aFormat.iUid == KVersitEntityUidVCard)
				{
				iConv=CPrivConverter::NewL(	TUid::Uid(KUidVCardConvDefaultImpl));
				}
			else
				{
				iConv=CPrivConverter::NewL(aFormat);
				}
			}
		break;
		default:
		User::Leave(KErrNotSupported);
		};

	return *iConv->Converter();
	}


/**
Searches the contact tables for the contact described by aGuid.

@publishedPartner
@released
@capability ReadUserData

@param aGuid Describes the contact item to be found.

@leave KErrNotReady The database is not yet ready to read from, could be because an asynchronous open is in progress 
or because a recover is required after a rollback.
@leave KErrBadHandle An asynchronous open either failed or was cancelled.
@leave KErrLocked The database has been closed for a restore.

@return The unique id of the contact item within the database.
*/
EXPORT_C TContactItemId CContactDatabase::ContactIdByGuidL(const TDesC& aGuid)
	{
	TTime time(0);
	MLplCollection& collection = FactoryL()->GetCollectorL();
	CContactIdArray* idArray = collection.CollectionL(MLplCollection::EFindGuid,time,aGuid);
	// Assume a contact with aGuid will not be found.
	TContactItemId id = KNullContactId;
	// Check there is an entry in idArray before attempting to access it.
	if(idArray->Count() > 0)
		{
		// Since aGuid is unique only one contact can match it therefore always
		// expect one and only one entry in the array.
		id = (*idArray)[0];
		}
	delete idArray;
	return id;
	}


/** 
Returns a pointer to the array of contact items which have been sorted by either 
SortByTypeL() or SortL(). This pointer is valid until a change is made to 
the database or until the database's active object is allowed to run. If 
the array is required after one of the above two events has occurred, a copy 
of the array must first be made.

@deprecated
@capability None

@return A pointer to the array of sorted items. The caller does not take ownership 
of this object.
*/
EXPORT_C const CContactIdArray* CContactDatabase::SortedItemsL()
	{
	if(!iSortedItems)
		{
		CArrayFix<TSortPref>* sortPref = iCntSvr->GetSortPreferenceL();
		CleanupStack::PushL(sortPref);
		iSortedItems = SortLC(sortPref,NULL);
		CleanupStack::Pop(iSortedItems);
		CleanupStack::PopAndDestroy(sortPref);
		}
	return iSortedItems;
	}


/**
Gets the database's UID. This value is used to identify a particular contact 
database. The database UID is generated when the database is first created.

Note: This method can leave.

@capability None

@return Descriptor containing the database UID.
*/
EXPORT_C TPtrC CContactDatabase::FileUid()
	{
	return iCntSvr->FileUidL(); // this can leave
	}


/**
Sorts an array of contact IDs. The sort uses the same logic as SortL(). The 
caller takes ownership of the returned object.

@deprecated
@capability None

@param aIdArray Pointer to array of contact IDs to sort.
@param aSortOrder Sort order array.

@return Pointer to sorted array of contact IDs.
*/
EXPORT_C CContactIdArray* CContactDatabase::SortArrayL(const CContactIdArray* aIdArray, const CArrayFix<TSortPref>* aSortOrder)
	{
	CContactIdArray* sortedItems = SortArrayLC(aIdArray, aSortOrder);
	CleanupStack::Pop(sortedItems);
	return (sortedItems);
	}


/**
Sorts an array of contact IDs. The sort uses the same logic as SortL(). The 
returned array is left on the cleanup stack. The caller takes ownership of 
the returned object.

@deprecated
@capability None

@param aIdArray Pointer to array of contact IDs to sort.
@param aSortOrder Sort order array.

@return Pointer to sorted array of contact IDs.
*/
EXPORT_C CContactIdArray* CContactDatabase::SortArrayLC(const CContactIdArray* aIdArray, const CArrayFix<TSortPref>* aSortOrder)
	{
	return SortLC(aSortOrder,aIdArray);
	}


/**
Sorts the database using the view type value set by SetDbViewContactType(). 
The database takes ownership of the sort order array passed in.

The sort uses the same logic as SortL(). The two functions have the same 
effect.

After calling this function, use CContactDatabase::SortedItemsL() to retrieve 
the sorted array of contact IDs.

@deprecated
@capability None

@param aSortOrder Sort order array. 
*/
EXPORT_C void CContactDatabase::SortByTypeL(CArrayFix<TSortPref>* aSortOrder)
	{
	CContactIdArray* sortedItems=SortLC(aSortOrder,NULL);
	CleanupStack::Pop(sortedItems);
	delete iSortedItems;
	iSortedItems=sortedItems;
	iCntSvr->SetSortPreferenceL(*aSortOrder);
	delete aSortOrder;
	}


/**
Sorts the database. The sort only includes items of the type set by SetDbViewContactType(). 
The database takes ownership of the sort order array passed in. Contacts are 
sorted using the first TSortPref in the array. Any identical matches are then 
sorted using the next TSortPref and so on. When there are no more TSortPrefs 
to use, any remaining unsorted contacts are left in the original database order.

Note: after calling this function, use CContactDatabase::SortedItemsL() to retrieve 
the sorted array of contact IDs.

@deprecated
@capability None

@param aSortOrder Sort order array. If the array's count is zero, no sorting 
takes place. 
*/
EXPORT_C void CContactDatabase::SortL(CArrayFix<TSortPref>* aSortOrder)
	{
	TBool reverse=ETrue;
	CArrayFix<TSortPref>* sortPref = iCntSvr->GetSortPreferenceL();
	CleanupStack::PushL(sortPref);
	if (aSortOrder->Count()!=sortPref->Count())
		reverse=EFalse;
	else for(TInt loop=0;loop<aSortOrder->Count();loop++)
		{
		TSortPref oldSort=(*sortPref)[loop];
		TSortPref newSort=(*aSortOrder)[loop];
		if (oldSort.iFieldType!=newSort.iFieldType || oldSort.iOrder==newSort.iOrder)
			{
			reverse=EFalse;
			break;
			}
		}
	if (reverse)
		{
		if (iSortedItems)
			iSortedItems->ReverseOrder();
		}
	else
		{
		ReSortL(aSortOrder);
		}

	iCntSvr->SetSortPreferenceL(*aSortOrder);
	CleanupStack::PopAndDestroy(sortPref);

	// Having taken ownership, we deleted aSortOrder here after storing the sort
	// preferences in iCntSrv. Earlier versions of cntmodel stored it in
	// iSortOrder. Some 3rd party apps wrongly use aSortOrder after calling us.
	// As it was held until deletion in the destructor, they used to get away
	// with it. Since the new way broke these apps, we've reverted to the old
	// delayed deletion to maintain compatibility, reinstating iSortOrder.	
	delete iSortOrder;
	iSortOrder = aSortOrder;
	}

	
/**
Gets the number of CContactItems in the database. The count includes non-system 
template items. It does not include items marked as deleted.

@deprecated
@capability None

@return The number of contact items in the database.
*/
EXPORT_C TInt CContactDatabase::CountL()
	{
	MLplCollection& collection = FactoryL()->GetCollectorL();
	return collection.ContactCountL();
	}

	
/**
Sets the type of contact items to be included in sorted views of the database. 

See also SortL() and SortByTypeL().

This value is initialised to KUidContactItem when the database is opened. 
This means that all CContactItem-derived types (cards, non-system templates, 
groups, own cards) are included in database views.

@deprecated
@capability None

@param aUid Specifies a contact type. One of the following: KUidContactCard 
(contact cards), KUidContactGroup (contact item groups), KUidContactOwnCard 
(own cards), KUidContactCardTemplate (templates which are not system templates, 
in other words, which have been added to the database), KUidContactItem (all of the above)
*/
EXPORT_C void CContactDatabase::SetDbViewContactType(const TUid aUid)
	{
	iDbViewContactType = aUid;
	iCntSvr->SetDbViewContactType(aUid);
	}


/**
Gets the type of contact items which are included in sorted views of the database, 
as set by SetDbViewContactType(). 

@deprecated

@return Specifies a contact type. One of the following: KUidContactCard 
(contact cards), KUidContactGroup (contact item groups), KUidContactOwnCard 
(own cards), KUidContactCardTemplate (templates which are not system, in other words, 
which have been added to the database), KUidContactItem (all of the above)
*/
EXPORT_C TUid CContactDatabase::GetDbViewContactType() const
	{
	return iDbViewContactType;
	}


/** 
This function does nothing and has been deprecated.

@capability WriteUserData
@deprecated
*/
EXPORT_C void CContactDatabase::CompactL()
	{
	}


/**
This function is deprecated. It returns an object whose functions do nothing.

@capability WriteUserData
@return Pointer to an active compressor.
@deprecated
*/
EXPORT_C CContactActiveCompress* CContactDatabase::CreateCompressorLC()
	{
	CContactActiveCompress* compressor = new (ELeave) CContactActiveCompress;
	CleanupStack::PushL(compressor);
	return compressor;
	}


/**
This function is deprecated. It returns an object whose functions do nothing.

@capability WriteUserData
@return Pointer to an active recoverer.
@deprecated
*/
EXPORT_C CContactActiveRecover* CContactDatabase::CreateRecoverLC()
	{
	CContactActiveRecover* recover = new(ELeave) CContactActiveRecover;
	CleanupStack::PushL(recover);		
	return recover;
	}


/**
Recovers the database from a rollback. It first closes all tables and then reopens 
them after the recover. 

@capability WriteUserData
*/
EXPORT_C void CContactDatabase::RecoverL()
	{
	}


/**
This function is deprecated. It always returns EFalse.

@capability None
@return EFalse
@deprecated
*/
EXPORT_C TBool CContactDatabase::CompressRequired()
	{
    return EFalse;
	}


/** 
This function is deprecated. It always returns EFalse.

@capability None
@return EFalse
@deprecated
*/
EXPORT_C TBool CContactDatabase::IsDamaged() const
	{
	return EFalse;
	}


/** 
Debug Only

@internalTechnology
@released 
@capability WriteUserData
*/
EXPORT_C void CContactDatabase::DamageDatabaseL(TInt /*aSecretCode*/)
	{
	}


/** 
Gets the size of the database file in bytes.

@capability None

@return The size of the contact database. 
*/
EXPORT_C TInt CContactDatabase::FileSize() const
	{
	return iCntSvr->FileSize();
	}


/** 
This function is deprecated and always returns 0.

@capability None
@return The wasted space in the contacts database.
@deprecated
*/
EXPORT_C TInt CContactDatabase::WastedSpaceInBytes() const
	{	
    return 0;  
	}


/**
Filters the database. On return, aFilter contains an array of filtered contact 
item IDs.

@capability ReadUserData

@param aFilter The filter to use. On return, contains a filtered array of 
contact item IDs.
*/
EXPORT_C void CContactDatabase::FilterDatabaseL(CCntFilter& aFilter)
	{
	iCntSvr->FilterDatabaseL(aFilter);
	}


/**
Gets an array of contacts modified since the specified date/time.  The array
includes those contacts that have changed since the beginning of the specified
micro-second.  The caller takes ownership of the returned object. 

@capability ReadUserData

@param aTime The date/time of interest.

@return Pointer to the array of contacts modified since the specified time.
*/
EXPORT_C CContactIdArray* CContactDatabase::ContactsChangedSinceL(const TTime& aTime)
	{
	MLplCollection& collection = FactoryL()->GetCollectorL();
	return collection.CollectionL(MLplCollection::EChangedSince,aTime);
	}


/**
Sets the date/time the database was last synchronised. 

This overload sets the last synchronised date/time where the sync ID is not
known, and returns the sync ID that was created (a sync ID identifies a machine
with which the database has been synchronised).

@deprecated

@param aSyncDate The database's new last synchronised date/time.

@return The sync ID created by the function.
*/
EXPORT_C TContactSyncId CContactDatabase::SetLastSyncDateL(const TTime& aSyncDate)
	{
	//
	// Quick workaround for these APIs rather than implement IPC call to server
	// and a Sync table class.  If we can establish that these APIs are never
	// used (they have been deprecated for a long time) then this workaround can
	// be made permanent.
	//
	iSyncDate = aSyncDate;
	return 0;
	}


/**
Sets the date/time the database was last synchronised. 

This overload is for a known sync ID and updates the database's last 
synchronised date/time for that ID.

@deprecated

@param aSyncId This argument should be ignored by developers.
@param aSyncDate The database's new last synchronised date/time.

@leave KErrNotFound The specified sync ID is not found.
*/
EXPORT_C void CContactDatabase::SetLastSyncDateL(TContactSyncId /*aSyncId*/, const TTime& aSyncDate)
	{
	//
	// Quick workaround for these APIs rather than implement IPC call to server
	// and a Sync table class.  If we can establish that these APIs are never
	// used (they have been deprecated for a long time) then this workaround can
	// be made permanent.
	//
	iSyncDate = aSyncDate;
	}


/**
Gets the date/time the database was last synchronised with a particular 
sync ID, as set by SetLastSyncDateL().

@deprecated

@param aSyncId This argument should be ignored by developers.
@param aSyncDate On return contains the date/time the database was last
synchronised with the sync ID specified.

@leave KErrNotFound The ID cannot be found in the database.
*/
EXPORT_C void CContactDatabase::GetLastSyncDateL(TContactSyncId /*aSyncId*/, TTime& aSyncDate)
	{
	//
	// Quick workaround for these APIs rather than implement IPC call to server
	// and a Sync table class.  If we can establish that these APIs are never
	// used (they have been deprecated for a long time) then this workaround can
	// be made permanent.
	//
	aSyncDate = iSyncDate;
	}


/**
Gets the ID of the connection to the Contacts server. 

This can be compared with the connection IDs of incoming messages to identify 
which connection generated the message.

@capability None

@return The ID of the connection to the Contacts server.
*/
EXPORT_C TUint CContactDatabase::ConnectionId() const
	{
	return iCntSvr->ConnectionId();
	}


/** 
Debug only.

@internalTechnology
@released 

@capability None

@return return the heap size usage of the server in debug mode, 0 in release mode.
*/
EXPORT_C TInt CContactDatabase::CntServerResourceCount()
	{
	return(iCntSvr->ResourceCount());
	}
	

/** 
Debug only.

@internalTechnology
@released 

@capability None
*/	
EXPORT_C void CContactDatabase::SetCntServerHeapFailure(TInt aTAllocFailType, TInt aRate)
	{
	iCntSvr->SetHeapFailure((RHeap::TAllocFail)aTAllocFailType,aRate);
	}


/** 
Debug only.

@internalTechnology
@released 

@capability None

@param aMachineUniqueId The Machine ID to set.
*/
EXPORT_C void CContactDatabase::OverrideMachineUniqueId(TInt64 aMachineUniqueId)
	{
	iCntSvr->OverrideMachineUniqueId(aMachineUniqueId);	
	}


/** 
Gets the contact model's version number.

@return The version number of the contacts model. 
*/
EXPORT_C TVersion CContactDatabase::Version() const
	{
	return(TVersion(KMajorVersion,KMinorVersion,KBuildNumber));
	}


/**
Returns a number unique to the contacts database. This value may be passed 
to CContactItem::UidStringL().

@capability None

@return The database's unique ID.
*/
EXPORT_C TInt64 CContactDatabase::MachineId() const
	{
	return iCntSvr->MachineId();
	}


/**
Gets an array of IDs for contact items that still exist in the database, but 
are marked as deleted. These are contact items which have been deleted, but 
which have a non-zero access count. The caller takes ownership of the returned 
object.

Debug only.

@internalTechnology
@released
@capability ReadUserData

@return Pointer to the array of contacts marked as deleted. 
*/
EXPORT_C CContactIdArray* CContactDatabase::DeletedContactsLC()
	{
#if defined(_DEBUG)
	MLplCollection& collection = FactoryL()->GetCollectorL();
	CContactIdArray* deletedContactsIdArray =
		collection.CollectionL(MLplCollection::EDeleted);
	CleanupStack::PushL(deletedContactsIdArray);
	return deletedContactsIdArray;
#else
	// Do nothing (except avoid compiler errors)
	return NULL;
#endif
	}


/** 
Requests that the server reset all its speed dials to a NULL state.
Needed so that T_NOMACH works (since deleting the db no longer resets the speed dials)

Debug only.

@internalTechnology
@released 
@capability WriteUserData
*/
EXPORT_C void CContactDatabase::ResetServerSpeedDialsL()
	{	
#if defined(_DEBUG)
	for(TInt i = KCntMinSpeedDialIndex; i <= KCntMaxSpeedDialIndex; i++)
		{
		// Pass -1 as field index to indicate that speed dial position is to
		// be reset.
		iCntSvr->SetFieldAsSpeedDialL(KNullContactId, -1, i);
		}
#endif
	}
	
	
/** 
Where there are multiple contact databases on a device, this function can be 
used to enquire which database is the current one. The current database functions 
are provided as part of current item functionality. In order to pass a current 
item from one contacts model client to another, the receiving client needs 
to be using the same database.

The current database is a path and filename, set using SetCurrentDatabase() 
which is persisted by the contacts server.

@deprecated
@capability None

@param aDatabase The path and filename of the current database. KNullDesC 
if no current database has been set.

@return KErrNone if the function completed successfully, otherwise one of the 
standard error codes. 
*/
EXPORT_C TInt CContactDatabase::GetCurrentDatabase(TDes& aDatabase) const
	{
	return iCntSvr->GetCurrentDatabase(aDatabase);
	}


/** 
Where there are multiple contact databases on a device, this function can be 
used to set a database as the current one.

Note: this function simply updates a file name which is stored by the contacts server 
and its use is optional. It is provided as part of current item functionality. 
In order to pass a current item from one contacts model client to another, 
the receiving client needs to be using the same database.

@deprecated
@capability WriteUserData

@param aDatabase The path and filename of the current database.

@return KErrNone if the function completed successfully, otherwise one of the 
standard error codes. 
*/
EXPORT_C TInt CContactDatabase::SetCurrentDatabase(const TDesC& aDatabase) const
	{
	return iCntSvr->SetCurrentDatabase(aDatabase);
	}


/**
Starts a new transaction, without placing a cleanup item to rollback
the database onto the cleanupstack. This is to enable clients to call
contacts methods from an active object.

@publishedPartner
@released
@capability WriteUserData

@param aIsInTransaction ETrue if transaction already started

@leave KErrDiskFull if used storage space above threshold
*/
EXPORT_C void CContactDatabase::DatabaseBeginL(TBool aIsInTransaction)
	{
	if (!aIsInTransaction)
		{
		User::LeaveIfError(iCntSvr->BeginDbTransaction());	
		}
	}
	

/**
Commits an existing transaction, without popping a cleanup item.

@publishedPartner
@released
@capability WriteUserData

@param aIsInTransaction ETrue if transaction already started
*/
EXPORT_C void CContactDatabase::DatabaseCommitL(TBool aIsInTransaction)
	{
	if (!aIsInTransaction)
		{
		User::LeaveIfError(iCntSvr->CommitDbTransaction());
		}
	}
	
/**
Asynchronous commit of an existing transaction, without popping a cleanup item.

@publishedPartner
@released
@capability WriteUserData

@param aIsInTransaction ETrue if transaction already started
@param aStatus Valid status to that will contain the completion value
*/
EXPORT_C void CContactDatabase::DatabaseCommit(TBool aIsInTransaction, TRequestStatus*& aStatus)
    {
    if (!aIsInTransaction)
        {
        iCntSvr->CommitDbTransaction(aStatus);
        }
    }

/**
Force a rollback of the database.

@publishedPartner
@released
@capability WriteUserData
*/
EXPORT_C void CContactDatabase::DatabaseRollback()
	{
	iCntSvr->RollbackDbTransaction();	
	}
	
	
/**
This method allows clients of contacts model to set the sorted item list 
and sort order from a default sort order server as proposed for Crystal 6.0

Note: This method can leave.

@param aSortedItems Specifies an array sorted items
@param aSortOrder Specifies the sort order
@deprecated
@capability None
*/
EXPORT_C void CContactDatabase::SetSortedItemsList(CContactIdArray* aSortedItems, CArrayFix<TSortPref>* aSortOrder)
	{
	__ASSERT_DEBUG(aSortedItems!=NULL,Panic(ECntPanicNullPointer));
	__ASSERT_DEBUG(aSortOrder!=NULL,Panic(ECntPanicNullPointer));

	delete iSortedItems;
	iSortedItems=aSortedItems;
	iCntSvr->SetSortPreferenceL(*aSortOrder); // this can leave
	delete aSortOrder;
	}


/**
aSortOrder is owned by the idle sorter.
@param aSortOrder Specifies the sort order
@param aStatus The request status for the asynchronous phase request.
@deprecated
*/
EXPORT_C void CContactDatabase::SortAsyncL(CArrayFix<TSortPref>* aSortOrder, TRequestStatus& aStatus)
	{
	iIdleSorter->ResetL();
	iIdleSorter->StartSortingL(aSortOrder, aStatus);
	}


/**
aSortOrder is owned by the idle sorter.
@param aSortOrder Specifies the sort order
@param aStatus The request status for the asynchronous phase request.
@deprecated
*/
EXPORT_C void CContactDatabase::SortAsyncL(CArrayFix<TSortPref>* aSortOrder, TRequestStatus& aStatus, MContactSortObserver& aObserver)
	{
	iIdleSorter->ResetL();
	iIdleSorter->StartSortingL(aSortOrder, aStatus, aObserver);
	}


/**
Cancel the CCntIdleSorter object and clean up resources.

@deprecated
*/
EXPORT_C void CContactDatabase::CancelAsyncSort()
	{
	iIdleSorter->Cancel();
	}


/**
Tests whether a contact item's hint bit field matches a filter.

For a match to occur, the item must be of the correct type for inclusion in 
the database (as returned by GetDbViewContactType()) and its hint bit field 
(which indicates whether the item contains a work or home telephone number, 
fax number or email address) must match the filter, according to the rules 
described in TContactViewFilter.

@internalTechnology
@capability None

@param aBitWiseFilter The filter to compare the item against. This is a combination 
of TContactViewFilter values.
@param aContactId The ID of the item in the database.

@return ETrue if the item is of the correct type for inclusion in the database, 
and its hint bit field matches the specified filter, EFalse if either of these 
conditions are not met.
*/
EXPORT_C TBool CContactDatabase::ContactMatchesHintFieldL(TInt aBitWiseFilter,TContactItemId aContactId)
	{//Returns ETrue if the contact Hint field matches any of the aBitWiseFilter fields
	return iCntSvr->ContactMatchesHintFieldL(aBitWiseFilter,aContactId);
	}


/**
Returns the ID of the template that should be used with CContactICCEntry items.

@capability None

@return A template ID.
*/
EXPORT_C TContactItemId CContactDatabase::ICCTemplateIdL()
	{
	LoadSyncPluginL();
	return iCntSvr->ICCTemplateIdL(KUidIccGlobalAdnPhonebook);
	}


/**
Returns the ID of the template that should be used with CContactICCEntry items 
belonging to the phonebook with TUid aPhonebookUid.

@capability None

@param aPhonebookUid The phonebook ID.

@return A template ID.
*/
EXPORT_C TContactItemId CContactDatabase::ICCTemplateIdL(TUid aPhonebookUid)
 	{
 	LoadSyncPluginL();
 	return iCntSvr->ICCTemplateIdL(aPhonebookUid);
 	}


/**
Returns the ID of the contacts model group which represents the ADN phonebook.

@capability None

@return Group ID.
*/ 
EXPORT_C TContactItemId CContactDatabase::PhonebookGroupIdL()
	{
	LoadSyncPluginL();
	return iCntSvr->PhonebookGroupIdL();
	}


/**
Returns a list of 'unfiled' contacts. These are contacts which do not belong to any group.

@publishedPartner
@released
@capability ReadUserData

@return The list of 'unfiled' contacts.
*/
EXPORT_C CContactIdArray* CContactDatabase::UnfiledContactsL()
	{
	MLplCollection& collection = FactoryL()->GetCollectorL();
	return collection.CollectionL(MLplCollection::EUnfiled);
	}


/**
Opens the default contact database asynchronously.

The Contacts server is asked to prepare the database to be opened. This may include
cleaning up incomplete writes from when the device was last switched off, or updating the 
database format.

If an error is encountered starting the asynchronous open the return value is NULL and the
error is returned in the TRequestStatus parameter.

Errors from the asynchronous open include:
KErrNotFound The database file was not found or it did not have the correct UIDs.
KErrLocked The file is in use by another client.
Other system wide error codes.

If the return value is not NULL the ownership of the CContactOpenOperation object is passed 
to the client. This may be deleted before the asynchronous open completes.

When the client supplied TRequestStatus is completed with KErrNone the TakeDatabase() method
of CContactOpenOperation is called to pass ownership of the open database to the client.

@publishedAll
@released
@capability ReadUserData

@param	aStatus
		On return, the request status for the asynchronous phase request.
		The Open() action can fail with one of the system wide error codes. In this case, the
		CContactDatabase object cannot access the database and must be deleted.
@param	aAccess
		This argument should be ignored by developers.

@return NULL if there is an error starting the asynhchronous open, otherwise a pointer to an
		active object that manages the open operation.

@see CContactOpenOperation
*/
EXPORT_C CContactOpenOperation* CContactDatabase::Open(TRequestStatus& aStatus, TThreadAccess /*aAccess*/)
	{
	aStatus = KRequestPending;
	CContactOpenOperation* openOperation = NULL;
	
	TRAPD(newError, openOperation = CContactOpenOperation::NewL(aStatus));
	// failed? return the error in the TRequestStatus
	if (newError != KErrNone)
		{
		TRequestStatus* ptrStatus = &aStatus;
		User::RequestComplete(ptrStatus, newError);
		}
	return openOperation;
	}


/**
Opens a named contact database asynchronously.

The Contacts server is asked to prepare the database to be opened. This may include
cleaning up incomplete writes from when the device was last switched off, or updating the 
database format.

In v8.1, contact databases can be located in any directory on any writeable drive, and the 
format of the filename must include an absolute directory path such as 
c:\\system\\data\\contacts.cdb.

From v9.0 onwards, contact databases can only be located in the correct data caged 
subdirectory. The filenames must have no path, for example c:contacts.cdb.
The maximum length for the drive, filename and extension is 190 characters.

If an empty path is entered, it will be treated as a request to open the default contact 
database.

If an error is encountered starting the asynchronous open the return value is NULL and the
error is returned in the TRequestStatus parameter.

Errors from the asynchronous open include:
KErrNotFound The database file was not found or it did not have the correct UIDs.
KErrLocked The file is in use by another client.
KErrBadName The filename is invalid; for example it includes wildcard characters
or the drive is missing.
Other system wide error codes.

If the return value is not NULL the ownership of the CContactOpenOperation object is passed 
to the client. This may be deleted before the asynchronous open completes.

When the client supplied TRequestStatus is completed with KErrNone the TakeDatabase() method
of CContactOpenOperation is called to pass ownership of the open database to the client.

@publishedAll
@released
@capability ReadUserData

@param	aFileName
		The filename of the database to open.
@param	aStatus
		On return, the request status for the asynchronous phase request.
		The Open() action can fail with one of the system wide error codes. In this case the
		CContactDatabase object cannot access the database and must be deleted.
@param	aAccess
		This argument should be ignored by developers.

@return NULL if there is an error starting the asynhchronous open, otherwise a pointer to an
		active object that manages the open operation.

@see CContactOpenOperation
*/
EXPORT_C CContactOpenOperation* CContactDatabase::Open(const TDesC& aFileName, TRequestStatus& aStatus, TThreadAccess /*aAccess*/)
	{
	TRequestStatus* ptrStatus = &aStatus;
	CContactOpenOperation* openOperation = NULL;

	TRAPD(newError, openOperation = CContactOpenOperation::NewL(aFileName, aStatus));
	// failed? return the error in the TRequestStatus
	if (newError != KErrNone)
		{
		User::RequestComplete(ptrStatus, newError);
		}

	return openOperation;
	}


/**
A static method to list the contact databases on all drives.

In v8.1, this function finds contact databases located anywhere on the drives, 
and the format of the returned filenames is c:\\system\\data\\contacts.cdb.

From v9.0 onwards, this function finds contact databases only in the correct 
data caged subdirectory. The returned filenames have no path, for example 
c:contacts.cdb. The maximum length for the drive, filename and extension is 190 
characters.

In either case, the filenames returned are in the correct format for Open(), 
OpenL(), CreateL(), ReplaceL() and DeleteDatabaseL().

@publishedAll
@released
@capability ReadUserData

@return An array containing zero or more contact database names.

@leave KErrNoMemory Out of memory.
*/
EXPORT_C CDesCArray* CContactDatabase::ListDatabasesL()
	{
	CContactDatabase* db = NewLC();
	CDesCArray* list = db->iCntSvr->ListDatabasesL();
	CleanupStack::PopAndDestroy(db);
	return list;
	}


/**
A static method to list the contact databases on a specified drive.

In v8.1, this function finds contact databases located anywhere on the drive, 
and the format of the returned filenames is c:\\system\\data\\contacts.cdb.

From v9.0 onwards, this function finds contact databases only in the correct 
data caged subdirectory. The returned filenames have no path, for example 
c:contacts.cdb. The maximum length for the drive, filename and extension is 190 
characters.

In either case, the filenames returned are in the correct format for Open(), 
OpenL(), CreateL(), ReplaceL() and DeleteDatabaseL().

@publishedAll
@released
@capability ReadUserData

@param	aDriveUnit
		The drive unit to search for contact databases.

@return An array containing zero or more contact database names.

@leave	KErrNoMemory Out of memory.
*/
EXPORT_C CDesCArray* CContactDatabase::ListDatabasesL(TDriveUnit aDriveUnit)
	{
	CContactDatabase* db = NewLC();
	CDesCArray* list = db->iCntSvr->ListDatabasesL(&aDriveUnit);
	CleanupStack::PopAndDestroy(db);
	return list;
	}


/**
A static method to delete a named contact database.

If the file is found, it is tested for the correct UIDs.

In v8.1, contact databases can be located in any directory on any writeable drive, 
and the format of the filename must include an absolute directory path such as 
c:\\system\\data\\contacts.cdb.

From v9.0 onwards, contact databases can only be located in the correct data caged 
subdirectory. The filenames must have no path, for example c:contacts.cdb.
The maximum length for the drive, filename and extension is 190 characters.

@publishedAll
@released
@capability WriteUserData

@param	aFileName
		The contact database file to delete.

@leave	KErrBadName The filename is invalid; for example it contains 
wildcard characters or the drive is missing.
@leave	KErrInUse Another client has the database open.
@leave	KErrNotFound The database file was not found or it did not have the correct UIDs.
@leave  KErrArgument if the given descriptor contains more than the maximum length 
        of 190 characters.

@see CContactDatabase::DeleteDefaultFileL()
*/
EXPORT_C void CContactDatabase::DeleteDatabaseL(const TDesC& aFileName)
	{
	CContactDatabase* db = NewLC();
	User::LeaveIfError(db->iCntSvr->DeleteDatabase(aFileName));
	CleanupStack::PopAndDestroy(db);
	}


/**
A static method to determine if the default contact database exists. 

It searches the drive set by SetDatabaseDriveL(), or if no drive has been 
set, it searches drive c:.

If the file is found, it is tested for the correct UIDs.

@publishedAll
@released
@capability None

@return ETrue if the file is found, EFalse otherwise.
@leave	KErrNotReady There is no media present in the drive.
@leave	KErrNotFound The database file was not found or it did not have the correct UIDs.
@leave	KErrCorrupt The file is not a valid database 

@see CContactDatabase::ContactDatabaseExistsL()
*/
EXPORT_C TBool CContactDatabase::DefaultContactDatabaseExistsL()
	{	
	CContactDatabase* db = NewLC();
	TBool theFlag = db->iCntSvr->DatabaseExistsL();
	CleanupStack::PopAndDestroy(db);	
	return theFlag;
	}


/**
A method to determine if a named contact database exists.

If the file is found, it is tested for the correct UIDs.

In v8.1, contact databases can be located in any directory on any writeable drive, 
and the format of the filename must include an absolute directory path such as 
c:\\system\\data\\contacts.cdb.

From v9.0 onwards, contact databases can only be located in the correct data caged
subdirectory. The filenames must have no path, for example c:contacts.cdb.
The maximum length for the drive, filename and extension is 190 characters.

@publishedAll
@released
@capability None

@param	aFileName
		The contact database to search for.

@return ETrue if the file is found, EFalse otherwise.

@leave	KErrNotReady There is no media present in the drive.
@leave	KErrBadName The filename is invalid; for example it contains 
wildcard characters or the drive is missing.
@leave	KErrNotFound The database file was not found or it did not have the correct UIDs.
@leave	KErrCorrupt The file is not a valid database 
@leave  KErrArgument if the given descriptor contains more than the maximum length 
        of 190 characters.

@see CContactDatabase::DefaultContactDatabaseExistsL()
@see CContactDatabase::ListDatabasesL()
*/
EXPORT_C TBool CContactDatabase::ContactDatabaseExistsL(const TDesC& aFileName)
	{
	// Leave if the filename format is bad
	TParse parseName;
	User::LeaveIfError(parseName.SetNoWild(aFileName,NULL,NULL));	
	CContactDatabase* db = NewLC();
	TBool dbExists = db->iCntSvr->DatabaseExistsL(aFileName);
	CleanupStack::PopAndDestroy(db);
	
	return dbExists;
	}


/**
Searches the database for a text string.  The function searches the fields
contained in the field definition.  The caller takes ownership of the returned
object. There is a limit of 255 characters on the search string length, due to
the implementation of the DBMS API, which also has a search string length
restriction of 255 chars. If the search string passed in is over 255 characters
this method will leave with KErrArgument.
   
@param aText The text to search for.
@param aFieldDef Specifies the fields to search.

@return Array of contact IDs identifying the contact items which contain the 
specified text.
*/
EXPORT_C CContactIdArray* CContactDatabase::FindLC(const TDesC& aText,const CContactItemFieldDef* aFieldDef)
	{
	CContactIdArray* idArray = iCntSvr->FindL(aText,aFieldDef);
	CleanupStack::PushL(idArray);
	return idArray;
	}


/**
Searches the database asynchronously for a text string. The function searches 
the fields contained in the field definition asynchronously using the MIdleFindObserver 
and CIdleFinder classes. The caller takes ownership of the returned object.

@param aText The text to search for.
@param aFieldDef Specifies the fields to search.
@param aObserver Implements the callback function IdleFindCallback(). NULL 
if no observer is needed.

@return A CIdle-derived object which provides information about the progress 
of the operation, and which can be used to retrieve an array of contact IDs.
*/
// !!! assert that the field definition doesn't contain any fields not included in the view?
// !!! should change to set the column found also
EXPORT_C CIdleFinder* CContactDatabase::FindAsyncL(const TDesC& aText,const CContactItemFieldDef *aFieldDef, MIdleFindObserver *aObserver)
	{
	return(CIdleFinder::NewL(*this,aText,aFieldDef,aObserver));
	}


/**
Enables the user to search the database for a string containing 
text that is stored in one or more fields.

The string is specified as an array of words.

For example, a user might want to search for the string "John Smith". 
To the user the string is a single item, but the text which makes up 
the string is stored in two separate fields in the database.

The caller of this function needs to provide an array of words to find 
(aFindWords), and a function to break down the text in the contact item 
into a list of words (aWordParserCallback).

The array of words to find would typically not contain punctuation. For 
example if the user searches for 'Smith, John' this would be passed to 
this function as an array of two words: 'Smith' and 'John', with the 
separator being discarded.

For a match to succeed, all words in the aFindWords array must match 
words in the array generated from the contact item by the aWordParserCallback 
function. To match, the word generated from the contact item must begin with 
the search word, i.e. a search for "Sm" would find any word beginning in "Sm". 
If a word is specified twice in the aFindWords array, then it must exist in 
two separate places in the contact item.

The function only searches the fields contained in the currently set text 
definition.

The caller takes ownership of the returned object.

@param aFindWords An array of words to find.
@param aWordParserCallback A function supplied by the caller to break the text 
in the contact down into a list of words.

@return Array of contact IDs.
*/
EXPORT_C CContactIdArray* CContactDatabase::FindInTextDefLC(const MDesCArray& aFindWords, const TCallBack &aWordParserCallback)
	{
	return(FindInTextDefLC(aFindWords,iTextDef,aWordParserCallback));
	}


/**
Enables the user to search the database for a string containing 
text that is stored in one or more fields.

The string is specified as an array of words.

For example, a user might want to search for the string "John Smith". 
To the user the string is a single item, but the text which makes up 
the string is stored in two separate fields in the database.

The caller of this function needs to provide an array of words to find 
(aFindWords), and a function to break down the text in the contact item 
into a list of words (aWordParserCallback).

The array of words to find would typically not contain punctuation. For 
example if the user searches for 'Smith, John' this would be passed to 
this function as an array of two words: 'Smith' and 'John', with the 
separator being discarded.

For a match to succeed, all words in the aFindWords array must match 
words in the array generated from the contact item by the aWordParserCallback 
function. To match, the word generated from the contact item must begin with 
the search word, i.e. a search for "Sm" would find any word beginning in "Sm". 
If a word is specified twice in the aFindWords array, then it must exist in 
two separate places in the contact item.

The function only searches the fields contained in the text definition aTextDef.

The caller takes ownership of the returned object.

@param aFindWords An array of words to find.
@param aTextDef The text definition.
@param aWordParserCallback A function supplied by the caller to break the text 
in the contact down into a list of words.

@return Array of contact IDs.
*/
EXPORT_C CContactIdArray* CContactDatabase::FindInTextDefLC(const MDesCArray& aFindWords,CContactTextDef* aTextDef, const TCallBack &aWordParserCallback)
	{
	CIdleFinder* idleFinder=FindInTextDefAsyncL(aFindWords,aTextDef,NULL,aWordParserCallback);
	CleanupStack::PushL(idleFinder);
	while(idleFinder->doFindL()) {};
	User::LeaveIfError(idleFinder->Error());
	CContactIdArray *ids=idleFinder->TakeContactIds();
	CleanupStack::PopAndDestroy();	// idleFinder
	CleanupStack::PushL(ids);
	return(ids);
	}


/**
Asynchronously searches the database for an array of words. 

This function works in the same way as its corresponding variant in FindInTextDefLC(), 
except that it operates asynchronously using the MIdleFindObserver and CIdleFinder 
classes. The caller takes ownership of the returned object.

@param aFindWords An array of words to find.
@param aObserver Implements the callback function IdleFindCallback(). May be NULL if 
no observer is needed.
@param aWordParserCallback A function to break the text in the contact down into a 
list of words.

@return A CIdle-derived object which provides information about the progress of the 
operation, and which can be used to retrieve an array of contact IDs.
*/
EXPORT_C CIdleFinder* CContactDatabase::FindInTextDefAsyncL(const MDesCArray& aFindWords, MIdleFindObserver *aObserver, const TCallBack &aWordParserCallback)
	{
	return(FindInTextDefAsyncL(aFindWords,iTextDef,aObserver,aWordParserCallback));
	}


/**
Asynchronously searches the database for an array of words. 

This function works in the same way as its corresponding variant in FindInTextDefLC(), 
except that it operates asynchronously using the MIdleFindObserver and CIdleFinder 
classes. The caller takes ownership of the returned object.

@param aFindWords An array of words to find.
@param aTextDef The text definition.
@param aObserver Implements the callback function IdleFindCallback(). May be NULL if 
no observer is needed.
@param aWordParserCallback A function to break the text in the contact down into a 
list of words.

@return A CIdle-derived object which provides information about the progress of the 
operation, and which can be used to retrieve an array of contact IDs.
*/
EXPORT_C CIdleFinder* CContactDatabase::FindInTextDefAsyncL(const MDesCArray& aFindWords,const CContactTextDef* aTextDef, MIdleFindObserver *aObserver, const TCallBack &aWordParserCallback)
	{
	return(CIdleFinder::NewL(*this,&aFindWords,aTextDef,aObserver,aWordParserCallback));
	}


/**
This function is not currently supported.
@param aFormat This parameter should be ignored.
@deprecated
*/
EXPORT_C void CContactDatabase::SetDateFormatTextL(const TDesC& /*aFormat*/)
	{//Does nothing, Parameter should be ignored
	}


/**
Returns an array of contact item IDs for all the contact items which may contain
the specified telephone number in a telephone, fax or SMS type field.

The comparison method used is not exact. The number is compared starting from
the right side of the number and the method returns an array of candidate 
matches. Punctuation (eg. spaces) and other alphabetic characters are 
ignored when comparing.

Additionally, if the contacts model phone parser (CNTPHONE.DLL) is available, 
then any DTMF digits are also excluded from the comparision.

Notes:
Due to the way numbers are stored in the database, it is recommended that at
least 7 match digits are specified even when matching a number containing fewer
digits. Failure to follow this guideline may (depending on the database contents)
mean that the function will not return the expected Contacts Id set.
  
@released
@capability ReadUserData

@param aNumber Phone number string. If the length of phone number string is greater than 
KCntMaxTextFieldLength then only the first KCntMaxTextFieldLength characters are used 
in the match.
@param aMatchLengthFromRight Number of digits from the right of the phone number to use
Up to 15 digits can be specified, and it is recommended that at least 7 match digits are
specified.

@return CContactIdArray of candidate matches
*/
EXPORT_C CContactIdArray* CContactDatabase::MatchPhoneNumberL(const TDesC& aNumber, const TInt aMatchLengthFromRight)
  	{
  	return iCntSvr->MatchPhoneNumberL(aNumber, aMatchLengthFromRight);
	}


TInt CContactDatabase::ContactPosL(TContactItemId aContactId) //for cntiter
	{
	return SortedItemsL()->Find(aContactId);
	}


TInt CContactDatabase::DoGotoL(TContactItemId /*aContactId*/)
	{
    return KErrNone; 
	}


EXPORT_C void CContactDatabase::AddObserverL(MContactDbObserver& aChangeNotifier)
	{
	iCntSvr->AddObserverL(aChangeNotifier);
	}


EXPORT_C void CContactDatabase::RemoveObserver(const MContactDbObserver& aChangeNotifier)
	{
	iCntSvr->RemoveObserver(aChangeNotifier);
	}
	
EXPORT_C void CContactDatabase::AddObserverV2L(MContactDbObserverV2& aChangeNotifier)
    {
    iCntSvr->AddObserverV2L(aChangeNotifier);
    }


EXPORT_C void CContactDatabase::RemoveObserverV2(const MContactDbObserverV2& aChangeNotifier)
    {
    iCntSvr->RemoveObserverV2(aChangeNotifier);
    }

void CContactDatabase::CancelNotifyRequestL()
	{
	}


TBool CContactDatabase::IsICCSynchronisedL()
	{
	return EFalse;
	}


MLplPersistenceLayerFactory* CContactDatabase::FactoryL()
	{
	if(iProxyFactory == NULL)
		{
		iProxyFactory = CProxyFactory::NewL(*this);
		}
	return iProxyFactory;
	}
	

void CContactDatabase::FetchGroupAndTemplateListsL()
	{
	delete iCardTemplateIds;
	// Set the iCardTemplateIds to null in order to avoid a corruption
	// should the FetchTemplateListIdsL leave. 
	iCardTemplateIds = NULL;
	iCardTemplateIds = iCntSvr->FetchTemplateListIdsL(); 
	
	delete iGroupIds;
	iGroupIds = NULL; // See previous comment
	iGroupIds = iCntSvr->FetchGroupListIdsL();	
	}
	
void CContactDatabase::LoadSyncPluginL()
    {
	if (iContactSynchroniser == NULL)
	    {
	    //Instantiate a CContactSynchroniser object which loads the plugin.
	    //This is required to avoid a deadlock in the contacts server code.
		iContactSynchroniser = CContactSynchroniser::NewL();
	    }
    }

/**
@capability ReadUserData
*/
CContactOpenOperation* CContactOpenOperation::NewL(TRequestStatus& aPtrStatus)
	{
	CContactOpenOperation* self = new (ELeave) CContactOpenOperation(aPtrStatus);

	CleanupStack::PushL(self);
	self->ConstructL();
	CleanupStack::Pop(self);
	return self;
	}

/**
@capability ReadUserData
*/
CContactOpenOperation* CContactOpenOperation::NewL(const TDesC& aFileName, TRequestStatus& aPtrStatus)
	{
	CContactOpenOperation* self = new (ELeave) CContactOpenOperation(aPtrStatus);
	
	CleanupStack::PushL(self);
	self->ConstructL(aFileName);
	CleanupStack::Pop(self);
	return self;
	}


CContactOpenOperation::CContactOpenOperation(TRequestStatus& aClientStatus) : 
CActive(EPriorityIdle), iClientStatus(&aClientStatus)
	{}	
	
/**
@capability ReadUserData
@leave  KErrArgument if the given descriptor contains more than the maximum length 
        of 190 characters.
*/
void CContactOpenOperation::ConstructL(const TDesC& aFileName)
	{
	iContactDatabase = CContactDatabase::NewLC();
	CleanupStack::Pop(iContactDatabase);
	iContactDatabase->iCntSvr->OpenDatabaseAsyncL(*iClientStatus, aFileName);
	}


/**
For BC only, CActive is not used here.
*/
void CContactOpenOperation::RunL()
	{
	}


/**
For BC only, CActive is not used here.
*/
TInt CContactOpenOperation::RunError(TInt)
	{
	return KErrNone;
	}


/**
For BC only, CActive is not used here.
*/
void CContactOpenOperation::DoCancel()
	{
	}


/**
Takes ownership of the contact database.

Ownership of the contact database is passed to the client.
Subsequent calls return NULL.

@return A pointer to the CContactDatabase on the first call after 
		the asynchronous open has succeeded. Otherwise NULL.

@see CContactDatabase::Open()
*/
EXPORT_C CContactDatabase* CContactOpenOperation::TakeDatabase()
	{
	// async open must have succeeded in server AND RunL must have completed
	CContactDatabase* contactDatabase = iContactDatabase;
	// prevent deletion of the database.
	iContactDatabase = NULL;
	return contactDatabase;
	}


/**
Deletes the active object.

If the asynchronous open is still in progress it is cancelled.

If the TakeDatabase() API has not been called and the database 
has been opened it is closed.

@capability None
*/
EXPORT_C CContactOpenOperation::~CContactOpenOperation()
	{
	if (iContactDatabase)
		{
		iContactDatabase->iCntSvr->CancelAsyncOpen();
		delete iContactDatabase;
		iContactDatabase = NULL;
		}
	}


CDataBaseChangeObserver* CDataBaseChangeObserver::NewL(MContactDbPrivObserver& aPrivateObserver)
	{
	CDataBaseChangeObserver* temp = new (ELeave) CDataBaseChangeObserver(aPrivateObserver);
	return temp;
	}


CDataBaseChangeObserver::CDataBaseChangeObserver(MContactDbPrivObserver& aPrivateObserver) : iPrivateObserver(aPrivateObserver)
	{}	


void CDataBaseChangeObserver::HandleDatabaseEventL(TContactDbObserverEvent aEvent)
	{
	iPrivateObserver.HandleDatabaseEventL(aEvent);
	}


CDataBaseChangeObserver::~CDataBaseChangeObserver()
	{}	


void CContactDatabase::HandleDiskSpaceEvent(TInt)
/** Default behaviour for handling a low disk event - This function is unimplemented. */
	{}//Do nothing.
	

void CContactDatabase::RespondToEventL(const TContactDbObserverEventType aEventType, const TContactItemId aContactId)
	{
	switch(aEventType)
		{
		case EContactDbObserverEventContactChanged:
		case EContactDbObserverEventGroupChanged:
			HandleDbObserverEventGroupOrContactChangedL(aContactId);
			break;
		
		case EContactDbObserverEventContactAdded:
		case EContactDbObserverEventGroupAdded:
			HandleDbObserverEventGroupOrContactAddedL(aEventType, aContactId);
			break;

		case EContactDbObserverEventSpeedDialsChanged:
			break;
			
		case EContactDbObserverEventOwnCardDeleted:
		case EContactDbObserverEventContactDeleted:
            RemoveFromSortArray(aContactId);
			break;
		
		case EContactDbObserverEventGroupDeleted:
			HandleDbObserverEventGroupDeletedL(aContactId);
			break;
		
		case EContactDbObserverEventTemplateAdded:
			{
			if (!iCardTemplateIds)
				{
				//if database was opened async, iCardTemplate is null.
				//keep same behaviour like CContactDatabase::AddToTemplateListL
				iCardTemplateIds = CContactIdArray::NewL();
				}
			iCardTemplateIds->AddL(aContactId);
			}
			break;

		case EContactDbObserverEventTemplateChanged:
			{
			iTemplateCache->RemoveTemplate(aContactId);
			}
			break;

		case EContactDbObserverEventTemplateDeleted:
			{
			iTemplateCache->RemoveTemplate(aContactId);
			RemoveFromTemplateList(aContactId);
			}
			break;
		
		case EContactDbObserverEventOwnCardChanged:
			break;

		case EContactDbObserverEventBackupBeginning:
		case EContactDbObserverEventRestoreBeginning:
		case EContactDbObserverEventBackupRestoreCompleted:
		case EContactDbObserverEventRestoreBadDatabase:
			// NB this handler decides on the event to send to observers
		//	HandleBackupOrRestoreEvent(aEvent);
			return;

		case EContactDbObserverEventTablesOpened:
			iTablesOpen = ETrue;
			break;
			
		case EContactDbObserverEventTablesClosed:
			iTablesOpen = EFalse;
			break;

		case EContactDbObserverEventUnknownChanges:
			{
			FetchGroupAndTemplateListsL();
			// Reset the template cache
			delete iTemplateCache;
            iTemplateCache = NULL;
			iTemplateCache = CCntTemplateCache::NewL(*iCntSvr); 
			
			TInt err=KErrGeneral;
			if (iTablesOpen)
				{
				CArrayFix<TSortPref>* sortOrder = const_cast<CArrayFix<TSortPref>*>(iCntSvr->GetSortPreferenceL());
				CleanupStack::PushL(sortOrder);
				TRAP(err,ReSortL(sortOrder));
				CleanupStack::PopAndDestroy(sortOrder);
				}
			CheckSortError(err);
			}
			break;
		default:;
		}	
	}


/**  
Handle the Database event
@internalTechnology
@param aEvent Database change event
*/
EXPORT_C void CContactDatabase::HandleDatabaseEventL(const TContactDbObserverEvent& aEvent)
	{
	//Just respond to events created by other sessions
	if (ConnectionId()!=aEvent.iConnectionId)
		{
		RespondToEventL(aEvent.iType, aEvent.iContactId);
		}
	}
	

void CContactDatabase::RemoveFromSortArray(TContactItemId aContactId)
	{
	if (iSortedItems)
		{
		const TInt pos=iSortedItems->Find(aContactId);
		if (pos!=KErrNotFound)
			iSortedItems->Remove(pos);
		}
	}
	

void CContactDatabase::RemoveFromGroupIds(const TContactItemId aContactId)
	{
     if (iGroupIds) 
         {
          TInt pos = iGroupIds->Find(aContactId); 
          if ( pos != KErrNotFound ) 
              { 
              iGroupIds->Remove( pos ); 
              }
         } 
	}


void CContactDatabase::HandleDbObserverEventGroupDeletedL(const TContactItemId aContactId)
    {
	 RemoveFromGroupIds(aContactId);
     RespondToEventL(EContactDbObserverEventContactDeleted, aContactId);
    }


TBool CContactDatabase::AddContactToSortListL(TContactItemId aReqId, TContactItemId& aActualId,CBase* aItems, TUid& aFieldType, TBool aHasSortOrder)
	{
	TUid contactType;
	TBool deleted;
	
	if(!FactoryL()->GetCollectorL().SeekContactL(aReqId,aActualId,contactType,deleted))
		{
		return EFalse;
		}
	
	if(deleted || contactType != KUidContactCard)
		{
		return ETrue;
		}
	if (!aHasSortOrder)
		{
		((CContactIdArray*)aItems)->AddL(aActualId);
		}
	else
		{
		CContactDatabase::TTextFieldMinimal textFieldMin;
		if	(aFieldType == KUidContactFieldDefinedText)
			{
			ReadContactTextDefL(aActualId,textFieldMin,iTextDef);
			}
		else
			{
			FactoryL()->GetViewIteratorManagerL().TextFieldL(aActualId,aFieldType,textFieldMin);
			}
		((CSortArray*) aItems)->AppendL(textFieldMin,aActualId);
		}
	return ETrue;
	}


TInt CContactDatabase::NextExistingL(TInt aIndex)
	{
	TInt ret=KErrNotFound;
	const CContactIdArray* sortedItems=SortedItemsL();
	const TInt count=sortedItems->Count();
	TContactItemId contactId=KNullContactId;
	while ((ret==KErrNotFound) && (aIndex<count-1))
		{
		contactId=(*sortedItems)[++aIndex];
		ret=DoGotoL(contactId);
		}
	if (ret==KErrNotFound)
		return ret;
	return aIndex;
	}


TInt CContactDatabase::PreviousExistingL(TInt aIndex)
	{
	TInt ret=KErrNotFound;
	TContactItemId contactId=KNullContactId;
	const CContactIdArray* sortedItems=SortedItemsL();
	while (ret==KErrNotFound && aIndex>=1)
		{
		contactId=(*sortedItems)[--aIndex];
		ret=DoGotoL(contactId);
		}
	if (ret==KErrNotFound)
		return ret;
	return aIndex+1;
	}


TInt CContactDatabase::NewSortIndexL(const CContactItem& aContact, TInt aMin, TInt aMax)
	{
	__ASSERT_DEBUG(&aContact!=NULL,Panic(ECntPanicNullPointer));
	FOREVER
		{
		if (aMin==aMax)
			return(aMin);
		TInt index=(aMax-aMin)/2+aMin;
		User::LeaveIfError(DoGotoL((*iSortedItems)[index]));
		TInt compare=CompareSortFieldsL(aContact);
		if (compare<=0)
			{
			if (aMin==index)
				aMin++;
			else
				aMin=index;
			}
		else if (compare>0)
			aMax=index;
		}
	}


TBool CContactDatabase::CheckSortError(TInt aError)
	{
	if (aError!=KErrNone)
		{
		delete iSortedItems;
		iSortedItems=NULL;
		return(ETrue);
		}
	return(EFalse);
	}


void CContactDatabase::MoveInSortArray(const CContactItem& aContact)
	{
	TRAPD(err,MoveInSortArrayL(aContact));
	CheckSortError(err);
	}


void CContactDatabase::InsertInSortArray(const CContactItem& aContact)
	{
	TRAPD(err,InsertInSortArrayL(aContact));
	CheckSortError(err);
	}


void CContactDatabase::InsertInSortArrayL(const CContactItem& aContact)
	{
	__ASSERT_DEBUG(&aContact!=NULL,Panic(ECntPanicNullPointer));
	if (CheckType(aContact.Type()) && iSortedItems)
		{
		const TContactItemId id=aContact.Id();
		if (iSortedItems->Find(id)==KErrNotFound)
			{
			const TInt index=NewSortIndexL(aContact,0,iSortedItems->Count());
			if (index<iSortedItems->Count())
				iSortedItems->InsertL(index,id);
			else
				iSortedItems->AddL(id);
			}
		}
	}


void CContactDatabase::MoveInSortArrayL(const CContactItem& aContact)
	{
	__ASSERT_DEBUG(&aContact!=NULL,Panic(ECntPanicNullPointer));
	if (iSortedItems && CheckType(aContact.Type()))
		{
		const TInt pos=iSortedItems->Find(aContact.Id());
		TInt compare=0;
		if (pos!=0 && PreviousExistingL(pos)!=KErrNotFound)
			compare=CompareSortFieldsL(aContact);
		TInt index;
		TInt start=0;
		TInt end=pos;
		if (compare<=0)
			{
			if (NextExistingL(pos)!=KErrNotFound)
				compare=CompareSortFieldsL(aContact);
			if (compare>=0)
				return;
			start=pos;
			end=iSortedItems->Count();
			}
		index=NewSortIndexL(aContact,start,end);
		iSortedItems->MoveL(pos,index>pos?index-1:index);
		}
	}


TInt CContactDatabase::CompareSortFieldsL(const CContactItem& aContact)
	{
	TInt compare=0;
	TInt index=0;
	CArrayFix<TSortPref>* sortOrder = iCntSvr->GetSortPreferenceL();
	CleanupStack::PushL(sortOrder);
	const TInt sortDefs=sortOrder->Count();
	while (compare==0 && index<sortDefs)
		{
		TUid fieldType=(*sortOrder)[index++].iFieldType;
		TTextFieldMinimal textFieldMin;
		TTextFieldMinimal textFieldMin2;
		if (fieldType==KUidContactFieldDefinedText)
			{
			// Reads from database.
			ReadContactTextDefL(aContact.Id(),textFieldMin);
			// Does not read from database.
			ReadContactTextDefL(aContact,textFieldMin2);
			}
		else
			{
			MLplViewIteratorManager& manager = FactoryL()->GetViewIteratorManagerL();
			manager.TextFieldL(aContact.Id(),fieldType,textFieldMin);
			aContact.CardFields().NonZeroFieldText(fieldType,textFieldMin2);
			}
		compare=textFieldMin.CompareC(textFieldMin2,3,&iCollateMethod);		
		}
	if (index>0)
		--index;
	
	TInt retVal = ((sortDefs==0) || ((*sortOrder)[index].iOrder==CContactDatabase::TSortPref::EAsc)? compare : -compare);
	CleanupStack::PopAndDestroy(); //sortOrder
	return retVal;
	}


/**
Looks at the sort order and identifes what tables are required.
*/
void CContactDatabase::ConstructTableUsageFlagsFromSortOrderL(TInt& aFlags)
	{
	CContactTextDef* textDef=CContactTextDef::NewLC();
	CArrayFix<TSortPref>* sortOrder = iCntSvr->GetSortPreferenceL();
	CleanupStack::PushL(sortOrder);
	TInt sortOrderCount=sortOrder->Count();
	TInt columns=0;
	aFlags=0;
	for (TInt sortIndex=0;sortIndex<sortOrderCount;sortIndex++)
		textDef->AppendL(TContactTextDefItem((*sortOrder)[sortIndex].iFieldType));
	MLplCollection& collection = FactoryL()->GetCollectorL();
	collection.ConstructBitwiseFlagsFromTextDef(aFlags,columns,textDef);
	CleanupStack::PopAndDestroy(sortOrder);
	CleanupStack::PopAndDestroy(textDef);
	}


/**
Update sorted items list using contact card/group change event.

@internalTechnology
@since 7.0

@param aEvent Database change event
*/ 
void CContactDatabase::HandleDbObserverEventGroupOrContactChangedL(const TContactItemId aContactId)
	{
	if (iSortedItems)
		{
	 	CArrayFix<TSortPref>* sortOrder = iCntSvr->GetSortPreferenceL();
		CleanupStack::PushL(sortOrder);
		if(sortOrder!=NULL && sortOrder->Count() > 0)
			{
			if (iTablesOpen)
				{
				CContactItem* contact = NULL;
				TRAPD(error, contact = ReadContactL(aContactId));
				if (CheckSortError(error)==EFalse && contact != NULL)
					{
					MoveInSortArray(*contact);
					delete contact;
					}
				}
			else
				{
				CheckSortError(KErrGeneral);
				}
			}
		CleanupStack::PopAndDestroy(sortOrder);
		}
	}


/**
Add new contact card/group to sorted items list using add event.

@internalTechnology
@since 7.0

@param aEvent Database change event
*/ 
void CContactDatabase::HandleDbObserverEventGroupOrContactAddedL(const TContactDbObserverEventType aEventType, const TContactItemId aContactId)
	{
	if (aEventType == EContactDbObserverEventGroupAdded)
		{
		if(iGroupIds == NULL)
			{
			//if database was opened async, iGroups is null, so we have to fetch the group ids first
			iGroupIds = iCntSvr->FetchGroupListIdsL();	
			if(iGroupIds->Find(aContactId) == KErrNotFound)
				{
				iGroupIds->AddL(aContactId);	
				}
			}
		else 
			{
			iGroupIds->AddL(aContactId);		
			}	
		}

	if (iSortedItems)
		{
		if (iTablesOpen)
			{
			CContactItem* contact = NULL;
			TInt error = KErrGeneral;
			CArrayFix<TSortPref>* sortOrder = iCntSvr->GetSortPreferenceL();
			CleanupStack::PushL(sortOrder);
			if(sortOrder!= NULL && sortOrder->Count() > 0)
				//There is a sort order, so the contact must be read
				//to find out where to insert it into the sorted list
				{
				TRAP(error, contact = ReadContactL(aContactId));
				CheckSortError(error);
				if (error == KErrNone && contact != NULL)
					{
					InsertInSortArray(*contact);
					delete contact;
					}
				}
			else
				{
				// No sort order is defined only the contact's type is needed.
				TContactItemId actualId;
				TUid contactType = KNullUid;
				TBool deleted = EFalse;
				TBool found = EFalse;
	
        		MLplCollection& collection = FactoryL()->GetCollectorL();
				TRAP(error, found = collection.SeekContactL(aContactId,actualId,contactType,deleted));
				
				if (found && CheckSortError(error)==EFalse)
					{
					if (CheckType(contactType))
						{
						iSortedItems->AddL(aContactId);
						}
					}
				}
			CleanupStack::PopAndDestroy(sortOrder);
			}
		else // iTablesOpen == EFalse
			{
			CheckSortError(KErrGeneral);
			}
		}
	}


/**
@internalTechnology
*/
void CContactDatabase::StartAsyncActivityL()
	{
	// starting: Recover, Async Find, Compress
	++iAsyncActivityCount;

	// At least one async activity in progress, tell server.
	if (iAsyncActivityCount == 1)
		{
		iCntSvr->SetAsyncActivityL(ETrue);
		}
	}
 
 
/**
@internalTechnology
*/
void CContactDatabase::EndAsyncActivityL()
	{
	// ending: Recover, Async Find, Compress
	--iAsyncActivityCount;
	
	// All async activities finished, tell server this so that it can process
	// any pending database close.
	if (iAsyncActivityCount == 0)
		{
		iCntSvr->SetAsyncActivityL(EFalse);
		}
	}


/**
Determine if the database is ready.  Ready in this context means that the
database is open and readable/writable (i.e. the state machine is in
CStateWritable).

@internalTechnology
@capability None

@return ETrue if the database is ready, EFalse if the database is not ready.
*/
TBool CContactDatabase::DatabaseReadyL() const
	{
	return iCntSvr->DatabaseReadyL();
	}


CCntIdleSorter::CCntIdleSorter(CContactDatabase &aContactDatabase)
:	iDb(aContactDatabase), iState(EReadContacts)
	{
	}


CCntIdleSorter::~CCntIdleSorter()
	{
	if (iSortStarted)
		{
		// async Sort blocks Backup or Restore closing the database handles
		TRAP_IGNORE(iDb.EndAsyncActivityL());
		iSortStarted = EFalse;
		}

	if	(iIdle)
		iIdle->Cancel();
	delete iIdle;
	delete iSortOrder;
	delete iSortedList;
	delete iFinalItems;
	}


void CCntIdleSorter::ConstructL()
	{
	iIdle		= CIdle::NewL(CActive::EPriorityIdle);
	iSortedList	= new(ELeave) CSortArray();
	iFinalItems	= CContactIdArray::NewL();

	// Must call this to ensure the system template is loaded
//	Not required in client for cntmodel
//	iDb.SystemTemplateL();
	}


CCntIdleSorter* CCntIdleSorter::NewL(CContactDatabase &aContactDatabase)
	{
	CCntIdleSorter* self= new(ELeave) CCntIdleSorter(aContactDatabase);
	CleanupStack::PushL(self);
	self->ConstructL();
	CleanupStack::Pop(self);
	return self;
	}


/**
Prepare and begin the sort.
*/
void CCntIdleSorter::StartSortingL(CArrayFix<CContactDatabase::TSortPref>* aSortOrder, TRequestStatus& aStatus)
	{
	// Take ownership of sort order
	iSortOrder = aSortOrder;

	// Save the TRequestStatus so we can signal the client
	iStatus = &aStatus;

	// Set up how many records we will have to read
	TotalCount() = iDb.CountL();

	// async Sort uses database tables, so Backup or Restore handling must wait for the async activity to finish
	iDb.StartAsyncActivityL();
	iSortStarted = ETrue;

	// Indicate that the sort is in progress. This will result in the client's
	// RunL (if it's using an AO framework) to be called when the sort is completed
	// or cancelled.
	*iStatus = KRequestPending;
	
	// Start the idle sorter.
	iIdle->Start(TCallBack(CCntIdleSorter::SortCallBack, this));
	}


/**
Sort with observer.
*/
void CCntIdleSorter::StartSortingL(CArrayFix<CContactDatabase::TSortPref>* aSortOrder, TRequestStatus& aStatus, MContactSortObserver& aObserver)
	{
	iObserver = &aObserver;
	HasObserver() = ETrue;
	StartSortingL(aSortOrder, aStatus);
	}


/**
Initialise values to defaults.
*/
void CCntIdleSorter::ResetL()
	{
//	iDb.iItemTable->iTable.BeginningL();
	iState = EReadContacts;
	iIdle->Cancel();

	delete iSortOrder;
	iSortOrder = NULL;

	delete iSortedList;
	iSortedList = NULL;
	iSortedList	= new(ELeave) CSortArray();

	if (iSortStarted)
		{
		// async Sort blocks Backup or Restore closing the database handles
		iDb.EndAsyncActivityL();
		iSortStarted = EFalse;
		}

	delete iFinalItems;
	iFinalItems = NULL;
	iFinalItems	= CContactIdArray::NewL();
	
	iObserver = NULL;
	iStatus = NULL;
	HasObserver() = EFalse;
	TotalCount() = 0;
	ReadSoFar() = 0;
	iCurrentId = 0;
	}


/**
Callback function for idle object.
*/
TInt CCntIdleSorter::SortCallBack(TAny* aThis)
	{
	return static_cast<CCntIdleSorter*>(aThis)->PeformSortStep();
	}


/**
Read a single contact.
*/
TBool CCntIdleSorter::ReadContactsL(TInt aNumber)
	{
	// Do we have to sort using specified order criteria?
	TBool moreToDo		= ETrue;
	TBool haveSortOrder	= (iSortOrder->Count() > 0);
	TUid fieldType		= (haveSortOrder) ? iSortOrder->At(0).iFieldType : KNullUid;
	CBase* array =  (haveSortOrder) ? (CBase*) iSortedList : (CBase*)iFinalItems;

	// Only retrieve aNumber contacts from the contact store before yeilding
	for (TInt i = 0; i < aNumber; i++)
		{
		++ReadSoFar();
		TContactItemId actualId(0);
		moreToDo = iDb.AddContactToSortListL(iCurrentId,actualId,array, fieldType, haveSortOrder) && moreToDo;
		iCurrentId = actualId+1;
		if(!moreToDo)
			break;
		}

	// Report progress to observer (if there is one)
	ReportProgressL();

	return moreToDo;
	}


/**
This function is called once the reading from the database is complete.
It replaces the contact database's sorted list (takes ownership of iFinalItems).
*/
void CCntIdleSorter::SortListAndSaveL()
	{
	iSortedList->SortL(iSortOrder->At(0).iOrder);
	iDb.SortDuplicatesL(*iSortOrder, *iSortedList, 1);
	const TInt count = iSortedList->Count();
	for (TInt i=0; i<count; i++)
		iFinalItems->AddL(iSortedList->Id(i));

	// Safe to do this now...
	delete iDb.iSortedItems;
	iDb.iSortedItems = iFinalItems;
	iFinalItems = NULL; // just so we don't delete it

	if (iSortStarted)
		{
		// async Sort blocks Backup or Restore closing the database handles
		iDb.EndAsyncActivityL();
		iSortStarted = EFalse;
		}

	// Set the sort order in the server.
	iDb.iCntSvr->SetSortPreferenceL(*iSortOrder);
	}


/**
Called as a result of a cancellation request by the CContactDatabase class.
*/
void CCntIdleSorter::Cancel() 
	{
	iIdle->Cancel();
	CompleteRequest(KErrCancel);
	TRAP_IGNORE(ResetL());
	}


/**
Complete the client's request status with the specified error value (KErrNone by default).
*/
void CCntIdleSorter::CompleteRequest(TInt aError)
	{
	if	(iStatus)
		User::RequestComplete(iStatus, aError);
	}


/**
if we have an observer, then we report progress as the sort is performed (in reality
we actually only report progress during the read stage, not the sort itself).
*/
void CCntIdleSorter::ReportProgressL()
	{
	if	(iObserver && HasObserver())
		iObserver->HandleSortEventL(Max(TotalCount(), ReadSoFar()), TotalCount());
	}


/**
Idle object callback which performs appropriate action based on internal state machine.
*/
TInt CCntIdleSorter::PeformSortStep()
	{
	TInt err = KErrNone;
	TBool moreToDo = EFalse;

	// Based on the current state machine value we perform either a read or a sort
	switch (iState)
		{
	case EReadContacts:
		// Read all contacts & when complete move to next state
		TRAP(err, moreToDo = ReadContactsL())
		if	(err)
			{
			// There was an error sorting
			CompleteRequest(err);
			moreToDo = EFalse;
			}
		else if	(!moreToDo) 
			{
			// Indicate that the reading is complete
			iState = ESortContacts;

			// Set this back to ETrue because we now have to do the sort...
			moreToDo = ETrue;
			}

		break;

	case ESortContacts:
		// Contact reading finished, now perform the sort
		TRAP(err, SortListAndSaveL());
		CompleteRequest(err);
		moreToDo = EFalse;
		break;
		}

	// Return a boolean indicating whether we want the idle to call this dispatch
	// function again in future.
	return moreToDo;
	}


/**
Allocates and constructs a new contact database change notifier.

@param aDatabase The contact database to observe.
@param aObserver The observer for aDatabase. Its HandleDatabaseEventL() function 
is called whenever a change occurs to the database.

@return Pointer to the newly created contact database change notifier.
*/
EXPORT_C CContactChangeNotifier* CContactChangeNotifier::NewL(CContactDatabase& aDatabase, MContactDbObserver* aObserver)
	{
	CContactChangeNotifier *self=new(ELeave) CContactChangeNotifier(aDatabase, aObserver);
	CleanupStack::PushL(self);
	self->ConstructL();
	CleanupStack::Pop(self);
	return(self);
	}
	

CContactChangeNotifier::CContactChangeNotifier(CContactDatabase& aDatabase, MContactDbObserver *aObserver) :
	iDatabase(aDatabase), iObserver(aObserver)
	{}


/**
Removes the observer from the contact database.
*/
EXPORT_C CContactChangeNotifier::~CContactChangeNotifier()
	{
    if (iObserver)
        {
	    iDatabase.RemoveObserver(*iObserver);
        }
	}

	
void CContactChangeNotifier::ConstructL()
	{
    if (iObserver)
        {
	    iDatabase.AddObserverL(*iObserver);
        }
	}


/**
Deletes a contact item. 
See doDeleteContactL() for details
*/
void CContactDatabase::DeleteContactSendEventActionL(TContactItemId aContactId, TCntSendEventAction aActionType)
	{
	iCntSvr->DeleteContactL(aContactId, aActionType);
	//Now we check if the contact belonged to the sort array, if so 
	//remove it from iSortedItems
	RemoveFromSortArray(aContactId);
	//Now we check if the contact belonged to the template list, if so 
	//remove it from iCardTemplateIds
	RemoveFromTemplateList(aContactId);
	//Now we check if the contact belonged to the Group Id list, if so 
	//remove it from iGroupIds	
	RemoveFromGroupIds(aContactId);
	}

/**
Deletes a contact item. 
See doDeleteContactL() for details
@return KErrNone if the function completed successfully, otherwise one of the 
standard error codes.
*/
TInt CContactDatabase::DeleteContactSendEventAction(TContactItemId aContactId, TCntSendEventAction aActionType)
	{
    TInt retValue=KErrNone;
    retValue=iCntSvr->DeleteContact(aContactId, aActionType);
	//Now we check if the contact belonged to the sort array, if so 
	//remove it from iSortedItems
	RemoveFromSortArray(aContactId);
	//Now we check if the contact belonged to the template list, if so 
	//remove it from iCardTemplateIds
	RemoveFromTemplateList(aContactId);
	//Now we check if the contact belonged to the Group Id list, if so 
	//remove it from iGroupIds	
	RemoveFromGroupIds(aContactId);
	return retValue;
	}