summaryrefslogtreecommitdiff
path: root/addressbook/libedata-book/e-book-backend-sexp.c
blob: c1dfb0fdcafab5a43186cc93483a81633886495c (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
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
/*
 * Copyright (C) 1999-2008 Novell, Inc. (www.novell.com)
 * Copyright (C) 2012 Intel Corporation
 *
 * Authors:
 *   Chris Lahey <clahey@ximian.com>
 *   Tristan Van Berkom <tristanvb@openismus.com>
 *
 * 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.
 *
 * 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 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, see <http://www.gnu.org/licenses/>.
 */

/**
 * SECTION: e-book-backend-sexp
 * @include: libedata-book/libedata-book.h
 * @short_description: A utility for comparing #EContacts or vcards with search expressions.
 *
 * This API is an all purpose utility for comparing #EContacts with search expressions generated by #EBookQuery.
 */
#include "e-book-backend-sexp.h"

#include <glib/gi18n.h>
#include <locale.h>
#include <string.h>

#define E_BOOK_BACKEND_SEXP_GET_PRIVATE(obj) \
	(G_TYPE_INSTANCE_GET_PRIVATE \
	((obj), E_TYPE_BOOK_BACKEND_SEXP, EBookBackendSExpPrivate))

G_DEFINE_TYPE (EBookBackendSExp, e_book_backend_sexp, G_TYPE_OBJECT)

typedef struct _SearchContext SearchContext;
typedef gboolean (*CompareFunc) (const gchar *, const gchar *, const gchar *);

struct _EBookBackendSExpPrivate {
	ESExp *search_sexp;
	gchar *text;
	SearchContext *search_context;
};

struct _SearchContext {
	EContact *contact;
};

static gboolean
compare_im (EContact *contact,
            const gchar *str,
            const gchar *region,
            CompareFunc compare,
            EContactField im_field)
{
	GList    *aims, *l;
	gboolean  found_it = FALSE;

	aims = e_contact_get (contact, im_field);

	for (l = aims; l != NULL; l = l->next) {
		gchar *im = (gchar *) l->data;

		if (im && compare (im, str, region)) {
			found_it = TRUE;
			break;
		}
	}

	e_contact_attr_list_free (aims);

	return found_it;
}

static gboolean
compare_im_aim (EContact *contact,
                const gchar *str,
                const gchar *region,
                CompareFunc compare)
{
	return compare_im (contact, str, region, compare, E_CONTACT_IM_AIM);
}

static gboolean
compare_im_msn (EContact *contact,
                const gchar *str,
                const gchar *region,
                CompareFunc compare)
{
	return compare_im (contact, str, region, compare, E_CONTACT_IM_MSN);
}

static gboolean
compare_im_skype (EContact *contact,
                  const gchar *str,
                  const gchar *region,
                  CompareFunc compare)
{
	return compare_im (contact, str, region, compare, E_CONTACT_IM_SKYPE);
}

static gboolean
compare_im_google_talk (EContact *contact,
                        const gchar *str,
                        const gchar *region,
                        CompareFunc compare)
{
	return compare_im (contact, str, region, compare, E_CONTACT_IM_GOOGLE_TALK);
}

static gboolean
compare_im_icq (EContact *contact,
                const gchar *str,
                const gchar *region,
                CompareFunc compare)
{
	return compare_im (contact, str, region, compare, E_CONTACT_IM_ICQ);
}

static gboolean
compare_im_yahoo (EContact *contact,
                  const gchar *str,
                  const gchar *region,
                  CompareFunc compare)
{
	return compare_im (contact, str, region, compare, E_CONTACT_IM_YAHOO);
}

static gboolean
compare_im_gadugadu (EContact *contact,
                     const gchar *str,
                     const gchar *region,
                     CompareFunc compare)
{
	return compare_im (contact, str, region, compare, E_CONTACT_IM_GADUGADU);
}

static gboolean
compare_im_jabber (EContact *contact,
                   const gchar *str,
                   const gchar *region,
                   CompareFunc compare)
{
	return compare_im (contact, str, region, compare, E_CONTACT_IM_JABBER);
}

static gboolean
compare_im_groupwise (EContact *contact,
                      const gchar *str,
                      const gchar *region,
                      CompareFunc compare)
{
	return compare_im (contact, str, region, compare, E_CONTACT_IM_GROUPWISE);
}

static gboolean
compare_email (EContact *contact,
               const gchar *str,
               const gchar *region,
               CompareFunc compare)
{
	gboolean rv = FALSE;
	GList *list, *l;

	list = e_contact_get (contact, E_CONTACT_EMAIL);

	for (l = list; l; l = l->next) {
		const gchar *email = l->data;

		rv = email && compare (email, str, region);

		if (rv)
			break;
	}

	e_contact_attr_list_free (list);

	return rv;
}

static gboolean
compare_phone (EContact *contact,
               const gchar *str,
               const gchar *region,
               CompareFunc compare)
{
	GList *list, *l;
	gboolean rv = FALSE;

	list = e_contact_get (contact, E_CONTACT_TEL);

	for (l = list; l; l = l->next) {
		const gchar *phone = l->data;

		rv = phone && compare (phone, str, region);

		if (rv)
			break;
	}

	e_contact_attr_list_free (list);

	return rv;
}

static gboolean
compare_name (EContact *contact,
              const gchar *str,
              const gchar *region,
              CompareFunc compare)
{
	const gchar *name;

	name = e_contact_get_const (contact, E_CONTACT_FULL_NAME);
	if (name && compare (name, str, region))
		return TRUE;

	name = e_contact_get_const (contact, E_CONTACT_FAMILY_NAME);
	if (name && compare (name, str, region))
		return TRUE;

	name = e_contact_get_const (contact, E_CONTACT_GIVEN_NAME);
	if (name && compare (name, str, region))
		return TRUE;

	name = e_contact_get_const (contact, E_CONTACT_NICKNAME);
	if (name && compare (name, str, region))
		return TRUE;

	return FALSE;
}

static gboolean
compare_photo_uri (EContact *contact,
                   const gchar *str,
                   const gchar *region,
                   CompareFunc compare)
{
	EContactPhoto *photo;
	gboolean ret_val = FALSE;

	photo = e_contact_get (contact, E_CONTACT_PHOTO);

	if (photo) {
		/* Compare the photo uri with the string */
		if ((photo->type == E_CONTACT_PHOTO_TYPE_URI)
		     && compare (photo->data.uri, str, region)) {
			ret_val = TRUE;
		}
		e_contact_photo_free (photo);
	}
	return ret_val;
}

static gboolean
compare_address (EContact *contact,
                 const gchar *str,
                 const gchar *region,
                 CompareFunc compare)
{

	gint i;
	gboolean rv = FALSE;

	for (i = E_CONTACT_FIRST_ADDRESS_ID; i <= E_CONTACT_LAST_ADDRESS_ID; i++) {
		EContactAddress *address = e_contact_get (contact, i);
		if (address) {
			rv = (address->po && compare (address->po, str, region)) ||
				(address->street && compare (address->street, str, region)) ||
				(address->ext && compare (address->ext, str, region)) ||
				(address->locality && compare (address->locality, str, region)) ||
				(address->region && compare (address->region, str, region)) ||
				(address->code && compare (address->code, str, region)) ||
				(address->country && compare (address->country, str, region));

			e_contact_address_free (address);

			if (rv)
				break;
		}
	}

	return rv;

}

static gboolean
compare_category (EContact *contact,
                  const gchar *str,
                  const gchar *region,
                  CompareFunc compare)
{
	GList *categories;
	GList *iterator;
	gboolean ret_val = FALSE;

	categories = e_contact_get (contact, E_CONTACT_CATEGORY_LIST);

	for (iterator = categories; iterator; iterator = iterator->next) {
		const gchar *category = iterator->data;

		if (compare (category, str, region)) {
			ret_val = TRUE;
			break;
		}
	}

	g_list_foreach (categories, (GFunc) g_free, NULL);
	g_list_free (categories);

	return ret_val;
}

static gboolean
compare_date (EContactDate *date,
              const gchar *str,
              const gchar *region,
              CompareFunc compare)
{
	gchar *date_str = e_contact_date_to_string (date);
	gboolean ret_val = FALSE;

	if (date_str) {
		if (compare (date_str, str, region)) {
			ret_val = TRUE;
		}
		g_free (date_str);
	}
	return ret_val;
}

enum prop_type {
	PROP_TYPE_NORMAL,
	PROP_TYPE_LIST,
	PROP_TYPE_DATE
};

static struct prop_info {
	EContactField field_id;
	const gchar *query_prop;
	enum prop_type prop_type;
	gboolean (*list_compare) (EContact *contact,
				  const gchar *str,
				  const gchar *region,
				  CompareFunc compare);

} prop_info_table[] = {
#define NORMAL_PROP(f,q) {f, q, PROP_TYPE_NORMAL, NULL}
#define LIST_PROP(q,c) {0, q, PROP_TYPE_LIST, c}
#define DATE_PROP(f,q) {f, q, PROP_TYPE_DATE, NULL}

	/* query prop,   type,              list compare function */
	NORMAL_PROP ( E_CONTACT_FILE_AS, "file_as" ),
	NORMAL_PROP ( E_CONTACT_UID, "id" ),
	LIST_PROP ( "full_name", compare_name), /* not really a list, but we need to compare both full and surname */
	LIST_PROP ( "photo", compare_photo_uri ), /* not really a list, but we need to compare the uri in the struct */
	DATE_PROP ( E_CONTACT_BIRTH_DATE, "birth_date" ),
	DATE_PROP ( E_CONTACT_ANNIVERSARY, "anniversary" ),
	NORMAL_PROP ( E_CONTACT_GIVEN_NAME, "given_name"),
	NORMAL_PROP ( E_CONTACT_FAMILY_NAME, "family_name"),
	NORMAL_PROP ( E_CONTACT_HOMEPAGE_URL, "url"),
	NORMAL_PROP ( E_CONTACT_BLOG_URL, "blog_url"),
	NORMAL_PROP ( E_CONTACT_CALENDAR_URI, "calurl"),
	NORMAL_PROP ( E_CONTACT_FREEBUSY_URL, "fburl"),
	NORMAL_PROP ( E_CONTACT_ICS_CALENDAR, "icscalendar"),
	NORMAL_PROP ( E_CONTACT_VIDEO_URL, "video_url"),

	NORMAL_PROP ( E_CONTACT_MAILER, "mailer"),
	NORMAL_PROP ( E_CONTACT_ORG, "org"),
	NORMAL_PROP ( E_CONTACT_ORG_UNIT, "org_unit"),
	NORMAL_PROP ( E_CONTACT_OFFICE, "office"),
	NORMAL_PROP ( E_CONTACT_TITLE, "title"),
	NORMAL_PROP ( E_CONTACT_ROLE, "role"),
	NORMAL_PROP ( E_CONTACT_MANAGER, "manager"),
	NORMAL_PROP ( E_CONTACT_ASSISTANT, "assistant"),
	NORMAL_PROP ( E_CONTACT_NICKNAME, "nickname"),
	NORMAL_PROP ( E_CONTACT_SPOUSE, "spouse" ),
	NORMAL_PROP ( E_CONTACT_NOTE, "note"),
	LIST_PROP ( "im_aim",    compare_im_aim ),
	LIST_PROP ( "im_msn",    compare_im_msn ),
	LIST_PROP ( "im_skype",    compare_im_skype ),
	LIST_PROP ( "im_google_talk",    compare_im_google_talk ),
	LIST_PROP ( "im_icq",    compare_im_icq ),
	LIST_PROP ( "im_jabber", compare_im_jabber ),
	LIST_PROP ( "im_yahoo",  compare_im_yahoo ),
	LIST_PROP ( "im_gadugadu",  compare_im_gadugadu ),
	LIST_PROP ( "im_groupwise", compare_im_groupwise ),
	LIST_PROP ( "email",     compare_email ),
	LIST_PROP ( "phone",     compare_phone ),
	LIST_PROP ( "address",   compare_address ),
	LIST_PROP ( "category_list",  compare_category ),
};

static ESExpResult *
entry_compare (SearchContext *ctx,
               struct _ESExp *f,
               gint argc,
               struct _ESExpResult **argv,
               CompareFunc compare)
{
	ESExpResult *r;
	gint truth = FALSE;

	if ((argc == 2
		&& argv[0]->type == ESEXP_RES_STRING
		&& argv[1]->type == ESEXP_RES_STRING) ||
	    (argc == 3
		&& argv[0]->type == ESEXP_RES_STRING
		&& argv[1]->type == ESEXP_RES_STRING
		&& argv[2]->type == ESEXP_RES_STRING)) {
		gchar *propname;
		struct prop_info *info = NULL;
		const gchar *region = NULL;
		gint i;
		gboolean any_field;
		gboolean saw_any = FALSE;

		if (argc > 2)
			region = argv[2]->value.string;

		propname = argv[0]->value.string;

		any_field = !strcmp (propname, "x-evolution-any-field");
		for (i = 0; i < G_N_ELEMENTS (prop_info_table); i++) {
			if (any_field
			    || !strcmp (prop_info_table[i].query_prop, propname)) {
				saw_any = TRUE;
				info = &prop_info_table[i];

				if (any_field && info->field_id == E_CONTACT_UID) {
					/* We need to skip UID from any field contains search
					 * any-field search should be supported for the
					 * visible fields only.
					 */
					truth = FALSE;
				}
				else if (info->prop_type == PROP_TYPE_NORMAL) {
					const gchar *prop = NULL;
					/* straight string property matches */

					prop = e_contact_get_const (ctx->contact, info->field_id);

					if (prop && compare (prop, argv[1]->value.string, region)) {
						truth = TRUE;
					}
					if ((!prop) && compare ("", argv[1]->value.string, region)) {
						truth = TRUE;
					}
				}
				else if (info->prop_type == PROP_TYPE_LIST) {
					/* the special searches that match any of the list elements */
					truth = info->list_compare (ctx->contact, argv[1]->value.string, region, compare);
				}
				else if (info->prop_type == PROP_TYPE_DATE) {
					/* the special searches that match dates */
					EContactDate *date;

					date = e_contact_get (ctx->contact, info->field_id);

					if (date) {
						truth = compare_date (date, argv[1]->value.string, region, compare);
						e_contact_date_free (date);
					}
				} else {
					g_warn_if_reached ();

					saw_any = FALSE;
					break;
				}

				/* if we're looking at all fields and find a match,
				 * or if we're just looking at this one field,
				 * break. */
				if ((any_field && truth)
				    || !any_field)
					break;
			}
		}

		if (!saw_any) {
			/* propname didn't match to any of our known "special" properties,
			 * so try to find if it isn't a real field and if so, then compare
			 * against value in this field only */
			EContactField fid = e_contact_field_id (propname);

			if (fid >= E_CONTACT_FIELD_FIRST && fid < E_CONTACT_FIELD_LAST) {
				const gchar *prop = e_contact_get_const (ctx->contact, fid);

				if (prop && compare (prop, argv[1]->value.string, region)) {
					truth = TRUE;
				}

				if ((!prop) && compare ("", argv[1]->value.string, region)) {
					truth = TRUE;
				}
			} else {
				/* it is not direct EContact known field, so try to find
				 * it in EVCard attributes */
				GList *a, *attrs = e_vcard_get_attributes (E_VCARD (ctx->contact));
				for (a = attrs; a && !truth; a = a->next) {
					EVCardAttribute *attr = (EVCardAttribute *) a->data;
					if (g_ascii_strcasecmp (e_vcard_attribute_get_name (attr), propname) == 0) {
						GList *l, *values = e_vcard_attribute_get_values (attr);

						for (l = values; l && !truth; l = l->next) {
							const gchar *value = l->data;

							if (value && compare (value, argv[1]->value.string, region)) {
								truth = TRUE;
							} else if ((!value) && compare ("", argv[1]->value.string, region)) {
								truth = TRUE;
							}
						}
					}
				}
			}
		}
	}

	r = e_sexp_result_new (f, ESEXP_RES_BOOL);
	r->value.boolean = truth;

	return r;
}

static void
contains_helper_free_word (gpointer data,
                           gpointer user_data)
{
	if (data) {
		g_string_free ((GString *) data, TRUE);
	}
}

static gboolean
try_contains_word (const gchar *s1,
                   GSList *word)
{
	const gchar *o, *p;
	gunichar unival, first_w_char;
	GString *w;

	if (s1 == NULL)
		return FALSE;
	if (word == NULL)
		return TRUE; /* previous was last word */
	if (word->data == NULL)
		return FALSE; /* illegal structure */

	w = word->data;
	first_w_char = g_utf8_get_char (w->str);

	o = s1;
	for (p = e_util_unicode_get_utf8 (o, &unival); p && unival; p = e_util_unicode_get_utf8 (p, &unival)) {
		if (unival == first_w_char) {
			gunichar unival2;
			const gchar *q = p;
			const gchar *r = e_util_unicode_get_utf8 (w->str, &unival2);
			while (q && r && unival && unival2) {
				q = e_util_unicode_get_utf8 (q, &unival);
				if (!q)
					break;
				r = e_util_unicode_get_utf8 (r, &unival2);
				if (!r)
					break;
				if (unival != unival2)
					break;
			}
			if (!unival2 && r && q) {
				/* we read whole word and no illegal character has been found */
				if (word->next == NULL ||
				    try_contains_word (e_util_unicode_get_utf8 (o, &unival), word->next)) {
					return TRUE;
				}
			}
		}
		o = p;
	}

	return FALSE;
}

/* first space between words is treated as wildcard character;
 * we are looking for s2 in s1, so s2 will be breaked into words
*/
static gboolean
contains_helper (const gchar *s1,
                 const gchar *s2,
                 const gchar *region)
{
	gchar *s1uni;
	gchar *s2uni;
	GSList *words;
	gchar *next;
	gboolean have_nonspace;
	gboolean have_space;
	GString *last_word, *w;
	gboolean res;
	gunichar unich;
	glong len1, len2;

	if (!s2)
		return FALSE;

	/* the initial word contains an empty string for sure */
	if (!*s2)
		return TRUE;

	s1uni = e_util_utf8_normalize (s1);
	if (s1uni == NULL)
		return FALSE;

	s2uni = e_util_utf8_normalize (s2);
	if (s2uni == NULL) {
		g_free (s1uni);
		return FALSE;
	}

	len1 = g_utf8_strlen (s1uni, -1);
	len2 = g_utf8_strlen (s2uni, -1);
	if (len1 == 0 || len2 == 0) {
		g_free (s1uni);
		g_free (s2uni);

		/* both are empty strings */
		if (len1 == len2)
			return TRUE;

		return FALSE;
	}

	/* breaking s2 into words */
	words = NULL;
	have_nonspace = FALSE;
	have_space = FALSE;
	last_word = NULL;
	w = g_string_new ("");
	for (next = e_util_unicode_get_utf8 (s2uni, &unich); next && unich; next = e_util_unicode_get_utf8 (next, &unich)) {
		if (unich == ' ') {
			if (have_nonspace && !have_space) {
				/* treat only first space after nonspace character as wildcard,
				 * so we will start new word here
				*/
				have_space = TRUE;
				words = g_slist_append (words, w);
				last_word = w;
				w = g_string_new ("");
			} else {
				g_string_append_unichar (w, unich);
			}
		} else {
			have_nonspace = TRUE;
			have_space = FALSE;
			g_string_append_unichar (w, unich);
		}
	}

	if (have_space) {
		/* there was one or more spaces at the end of string,
		 * concat actual word with that last one
		*/
		g_string_append_len (last_word, w->str, w->len);
		g_string_free (w, TRUE);
	} else {
		/* append actual word into words list */
		words = g_slist_append (words, w);
	}

	res = try_contains_word (s1uni, words);

	g_free (s1uni);
	g_free (s2uni);
	g_slist_foreach (words, contains_helper_free_word, NULL);
	g_slist_free (words);

	return res;
}

static ESExpResult *
func_contains (struct _ESExp *f,
               gint argc,
               struct _ESExpResult **argv,
               gpointer data)
{
	SearchContext *ctx = data;

	return entry_compare (ctx, f, argc, argv, contains_helper);
}

static gboolean
is_helper (const gchar *ps1,
           const gchar *ps2,
           const gchar *region)
{
	gchar *s1, *s2;
	gboolean res = FALSE;

	s1 = e_util_utf8_remove_accents (ps1);
	s2 = e_util_utf8_remove_accents (ps2);

	if (!e_util_utf8_strcasecmp (s1, s2))
		res = TRUE;

	g_free (s1);
	g_free (s2);

	return res;
}

static ESExpResult *
func_is (struct _ESExp *f,
         gint argc,
         struct _ESExpResult **argv,
         gpointer data)
{
	SearchContext *ctx = data;

	return entry_compare (ctx, f, argc, argv, is_helper);
}

static gboolean
endswith_helper (const gchar *ps1,
                 const gchar *ps2,
                 const gchar *region)
{
	gchar *s1 = e_util_utf8_remove_accents (ps1);
	gchar *s2 = e_util_utf8_remove_accents (ps2);
	gboolean res = FALSE;
	glong s1len = g_utf8_strlen (s1, -1);
	glong s2len = g_utf8_strlen (s2, -1);

	if (s1len < s2len)
		res = FALSE;
	else
		res = e_util_utf8_strstrcase (g_utf8_offset_to_pointer (s1, s1len - s2len), s2) != NULL;

	g_free (s1);
	g_free (s2);

	return res;
}

static ESExpResult *
func_endswith (struct _ESExp *f,
               gint argc,
               struct _ESExpResult **argv,
               gpointer data)
{
	SearchContext *ctx = data;

	return entry_compare (ctx, f, argc, argv, endswith_helper);
}

static gboolean
beginswith_helper (const gchar *ps1,
                   const gchar *ps2,
                   const gchar *region)
{
	gchar *p;
	gboolean res = FALSE;
	gchar *s1 = e_util_utf8_remove_accents (ps1);
	gchar *s2 = e_util_utf8_remove_accents (ps2);

	if ((p = (gchar *) e_util_utf8_strstrcase (s1, s2))
	    && (p == s1))
		res = TRUE;

	g_free (s1);
	g_free (s2);

	return res;
}

static ESExpResult *
func_beginswith (struct _ESExp *f,
                 gint argc,
                 struct _ESExpResult **argv,
                 gpointer data)
{
	SearchContext *ctx = data;

	return entry_compare (ctx, f, argc, argv, beginswith_helper);
}

static gboolean
eqphone_helper (const gchar *ps1,
                const gchar *ps2,
                const gchar *region,
                EPhoneNumberMatch required_match)
{
	const EPhoneNumberMatch actual_match =
		e_phone_number_compare_strings_with_region (
			ps1, ps2, region, NULL);

	return actual_match >= E_PHONE_NUMBER_MATCH_EXACT
		&& actual_match <= required_match;
}

static gboolean
eqphone_exact_helper (const gchar *ps1,
                      const gchar *ps2,
                      const gchar *region)
{
	return eqphone_helper (ps1, ps2, region, E_PHONE_NUMBER_MATCH_EXACT);
}

static gboolean
eqphone_national_helper (const gchar *ps1,
                         const gchar *ps2,
                         const gchar *region)
{
	return eqphone_helper (ps1, ps2, region, E_PHONE_NUMBER_MATCH_NATIONAL);
}

static gboolean
eqphone_short_helper (const gchar *ps1,
                      const gchar *ps2,
                      const gchar *region)
{
	return eqphone_helper (ps1, ps2, region, E_PHONE_NUMBER_MATCH_SHORT);
}

static ESExpResult *
func_eqphone (struct _ESExp *f,
              gint argc,
              struct _ESExpResult **argv,
              gpointer data)
{
	SearchContext *ctx = data;

	return entry_compare (ctx, f, argc, argv, eqphone_exact_helper);
}

static ESExpResult *
func_eqphone_national (struct _ESExp *f,
                       gint argc,
                       struct _ESExpResult **argv,
                       gpointer data)
{
	SearchContext *ctx = data;

	return entry_compare (ctx, f, argc, argv, eqphone_national_helper);
}

static ESExpResult *
func_eqphone_short (struct _ESExp *f,
                    gint argc,
                    struct _ESExpResult **argv,
                    gpointer data)
{
	SearchContext *ctx = data;

	return entry_compare (ctx, f, argc, argv, eqphone_short_helper);
}

static gboolean
eqphone_is_helper (const gchar *ps1,
                   const gchar *ps2,
                   const gchar *region)
{
        gchar *p1, *p2;
        gboolean res = FALSE;
	GError *error = NULL;

        p1 = e_phone_number_normalize(ps1, &error);
        p2 = e_phone_number_normalize(ps2, &error);

        res = e_phone_number_equal (p1, p2);

        g_free (p1);
        g_free (p2);

        return res;
}

static ESExpResult *
func_eqphone_is (struct _ESExp *f,
	       gint argc,
	       struct _ESExpResult **argv,
               gpointer data)
{
	SearchContext *ctx = data;

	return entry_compare (ctx, f, argc, argv, eqphone_is_helper);
}


static gboolean
regex_helper (const gchar *ps1,
              const gchar *ps2,
              const gchar *region,
              gboolean normalize)
{
	const gchar *field_data = ps1;
	const gchar *expression = ps2;
	GRegex      *regex;
	GError      *error = NULL;
	gboolean     match = FALSE;

	regex = g_regex_new (expression, 0, 0, &error);
	if (!regex) {
		g_warning (
			"Failed to parse regular expression '%s': %s",
			expression, error ? error->message : _("Unknown error"));
		g_clear_error (&error);
		return FALSE;
	}

	if (normalize) {
		gchar *normal = e_util_utf8_normalize (field_data);

		match = g_regex_match (regex, normal, 0, NULL);

		g_free (normal);
	} else
		match = g_regex_match (regex, field_data, 0, NULL);

	g_regex_unref (regex);

	return match;
}

static gboolean
regex_normal_helper (const gchar *ps1,
                     const gchar *ps2,
                     const gchar *region)
{
	return regex_helper (ps1, ps2, region, TRUE);
}

static gboolean
regex_raw_helper (const gchar *ps1,
                  const gchar *ps2,
                  const gchar *region)
{
	return regex_helper (ps1, ps2, region, FALSE);
}

static ESExpResult *
func_regex_normal (struct _ESExp *f,
                   gint argc,
                   struct _ESExpResult **argv,
                   gpointer data)
{
	SearchContext *ctx = data;

	return entry_compare (ctx, f, argc, argv, regex_normal_helper);
}

static ESExpResult *
func_regex_raw (struct _ESExp *f,
                gint argc,
                struct _ESExpResult **argv,
                gpointer data)
{
	SearchContext *ctx = data;

	return entry_compare (ctx, f, argc, argv, regex_raw_helper);
}

static gboolean
exists_helper (const gchar *ps1,
               const gchar *ps2,
               const gchar *region)
{
	gboolean res = FALSE;
	gchar *s1 = e_util_utf8_remove_accents (ps1);
	gchar *s2 = e_util_utf8_remove_accents (ps2);

	if (e_util_utf8_strstrcase (s1, s2))
		res = TRUE;

	g_free (s1);
	g_free (s2);

	return res;
}

static ESExpResult *
func_exists (struct _ESExp *f,
             gint argc,
             struct _ESExpResult **argv,
             gpointer data)
{
	SearchContext *ctx = data;
	ESExpResult *r;
	gint truth = FALSE;

	if (argc == 1
	    && argv[0]->type == ESEXP_RES_STRING) {
		gchar *propname;
		struct prop_info *info = NULL;
		gint i;
		gboolean saw_any = FALSE;

		propname = argv[0]->value.string;

		for (i = 0; i < G_N_ELEMENTS (prop_info_table); i++) {
			if (!strcmp (prop_info_table[i].query_prop, propname)) {
				saw_any = TRUE;
				info = &prop_info_table[i];

				if (info->prop_type == PROP_TYPE_NORMAL) {
					const gchar *prop = NULL;
					/* searches where the query's property
					 * maps directly to an ecard property */

					prop = e_contact_get_const (ctx->contact, info->field_id);

					if (prop && *prop)
						truth = TRUE;
				}
				else if (info->prop_type == PROP_TYPE_LIST) {
					/* the special searches that match any of the list elements */
					truth = info->list_compare (ctx->contact, "", NULL, exists_helper);
				}
				else if (info->prop_type == PROP_TYPE_DATE) {
					EContactDate *date;

					date = e_contact_get (ctx->contact, info->field_id);

					if (date) {
						truth = TRUE;
						e_contact_date_free (date);
					}
				} else {
					g_warn_if_reached ();

					saw_any = FALSE;
				}

				break;
			}
		}

		if (!saw_any) {
			/* propname didn't match to any of our known "special" properties,
			 * so try to find if it isn't a real field and if so, then check
			 * against value in this field only */
			EContactField fid = e_contact_field_id (propname);

			if (fid >= E_CONTACT_FIELD_FIRST && fid < E_CONTACT_FIELD_LAST) {
				const gchar *prop = e_contact_get_const (ctx->contact, fid);

				if (prop && *prop)
					truth = TRUE;
			} else {
				/* is is not a known EContact field, try with EVCard attributes */
				EVCardAttribute *attr = e_vcard_get_attribute (E_VCARD (ctx->contact), propname);
				GList *l, *values = attr ? e_vcard_attribute_get_values (attr) : NULL;

				for (l = values; l && !truth; l = l->next) {
					const gchar *value = l->data;

					if (value && *value)
						truth = TRUE;
				}
			}
		}
	}
	r = e_sexp_result_new (f, ESEXP_RES_BOOL);
	r->value.boolean = truth;

	return r;
}

static ESExpResult *
func_exists_vcard (struct _ESExp *f,
                   gint argc,
                   struct _ESExpResult **argv,
                   gpointer data)
{
	SearchContext *ctx = data;
	ESExpResult *r;
	gint truth = FALSE;

	if (argc == 1 && argv[0]->type == ESEXP_RES_STRING) {
		const gchar *attr_name;
		EVCardAttribute *attr;
		GList *values;
		gchar *s;

		attr_name = argv[0]->value.string;
		attr = e_vcard_get_attribute (E_VCARD (ctx->contact), attr_name);
		if (attr) {
			values = e_vcard_attribute_get_values (attr);
			if (g_list_length (values) > 0) {
				s = values->data;
				if (s[0] != '\0') {
					truth = TRUE;
				}
			}
		}
	}

	r = e_sexp_result_new (f, ESEXP_RES_BOOL);
	r->value.boolean = truth;

	return r;
}

/* first space between words is treated as wildcard character;
 * we are looking for s2 in s1, so s2 will be breaked into words
 */
static gboolean
translit_contains_helper (const gchar *s1,
			  const gchar *s2,
			  const gchar *region)
{
	ETransliterator *transliterator;
	gchar *t1, *t2;
	gboolean res = FALSE;

	transliterator = e_transliterator_new ("Any-Latin");
	t1 = e_transliterator_transliterate (transliterator, s1);
	t2 = e_transliterator_transliterate (transliterator, s2);
	e_transliterator_unref (transliterator);

	res = contains_helper (t1, t2, region);

	g_free (t1);
	g_free (t2);

	return res;
}

static ESExpResult *
func_translit_contains (struct _ESExp *f,
			gint argc,
			struct _ESExpResult **argv,
			gpointer data)
{
	SearchContext *ctx = data;

	return entry_compare (ctx, f, argc, argv, translit_contains_helper);
}

static gboolean
translit_is_helper (const gchar *ps1,
		    const gchar *ps2,
		    const gchar *region)
{
	ETransliterator *transliterator;
	gchar *t1, *t2;
	gboolean res = FALSE;

	transliterator = e_transliterator_new ("Any-Latin");
	t1 = e_transliterator_transliterate (transliterator, ps1);
	t2 = e_transliterator_transliterate (transliterator, ps2);
	e_transliterator_unref (transliterator);

	res = is_helper (t1, t2, region);

	g_free (t1);
	g_free (t2);

	return res;
}

static ESExpResult *
func_translit_is (struct _ESExp *f,
		  gint argc,
		  struct _ESExpResult **argv,
		  gpointer data)
{
	SearchContext *ctx = data;

	return entry_compare (ctx, f, argc, argv, translit_is_helper);
}

static gboolean
translit_endswith_helper (const gchar *ps1,
			  const gchar *ps2,
			  const gchar *region)
{
	ETransliterator *transliterator;
	gchar *t1, *t2;
	gboolean res = FALSE;

	transliterator = e_transliterator_new ("Any-Latin");
	t1 = e_transliterator_transliterate (transliterator, ps1);
	t2 = e_transliterator_transliterate (transliterator, ps2);
	e_transliterator_unref (transliterator);

	res = endswith_helper (t1, t2, region);

	g_free (t1);
	g_free (t2);

	return res;
}

static ESExpResult *
func_translit_endswith (struct _ESExp *f,
			gint argc,
			struct _ESExpResult **argv,
			gpointer data)
{
	SearchContext *ctx = data;

	return entry_compare (ctx, f, argc, argv, translit_endswith_helper);
}

static gboolean
translit_beginswith_helper (const gchar *ps1,
			    const gchar *ps2,
			    const gchar *region)
{
	ETransliterator *transliterator;
	gchar *t1, *t2;
	gboolean res = FALSE;

	transliterator = e_transliterator_new ("Any-Latin");
	t1 = e_transliterator_transliterate (transliterator, ps1);
	t2 = e_transliterator_transliterate (transliterator, ps2);
	e_transliterator_unref (transliterator);

	res = beginswith_helper (t1, t2, region);

	g_free (t1);
	g_free (t2);

	return res;
}

static ESExpResult *
func_translit_beginswith (struct _ESExp *f,
			  gint argc,
			  struct _ESExpResult **argv,
			  gpointer data)
{
	SearchContext *ctx = data;

	return entry_compare (ctx, f, argc, argv, translit_beginswith_helper);
}

static void
book_backend_sexp_finalize (GObject *object)
{
	EBookBackendSExpPrivate *priv;

	priv = E_BOOK_BACKEND_SEXP_GET_PRIVATE (object);

	e_sexp_unref (priv->search_sexp);
	g_free (priv->text);
	g_free (priv->search_context);

	/* Chain up to parent's finalize() method. */
	G_OBJECT_CLASS (e_book_backend_sexp_parent_class)->finalize (object);
}

static void
e_book_backend_sexp_class_init (EBookBackendSExpClass *class)
{
	GObjectClass *object_class;

	g_type_class_add_private (class, sizeof (EBookBackendSExpPrivate));

	object_class = G_OBJECT_CLASS (class);
	object_class->finalize = book_backend_sexp_finalize;
}

static void
e_book_backend_sexp_init (EBookBackendSExp *sexp)
{
	sexp->priv = E_BOOK_BACKEND_SEXP_GET_PRIVATE (sexp);
	sexp->priv->search_context = g_new (SearchContext, 1);
}

/* 'builtin' functions */
static struct {
	const gchar *name;
	ESExpFunc *func;
	gint type;	/* 1 if a function can perform shortcut evaluation,
			 * or doesn't execute everything, 0 otherwise */
} symbols[] = {
	{ "contains", func_contains, 0 },
	{ "is", func_is, 0 },
	{ "beginswith", func_beginswith, 0 },
	{ "endswith", func_endswith, 0 },
	{ "eqphone", func_eqphone, 0 },
	{ "eqphone_national", func_eqphone_national, 0 },
	{ "eqphone_short", func_eqphone_short, 0 },
	{ "eqphone_is", func_eqphone_is, 0 },
	{ "regex_normal", func_regex_normal, 0 },
	{ "regex_translit", func_regex_normal, 0 },
	{ "regex_raw", func_regex_raw, 0 },
	{ "exists", func_exists, 0 },
	{ "exists_vcard", func_exists_vcard, 0 },
	{ "translit_contains", func_translit_contains, 0 },
	{ "translit_is", func_translit_is, 0 },
	{ "translit_beginswith", func_translit_beginswith, 0 },
	{ "translit_endswith", func_translit_endswith, 0 },
};

/**
 * e_book_backend_sexp_new:
 * @text: an s-expression to parse
 *
 * Creates a new #EBookBackendSExp from @text.
 *
 * Returns: a new #EBookBackendSExp
 **/
EBookBackendSExp *
e_book_backend_sexp_new (const gchar *text)
{
	EBookBackendSExp *sexp;
	gint ii;

	g_return_val_if_fail (text != NULL, NULL);

	sexp = g_object_new (E_TYPE_BOOK_BACKEND_SEXP, NULL);
	sexp->priv->search_sexp = e_sexp_new ();
	sexp->priv->text = g_strdup (text);

	for (ii = 0; ii < G_N_ELEMENTS (symbols); ii++) {
		if (symbols[ii].type == 1) {
			e_sexp_add_ifunction (
				sexp->priv->search_sexp, 0,
				symbols[ii].name,
				(ESExpIFunc *) symbols[ii].func,
				sexp->priv->search_context);
		} else {
			e_sexp_add_function (
				sexp->priv->search_sexp, 0,
				symbols[ii].name,
				symbols[ii].func,
				sexp->priv->search_context);
		}
	}

	e_sexp_input_text (sexp->priv->search_sexp, text, strlen (text));

	if (e_sexp_parse (sexp->priv->search_sexp) == -1) {
		g_warning (
			"%s: Error in parsing: %s",
			G_STRFUNC, sexp->priv->search_sexp->error);
		g_object_unref (sexp);
		sexp = NULL;
	}

	return sexp;
}

/**
 * e_book_backend_sexp_text:
 * @sexp: an #EBookBackendSExp
 *
 * Retrieve the text expression for the given #EBookBackendSExp object.
 *
 * Returns: the text expression
 *
 * Since: 3.8
 **/
const gchar *
e_book_backend_sexp_text (EBookBackendSExp *sexp)
{
	g_return_val_if_fail (E_IS_BOOK_BACKEND_SEXP (sexp), NULL);

	return sexp->priv->text;
}

/**
 * e_book_backend_sexp_match_contact:
 * @sexp: an #EBookBackendSExp
 * @contact: an #EContact
 *
 * Checks if @contact matches @sexp.
 *
 * Returns: %TRUE if the contact matches, %FALSE otherwise
 **/
gboolean
e_book_backend_sexp_match_contact (EBookBackendSExp *sexp,
                                   EContact *contact)
{
	ESExpResult *r;
	gboolean retval;

	g_return_val_if_fail (E_IS_BOOK_BACKEND_SEXP (sexp), FALSE);
	g_return_val_if_fail (E_IS_CONTACT (contact), FALSE);

	sexp->priv->search_context->contact = g_object_ref (contact);

	r = e_sexp_eval (sexp->priv->search_sexp);

	retval = (r && r->type == ESEXP_RES_BOOL && r->value.boolean);

	g_object_unref (sexp->priv->search_context->contact);

	e_sexp_result_free (sexp->priv->search_sexp, r);

	return retval;
}

/**
 * e_book_backend_sexp_match_vcard:
 * @sexp: an #EBookBackendSExp
 * @vcard: a vCard string
 *
 * Checks if @vcard matches @sexp.
 *
 * Returns: %TRUE if the vCard matches, %FALSE otherwise
 **/
gboolean
e_book_backend_sexp_match_vcard (EBookBackendSExp *sexp,
                                 const gchar *vcard)
{
	EContact *contact;
	gboolean retval;

	g_return_val_if_fail (E_IS_BOOK_BACKEND_SEXP (sexp), FALSE);
	g_return_val_if_fail (vcard != NULL, FALSE);

	contact = e_contact_new_from_vcard (vcard);

	retval = e_book_backend_sexp_match_contact (sexp, contact);

	g_object_unref (contact);

	return retval;
}