summaryrefslogtreecommitdiff
path: root/src/dbus/server/pim/locale-factory-boost.cpp
blob: 2a3e69054657a63295d9e18ce51663d2ec1a10f6 (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
/*
 * Copyright (C) 2012 Intel Corporation
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) version 3.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301  USA
 */

/**
 * The boost::locale based implementation of locale-factory.h.
 */

#include "locale-factory.h"
#include "folks.h"

#include <libebook/libebook.h>

#include <phonenumbers/phonenumberutil.h>
#include <phonenumbers/logger.h>
#include <boost/locale.hpp>
#include <boost/lexical_cast.hpp>

#include <unicode/unistr.h>
#include <unicode/translit.h>
#include <unicode/bytestream.h>
#include <unicode/locid.h>

SE_GLIB_TYPE(EBookQuery, e_book_query)

SE_BEGIN_CXX

typedef boost::shared_ptr<EPhoneNumber> EPhoneNumberCXX;
EPhoneNumberCXX EPhoneNumberCXXNew(EPhoneNumber *number) { return EPhoneNumberCXX(number, e_phone_number_free); }

/**
 * Use higher levels to break ties between strings which are
 * considered equal at the lower levels. For example, "Façade" and
 * "facade" would be compared as equal when using only base
 * characters, but compare differently when also considering a higher
 * level which includes accents.
 *
 * The drawback of higher levels is that they are computationally more
 * expensive (transformation is slower and leads to longer transformed
 * strings, thus a longer string comparisons during compare).
 *
 * The default here pays attention to accents, case, and
 * punctuation. According to
 * http://userguide.icu-project.org/collation/concepts, it is required
 * for Japanese.
 */
static const boost::locale::collator_base::level_type DEFAULT_COLLATION_LEVEL =
    boost::locale::collator_base::quaternary;

class CompareBoost : public IndividualCompare, private boost::noncopyable {
    std::locale m_locale;
    const boost::locale::collator<char> &m_collator;
    std::unique_ptr<icu::Transliterator> m_trans;

public:
    CompareBoost(const std::locale &locale);

    std::string transform(const char *string) const;
    std::string transform(const std::string &string) const;
};

CompareBoost::CompareBoost(const std::locale &locale) :
    m_locale(locale),
    m_collator(std::use_facet< boost::locale::collator<char> >(m_locale))
{
    std::string language = std::use_facet<boost::locale::info>(m_locale).language();
    if (language == "zh") {
        // Hard-code Pinyin sorting for all Chinese countries.
        //
        // There are three different ways of sorting Chinese and Western names:
        // 1. Sort Chinese characters in pinyin order, but separate from Latin
        // 2. Sort them interleaved with Latin, by the first character.
        // 3. Sort them fully interleaved with Latin.
        // Source: Mark Davis, ICU, http://sourceforge.net/mailarchive/forum.php?thread_name=CAJ2xs_GEnN-u3%3D%2B7P5puaF1%2BU__fX-4tuA-kEybThN9xsw577Q%40mail.gmail.com&forum_name=icu-support
        //
        // Either 2 or 3 is what apparently more people expect. Implementing 2 is
        // harder, whereas 3 fits into the "generate keys, compare keys" concept
        // of IndividualCompare, so we kind of arbitrarily implement that.
        SE_LOG_DEBUG(NULL, "enabling Pinyin");

        UErrorCode status = U_ZERO_ERROR;
        icu::Transliterator *trans = icu::Transliterator::createInstance("Han-Latin", UTRANS_FORWARD, status);
        m_trans.reset(trans);
        if (U_FAILURE(status)) {
            SE_LOG_WARNING(NULL, "creating ICU Han-Latin Transliterator for Pinyin failed, error code %s; falling back to normal collation", u_errorName(status));
            m_trans.reset();
        } else if (!trans) {
            SE_LOG_WARNING(NULL, "creating ICU Han-Latin Transliterator for Pinyin failed, no error code; falling back to normal collation");
        }
    }
}

std::string CompareBoost::transform(const char *string) const
{
    if (!string) {
        return "";
    }
    return transform(std::string(string));
}

std::string CompareBoost::transform(const std::string &string) const
{
    // TODO: use e_collator_generate_key

    if (m_trans.get()) {
        // std::string result;
        // m_trans->transliterate(icu::StringPiece(string), icu::StringByteSink<std::string>(&result));
        icu::UnicodeString buffer(string.c_str());
        m_trans->transliterate(buffer);
        std::string result;
        buffer.toUTF8String(result);
        result = m_collator.transform(DEFAULT_COLLATION_LEVEL, result);
        return result;
    } else {
        return m_collator.transform(DEFAULT_COLLATION_LEVEL, string);
    }
}

class CompareFirstLastBoost : public CompareBoost {
public:
    CompareFirstLastBoost(const std::locale &locale) :
        CompareBoost(locale)
    {}

    virtual void createCriteria(FolksIndividual *individual, Criteria_t &criteria) const {
        FolksStructuredName *fn =
            folks_name_details_get_structured_name(FOLKS_NAME_DETAILS(individual));
        if (fn) {
            const char *family = folks_structured_name_get_family_name(fn);
            const char *given = folks_structured_name_get_given_name(fn);
            criteria.push_back(transform(given));
            criteria.push_back(transform(family));
        }
    }
};

class CompareLastFirstBoost : public CompareBoost {
public:
    CompareLastFirstBoost(const std::locale &locale) :
        CompareBoost(locale)
    {}

    virtual void createCriteria(FolksIndividual *individual, Criteria_t &criteria) const {
        FolksStructuredName *fn =
            folks_name_details_get_structured_name(FOLKS_NAME_DETAILS(individual));
        if (fn) {
            const char *family = folks_structured_name_get_family_name(fn);
            const char *given = folks_structured_name_get_given_name(fn);
            criteria.push_back(transform(family));
            criteria.push_back(transform(given));
        }
    }
};

class CompareFullnameBoost : public CompareBoost {
public:
    CompareFullnameBoost(const std::locale &locale) :
        CompareBoost(locale)
    {}

    virtual void createCriteria(FolksIndividual *individual, Criteria_t &criteria) const {
        const char *fullname = folks_name_details_get_full_name(FOLKS_NAME_DETAILS(individual));
        if (fullname) {
            criteria.push_back(transform(fullname));
        } else {
            FolksStructuredName *fn =
                folks_name_details_get_structured_name(FOLKS_NAME_DETAILS(individual));
            if (fn) {
                const char *given = folks_structured_name_get_given_name(fn);
                const char *middle = folks_structured_name_get_additional_names(fn);
                const char *family = folks_structured_name_get_family_name(fn);
                const char *suffix = folks_structured_name_get_suffixes(fn);
                std::string buffer;
                buffer.reserve(256);
#define APPEND(_str) \
                if (_str && *_str) { \
                    if (!buffer.empty()) { \
                        buffer += _str; \
                    } \
                }
                APPEND(given);
                APPEND(middle);
                APPEND(family);
                APPEND(suffix);
#undef APPEND
                criteria.push_back(transform(buffer));
            }
        }
    }
};

/**
 * Implements 'any-contains' and acts as utility base class
 * for the other text comparison operators.
 */
class AnyContainsBoost : public IndividualFilter
{
public:
    enum Mode {
        EXACT = 0,
        CASE_INSENSITIVE = 1<<0,
        ACCENT_INSENSITIVE = 1<<1,
        TRANSLITERATE = 1<<2,
        ALL =
        CASE_INSENSITIVE|
        ACCENT_INSENSITIVE|
        TRANSLITERATE|
        0
    };

    AnyContainsBoost(const std::locale &locale,
                     const std::string &searchValue,
                     int mode) :
        m_locale(locale),
        // For performance reasons we use ICU directly and thus need
        // an ICU::Locale.
        //         m_ICULocale(std::use_facet<boost::locale::info>(m_locale).language().c_str(),
        //            std::use_facet<boost::locale::info>(m_locale).country().c_str(),
        //            std::use_facet<boost::locale::info>(m_locale).variant().c_str()),
        // m_collator(std::use_facet<boost::locale::collator>(locale)),
        m_searchValue(searchValue),
        m_mode(mode)
    {
        if (mode & TRANSLITERATE) {
            UErrorCode status = U_ZERO_ERROR;
            m_transliterator.reset(Transliterator::createInstance ("Any-Latin", UTRANS_FORWARD, status));
            if (!m_transliterator ||
                U_FAILURE(status)) {
                SE_LOG_WARNING(NULL, "creating ICU Any-Latin Transliterator failed, error code %s; falling back to not transliterating", u_errorName(status));
                m_transliterator.reset();
                mode ^= TRANSLITERATE;
                m_mode = mode;
            }
        }

        switch (mode) {
        case EXACT:
            break;
        default:
            m_searchValueTransformed = transform(m_searchValue);
            break;
        }
        m_searchValueTel = normalizePhoneText(m_searchValue.c_str());
    }

    /**
     * Turn filter arguments into bit field.
     */
    static int getFilterMode(const std::vector<LocaleFactory::Filter_t> &terms,
                             size_t start);

    /** simplify according to mode */
    std::string transform(const char *in) const;
    std::string transform(const std::string &in) const { return transform(in.c_str()); }

    /**
     * The search text is not necessarily a full phone number,
     * therefore we cannot parse it with libphonenumber. Instead
     * do a sub-string search after telephone specific normalization,
     * to let the search ignore irrelevant formatting aspects:
     *
     * - Map ASCII characters to the corresponding digit.
     * - Reduce to just the digits before comparison (no spaces, no
     *   punctuation).
     *
     * Example: +1-800-FOOBAR -> 1800366227
     */
    static std::string normalizePhoneText(const char *tel)
    {
        static const i18n::phonenumbers::PhoneNumberUtil &util(*i18n::phonenumbers::PhoneNumberUtil::GetInstance());
        std::string res;
        char c;
        bool haveAlpha = false;
        while ((c = *tel) != '\0') {
            if (isdigit(c)) {
                res += c;
            } else if (isalpha(c)) {
                haveAlpha = true;
                res += c;
            }
            ++tel;
        }
        // Only scan through the string again if we really have to.
        if (haveAlpha) {
            util.ConvertAlphaCharactersInNumber(&res);
        }

        return res;
    }

    bool containsSearchText(const char *text) const
    {
        if (!text) {
            return false;
        }
        switch (m_mode) {
        case EXACT:
            return boost::contains(text, m_searchValue);
            break;
        default: {
            std::string transformed = transform(text);
            return boost::contains(transformed, m_searchValueTransformed);
            break;
        }
        }
        // not reached
        return false;
    }

    bool containsSearchTel(const char *text) const
    {
        std::string tel = normalizePhoneText(text);
        return boost::contains(tel, m_searchValueTel);
    }

    bool isSearchText(const char *text) const
    {
        if (!text) {
            return false;
        }
        switch (m_mode) {
        case EXACT:
            return boost::equals(text, m_searchValue);
            break;
        default: {
            std::string transformed = transform(text);
            return boost::equals(transformed, m_searchValueTransformed);
            break;
        }
        }
        // not reached
        return false;
    }

    bool isSearchTel(const char *text) const
    {
        std::string tel = normalizePhoneText(text);
        return boost::equals(tel, m_searchValueTel);
    }

    bool beginsWithSearchText(const char *text) const
    {
        if (!text) {
            return false;
        }
        switch (m_mode) {
        case EXACT:
            return boost::starts_with(text, m_searchValue);
            break;
        default:  {
            std::string transformed = transform(text);
            return boost::starts_with(transformed, m_searchValueTransformed);
            break;
        }
        }
        // not reached
        return false;
    }

    bool beginsWithSearchTel(const char *text) const
    {
        std::string tel = normalizePhoneText(text);
        return boost::starts_with(tel, m_searchValueTel);
    }

    bool endsWithSearchText(const char *text) const
    {
        if (!text) {
            return false;
        }
        switch (m_mode) {
        case EXACT:
            return boost::ends_with(text, m_searchValue);
            break;
        default: {
            std::string transformed = transform(text);
            return boost::ends_with(transformed, m_searchValueTransformed);
            break;
        }
        }
        // not reached
        return false;
    }

    bool endsWithSearchTel(const char *text) const
    {
        std::string tel = normalizePhoneText(text);
        return boost::ends_with(tel, m_searchValueTel);
    }

    virtual bool matches(const IndividualData &data) const
    {
        FolksIndividual *individual = data.m_individual.get();
        FolksNameDetails *name = FOLKS_NAME_DETAILS(individual);
        const char *fullname = folks_name_details_get_full_name(name);
        if (containsSearchText(fullname)) {
            return true;
        }
        const char *nickname = folks_name_details_get_nickname(name);
        if (containsSearchText(nickname)) {
            return true;
        }
        FolksStructuredName *fn =
            folks_name_details_get_structured_name(FOLKS_NAME_DETAILS(individual));
        if (fn) {
            const char *given = folks_structured_name_get_given_name(fn);
            if (containsSearchText(given)) {
                return true;
            }
            const char *middle = folks_structured_name_get_additional_names(fn);
            if (containsSearchText(middle)) {
                return true;
            }
            const char *family = folks_structured_name_get_family_name(fn);
            if (containsSearchText(family)) {
                return true;
            }
        }
        FolksEmailDetails *emailDetails = FOLKS_EMAIL_DETAILS(individual);
        GeeSet *emails = folks_email_details_get_email_addresses(emailDetails);
        BOOST_FOREACH (FolksAbstractFieldDetails *email, GeeCollCXX<FolksAbstractFieldDetails *>(emails, ADD_REF)) {
            const gchar *value =
                reinterpret_cast<const gchar *>(folks_abstract_field_details_get_value(email));
            if (containsSearchText(value)) {
                return true;
            }
        }
        FolksPhoneDetails *phoneDetails = FOLKS_PHONE_DETAILS(individual);
        GeeSet *phones = folks_phone_details_get_phone_numbers(phoneDetails);
        BOOST_FOREACH (FolksAbstractFieldDetails *phone, GeeCollCXX<FolksAbstractFieldDetails *>(phones, ADD_REF)) {
            const gchar *value =
                reinterpret_cast<const gchar *>(folks_abstract_field_details_get_value(phone));
            if (containsSearchTel(value)) {
                return true;
            }
        }
        return false;
    }

private:
    std::locale m_locale;
    // icu::Locale m_ICULocale;
    boost::shared_ptr<icu::Transliterator> m_transliterator;
    std::string m_searchValue;
    std::string m_searchValueTransformed;
    std::string m_searchValueTel;
    int m_mode;
    // const bool (*m_contains)(const std::string &, const std::string &, const std::locale &);
};

std::string AnyContainsBoost::transform(const char *in) const
{
    icu::UnicodeString unicode = icu::UnicodeString::fromUTF8(in);
    if (m_mode & TRANSLITERATE) {
        m_transliterator->transliterate(unicode);
    }
    if (m_mode & CASE_INSENSITIVE) {
        unicode.foldCase();
    }
    std::string utf8;
    unicode.toUTF8String(utf8);
    if (m_mode & ACCENT_INSENSITIVE) {
        // Haven't found an easy way to do this with ICU.
        // Use e_util_utf8_remove_accents(), which also ensures
        // consistency with EDS.
        PlainGStr res = e_util_utf8_remove_accents(utf8.c_str());
        return std::string(res);
    } else {
        return utf8;
    }
}

int AnyContainsBoost::getFilterMode(const std::vector<LocaleFactory::Filter_t> &terms,
                                    size_t start)
{
    int mode = ALL;
    for (size_t i = start; i < terms.size(); i++) {
        const std::string &flag = LocaleFactory::getFilterString(terms[i], "any-contains flag");
        if (flag == "case-sensitive") {
            mode &= ~CASE_INSENSITIVE;
        } else if (flag == "case-insensitive") {
            mode |= CASE_INSENSITIVE;
        } else if (flag == "accent-sensitive") {
            mode &= ~ACCENT_INSENSITIVE;
        } else if (flag == "accent-insensitive") {
            mode |= ACCENT_INSENSITIVE;
        } else if (flag == "no-transliteration") {
            mode &= ~TRANSLITERATE;
        } else if (flag == "transliteration") {
            mode |= TRANSLITERATE;
        } else {
            SE_THROW("unsupported filter flag: " + flag);
        }
    }
    return mode;
}

class FilterFullName : public AnyContainsBoost
{
    bool (AnyContainsBoost::*m_operation)(const char *text) const;

public:
    FilterFullName(const std::locale &locale,
                   const std::string &searchValue,
                   int mode,
                   bool (AnyContainsBoost::*operation)(const char *text) const) :
        AnyContainsBoost(locale, searchValue, mode),
        m_operation(operation)
    {
    }

    virtual bool matches(const IndividualData &data) const
    {
        FolksIndividual *individual = data.m_individual.get();
        FolksNameDetails *name = FOLKS_NAME_DETAILS(individual);
        const char *fullname = folks_name_details_get_full_name(name);
        return (this->*m_operation)(fullname);
    }
};

class FilterNickname : public AnyContainsBoost
{
    bool (AnyContainsBoost::*m_operation)(const char *text) const;

public:
    FilterNickname(const std::locale &locale,
                   const std::string &searchValue,
                   int mode,
                   bool (AnyContainsBoost::*operation)(const char *text) const) :
        AnyContainsBoost(locale, searchValue, mode),
        m_operation(operation)
    {
    }

    virtual bool matches(const IndividualData &data) const
    {
        FolksIndividual *individual = data.m_individual.get();
        FolksNameDetails *name = FOLKS_NAME_DETAILS(individual);
        const char *fullname = folks_name_details_get_nickname(name);
        return (this->*m_operation)(fullname);
    }
};

class FilterFamilyName : public AnyContainsBoost
{
    bool (AnyContainsBoost::*m_operation)(const char *text) const;

public:
    FilterFamilyName(const std::locale &locale,
                     const std::string &searchValue,
                     int mode,
                     bool (AnyContainsBoost::*operation)(const char *text) const) :
        AnyContainsBoost(locale, searchValue, mode),
        m_operation(operation)
    {
    }

    virtual bool matches(const IndividualData &data) const
    {
        FolksIndividual *individual = data.m_individual.get();
        FolksStructuredName *fn =
            folks_name_details_get_structured_name(FOLKS_NAME_DETAILS(individual));
        if (fn) {
            const char *name = folks_structured_name_get_family_name(fn);
            return (this->*m_operation)(name);
        } else {
            return false;
        }
    }
};

class FilterGivenName : public AnyContainsBoost
{
    bool (AnyContainsBoost::*m_operation)(const char *text) const;

public:
    FilterGivenName(const std::locale &locale,
                    const std::string &searchValue,
                    int mode,
                    bool (AnyContainsBoost::*operation)(const char *text) const) :
        AnyContainsBoost(locale, searchValue, mode),
        m_operation(operation)
    {
    }

    virtual bool matches(const IndividualData &data) const
    {
        FolksIndividual *individual = data.m_individual.get();
        FolksStructuredName *fn =
            folks_name_details_get_structured_name(FOLKS_NAME_DETAILS(individual));
        if (fn) {
            const char *name = folks_structured_name_get_given_name(fn);
            return (this->*m_operation)(name);
        } else {
            return false;
        }
    }
};

class FilterAdditionalName : public AnyContainsBoost
{
    bool (AnyContainsBoost::*m_operation)(const char *text) const;

public:
    FilterAdditionalName(const std::locale &locale,
                         const std::string &searchValue,
                         int mode,
                         bool (AnyContainsBoost::*operation)(const char *text) const) :
        AnyContainsBoost(locale, searchValue, mode),
        m_operation(operation)
    {
    }

    virtual bool matches(const IndividualData &data) const
    {
        FolksIndividual *individual = data.m_individual.get();
        FolksStructuredName *fn =
            folks_name_details_get_structured_name(FOLKS_NAME_DETAILS(individual));
        if (fn) {
            const char *name = folks_structured_name_get_additional_names(fn);
            return (this->*m_operation)(name);
        } else {
            return false;
        }
    }
};

class FilterEmails : public AnyContainsBoost
{
    bool (AnyContainsBoost::*m_operation)(const char *text) const;

public:
    FilterEmails(const std::locale &locale,
                 const std::string &searchValue,
                 int mode,
                 bool (AnyContainsBoost::*operation)(const char *text) const) :
        AnyContainsBoost(locale, searchValue, mode),
        m_operation(operation)
    {
    }

    virtual bool matches(const IndividualData &data) const
    {
        FolksIndividual *individual = data.m_individual.get();
        FolksEmailDetails *emailDetails = FOLKS_EMAIL_DETAILS(individual);
        GeeSet *emails = folks_email_details_get_email_addresses(emailDetails);
        BOOST_FOREACH (FolksAbstractFieldDetails *email, GeeCollCXX<FolksAbstractFieldDetails *>(emails, ADD_REF)) {
            const gchar *value =
                reinterpret_cast<const gchar *>(folks_abstract_field_details_get_value(email));
            if ((this->*m_operation)(value)) {
                return true;
            }
        }
        return false;
    }
};

class FilterTel : public AnyContainsBoost
{
    bool (AnyContainsBoost::*m_operation)(const char *text) const;

public:
    FilterTel(const std::locale &locale,
              const std::string &searchValue,
              bool (AnyContainsBoost::*operation)(const char *text) const) :
        AnyContainsBoost(locale, searchValue, 0 /* doesn't matter */),
        m_operation(operation)
    {
    }

    virtual bool matches(const IndividualData &data) const
    {
        FolksIndividual *individual = data.m_individual.get();
        FolksPhoneDetails *phoneDetails = FOLKS_PHONE_DETAILS(individual);
        GeeSet *phones = folks_phone_details_get_phone_numbers(phoneDetails);
        BOOST_FOREACH (FolksAbstractFieldDetails *phone, GeeCollCXX<FolksAbstractFieldDetails *>(phones, ADD_REF)) {
            const gchar *value =
                reinterpret_cast<const gchar *>(folks_abstract_field_details_get_value(phone));
            if ((this->*m_operation)(value)) {
                return true;
            }
        }
        return false;
    }
};

class FilterAddr : public AnyContainsBoost
{
protected:
    bool (AnyContainsBoost::*m_operation)(const char *text) const;

public:
    FilterAddr(const std::locale &locale,
               const std::string &searchValue,
               int mode,
               bool (AnyContainsBoost::*operation)(const char *text) const) :
        AnyContainsBoost(locale, searchValue, mode),
        m_operation(operation)
    {
    }

    virtual bool matches(const IndividualData &data) const
    {
        FolksIndividual *individual = data.m_individual.get();
        FolksPostalAddressDetails *addressDetails = FOLKS_POSTAL_ADDRESS_DETAILS(individual);
        GeeSet *addresses = folks_postal_address_details_get_postal_addresses(addressDetails);
        BOOST_FOREACH (FolksPostalAddressFieldDetails *address, GeeCollCXX<FolksPostalAddressFieldDetails *>(addresses, ADD_REF)) {
            const FolksPostalAddress *value =
                reinterpret_cast<const FolksPostalAddress *>(folks_abstract_field_details_get_value(FOLKS_ABSTRACT_FIELD_DETAILS(address)));
            if (matchesAddr(value)) {
                return true;
            }
        }
        return false;
    }

    virtual bool matchesAddr(const FolksPostalAddress *addr) const = 0;
};

class FilterAddrPOBox : public FilterAddr
{
public:
    FilterAddrPOBox(const std::locale &locale,
                    const std::string &searchValue,
                    int mode,
                    bool (AnyContainsBoost::*operation)(const char *text) const) :
        FilterAddr(locale, searchValue, mode, operation)
    {
    }

    virtual bool matchesAddr(const FolksPostalAddress *addr) const
    {
        const char *attr = folks_postal_address_get_po_box(const_cast<FolksPostalAddress *>(addr));
        return (this->*m_operation)(attr);
    }
};

class FilterAddrExtension : public FilterAddr
{
public:
    FilterAddrExtension(const std::locale &locale,
                        const std::string &searchValue,
                        int mode,
                        bool (AnyContainsBoost::*operation)(const char *text) const) :
        FilterAddr(locale, searchValue, mode, operation)
    {
    }

    virtual bool matchesAddr(const FolksPostalAddress *addr) const
    {
        const char *attr = folks_postal_address_get_extension(const_cast<FolksPostalAddress *>(addr));
        return (this->*m_operation)(attr);
    }
};

class FilterAddrStreet : public FilterAddr
{
public:
    FilterAddrStreet(const std::locale &locale,
                     const std::string &searchValue,
                     int mode,
                     bool (AnyContainsBoost::*operation)(const char *text) const) :
        FilterAddr(locale, searchValue, mode, operation)
    {
    }

    virtual bool matchesAddr(const FolksPostalAddress *addr) const
    {
        const char *attr = folks_postal_address_get_street(const_cast<FolksPostalAddress *>(addr));
        return (this->*m_operation)(attr);
    }
};

class FilterAddrLocality : public FilterAddr
{
public:
    FilterAddrLocality(const std::locale &locale,
                       const std::string &searchValue,
                       int mode,
                       bool (AnyContainsBoost::*operation)(const char *text) const) :
        FilterAddr(locale, searchValue, mode, operation)
    {
    }

    virtual bool matchesAddr(const FolksPostalAddress *addr) const
    {
        const char *attr = folks_postal_address_get_locality(const_cast<FolksPostalAddress *>(addr));
        return (this->*m_operation)(attr);
    }
};

class FilterAddrRegion : public FilterAddr
{
public:
    FilterAddrRegion(const std::locale &locale,
                     const std::string &searchValue,
                     int mode,
                     bool (AnyContainsBoost::*operation)(const char *text) const) :
        FilterAddr(locale, searchValue, mode, operation)
    {
    }

    virtual bool matchesAddr(const FolksPostalAddress *addr) const
    {
        const char *attr = folks_postal_address_get_region(const_cast<FolksPostalAddress *>(addr));
        return (this->*m_operation)(attr);
    }
};

class FilterAddrPostalCode : public FilterAddr
{
public:
    FilterAddrPostalCode(const std::locale &locale,
                         const std::string &searchValue,
                         int mode,
                         bool (AnyContainsBoost::*operation)(const char *text) const) :
        FilterAddr(locale, searchValue, mode, operation)
    {
    }

    virtual bool matchesAddr(const FolksPostalAddress *addr) const
    {
        const char *attr = folks_postal_address_get_postal_code(const_cast<FolksPostalAddress *>(addr));
        return (this->*m_operation)(attr);
    }
};

class FilterAddrCountry : public FilterAddr
{
public:
    FilterAddrCountry(const std::locale &locale,
                      const std::string &searchValue,
                      int mode,
                      bool (AnyContainsBoost::*operation)(const char *text) const) :
        FilterAddr(locale, searchValue, mode, operation)
    {
    }

    virtual bool matchesAddr(const FolksPostalAddress *addr) const
    {
        const char *attr = folks_postal_address_get_country(const_cast<FolksPostalAddress *>(addr));
        return (this->*m_operation)(attr);
    }
};


SimpleE164 String2E164(const char *tel, const char *country)
{
    SimpleE164 e164;
    GErrorCXX gerror;
    EPhoneNumberCXX number(EPhoneNumberCXXNew(e_phone_number_from_string(tel, country, gerror)));
    if (!number) {
        gerror.throwError(SE_HERE, "parsing number");
    }
    EPhoneNumberCountrySource source;
    e164.m_countryCode = e_phone_number_get_country_code(number.get(), &source);
    if (source == E_PHONE_NUMBER_COUNTRY_FROM_DEFAULT) {
        e164.m_countryCode = 0;
    }
    PlainGStr national(e_phone_number_get_national_number(number.get()));
    e164.m_nationalNumber = national.get() ?
        boost::lexical_cast<SimpleE164::NationalNumber_t>(national.get()) :
        0;
    return e164;
}

/**
 * Search value must be a valid caller ID (with or without a country
 * code). The telephone numbers in the contacts may or may not be
 * valid; only valid ones will match. The user is expected to clean up
 * that data to get exact matches for the others.
 *
 * The matching uses the same semantic as EQUALS_NATIONAL_PHONE_NUMBER:
 * - If both numbers have an explicit country code, that code must be
 *   the same for a match.
 * - If one or both numbers have no country code, matching the national
 *   part is enough for a match.
 */
class PhoneStartsWith : public IndividualFilter
{
public:
    PhoneStartsWith(const std::locale &m_locale,
                    const std::string &tel) :
        m_phoneNumberUtil(*i18n::phonenumbers::PhoneNumberUtil::GetInstance()),
        m_simpleEDSSearch(getenv("SYNCEVOLUTION_PIM_EDS_SUBSTRING") || !e_phone_number_is_supported()),
        m_country(std::use_facet<boost::locale::info>(m_locale).country())
    {
        m_number = String2E164(tel.c_str(), m_country.c_str());
    }

    virtual bool matches(const IndividualData &data) const
    {
        BOOST_FOREACH(const SimpleE164 &number, data.m_precomputed.m_phoneNumbers) {
            // National part must always match, country code only if
            // set explicitly in both (NSN_MATCH in libphonenumber,
            // EQUALS_NATIONAL_PHONE_NUMBER in EDS).
            if (number.m_nationalNumber == m_number.m_nationalNumber &&
                (!number.m_countryCode || !m_number.m_countryCode ||
                 number.m_countryCode == m_number.m_countryCode)) {
                return true;
            }
        }
        return false;
    }

    virtual std::string getEBookFilter() const
    {
        std::string tel = m_number.toString();
        size_t len = std::min((size_t)4, tel.size());
        EBookQueryCXX query(m_simpleEDSSearch ?
                            // A suffix match with a limited number of digits is most
                            // likely to find the right contacts.
                            e_book_query_field_test(E_CONTACT_TEL, E_BOOK_QUERY_ENDS_WITH,
                                                    tel.substr(tel.size() - len, len).c_str()) :
                            // We use EQUALS_NATIONAL_PHONE_NUMBER
                            // instead of EQUALS_PHONE_NUMBER here,
                            // because it will also match contacts
                            // were the country code was not set
                            // explicitly. EQUALS_PHONE_NUMBER would
                            // do a stricter comparison and not match
                            // those.
                            //
                            // If the contact has a country code set,
                            // then EQUALS_NATIONAL_PHONE_NUMBER will
                            // check that and not return a false match
                            // if the country code is different.
                            //
                            // We try to pass the E164 string here. If
                            // the search term had no country code,
                            // that's a bit difficult because we can't
                            // just add the default country code.
                            // That would break the
                            // NATIONAL_PHONE_NUMBER semantic because
                            // EDS wouldn't know that the search term
                            // had no country code. We resort to the
                            // format of SimpleE164.toString(), which
                            // is passing the national number
                            // formatted as string.
                            e_book_query_field_test(E_CONTACT_TEL, E_BOOK_QUERY_EQUALS_NATIONAL_PHONE_NUMBER,
                                                    tel.c_str()),
                            TRANSFER_REF);
        PlainGStr filter(e_book_query_to_string(query.get()));
        return filter.get();
    }

private:
    const i18n::phonenumbers::PhoneNumberUtil &m_phoneNumberUtil;
    bool m_simpleEDSSearch;
    std::string m_country;
    SimpleE164 m_number;
};

class PhoneNumberLogger : public i18n::phonenumbers::Logger
{
    const char *getPrefix()
    {
        switch (level()) {
        case i18n::phonenumbers::LOG_FATAL:
            return "phonenumber fatal";
            break;
        case i18n::phonenumbers::LOG_ERROR:
            return "phonenumber error";
            break;
        case i18n::phonenumbers::LOG_WARNING:
            return "phonenumber warning";
            break;
        case i18n::phonenumbers::LOG_INFO:
            return "phonenumber info";
            break;
        case i18n::phonenumbers::LOG_DEBUG:
            return "phonenumber debug";
            break;
        default:
            return "phonenumber ???";
            break;
        }
    }

public:
    virtual void WriteMessage(const std::string &msg)
    {
        SE_LOG(getPrefix(),
               level() == i18n::phonenumbers::LOG_FATAL ? SyncEvo::Logger::ERROR : SyncEvo::Logger::DEBUG,
               "%s", msg.c_str());
    }
};

class LocaleFactoryBoost : public LocaleFactory
{
    const i18n::phonenumbers::PhoneNumberUtil &m_phoneNumberUtil;
    bool m_edsSupportsPhoneNumbers;
    std::locale m_locale;
    std::string m_country;
    std::string m_defaultCountryCode;
    PhoneNumberLogger m_logger;

public:
    LocaleFactoryBoost() :
        m_phoneNumberUtil(*i18n::phonenumbers::PhoneNumberUtil::GetInstance()),
        m_edsSupportsPhoneNumbers(e_phone_number_is_supported() && !getenv("SYNCEVOLUTION_PIM_EDS_NO_E164")),
        m_locale(genLocale()),
        m_country(std::use_facet<boost::locale::info>(m_locale).country()),
        m_defaultCountryCode(StringPrintf("+%d", m_phoneNumberUtil.GetCountryCodeForRegion(m_country)))
    {
        // Redirect output of libphonenumber and make it a bit quieter
        // than it is by default. We map fatal libphonenumber errors
        // to ERROR and everything else to DEBUG.
        //
        // The PhoneNumberUtil instance owns the logger, so we don't
        // need (and must not) free it. libphonenumber < r571 has the
        // same API and thus this code compiles. However, older
        // libphonenumer does not actually free the instance, causing
        // a minor memory leak.
        i18n::phonenumbers::PhoneNumberUtil::GetInstance()->SetLogger(new PhoneNumberLogger);
    }

    static std::locale genLocale()
    {
        // Get current locale from environment. Configure the
        // generated locale so that it supports what we need and
        // nothing more.
        boost::locale::generator gen;
        gen.characters(boost::locale::char_facet);
        gen.categories(boost::locale::collation_facet |
                       boost::locale::convert_facet |
                       boost::locale::information_facet);
        // Hard-code "phonebook" collation for certain languages
        // where we know that it is desirable. We could use it
        // in all cases, except that ICU has a bug where it does not
        // fall back properly to the base collation. See
        // http://sourceforge.net/mailarchive/message.php?msg_id=30802924
        // and http://bugs.icu-project.org/trac/ticket/10149
        std::locale locale = gen("");
        std::string name = std::use_facet<boost::locale::info>(locale).name();
        std::string language = std::use_facet<boost::locale::info>(locale).language();
        std::string country = std::use_facet<boost::locale::info>(locale).country();
        SE_LOG_DEV(NULL, "PIM Manager running with locale %s = language %s in country %s",
                   name.c_str(),
                   language.c_str(),
                   country.c_str());
        if (language == "de" ||
            language == "fi") {
            SE_LOG_DEV(NULL, "enabling phonebook collation for language %s", language.c_str());
            locale = gen(name + "@collation=phonebook");
        }
        return locale;
    }

    virtual boost::shared_ptr<IndividualCompare> createCompare(const std::string &order)
    {
        boost::shared_ptr<IndividualCompare> res;
        if (order == "first/last") {
            res.reset(new CompareFirstLastBoost(m_locale));
        } else if (order == "last/first") {
            res.reset(new CompareLastFirstBoost(m_locale));
        } else if (order == "fullname") {
            res.reset(new CompareFullnameBoost(m_locale));
        } else {
            SE_THROW("boost locale factory: sort order '" + order + "' not supported");
        }
        return res;
    }

    virtual boost::shared_ptr<IndividualFilter> createFilter(const Filter_t &filter, int level)
    {
        boost::shared_ptr<IndividualFilter> res;

        try {
            const std::vector<Filter_t> &terms = getFilterArray(filter, "array of terms");

            // Only handle arrays where the first entry is a string
            // that we recognize. All other cases are handled by the generic
            // LocaleFactory.
            if (!terms.empty() &&
                boost::get<std::string>(&terms[0])) {
                const std::string &operation = getFilterString(terms[0], "operation name");

                // Pick default operation. Will be replaced with
                // telephone-specific operation once we know that the
                // field is 'phones/value'.
                bool (AnyContainsBoost::*func)(const char *text) const;
                if (operation == "contains") {
                    func = &AnyContainsBoost::containsSearchText;
                } else if (operation == "is") {
                    func = &AnyContainsBoost::isSearchText;
                } else if (operation == "begins-with") {
                    func = &AnyContainsBoost::beginsWithSearchText;
                } else if (operation == "ends-with") {
                    func = &AnyContainsBoost::endsWithSearchText;
                } else {
                    func = NULL;
                }
                if (func) {
                    switch (terms.size()) {
                    case 1:
                        SE_THROW("missing field name and search value");
                        break;
                    case 2:
                        SE_THROW("missing search value");
                        break;
                    }
                    const std::string &field = getFilterString(terms[1], "search field");
                    const std::string &value = getFilterString(terms[2], "search string");
                    if (field == "phones/value") {
                        if (terms.size() > 3) {
                            SE_THROW("Additional entries after 'phones/value' field filter not allowed.");
                        }
                        // Use the telephone specific functions.
                        res.reset(new FilterTel(m_locale, value,
                                                func == &AnyContainsBoost::containsSearchText ? &AnyContainsBoost::containsSearchTel :
                                                func == &AnyContainsBoost::isSearchText ? &AnyContainsBoost::isSearchTel :
                                                func == &AnyContainsBoost::beginsWithSearchText ? &AnyContainsBoost::beginsWithSearchTel :
                                                func == &AnyContainsBoost::endsWithSearchText ? &AnyContainsBoost::endsWithSearchTel :
                                                func));
                    } else {
                        int mode = AnyContainsBoost::getFilterMode(terms, 3);
                        if (field == "full-name") {
                            res.reset(new FilterFullName(m_locale, value, mode, func));
                        } else if (field == "nickname") {
                            res.reset(new FilterNickname(m_locale, value, mode, func));
                        } else if (field == "structured-name/family") {
                            res.reset(new FilterFamilyName(m_locale, value, mode, func));
                        } else if (field == "structured-name/given") {
                            res.reset(new FilterGivenName(m_locale, value, mode, func));
                        } else if (field == "structured-name/additional") {
                            res.reset(new FilterAdditionalName(m_locale, value, mode, func));
                        } else if (field == "emails/value") {
                            res.reset(new FilterEmails(m_locale, value, mode, func));
                        } else if (field == "addresses/po-box") {
                            res.reset(new FilterAddrPOBox(m_locale, value, mode, func));
                        } else if (field == "addresses/extension") {
                            res.reset(new FilterAddrExtension(m_locale, value, mode, func));
                        } else if (field == "addresses/street") {
                            res.reset(new FilterAddrStreet(m_locale, value, mode, func));
                        } else if (field == "addresses/locality") {
                            res.reset(new FilterAddrLocality(m_locale, value, mode, func));
                        } else if (field == "addresses/region") {
                            res.reset(new FilterAddrRegion(m_locale, value, mode, func));
                        } else if (field == "addresses/postal-code") {
                            res.reset(new FilterAddrPostalCode(m_locale, value, mode, func));
                        } else if (field == "addresses/country") {
                            res.reset(new FilterAddrCountry(m_locale, value, mode, func));
                        } else {
                            SE_THROW("Unknown field name: " + field);
                        }
                    }
                } else if (operation == "any-contains") {
                    if (terms.size() < 2) {
                        SE_THROW("missing search value");
                    }
                    const std::string &value = getFilterString(terms[1], "search string");
                    int mode = AnyContainsBoost::getFilterMode(terms, 2);
                    res.reset(new AnyContainsBoost(m_locale, value, mode));
                } else if (operation == "phone") {
                    if (terms.size() != 2) {
                        SE_THROW("'phone' filter needs exactly one parameter.");
                    }
                    const std::string &value = getFilterString(terms[1], "search string");
                    res.reset(new PhoneStartsWith(m_locale, value));
                }
            }
        } catch (const Exception &ex) {
            handleFilterException(filter, level, &ex.m_file, ex.m_line);
        } catch (...) {
            handleFilterException(filter, level, NULL, 0);
        }

        // Let base class handle it if we didn't recognize the operation.
        return res ? res : LocaleFactory::createFilter(filter, level);
    }

    virtual bool precompute(FolksIndividual *individual, Precomputed &precomputed) const
    {
        LocaleFactory::Precomputed old;
        std::swap(old, precomputed);

        FolksPhoneDetails *phoneDetails = FOLKS_PHONE_DETAILS(individual);
        GeeSet *phones = folks_phone_details_get_phone_numbers(phoneDetails);
        precomputed.m_phoneNumbers.reserve(gee_collection_get_size(GEE_COLLECTION(phones)));
        BOOST_FOREACH (FolksAbstractFieldDetails *phone, GeeCollCXX<FolksAbstractFieldDetails *>(phones, ADD_REF)) {
            const gchar *value =
                reinterpret_cast<const gchar *>(folks_abstract_field_details_get_value(phone));
            if (value) {
                if (m_edsSupportsPhoneNumbers) {
                    // Check X-EVOLUTION-E164 (made lowercase by folks!).
                    //
                    // It has the format <local number>,<country code>,
                    // where <country code> happens to be in quotation marks.
                    // This ends up being split into individual values which
                    // are returned in random order by folks (a bug?!).
                    //
                    // Example: TEL;X-EVOLUTION-E164=891234,"+49":+49-89-1234
                    // => value '+49-89-1234', params [ '+49', '891234' ].
                    //
                    // We restore the right order by sorting, which puts the
                    // country code first, and then joining.
                    GeeCollectionCXX coll(folks_abstract_field_details_get_parameter_values(phone, "x-evolution-e164"), TRANSFER_REF);
                    if (coll) {
                        std::vector<std::string> components;
                        components.reserve(2);
                        BOOST_FOREACH (const gchar *component, GeeStringCollection(coll)) {
                            // Empty component represents an unset
                            // country code. Note that it is not
                            // certain whether we get to see the empty
                            // component. At the moment (EDS 3.7,
                            // folks 0.9.1), someone swallows it.
                            components.push_back(component);
                        }
                        if (!components.empty()) {
                            // Only one component? We must still miss the country code.
                            if (components.size() == 1) {
                                components.push_back("");
                            }
                            std::sort(components.begin(), components.end());
                            try {
                                SimpleE164 number;
                                number.m_countryCode = components[0].empty() ?
                                    0 :
                                    boost::lexical_cast<SimpleE164::CountryCode_t>(components[0]);
                                number.m_nationalNumber = components[1].empty() ?
                                    0 :
                                    boost::lexical_cast<SimpleE164::NationalNumber_t>(components[1]);
                                precomputed.m_phoneNumbers.push_back(number);
                            } catch (const boost::bad_lexical_cast &ex) {
                                SE_LOG_WARNING(NULL, "ignoring malformed X-EVOLUTION-E164 (sorted): %s",
                                               boost::join(components, ", ").c_str());
                            }
                        }
                    }
                    // Either EDS had a normalized value or there is none because
                    // the value is not a phone number. No need to try parsing again.
                    continue;
                }

                try {
                    // This fallback for missing X-EVOLUTION-E164 in EDS still relies
                    // on libphonenumber support in libebook, so it does not really help
                    // if EDS was compiled without libphonenumber. It is primarily useful
                    // for testing (see TestContacts.testLocaledPhone).
                    SimpleE164 e164 = String2E164(value, m_country.c_str());
                    if (e164.m_countryCode || e164.m_nationalNumber) {
                        precomputed.m_phoneNumbers.push_back(e164);
                    }
                } catch (const Exception &ex) {
                    // Silently ignore parse errors.
                    SE_LOG_DEBUG(NULL, "ignoring unparsable TEL '%s': %s", value, ex.what());
                }
            }
        }

        // Now check if any phone number changed.
        return old != precomputed;
    }
};

boost::shared_ptr<LocaleFactory> LocaleFactory::createFactory()
{
    return boost::shared_ptr<LocaleFactory>(new LocaleFactoryBoost());
}

SE_END_CXX