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