** See bug #69446.
[platform/upstream/evolution-data-server.git] / camel / camel-folder-search.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3  *  Copyright (C) 2000-2003 Ximian Inc.
4  *
5  *  Authors: Michael Zucchi <notzed@ximian.com>
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of version 2 of the GNU General Public
9  * License as published by the Free Software Foundation.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public
17  * License along with this program; if not, write to the
18  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
19  * Boston, MA 02111-1307, USA.
20  */
21
22 /* This is a helper class for folders to implement the search function.
23    It implements enough to do basic searches on folders that can provide
24    an in-memory summary and a body index. */
25
26 #ifdef HAVE_CONFIG_H
27 #include <config.h>
28 #endif
29
30 #include <stdio.h>
31 #include <string.h>
32 #include <ctype.h>
33 #include <sys/types.h>
34 #include <regex.h>
35
36 #include <glib.h>
37
38 #include "camel-folder-search.h"
39 #include "camel-folder-thread.h"
40
41 #include "camel-exception.h"
42 #include "camel-medium.h"
43 #include "camel-multipart.h"
44 #include "camel-mime-message.h"
45 #include "camel-stream-mem.h"
46 #include "e-util/e-memory.h"
47 #include "camel-search-private.h"
48 #include "camel-i18n.h"
49
50 #define d(x) 
51 #define r(x) 
52
53 struct _CamelFolderSearchPrivate {
54         GHashTable *mempool_hash;
55         CamelException *ex;
56
57         CamelFolderThread *threads;
58         GHashTable *threads_hash;
59 };
60
61 #define _PRIVATE(o) (((CamelFolderSearch *)(o))->priv)
62
63 static ESExpResult *search_not(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search);
64
65 static ESExpResult *search_header_contains(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search);
66 static ESExpResult *search_header_matches(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search);
67 static ESExpResult *search_header_starts_with(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search);
68 static ESExpResult *search_header_ends_with(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search);
69 static ESExpResult *search_header_exists(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search);
70 static ESExpResult *search_match_all(struct _ESExp *f, int argc, struct _ESExpTerm **argv, CamelFolderSearch *search);
71 static ESExpResult *search_match_threads(struct _ESExp *f, int argc, struct _ESExpTerm **argv, CamelFolderSearch *s);
72 static ESExpResult *search_body_contains(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search);
73 static ESExpResult *search_user_flag(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *s);
74 static ESExpResult *search_user_tag(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *s);
75 static ESExpResult *search_system_flag(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *s);
76 static ESExpResult *search_get_sent_date(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *s);
77 static ESExpResult *search_get_received_date(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *s);
78 static ESExpResult *search_get_current_date(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *s);
79 static ESExpResult *search_get_size(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *s);
80 static ESExpResult *search_uid(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *s);
81
82 static ESExpResult *search_dummy(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search);
83
84 static void camel_folder_search_class_init (CamelFolderSearchClass *klass);
85 static void camel_folder_search_init       (CamelFolderSearch *obj);
86 static void camel_folder_search_finalize   (CamelObject *obj);
87
88 static CamelObjectClass *camel_folder_search_parent;
89
90 static void
91 camel_folder_search_class_init (CamelFolderSearchClass *klass)
92 {
93         camel_folder_search_parent = camel_type_get_global_classfuncs (camel_object_get_type ());
94
95         klass->not = search_not;
96
97         klass->match_all = search_match_all;
98         klass->match_threads = search_match_threads;
99         klass->body_contains = search_body_contains;
100         klass->header_contains = search_header_contains;
101         klass->header_matches = search_header_matches;
102         klass->header_starts_with = search_header_starts_with;
103         klass->header_ends_with = search_header_ends_with;
104         klass->header_exists = search_header_exists;
105         klass->user_tag = search_user_tag;
106         klass->user_flag = search_user_flag;
107         klass->system_flag = search_system_flag;
108         klass->get_sent_date = search_get_sent_date;
109         klass->get_received_date = search_get_received_date;
110         klass->get_current_date = search_get_current_date;
111         klass->get_size = search_get_size;
112         klass->uid = search_uid;
113 }
114
115 static void
116 camel_folder_search_init (CamelFolderSearch *obj)
117 {
118         struct _CamelFolderSearchPrivate *p;
119
120         p = _PRIVATE(obj) = g_malloc0(sizeof(*p));
121
122         obj->sexp = e_sexp_new();
123
124         /* use a hash of mempools to associate the returned uid lists with
125            the backing mempool.  yes pretty weird, but i didn't want to change
126            the api just yet */
127
128         p->mempool_hash = g_hash_table_new(0, 0);
129 }
130
131 static void
132 free_mempool(void *key, void *value, void *data)
133 {
134         GPtrArray *uids = key;
135         EMemPool *pool = value;
136
137         g_warning("Search closed with outstanding result unfreed: %p", uids);
138
139         g_ptr_array_free(uids, TRUE);
140         e_mempool_destroy(pool);
141 }
142
143 static void
144 camel_folder_search_finalize (CamelObject *obj)
145 {
146         CamelFolderSearch *search = (CamelFolderSearch *)obj;
147         struct _CamelFolderSearchPrivate *p = _PRIVATE(obj);
148
149         if (search->sexp)
150                 e_sexp_unref(search->sexp);
151         if (search->summary_hash)
152                 g_hash_table_destroy(search->summary_hash);
153
154         g_free(search->last_search);
155         g_hash_table_foreach(p->mempool_hash, free_mempool, obj);
156         g_hash_table_destroy(p->mempool_hash);
157         g_free(p);
158 }
159
160 CamelType
161 camel_folder_search_get_type (void)
162 {
163         static CamelType type = CAMEL_INVALID_TYPE;
164         
165         if (type == CAMEL_INVALID_TYPE) {
166                 type = camel_type_register (camel_object_get_type (), "CamelFolderSearch",
167                                             sizeof (CamelFolderSearch),
168                                             sizeof (CamelFolderSearchClass),
169                                             (CamelObjectClassInitFunc) camel_folder_search_class_init,
170                                             NULL,
171                                             (CamelObjectInitFunc) camel_folder_search_init,
172                                             (CamelObjectFinalizeFunc) camel_folder_search_finalize);
173         }
174         
175         return type;
176 }
177
178 #ifdef offsetof
179 #define CAMEL_STRUCT_OFFSET(type, field)        ((gint) offsetof (type, field))
180 #else
181 #define CAMEL_STRUCT_OFFSET(type, field)        ((gint) ((gchar*) &((type *) 0)->field))
182 #endif
183
184 struct {
185         char *name;
186         int offset;
187         int flags;              /* 0x02 = immediate, 0x01 = always enter */
188 } builtins[] = {
189         /* these have default implementations in e-sexp */
190         { "and", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, and), 2 },
191         { "or", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, or), 2 },
192         /* we need to override this one though to implement an 'array not' */
193         { "not", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, not), 0 },
194         { "<", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, lt), 2 },
195         { ">", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, gt), 2 },
196         { "=", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, eq), 2 },
197
198         /* these we have to use our own default if there is none */
199         /* they should all be defined in the language? so it parses, or should they not?? */
200         { "match-all", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, match_all), 3 },
201         { "match-threads", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, match_threads), 3 },
202         { "body-contains", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, body_contains), 1 },
203         { "header-contains", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, header_contains), 1 },
204         { "header-matches", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, header_matches), 1 },
205         { "header-starts-with", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, header_starts_with), 1 },
206         { "header-ends-with", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, header_ends_with), 1 },
207         { "header-exists", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, header_exists), 1 },
208         { "user-tag", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, user_tag), 1 },
209         { "user-flag", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, user_flag), 1 },
210         { "system-flag", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, system_flag), 1 },
211         { "get-sent-date", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, get_sent_date), 1 },
212         { "get-received-date", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, get_received_date), 1 },
213         { "get-current-date", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, get_current_date), 1 },
214         { "get-size", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, get_size), 1 },
215         { "uid", CAMEL_STRUCT_OFFSET(CamelFolderSearchClass, uid), 1 },
216 };
217
218 void
219 camel_folder_search_construct (CamelFolderSearch *search)
220 {
221         int i;
222         CamelFolderSearchClass *klass = (CamelFolderSearchClass *)CAMEL_OBJECT_GET_CLASS(search);
223
224         for (i=0;i<sizeof(builtins)/sizeof(builtins[0]);i++) {
225                 void *func;
226                 /* c is sure messy sometimes */
227                 func = *((void **)(((char *)klass)+builtins[i].offset));
228                 if (func == NULL && builtins[i].flags&1) {
229                         g_warning("Search class doesn't implement '%s' method: %s", builtins[i].name, camel_type_to_name(CAMEL_OBJECT_GET_CLASS(search)));
230                         func = (void *)search_dummy;
231                 }
232                 if (func != NULL) {
233                         if (builtins[i].flags&2) {
234                                 e_sexp_add_ifunction(search->sexp, 0, builtins[i].name, (ESExpIFunc *)func, search);
235                         } else {
236                                 e_sexp_add_function(search->sexp, 0, builtins[i].name, (ESExpFunc *)func, search);
237                         }
238                 }
239         }
240 }
241
242 /**
243  * camel_folder_search_new:
244  *
245  * Create a new CamelFolderSearch object.
246  * 
247  * A CamelFolderSearch is a subclassable, extensible s-exp
248  * evaluator which enforces a particular set of s-expressions.
249  * Particular methods may be overriden by an implementation to
250  * implement a search for any sort of backend.
251  *
252  * Return value: A new CamelFolderSearch widget.
253  **/
254 CamelFolderSearch *
255 camel_folder_search_new (void)
256 {
257         CamelFolderSearch *new = CAMEL_FOLDER_SEARCH (camel_object_new (camel_folder_search_get_type ()));
258
259         camel_folder_search_construct(new);
260         return new;
261 }
262
263 /**
264  * camel_folder_search_set_folder:
265  * @search:
266  * @folder: A folder.
267  * 
268  * Set the folder attribute of the search.  This is currently unused, but
269  * could be used to perform a slow-search when indexes and so forth are not
270  * available.  Or for use by subclasses.
271  **/
272 void
273 camel_folder_search_set_folder(CamelFolderSearch *search, CamelFolder *folder)
274 {
275         search->folder = folder;
276 }
277
278 /**
279  * camel_folder_search_set_summary:
280  * @search: 
281  * @summary: An array of CamelMessageInfo pointers.
282  * 
283  * Set the array of summary objects representing the span of the search.
284  *
285  * If this is not set, then a subclass must provide the functions
286  * for searching headers and for the match-all operator.
287  **/
288 void
289 camel_folder_search_set_summary(CamelFolderSearch *search, GPtrArray *summary)
290 {
291         int i;
292
293         search->summary = summary;
294         if (search->summary_hash)
295                 g_hash_table_destroy(search->summary_hash);
296         search->summary_hash = g_hash_table_new(g_str_hash, g_str_equal);
297         for (i=0;i<summary->len;i++)
298                 g_hash_table_insert(search->summary_hash, (char *)camel_message_info_uid(summary->pdata[i]), summary->pdata[i]);
299 }
300
301 /**
302  * camel_folder_search_set_body_index:
303  * @search: 
304  * @index: 
305  * 
306  * Set the index representing the contents of all messages
307  * in this folder.  If this is not set, then the folder implementation
308  * should sub-class the CamelFolderSearch and provide its own
309  * body-contains function.
310  **/
311 void
312 camel_folder_search_set_body_index(CamelFolderSearch *search, CamelIndex *index)
313 {
314         if (search->body_index)
315                 camel_object_unref((CamelObject *)search->body_index);
316         search->body_index = index;
317         if (index)
318                 camel_object_ref((CamelObject *)index);
319 }
320
321 /**
322  * camel_folder_search_execute_expression:
323  * @search: 
324  * @expr: 
325  * @ex: 
326  * 
327  * Execute the search expression @expr, returning an array of
328  * all matches as a GPtrArray of uid's of matching messages.
329  *
330  * Note that any settings such as set_body_index(), set_folder(),
331  * and so on are reset to #NULL once the search has completed.
332  *
333  * TODO: The interface should probably return summary items instead
334  * (since they are much more useful to any client).
335  * 
336  * Return value: A GPtrArray of strings of all matching messages.
337  * This must only be freed by camel_folder_search_free_result.
338  **/
339 GPtrArray *
340 camel_folder_search_execute_expression(CamelFolderSearch *search, const char *expr, CamelException *ex)
341 {
342         ESExpResult *r;
343         GPtrArray *matches;
344         int i;
345         GHashTable *results;
346         EMemPool *pool;
347         struct _CamelFolderSearchPrivate *p = _PRIVATE(search);
348
349         p->ex = ex;
350
351         /* only re-parse if the search has changed */
352         if (search->last_search == NULL
353             || strcmp(search->last_search, expr)) {
354                 e_sexp_input_text(search->sexp, expr, strlen(expr));
355                 if (e_sexp_parse(search->sexp) == -1) {
356                         camel_exception_setv(ex, 1, _("Cannot parse search expression: %s:\n%s"), e_sexp_error(search->sexp), expr);
357                         return NULL;
358                 }
359
360                 g_free(search->last_search);
361                 search->last_search = g_strdup(expr);
362         }
363         r = e_sexp_eval(search->sexp);
364         if (r == NULL) {
365                 if (!camel_exception_is_set(ex))
366                         camel_exception_setv(ex, 1, _("Error executing search expression: %s:\n%s"), e_sexp_error(search->sexp), expr);
367                 return NULL;
368         }
369
370         matches = g_ptr_array_new();
371
372         /* now create a folder summary to return?? */
373         if (r->type == ESEXP_RES_ARRAY_PTR) {
374                 d(printf("got result ...\n"));
375                 /* we use a mempool to store the strings, packed in tight as possible, and freed together */
376                 /* because the strings are often short (like <8 bytes long), we would be wasting appx 50%
377                    of memory just storing the size tag that malloc assigns us and alignment padding, so this
378                    gets around that (and is faster to allocate and free as a bonus) */
379                 pool = e_mempool_new(512, 256, E_MEMPOOL_ALIGN_BYTE);
380                 if (search->summary) {
381                         /* reorder result in summary order */
382                         results = g_hash_table_new(g_str_hash, g_str_equal);
383                         for (i=0;i<r->value.ptrarray->len;i++) {
384                                 d(printf("adding match: %s\n", (char *)g_ptr_array_index(r->value.ptrarray, i)));
385                                 g_hash_table_insert(results, g_ptr_array_index(r->value.ptrarray, i), GINT_TO_POINTER (1));
386                         }
387                         for (i=0;i<search->summary->len;i++) {
388                                 CamelMessageInfo *info = g_ptr_array_index(search->summary, i);
389                                 char *uid = (char *)camel_message_info_uid(info);
390                                 if (g_hash_table_lookup(results, uid)) {
391                                         g_ptr_array_add(matches, e_mempool_strdup(pool, uid));
392                                 }
393                         }
394                         g_hash_table_destroy(results);
395                 } else {
396                         for (i=0;i<r->value.ptrarray->len;i++) {
397                                 d(printf("adding match: %s\n", (char *)g_ptr_array_index(r->value.ptrarray, i)));
398                                 g_ptr_array_add(matches, e_mempool_strdup(pool, g_ptr_array_index(r->value.ptrarray, i)));
399                         }
400                 }
401                 /* instead of putting the mempool_hash in the structure, we keep the api clean by
402                    putting a reference to it in a hashtable.  Lets us do some debugging and catch
403                    unfree'd results as well. */
404                 g_hash_table_insert(p->mempool_hash, matches, pool);
405         } else {
406                 g_warning("Search returned an invalid result type");
407         }
408
409         e_sexp_result_free(search->sexp, r);
410
411         if (p->threads)
412                 camel_folder_thread_messages_unref(p->threads);
413         if (p->threads_hash)
414                 g_hash_table_destroy(p->threads_hash);
415
416         p->threads = NULL;
417         p->threads_hash = NULL;
418         search->folder = NULL;
419         search->summary = NULL;
420         search->current = NULL;
421         search->body_index = NULL;
422
423         return matches;
424 }
425
426 /**
427  * camel_folder_search_search:
428  * @search: 
429  * @expr: 
430  * @uids: to search against, NULL for all uid's.
431  * @ex: 
432  * 
433  * Run a search.  Search must have had Folder already set on it, and
434  * it must implement summaries.
435  * 
436  * Return value: 
437  **/
438 GPtrArray *
439 camel_folder_search_search(CamelFolderSearch *search, const char *expr, GPtrArray *uids, CamelException *ex)
440 {
441         ESExpResult *r;
442         GPtrArray *matches = NULL, *summary_set;
443         int i;
444         GHashTable *results;
445         EMemPool *pool;
446         struct _CamelFolderSearchPrivate *p = _PRIVATE(search);
447
448         g_assert(search->folder);
449
450         p->ex = ex;
451
452         /* setup our search list, summary_hash only contains those we're interested in */
453         search->summary = camel_folder_get_summary(search->folder);
454         search->summary_hash = g_hash_table_new(g_str_hash, g_str_equal);
455
456         if (uids) {
457                 GHashTable *uids_hash = g_hash_table_new(g_str_hash, g_str_equal);
458
459                 summary_set = search->summary_set = g_ptr_array_new();
460                 for (i=0;i<uids->len;i++)
461                         g_hash_table_insert(uids_hash, uids->pdata[i], uids->pdata[i]);
462                 for (i=0;i<search->summary->len;i++)
463                         if (g_hash_table_lookup(uids_hash, camel_message_info_uid(search->summary->pdata[i])))
464                                 g_ptr_array_add(search->summary_set, search->summary->pdata[i]);
465         } else {
466                 summary_set = search->summary;
467         }
468
469         for (i=0;i<summary_set->len;i++)
470                 g_hash_table_insert(search->summary_hash, (char *)camel_message_info_uid(summary_set->pdata[i]), summary_set->pdata[i]);
471
472         /* only re-parse if the search has changed */
473         if (search->last_search == NULL
474             || strcmp(search->last_search, expr)) {
475                 e_sexp_input_text(search->sexp, expr, strlen(expr));
476                 if (e_sexp_parse(search->sexp) == -1) {
477                         camel_exception_setv(ex, 1, _("Cannot parse search expression: %s:\n%s"), e_sexp_error(search->sexp), expr);
478                         goto fail;
479                 }
480
481                 g_free(search->last_search);
482                 search->last_search = g_strdup(expr);
483         }
484         r = e_sexp_eval(search->sexp);
485         if (r == NULL) {
486                 if (!camel_exception_is_set(ex))
487                         camel_exception_setv(ex, 1, _("Error executing search expression: %s:\n%s"), e_sexp_error(search->sexp), expr);
488                 goto fail;
489         }
490
491         matches = g_ptr_array_new();
492
493         /* now create a folder summary to return?? */
494         if (r->type == ESEXP_RES_ARRAY_PTR) {
495                 d(printf("got result ...\n"));
496
497                 /* we use a mempool to store the strings, packed in tight as possible, and freed together */
498                 /* because the strings are often short (like <8 bytes long), we would be wasting appx 50%
499                    of memory just storing the size tag that malloc assigns us and alignment padding, so this
500                    gets around that (and is faster to allocate and free as a bonus) */
501                 pool = e_mempool_new(512, 256, E_MEMPOOL_ALIGN_BYTE);
502                 /* reorder result in summary order */
503                 results = g_hash_table_new(g_str_hash, g_str_equal);
504                 for (i=0;i<r->value.ptrarray->len;i++) {
505                         d(printf("adding match: %s\n", (char *)g_ptr_array_index(r->value.ptrarray, i)));
506                         g_hash_table_insert(results, g_ptr_array_index(r->value.ptrarray, i), GINT_TO_POINTER (1));
507                 }
508
509                 for (i=0;i<summary_set->len;i++) {
510                         CamelMessageInfo *info = g_ptr_array_index(summary_set, i);
511                         char *uid = (char *)camel_message_info_uid(info);
512                         if (g_hash_table_lookup(results, uid))
513                                 g_ptr_array_add(matches, e_mempool_strdup(pool, uid));
514                 }
515                 g_hash_table_destroy(results);
516
517                 /* instead of putting the mempool_hash in the structure, we keep the api clean by
518                    putting a reference to it in a hashtable.  Lets us do some debugging and catch
519                    unfree'd results as well. */
520                 g_hash_table_insert(p->mempool_hash, matches, pool);
521         } else {
522                 g_warning("Search returned an invalid result type");
523         }
524
525         e_sexp_result_free(search->sexp, r);
526 fail:
527         /* these might be allocated by match-threads */
528         if (p->threads)
529                 camel_folder_thread_messages_unref(p->threads);
530         if (p->threads_hash)
531                 g_hash_table_destroy(p->threads_hash);
532         if (search->summary_set)
533                 g_ptr_array_free(search->summary_set, TRUE);
534         g_hash_table_destroy(search->summary_hash);
535         camel_folder_free_summary(search->folder, search->summary);
536
537         p->threads = NULL;
538         p->threads_hash = NULL;
539         search->folder = NULL;
540         search->summary = NULL;
541         search->summary_hash = NULL;
542         search->summary_set = NULL;
543         search->current = NULL;
544         search->body_index = NULL;
545
546         return matches;
547 }
548
549 void camel_folder_search_free_result(CamelFolderSearch *search, GPtrArray *result)
550 {
551         int i;
552         struct _CamelFolderSearchPrivate *p = _PRIVATE(search);
553         EMemPool *pool;
554
555         pool = g_hash_table_lookup(p->mempool_hash, result);
556         if (pool) {
557                 e_mempool_destroy(pool);
558                 g_hash_table_remove(p->mempool_hash, result);
559         } else {
560                 for (i=0;i<result->len;i++)
561                         g_free(g_ptr_array_index(result, i));
562         }
563         g_ptr_array_free(result, TRUE);
564 }
565
566 /* dummy function, returns false always, or an empty match array */
567 static ESExpResult *
568 search_dummy(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
569 {
570         ESExpResult *r;
571
572         if (search->current == NULL) {
573                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
574                 r->value.bool = FALSE;
575         } else {
576                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
577                 r->value.ptrarray = g_ptr_array_new();
578         }
579
580         return r;
581 }
582
583 /* impelemnt an 'array not', i.e. everything in the summary, not in the supplied array */
584 static ESExpResult *
585 search_not(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
586 {
587         ESExpResult *r;
588         int i;
589
590         if (argc>0) {
591                 if (argv[0]->type == ESEXP_RES_ARRAY_PTR) {
592                         GPtrArray *v = argv[0]->value.ptrarray;
593                         const char *uid;
594
595                         r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
596                         r->value.ptrarray = g_ptr_array_new();
597
598                         /* not against a single message?*/
599                         if (search->current) {
600                                 int found = FALSE;
601
602                                 uid = camel_message_info_uid(search->current);
603                                 for (i=0;!found && i<v->len;i++) {
604                                         if (strcmp(uid, v->pdata[i]) == 0)
605                                                 found = TRUE;
606                                 }
607
608                                 if (!found)
609                                         g_ptr_array_add(r->value.ptrarray, (char *)uid);
610                         } else if (search->summary == NULL) {
611                                 g_warning("No summary set, 'not' against an array requires a summary");
612                         } else {
613                                 /* 'not' against the whole summary */
614                                 GHashTable *have = g_hash_table_new(g_str_hash, g_str_equal);
615                                 char **s;
616                                 CamelMessageInfo **m;
617
618                                 s = (char **)v->pdata;
619                                 for (i=0;i<v->len;i++)
620                                         g_hash_table_insert(have, s[i], s[i]);
621
622                                 v = search->summary_set?search->summary_set:search->summary;
623                                 m = (CamelMessageInfo **)v->pdata;
624                                 for (i=0;i<v->len;i++) {
625                                         char *uid = (char *)camel_message_info_uid(m[i]);
626
627                                         if (g_hash_table_lookup(have, uid) == NULL)
628                                                 g_ptr_array_add(r->value.ptrarray, uid);
629                                 }
630                                 g_hash_table_destroy(have);
631                         }
632                 } else {
633                         int res = TRUE;
634
635                         if (argv[0]->type == ESEXP_RES_BOOL)
636                                 res = ! argv[0]->value.bool;
637
638                         r = e_sexp_result_new(f, ESEXP_RES_BOOL);
639                         r->value.bool = res;
640                 }
641         } else {
642                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
643                 r->value.bool = TRUE;
644         }
645
646         return r;
647 }
648
649 static ESExpResult *
650 search_match_all(struct _ESExp *f, int argc, struct _ESExpTerm **argv, CamelFolderSearch *search)
651 {
652         int i;
653         ESExpResult *r, *r1;
654         GPtrArray *v;
655
656         if (argc>1) {
657                 g_warning("match-all only takes a single argument, other arguments ignored");
658         }
659
660         /* we are only matching a single message?  or already inside a match-all? */
661         if (search->current) {
662                 d(printf("matching against 1 message: %s\n", camel_message_info_subject(search->current)));
663
664                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
665                 r->value.bool = FALSE;
666
667                 if (argc>0) {
668                         r1 = e_sexp_term_eval(f, argv[0]);
669                         if (r1->type == ESEXP_RES_BOOL) {
670                                 r->value.bool = r1->value.bool;
671                         } else {
672                                 g_warning("invalid syntax, matches require a single bool result");
673                                 e_sexp_fatal_error(f, _("(match-all) requires a single bool result"));
674                         }
675                         e_sexp_result_free(f, r1);
676                 } else {
677                         r->value.bool = TRUE;
678                 }
679                 return r;
680         }
681
682         r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
683         r->value.ptrarray = g_ptr_array_new();
684
685         if (search->summary == NULL) {
686                 /* TODO: make it work - e.g. use the folder and so forth for a slower search */
687                 g_warning("No summary supplied, match-all doesn't work with no summary");
688                 g_assert(0);
689                 return r;
690         }
691
692         v = search->summary_set?search->summary_set:search->summary;
693         for (i=0;i<v->len;i++) {
694                 const char *uid;
695
696                 search->current = g_ptr_array_index(v, i);
697                 uid = camel_message_info_uid(search->current);
698
699                 if (argc>0) {
700                         r1 = e_sexp_term_eval(f, argv[0]);
701                         if (r1->type == ESEXP_RES_BOOL) {
702                                 if (r1->value.bool)
703                                         g_ptr_array_add(r->value.ptrarray, (char *)uid);
704                         } else {
705                                 g_warning("invalid syntax, matches require a single bool result");
706                                 e_sexp_fatal_error(f, _("(match-all) requires a single bool result"));
707                         }
708                         e_sexp_result_free(f, r1);
709                 } else {
710                         g_ptr_array_add(r->value.ptrarray, (char *)uid);
711                 }
712         }
713         search->current = NULL;
714
715         return r;
716 }
717
718 static void
719 fill_thread_table(struct _CamelFolderThreadNode *root, GHashTable *id_hash)
720 {
721         while (root) {
722                 g_hash_table_insert(id_hash, (char *)camel_message_info_uid(root->message), root);
723                 if (root->child)
724                         fill_thread_table(root->child, id_hash);
725                 root = root->next;
726         }
727 }
728
729 static void
730 add_thread_results(struct _CamelFolderThreadNode *root, GHashTable *result_hash)
731 {
732         while (root) {
733                 g_hash_table_insert(result_hash, (char *)camel_message_info_uid(root->message), GINT_TO_POINTER (1));
734                 if (root->child)
735                         add_thread_results(root->child, result_hash);
736                 root = root->next;
737         }
738 }
739
740 static void
741 add_results(char *uid, void *dummy, GPtrArray *result)
742 {
743         g_ptr_array_add(result, uid);
744 }
745
746 static ESExpResult *
747 search_match_threads(struct _ESExp *f, int argc, struct _ESExpTerm **argv, CamelFolderSearch *search)
748 {
749         ESExpResult *r;
750         struct _CamelFolderSearchPrivate *p = search->priv;
751         int i, type;
752         GHashTable *results;
753
754         /* not supported in match-all */
755         if (search->current)
756                 e_sexp_fatal_error(f, _("(match-threads) not allowed inside match-all"));
757
758         if (argc == 0)
759                 e_sexp_fatal_error(f, _("(match-threads) requires a match type string"));
760
761         r = e_sexp_term_eval(f, argv[0]);
762         if (r->type != ESEXP_RES_STRING)
763                 e_sexp_fatal_error(f, _("(match-threads) requires a match type string"));
764
765         type = 0;
766         if (!strcmp(r->value.string, "none"))
767                 type = 0;
768         else if (!strcmp(r->value.string, "all"))
769                 type = 1;
770         else if (!strcmp(r->value.string, "replies"))
771                 type = 2;
772         else if (!strcmp(r->value.string, "replies_parents"))
773                 type = 3;
774         e_sexp_result_free(f, r);
775
776         /* behave as (begin does */
777         r = NULL;
778         for (i=1;i<argc;i++) {
779                 if (r)
780                         e_sexp_result_free(f, r);
781                 r = e_sexp_term_eval(f, argv[i]);
782         }
783
784         if (r == NULL || r->type != ESEXP_RES_ARRAY_PTR)
785                 e_sexp_fatal_error(f, _("(match-threads) expects an array result"));
786
787         if (type == 0)
788                 return r;
789
790         if (search->folder == NULL)
791                 e_sexp_fatal_error(f, _("(match-threads) requires the folder set"));
792
793         /* cache this, so we only have to re-calculate once per search at most */
794         if (p->threads == NULL) {
795                 p->threads = camel_folder_thread_messages_new(search->folder, NULL, TRUE);
796                 p->threads_hash = g_hash_table_new(g_str_hash, g_str_equal);
797
798                 fill_thread_table(p->threads->tree, p->threads_hash);
799         }
800
801         results = g_hash_table_new(g_str_hash, g_str_equal);
802         for (i=0;i<r->value.ptrarray->len;i++) {
803                 d(printf("adding match: %s\n", (char *)g_ptr_array_index(r->value.ptrarray, i)));
804                 g_hash_table_insert(results, g_ptr_array_index(r->value.ptrarray, i), GINT_TO_POINTER (1));
805         }
806
807         for (i=0;i<r->value.ptrarray->len;i++) {
808                 struct _CamelFolderThreadNode *node, *scan;
809
810                 node = g_hash_table_lookup(p->threads_hash, (char *)g_ptr_array_index(r->value.ptrarray, i));
811                 if (node == NULL) /* this shouldn't happen but why cry over spilt milk */
812                         continue;
813
814                 /* select messages in thread according to search criteria */
815                 if (type == 3) {
816                         scan = node;
817                         while (scan && scan->parent) {
818                                 scan = scan->parent;
819                                 g_hash_table_insert(results, (char *)camel_message_info_uid(scan->message), GINT_TO_POINTER(1));
820                         }
821                 } else if (type == 1) {
822                         while (node && node->parent)
823                                 node = node->parent;
824                 }
825                 g_hash_table_insert(results, (char *)camel_message_info_uid(node->message), GINT_TO_POINTER(1));
826                 if (node->child)
827                         add_thread_results(node->child, results);
828         }
829         e_sexp_result_free(f, r);
830
831         r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
832         r->value.ptrarray = g_ptr_array_new();
833
834         g_hash_table_foreach(results, (GHFunc)add_results, r->value.ptrarray);
835         g_hash_table_destroy(results);
836
837         return r;
838 }
839
840 static ESExpResult *
841 check_header(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search, camel_search_match_t how)
842 {
843         ESExpResult *r;
844         int truth = FALSE;
845
846         r(printf("executing check-header %d\n", how));
847
848         /* are we inside a match-all? */
849         if (search->current && argc>1
850             && argv[0]->type == ESEXP_RES_STRING) {
851                 char *headername;
852                 const char *header = NULL;
853                 char strbuf[32];
854                 int i, j;
855                 camel_search_t type = CAMEL_SEARCH_TYPE_ASIS;
856                 struct _camel_search_words *words;
857
858                 /* only a subset of headers are supported .. */
859                 headername = argv[0]->value.string;
860                 if (!strcasecmp(headername, "subject")) {
861                         header = camel_message_info_subject(search->current);
862                 } else if (!strcasecmp(headername, "date")) {
863                         /* FIXME: not a very useful form of the date */
864                         sprintf(strbuf, "%d", (int)camel_message_info_date_sent(search->current));
865                         header = strbuf;
866                 } else if (!strcasecmp(headername, "from")) {
867                         header = camel_message_info_from(search->current);
868                         type = CAMEL_SEARCH_TYPE_ADDRESS;
869                 } else if (!strcasecmp(headername, "to")) {
870                         header = camel_message_info_to(search->current);
871                         type = CAMEL_SEARCH_TYPE_ADDRESS;
872                 } else if (!strcasecmp(headername, "cc")) {
873                         header = camel_message_info_cc(search->current);
874                         type = CAMEL_SEARCH_TYPE_ADDRESS;
875                 } else if (!g_ascii_strcasecmp(headername, "x-camel-mlist")) {
876                         header = camel_message_info_mlist(search->current);
877                         type = CAMEL_SEARCH_TYPE_MLIST;
878                 } else {
879                         e_sexp_resultv_free(f, argc, argv);
880                         e_sexp_fatal_error(f, _("Performing query on unknown header: %s"), headername);
881                 }
882
883                 if (header) {
884                         /* performs an OR of all words */
885                         for (i=1;i<argc && !truth;i++) {
886                                 if (argv[i]->type == ESEXP_RES_STRING) {
887                                         if (argv[i]->value.string[0] == 0) {
888                                                 truth = TRUE;
889                                         } else if (how == CAMEL_SEARCH_MATCH_CONTAINS) {
890                                                 /* doesn't make sense to split words on anything but contains i.e. we can't have an ending match different words */
891                                                 words = camel_search_words_split(argv[i]->value.string);
892                                                 truth = TRUE;
893                                                 for (j=0;j<words->len && truth;j++) {
894                                                         truth = camel_search_header_match(header, words->words[j]->word, how, type, NULL);
895                                                 }
896                                                 camel_search_words_free(words);
897                                         } else {
898                                                 truth = camel_search_header_match(header, argv[i]->value.string, how, type, NULL);
899                                         }
900                                 }
901                         }
902                 }
903         }
904         /* TODO: else, find all matches */
905
906         r = e_sexp_result_new(f, ESEXP_RES_BOOL);
907         r->value.bool = truth;
908
909         return r;
910 }
911
912 static ESExpResult *
913 search_header_contains(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
914 {
915         return check_header(f, argc, argv, search, CAMEL_SEARCH_MATCH_CONTAINS);
916 }
917
918 static ESExpResult *
919 search_header_matches(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
920 {
921         return check_header(f, argc, argv, search, CAMEL_SEARCH_MATCH_EXACT);
922 }
923
924 static ESExpResult *
925 search_header_starts_with (struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
926 {
927         return check_header(f, argc, argv, search, CAMEL_SEARCH_MATCH_STARTS);
928 }
929
930 static ESExpResult *
931 search_header_ends_with (struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
932 {
933         return check_header(f, argc, argv, search, CAMEL_SEARCH_MATCH_ENDS);
934 }
935
936 static ESExpResult *
937 search_header_exists (struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
938 {
939         ESExpResult *r;
940         
941         r(printf ("executing header-exists\n"));
942         
943         if (search->current) {
944                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
945                 if (argc == 1 && argv[0]->type == ESEXP_RES_STRING)
946                         r->value.bool = camel_medium_get_header(CAMEL_MEDIUM(search->current), argv[0]->value.string) != NULL;
947                 
948         } else {
949                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
950                 r->value.ptrarray = g_ptr_array_new();
951         }
952         
953         return r;
954 }
955
956 /* this is just to OR results together */
957 struct _glib_sux_donkeys {
958         int count;
959         GPtrArray *uids;
960 };
961
962 /* or, store all unique values */
963 static void
964 g_lib_sux_htor(char *key, int value, struct _glib_sux_donkeys *fuckup)
965 {
966         g_ptr_array_add(fuckup->uids, key);
967 }
968
969 /* and, only store duplicates */
970 static void
971 g_lib_sux_htand(char *key, int value, struct _glib_sux_donkeys *fuckup)
972 {
973         if (value == fuckup->count)
974                 g_ptr_array_add(fuckup->uids, key);
975 }
976
977 static int
978 match_message_index(CamelIndex *idx, const char *uid, const char *match, CamelException *ex)
979 {
980         CamelIndexCursor *wc, *nc;
981         const char *word, *name;
982         int truth = FALSE;
983
984         wc = camel_index_words(idx);
985         if (wc) {
986                 while (!truth && (word = camel_index_cursor_next(wc))) {
987                         if (camel_ustrstrcase(word,match) != NULL) {
988                                 /* perf: could have the wc cursor return the name cursor */
989                                 nc = camel_index_find(idx, word);
990                                 if (nc) {
991                                         while (!truth && (name = camel_index_cursor_next(nc)))
992                                                 truth = strcmp(name, uid) == 0;
993                                         camel_object_unref((CamelObject *)nc);
994                                 }
995                         }
996                 }
997                 camel_object_unref((CamelObject *)wc);
998         }
999
1000         return truth;
1001 }
1002
1003 /*
1004  "one two" "three" "four five"
1005
1006   one and two
1007 or
1008   three
1009 or
1010   four and five
1011 */
1012
1013 /* returns messages which contain all words listed in words */
1014 static GPtrArray *
1015 match_words_index(CamelFolderSearch *search, struct _camel_search_words *words, CamelException *ex)
1016 {
1017         GPtrArray *result = g_ptr_array_new();
1018         GHashTable *ht = g_hash_table_new(g_str_hash, g_str_equal);
1019         struct _glib_sux_donkeys lambdafoo;
1020         CamelIndexCursor *wc, *nc;
1021         const char *word, *name;
1022         CamelMessageInfo *mi;
1023         int i;
1024
1025         /* we can have a maximum of 32 words, as we use it as the AND mask */
1026                         
1027         wc = camel_index_words(search->body_index);
1028         if (wc) {
1029                 while ((word = camel_index_cursor_next(wc))) {
1030                         for (i=0;i<words->len;i++) {
1031                                 if (camel_ustrstrcase(word, words->words[i]->word) != NULL) {
1032                                         /* perf: could have the wc cursor return the name cursor */
1033                                         nc = camel_index_find(search->body_index, word);
1034                                         if (nc) {
1035                                                 while ((name = camel_index_cursor_next(nc))) {
1036                                                         mi = g_hash_table_lookup(search->summary_hash, name);
1037                                                         if (mi) {
1038                                                                 int mask;
1039                                                                 const char *uid = camel_message_info_uid(mi);
1040
1041                                                                 mask = (GPOINTER_TO_INT(g_hash_table_lookup(ht, uid))) | (1<<i);
1042                                                                 g_hash_table_insert(ht, (char *)uid, GINT_TO_POINTER(mask));
1043                                                         }
1044                                                 }
1045                                                 camel_object_unref((CamelObject *)nc);
1046                                         }
1047                                 }
1048                         }
1049                 }
1050                 camel_object_unref((CamelObject *)wc);
1051
1052                 lambdafoo.uids = result;
1053                 lambdafoo.count = (1<<words->len) - 1;
1054                 g_hash_table_foreach(ht, (GHFunc)g_lib_sux_htand, &lambdafoo);
1055                 g_hash_table_destroy(ht);
1056         }
1057
1058         return result;
1059 }
1060
1061 static gboolean
1062 match_words_1message (CamelDataWrapper *object, struct _camel_search_words *words, guint32 *mask)
1063 {
1064         CamelDataWrapper *containee;
1065         int truth = FALSE;
1066         int parts, i;
1067         
1068         containee = camel_medium_get_content_object (CAMEL_MEDIUM (object));
1069         
1070         if (containee == NULL)
1071                 return FALSE;
1072         
1073         /* using the object types is more accurate than using the mime/types */
1074         if (CAMEL_IS_MULTIPART (containee)) {
1075                 parts = camel_multipart_get_number (CAMEL_MULTIPART (containee));
1076                 for (i = 0; i < parts && truth == FALSE; i++) {
1077                         CamelDataWrapper *part = (CamelDataWrapper *)camel_multipart_get_part (CAMEL_MULTIPART (containee), i);
1078                         if (part)
1079                                 truth = match_words_1message(part, words, mask);
1080                 }
1081         } else if (CAMEL_IS_MIME_MESSAGE (containee)) {
1082                 /* for messages we only look at its contents */
1083                 truth = match_words_1message((CamelDataWrapper *)containee, words, mask);
1084         } else if (camel_content_type_is(CAMEL_DATA_WRAPPER (containee)->mime_type, "text", "*")) {
1085                 /* for all other text parts, we look inside, otherwise we dont care */
1086                 CamelStreamMem *mem = (CamelStreamMem *)camel_stream_mem_new ();
1087
1088                 /* FIXME: The match should be part of a stream op */
1089                 camel_data_wrapper_decode_to_stream (containee, CAMEL_STREAM (mem));
1090                 camel_stream_write (CAMEL_STREAM (mem), "", 1);
1091                 for (i=0;i<words->len;i++) {
1092                         /* FIXME: This is horridly slow, and should use a real search algorithm */
1093                         if (camel_ustrstrcase(mem->buffer->data, words->words[i]->word) != NULL) {
1094                                 *mask |= (1<<i);
1095                                 /* shortcut a match */
1096                                 if (*mask == (1<<(words->len))-1)
1097                                         return TRUE;
1098                         }
1099                 }
1100                 
1101                 camel_object_unref (mem);
1102         }
1103         
1104         return truth;
1105 }
1106
1107 static gboolean
1108 match_words_message(CamelFolder *folder, const char *uid, struct _camel_search_words *words, CamelException *ex)
1109 {
1110         guint32 mask;
1111         CamelMimeMessage *msg;
1112         CamelException x = CAMEL_EXCEPTION_INITIALISER;
1113         int truth;
1114
1115         msg = camel_folder_get_message(folder, uid, &x);
1116         if (msg) {
1117                 mask = 0;
1118                 truth = match_words_1message((CamelDataWrapper *)msg, words, &mask);
1119                 camel_object_unref((CamelObject *)msg);
1120         } else {
1121                 camel_exception_clear(&x);
1122                 truth = FALSE;
1123         }
1124
1125         return truth;
1126 }
1127
1128 static GPtrArray *
1129 match_words_messages(CamelFolderSearch *search, struct _camel_search_words *words, CamelException *ex)
1130 {
1131         int i;
1132         GPtrArray *matches = g_ptr_array_new();
1133
1134         if (search->body_index) {
1135                 GPtrArray *indexed;
1136                 struct _camel_search_words *simple;
1137
1138                 simple = camel_search_words_simple(words);
1139                 indexed = match_words_index(search, simple, ex);
1140                 camel_search_words_free(simple);
1141
1142                 for (i=0;i<indexed->len;i++) {
1143                         const char *uid = g_ptr_array_index(indexed, i);
1144                         
1145                         if (match_words_message(search->folder, uid, words, ex))
1146                                 g_ptr_array_add(matches, (char *)uid);
1147                 }
1148                 
1149                 g_ptr_array_free(indexed, TRUE);
1150         } else {
1151                 GPtrArray *v = search->summary_set?search->summary_set:search->summary;
1152
1153                 for (i=0;i<v->len;i++) {
1154                         CamelMessageInfo *info = g_ptr_array_index(v, i);
1155                         const char *uid = camel_message_info_uid(info);
1156                         
1157                         if (match_words_message(search->folder, uid, words, ex))
1158                                 g_ptr_array_add(matches, (char *)uid);
1159                 }
1160         }
1161
1162         return matches;
1163 }
1164
1165 static ESExpResult *
1166 search_body_contains(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1167 {
1168         int i, j;
1169         CamelException *ex = search->priv->ex;
1170         struct _camel_search_words *words;
1171         ESExpResult *r;
1172         struct _glib_sux_donkeys lambdafoo;
1173
1174         if (search->current) {  
1175                 int truth = FALSE;
1176
1177                 if (argc == 1 && argv[0]->value.string[0] == 0) {
1178                         truth = TRUE;
1179                 } else {
1180                         for (i=0;i<argc && !truth;i++) {
1181                                 if (argv[i]->type == ESEXP_RES_STRING) {
1182                                         words = camel_search_words_split(argv[i]->value.string);
1183                                         truth = TRUE;
1184                                         if ((words->type & CAMEL_SEARCH_WORD_COMPLEX) == 0 && search->body_index) {
1185                                                 for (j=0;j<words->len && truth;j++)
1186                                                         truth = match_message_index(search->body_index, camel_message_info_uid(search->current), words->words[j]->word, ex);
1187                                         } else {
1188                                                 /* TODO: cache current message incase of multiple body search terms */
1189                                                 truth = match_words_message(search->folder, camel_message_info_uid(search->current), words, ex);
1190                                         }
1191                                         camel_search_words_free(words);
1192                                 }
1193                         }
1194                 }
1195                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
1196                 r->value.bool = truth;
1197         } else {
1198                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
1199                 r->value.ptrarray = g_ptr_array_new();
1200
1201                 if (argc == 1 && argv[0]->value.string[0] == 0) {
1202                         GPtrArray *v = search->summary_set?search->summary_set:search->summary;
1203
1204                         for (i=0;i<v->len;i++) {
1205                                 CamelMessageInfo *info = g_ptr_array_index(v, i);
1206
1207                                 g_ptr_array_add(r->value.ptrarray, (char *)camel_message_info_uid(info));
1208                         }
1209                 } else {
1210                         GHashTable *ht = g_hash_table_new(g_str_hash, g_str_equal);
1211                         GPtrArray *matches;
1212
1213                         for (i=0;i<argc;i++) {
1214                                 if (argv[i]->type == ESEXP_RES_STRING) {
1215                                         words = camel_search_words_split(argv[i]->value.string);
1216                                         if ((words->type & CAMEL_SEARCH_WORD_COMPLEX) == 0 && search->body_index) {
1217                                                 matches = match_words_index(search, words, ex);
1218                                         } else {
1219                                                 matches = match_words_messages(search, words, ex);
1220                                         }
1221                                         for (j=0;j<matches->len;j++)
1222                                                 g_hash_table_insert(ht, matches->pdata[j], matches->pdata[j]);
1223                                         g_ptr_array_free(matches, TRUE);
1224                                         camel_search_words_free(words);
1225                                 }
1226                         }
1227                         lambdafoo.uids = r->value.ptrarray;
1228                         g_hash_table_foreach(ht, (GHFunc)g_lib_sux_htor, &lambdafoo);
1229                         g_hash_table_destroy(ht);
1230                 }
1231         }
1232
1233         return r;
1234 }
1235
1236 static ESExpResult *
1237 search_user_flag(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1238 {
1239         ESExpResult *r;
1240         int i;
1241
1242         r(printf("executing user-flag\n"));
1243
1244         /* are we inside a match-all? */
1245         if (search->current) {
1246                 int truth = FALSE;
1247                 /* performs an OR of all words */
1248                 for (i=0;i<argc && !truth;i++) {
1249                         if (argv[i]->type == ESEXP_RES_STRING
1250                             && camel_message_info_user_flag(search->current, argv[i]->value.string)) {
1251                                 truth = TRUE;
1252                                 break;
1253                         }
1254                 }
1255                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
1256                 r->value.bool = truth;
1257         } else {
1258                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
1259                 r->value.ptrarray = g_ptr_array_new();
1260         }
1261
1262         return r;
1263 }
1264
1265 static ESExpResult *
1266 search_system_flag (struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1267 {
1268         ESExpResult *r;
1269         
1270         r(printf ("executing system-flag\n"));
1271         
1272         if (search->current) {
1273                 gboolean truth = FALSE;
1274                 
1275                 if (argc == 1)
1276                         truth = camel_system_flag_get (camel_message_info_flags(search->current), argv[0]->value.string);
1277                 
1278                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
1279                 r->value.bool = truth;
1280         } else {
1281                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
1282                 r->value.ptrarray = g_ptr_array_new ();
1283         }
1284         
1285         return r;
1286 }
1287
1288 static ESExpResult *
1289 search_user_tag(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1290 {
1291         const char *value = NULL;
1292         ESExpResult *r;
1293         
1294         r(printf("executing user-tag\n"));
1295         
1296         if (argc == 1)
1297                 value = camel_message_info_user_tag(search->current, argv[0]->value.string);
1298         
1299         r = e_sexp_result_new(f, ESEXP_RES_STRING);
1300         r->value.string = g_strdup (value ? value : "");
1301         
1302         return r;
1303 }
1304
1305 static ESExpResult *
1306 search_get_sent_date(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *s)
1307 {
1308         ESExpResult *r;
1309
1310         r(printf("executing get-sent-date\n"));
1311
1312         /* are we inside a match-all? */
1313         if (s->current) {
1314                 r = e_sexp_result_new(f, ESEXP_RES_INT);
1315
1316                 r->value.number = camel_message_info_date_sent(s->current);
1317         } else {
1318                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
1319                 r->value.ptrarray = g_ptr_array_new ();
1320         }
1321
1322         return r;
1323 }
1324
1325 static ESExpResult *
1326 search_get_received_date(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *s)
1327 {
1328         ESExpResult *r;
1329
1330         r(printf("executing get-received-date\n"));
1331
1332         /* are we inside a match-all? */
1333         if (s->current) {
1334                 r = e_sexp_result_new(f, ESEXP_RES_INT);
1335
1336                 r->value.number = camel_message_info_date_received(s->current);
1337         } else {
1338                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
1339                 r->value.ptrarray = g_ptr_array_new ();
1340         }
1341
1342         return r;
1343 }
1344
1345 static ESExpResult *
1346 search_get_current_date(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *s)
1347 {
1348         ESExpResult *r;
1349
1350         r(printf("executing get-current-date\n"));
1351
1352         r = e_sexp_result_new(f, ESEXP_RES_INT);
1353         r->value.number = time (NULL);
1354         return r;
1355 }
1356
1357 static ESExpResult *
1358 search_get_size (struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *s)
1359 {
1360         ESExpResult *r;
1361         
1362         r(printf("executing get-size\n"));
1363         
1364         /* are we inside a match-all? */
1365         if (s->current) {
1366                 r = e_sexp_result_new (f, ESEXP_RES_INT);
1367                 r->value.number = camel_message_info_size(s->current) / 1024;
1368         } else {
1369                 r = e_sexp_result_new (f, ESEXP_RES_ARRAY_PTR);
1370                 r->value.ptrarray = g_ptr_array_new ();
1371         }
1372         
1373         return r;
1374 }
1375
1376 static ESExpResult *
1377 search_uid(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1378 {
1379         ESExpResult *r;
1380         int i;
1381
1382         r(printf("executing uid\n"));
1383
1384         /* are we inside a match-all? */
1385         if (search->current) {
1386                 int truth = FALSE;
1387                 const char *uid = camel_message_info_uid(search->current);
1388
1389                 /* performs an OR of all words */
1390                 for (i=0;i<argc && !truth;i++) {
1391                         if (argv[i]->type == ESEXP_RES_STRING
1392                             && !strcmp(uid, argv[i]->value.string)) {
1393                                 truth = TRUE;
1394                                 break;
1395                         }
1396                 }
1397                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
1398                 r->value.bool = truth;
1399         } else {
1400                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
1401                 r->value.ptrarray = g_ptr_array_new();
1402                 for (i=0;i<argc;i++) {
1403                         if (argv[i]->type == ESEXP_RES_STRING)
1404                                 g_ptr_array_add(r->value.ptrarray, argv[i]->value.string);
1405                 }
1406         }
1407
1408         return r;
1409 }