reverted rev 8210 which just changed whitespace indent
[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., 51 Franklin Street, Fifth Floor,
19  * Boston, MA 02110-1301, 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", (void *) 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         gchar *error_msg;
659
660         if (argc>1) {
661                 g_warning("match-all only takes a single argument, other arguments ignored");
662         }
663
664         /* we are only matching a single message?  or already inside a match-all? */
665         if (search->current) {
666                 d(printf("matching against 1 message: %s\n", camel_message_info_subject(search->current)));
667
668                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
669                 r->value.bool = FALSE;
670
671                 if (argc>0) {
672                         r1 = e_sexp_term_eval(f, argv[0]);
673                         if (r1->type == ESEXP_RES_BOOL) {
674                                 r->value.bool = r1->value.bool;
675                         } else {
676                                 g_warning("invalid syntax, matches require a single bool result");
677                                 error_msg = g_strdup_printf(_("(%s) requires a single bool result"), "match-all");
678                                 e_sexp_fatal_error(f, error_msg);
679                                 g_free(error_msg);
680                         }
681                         e_sexp_result_free(f, r1);
682                 } else {
683                         r->value.bool = TRUE;
684                 }
685                 return r;
686         }
687
688         r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
689         r->value.ptrarray = g_ptr_array_new();
690
691         if (search->summary == NULL) {
692                 /* TODO: make it work - e.g. use the folder and so forth for a slower search */
693                 g_warning("No summary supplied, match-all doesn't work with no summary");
694                 g_assert(0);
695                 return r;
696         }
697
698         v = search->summary_set?search->summary_set:search->summary;
699         for (i=0;i<v->len;i++) {
700                 const char *uid;
701
702                 search->current = g_ptr_array_index(v, i);
703                 uid = camel_message_info_uid(search->current);
704
705                 if (argc>0) {
706                         r1 = e_sexp_term_eval(f, argv[0]);
707                         if (r1->type == ESEXP_RES_BOOL) {
708                                 if (r1->value.bool)
709                                         g_ptr_array_add(r->value.ptrarray, (char *)uid);
710                         } else {
711                                 g_warning("invalid syntax, matches require a single bool result");
712                                 error_msg = g_strdup_printf(_("(%s) requires a single bool result"), "match-all");
713                                 e_sexp_fatal_error(f, error_msg);
714                                 g_free(error_msg);
715                         }
716                         e_sexp_result_free(f, r1);
717                 } else {
718                         g_ptr_array_add(r->value.ptrarray, (char *)uid);
719                 }
720         }
721         search->current = NULL;
722
723         return r;
724 }
725
726 static void
727 fill_thread_table(struct _CamelFolderThreadNode *root, GHashTable *id_hash)
728 {
729         while (root) {
730                 g_hash_table_insert(id_hash, (char *)camel_message_info_uid(root->message), root);
731                 if (root->child)
732                         fill_thread_table(root->child, id_hash);
733                 root = root->next;
734         }
735 }
736
737 static void
738 add_thread_results(struct _CamelFolderThreadNode *root, GHashTable *result_hash)
739 {
740         while (root) {
741                 g_hash_table_insert(result_hash, (char *)camel_message_info_uid(root->message), GINT_TO_POINTER (1));
742                 if (root->child)
743                         add_thread_results(root->child, result_hash);
744                 root = root->next;
745         }
746 }
747
748 static void
749 add_results(char *uid, void *dummy, GPtrArray *result)
750 {
751         g_ptr_array_add(result, uid);
752 }
753
754 static ESExpResult *
755 search_match_threads(struct _ESExp *f, int argc, struct _ESExpTerm **argv, CamelFolderSearch *search)
756 {
757         ESExpResult *r;
758         struct _CamelFolderSearchPrivate *p = search->priv;
759         int i, type;
760         GHashTable *results;
761         gchar *error_msg;
762
763         /* not supported in match-all */
764         if (search->current) {
765                 error_msg = g_strdup_printf(_("(%s) not allowed inside %s"), "match-threads", "match-all");
766                 e_sexp_fatal_error(f, error_msg);
767                 g_free(error_msg);
768         }
769
770         if (argc == 0) {
771                 error_msg = g_strdup_printf(_("(%s) requires a match type string"), "match-threads");
772                 e_sexp_fatal_error(f, error_msg);
773                 g_free(error_msg);
774         }
775
776         r = e_sexp_term_eval(f, argv[0]);
777         if (r->type != ESEXP_RES_STRING) {
778                 error_msg = g_strdup_printf(_("(%s) requires a match type string"), "match-threads");
779                 e_sexp_fatal_error(f, error_msg);
780                 g_free(error_msg);
781         }
782
783         type = 0;
784         if (!strcmp(r->value.string, "none"))
785                 type = 0;
786         else if (!strcmp(r->value.string, "all"))
787                 type = 1;
788         else if (!strcmp(r->value.string, "replies"))
789                 type = 2;
790         else if (!strcmp(r->value.string, "replies_parents"))
791                 type = 3;
792         else if (!strcmp(r->value.string, "single"))
793                 type = 4;
794         e_sexp_result_free(f, r);
795
796         /* behave as (begin does */
797         r = NULL;
798         for (i=1;i<argc;i++) {
799                 if (r)
800                         e_sexp_result_free(f, r);
801                 r = e_sexp_term_eval(f, argv[i]);
802         }
803
804         if (r == NULL || r->type != ESEXP_RES_ARRAY_PTR) {
805                 error_msg = g_strdup_printf(_("(%s) expects an array result"), "match-threads");
806                 e_sexp_fatal_error(f, error_msg);
807                 g_free(error_msg);
808         }
809
810         if (type == 0)
811                 return r;
812
813         if (search->folder == NULL) {
814                 error_msg = g_strdup_printf(_("(%s) requires the folder set"), "match-threads");
815                 e_sexp_fatal_error(f, error_msg);
816                 g_free(error_msg);
817         }
818
819         /* cache this, so we only have to re-calculate once per search at most */
820         if (p->threads == NULL) {
821                 p->threads = camel_folder_thread_messages_new(search->folder, NULL, TRUE);
822                 p->threads_hash = g_hash_table_new(g_str_hash, g_str_equal);
823
824                 fill_thread_table(p->threads->tree, p->threads_hash);
825         }
826
827         results = g_hash_table_new(g_str_hash, g_str_equal);
828         for (i=0;i<r->value.ptrarray->len;i++) {
829                 struct _CamelFolderThreadNode *node, *scan;
830
831                 if (type != 4)
832                         g_hash_table_insert(results, g_ptr_array_index(r->value.ptrarray, i), GINT_TO_POINTER(1));
833
834                 node = g_hash_table_lookup(p->threads_hash, (char *)g_ptr_array_index(r->value.ptrarray, i));
835                 if (node == NULL) /* this shouldn't happen but why cry over spilt milk */
836                         continue;
837
838                 /* select messages in thread according to search criteria */
839                 if (type == 4) {
840                         if (node->child == NULL && node->parent == NULL)
841                                 g_hash_table_insert(results, (char *)camel_message_info_uid(node->message), GINT_TO_POINTER(1));
842                 } else {
843                         if (type == 3) {
844                                 scan = node;
845                                 while (scan && scan->parent) {
846                                         scan = scan->parent;
847                                         g_hash_table_insert(results, (char *)camel_message_info_uid(scan->message), GINT_TO_POINTER(1));
848                                 }
849                         } else if (type == 1) {
850                                 while (node && node->parent)
851                                         node = node->parent;
852                         }
853                         g_hash_table_insert(results, (char *)camel_message_info_uid(node->message), GINT_TO_POINTER(1));
854                         if (node->child)
855                                 add_thread_results(node->child, results);
856                 }
857         }
858         e_sexp_result_free(f, r);
859
860         r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
861         r->value.ptrarray = g_ptr_array_new();
862
863         g_hash_table_foreach(results, (GHFunc)add_results, r->value.ptrarray);
864         g_hash_table_destroy(results);
865
866         return r;
867 }
868
869 static ESExpResult *
870 check_header(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search, camel_search_match_t how)
871 {
872         ESExpResult *r;
873         int truth = FALSE;
874
875         r(printf("executing check-header %d\n", how));
876
877         /* are we inside a match-all? */
878         if (search->current && argc>1
879             && argv[0]->type == ESEXP_RES_STRING) {
880                 char *headername;
881                 const char *header = NULL;
882                 char strbuf[32];
883                 int i, j;
884                 camel_search_t type = CAMEL_SEARCH_TYPE_ASIS;
885                 struct _camel_search_words *words;
886
887                 /* only a subset of headers are supported .. */
888                 headername = argv[0]->value.string;
889                 if (!g_ascii_strcasecmp(headername, "subject")) {
890                         header = camel_message_info_subject(search->current);
891                 } else if (!g_ascii_strcasecmp(headername, "date")) {
892                         /* FIXME: not a very useful form of the date */
893                         sprintf(strbuf, "%d", (int)camel_message_info_date_sent(search->current));
894                         header = strbuf;
895                 } else if (!g_ascii_strcasecmp(headername, "from")) {
896                         header = camel_message_info_from(search->current);
897                         type = CAMEL_SEARCH_TYPE_ADDRESS;
898                 } else if (!g_ascii_strcasecmp(headername, "to")) {
899                         header = camel_message_info_to(search->current);
900                         type = CAMEL_SEARCH_TYPE_ADDRESS;
901                 } else if (!g_ascii_strcasecmp(headername, "cc")) {
902                         header = camel_message_info_cc(search->current);
903                         type = CAMEL_SEARCH_TYPE_ADDRESS;
904                 } else if (!g_ascii_strcasecmp(headername, "x-camel-mlist")) {
905                         header = camel_message_info_mlist(search->current);
906                         type = CAMEL_SEARCH_TYPE_MLIST;
907                 } else {
908                         e_sexp_resultv_free(f, argc, argv);
909                         e_sexp_fatal_error(f, _("Performing query on unknown header: %s"), headername);
910                 }
911
912                 if (header == NULL)
913                         header = "";
914
915                 /* performs an OR of all words */
916                 for (i=1;i<argc && !truth;i++) {
917                         if (argv[i]->type == ESEXP_RES_STRING) {
918                                 if (argv[i]->value.string[0] == 0) {
919                                         truth = TRUE;
920                                 } else if (how == CAMEL_SEARCH_MATCH_CONTAINS) {
921                                         /* doesn't make sense to split words on anything but contains i.e. we can't have an ending match different words */
922                                         words = camel_search_words_split((const unsigned char *) argv[i]->value.string);
923                                         truth = TRUE;
924                                         for (j=0;j<words->len && truth;j++) {
925                                                 truth = camel_search_header_match(header, words->words[j]->word, how, type, NULL);
926                                         }
927                                         camel_search_words_free(words);
928                                 } else {
929                                         truth = camel_search_header_match(header, argv[i]->value.string, how, type, NULL);
930                                 }
931                         }
932                 }
933         }
934         /* TODO: else, find all matches */
935
936         r = e_sexp_result_new(f, ESEXP_RES_BOOL);
937         r->value.bool = truth;
938
939         return r;
940 }
941
942 static ESExpResult *
943 search_header_contains(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
944 {
945         return check_header(f, argc, argv, search, CAMEL_SEARCH_MATCH_CONTAINS);
946 }
947
948 static ESExpResult *
949 search_header_matches(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
950 {
951         return check_header(f, argc, argv, search, CAMEL_SEARCH_MATCH_EXACT);
952 }
953
954 static ESExpResult *
955 search_header_starts_with (struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
956 {
957         return check_header(f, argc, argv, search, CAMEL_SEARCH_MATCH_STARTS);
958 }
959
960 static ESExpResult *
961 search_header_ends_with (struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
962 {
963         return check_header(f, argc, argv, search, CAMEL_SEARCH_MATCH_ENDS);
964 }
965
966 static ESExpResult *
967 search_header_exists (struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
968 {
969         ESExpResult *r;
970         
971         r(printf ("executing header-exists\n"));
972         
973         if (search->current) {
974                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
975                 if (argc == 1 && argv[0]->type == ESEXP_RES_STRING)
976                         r->value.bool = camel_medium_get_header(CAMEL_MEDIUM(search->current), argv[0]->value.string) != NULL;
977                 
978         } else {
979                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
980                 r->value.ptrarray = g_ptr_array_new();
981         }
982         
983         return r;
984 }
985
986 /* this is just to OR results together */
987 struct _glib_sux_donkeys {
988         int count;
989         GPtrArray *uids;
990 };
991
992 /* or, store all unique values */
993 static void
994 g_lib_sux_htor(char *key, int value, struct _glib_sux_donkeys *fuckup)
995 {
996         g_ptr_array_add(fuckup->uids, key);
997 }
998
999 /* and, only store duplicates */
1000 static void
1001 g_lib_sux_htand(char *key, int value, struct _glib_sux_donkeys *fuckup)
1002 {
1003         if (value == fuckup->count)
1004                 g_ptr_array_add(fuckup->uids, key);
1005 }
1006
1007 static int
1008 match_message_index(CamelIndex *idx, const char *uid, const char *match, CamelException *ex)
1009 {
1010         CamelIndexCursor *wc, *nc;
1011         const char *word, *name;
1012         int truth = FALSE;
1013
1014         wc = camel_index_words(idx);
1015         if (wc) {
1016                 while (!truth && (word = camel_index_cursor_next(wc))) {
1017                         if (camel_ustrstrcase(word,match) != NULL) {
1018                                 /* perf: could have the wc cursor return the name cursor */
1019                                 nc = camel_index_find(idx, word);
1020                                 if (nc) {
1021                                         while (!truth && (name = camel_index_cursor_next(nc)))
1022                                                 truth = strcmp(name, uid) == 0;
1023                                         camel_object_unref((CamelObject *)nc);
1024                                 }
1025                         }
1026                 }
1027                 camel_object_unref((CamelObject *)wc);
1028         }
1029
1030         return truth;
1031 }
1032
1033 /*
1034  "one two" "three" "four five"
1035
1036   one and two
1037 or
1038   three
1039 or
1040   four and five
1041 */
1042
1043 /* returns messages which contain all words listed in words */
1044 static GPtrArray *
1045 match_words_index(CamelFolderSearch *search, struct _camel_search_words *words, CamelException *ex)
1046 {
1047         GPtrArray *result = g_ptr_array_new();
1048         GHashTable *ht = g_hash_table_new(g_str_hash, g_str_equal);
1049         struct _glib_sux_donkeys lambdafoo;
1050         CamelIndexCursor *wc, *nc;
1051         const char *word, *name;
1052         CamelMessageInfo *mi;
1053         int i;
1054
1055         /* we can have a maximum of 32 words, as we use it as the AND mask */
1056                         
1057         wc = camel_index_words(search->body_index);
1058         if (wc) {
1059                 while ((word = camel_index_cursor_next(wc))) {
1060                         for (i=0;i<words->len;i++) {
1061                                 if (camel_ustrstrcase(word, words->words[i]->word) != NULL) {
1062                                         /* perf: could have the wc cursor return the name cursor */
1063                                         nc = camel_index_find(search->body_index, word);
1064                                         if (nc) {
1065                                                 while ((name = camel_index_cursor_next(nc))) {
1066                                                         mi = g_hash_table_lookup(search->summary_hash, name);
1067                                                         if (mi) {
1068                                                                 int mask;
1069                                                                 const char *uid = camel_message_info_uid(mi);
1070
1071                                                                 mask = (GPOINTER_TO_INT(g_hash_table_lookup(ht, uid))) | (1<<i);
1072                                                                 g_hash_table_insert(ht, (char *)uid, GINT_TO_POINTER(mask));
1073                                                         }
1074                                                 }
1075                                                 camel_object_unref((CamelObject *)nc);
1076                                         }
1077                                 }
1078                         }
1079                 }
1080                 camel_object_unref((CamelObject *)wc);
1081
1082                 lambdafoo.uids = result;
1083                 lambdafoo.count = (1<<words->len) - 1;
1084                 g_hash_table_foreach(ht, (GHFunc)g_lib_sux_htand, &lambdafoo);
1085                 g_hash_table_destroy(ht);
1086         }
1087
1088         return result;
1089 }
1090
1091 static gboolean
1092 match_words_1message (CamelDataWrapper *object, struct _camel_search_words *words, guint32 *mask)
1093 {
1094         CamelDataWrapper *containee;
1095         int truth = FALSE;
1096         int parts, i;
1097         
1098         containee = camel_medium_get_content_object (CAMEL_MEDIUM (object));
1099         
1100         if (containee == NULL)
1101                 return FALSE;
1102         
1103         /* using the object types is more accurate than using the mime/types */
1104         if (CAMEL_IS_MULTIPART (containee)) {
1105                 parts = camel_multipart_get_number (CAMEL_MULTIPART (containee));
1106                 for (i = 0; i < parts && truth == FALSE; i++) {
1107                         CamelDataWrapper *part = (CamelDataWrapper *)camel_multipart_get_part (CAMEL_MULTIPART (containee), i);
1108                         if (part)
1109                                 truth = match_words_1message(part, words, mask);
1110                 }
1111         } else if (CAMEL_IS_MIME_MESSAGE (containee)) {
1112                 /* for messages we only look at its contents */
1113                 truth = match_words_1message((CamelDataWrapper *)containee, words, mask);
1114         } else if (camel_content_type_is(CAMEL_DATA_WRAPPER (containee)->mime_type, "text", "*")) {
1115                 /* for all other text parts, we look inside, otherwise we dont care */
1116                 CamelStreamMem *mem = (CamelStreamMem *)camel_stream_mem_new ();
1117
1118                 /* FIXME: The match should be part of a stream op */
1119                 camel_data_wrapper_decode_to_stream (containee, CAMEL_STREAM (mem));
1120                 camel_stream_write (CAMEL_STREAM (mem), "", 1);
1121                 for (i=0;i<words->len;i++) {
1122                         /* FIXME: This is horridly slow, and should use a real search algorithm */
1123                         if (camel_ustrstrcase((const char *) mem->buffer->data, words->words[i]->word) != NULL) {
1124                                 *mask |= (1<<i);
1125                                 /* shortcut a match */
1126                                 if (*mask == (1<<(words->len))-1)
1127                                         return TRUE;
1128                         }
1129                 }
1130                 
1131                 camel_object_unref (mem);
1132         }
1133         
1134         return truth;
1135 }
1136
1137 static gboolean
1138 match_words_message(CamelFolder *folder, const char *uid, struct _camel_search_words *words, CamelException *ex)
1139 {
1140         guint32 mask;
1141         CamelMimeMessage *msg;
1142         CamelException x = CAMEL_EXCEPTION_INITIALISER;
1143         int truth;
1144
1145         msg = camel_folder_get_message(folder, uid, &x);
1146         if (msg) {
1147                 mask = 0;
1148                 truth = match_words_1message((CamelDataWrapper *)msg, words, &mask);
1149                 camel_object_unref((CamelObject *)msg);
1150         } else {
1151                 camel_exception_clear(&x);
1152                 truth = FALSE;
1153         }
1154
1155         return truth;
1156 }
1157
1158 static GPtrArray *
1159 match_words_messages(CamelFolderSearch *search, struct _camel_search_words *words, CamelException *ex)
1160 {
1161         int i;
1162         GPtrArray *matches = g_ptr_array_new();
1163
1164         if (search->body_index) {
1165                 GPtrArray *indexed;
1166                 struct _camel_search_words *simple;
1167
1168                 simple = camel_search_words_simple(words);
1169                 indexed = match_words_index(search, simple, ex);
1170                 camel_search_words_free(simple);
1171
1172                 for (i=0;i<indexed->len;i++) {
1173                         const char *uid = g_ptr_array_index(indexed, i);
1174                         
1175                         if (match_words_message(search->folder, uid, words, ex))
1176                                 g_ptr_array_add(matches, (char *)uid);
1177                 }
1178                 
1179                 g_ptr_array_free(indexed, TRUE);
1180         } else {
1181                 GPtrArray *v = search->summary_set?search->summary_set:search->summary;
1182
1183                 for (i=0;i<v->len;i++) {
1184                         CamelMessageInfo *info = g_ptr_array_index(v, i);
1185                         const char *uid = camel_message_info_uid(info);
1186                         
1187                         if (match_words_message(search->folder, uid, words, ex))
1188                                 g_ptr_array_add(matches, (char *)uid);
1189                 }
1190         }
1191
1192         return matches;
1193 }
1194
1195 static ESExpResult *
1196 search_body_contains(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1197 {
1198         int i, j;
1199         CamelException *ex = search->priv->ex;
1200         struct _camel_search_words *words;
1201         ESExpResult *r;
1202         struct _glib_sux_donkeys lambdafoo;
1203
1204         if (search->current) {  
1205                 int truth = FALSE;
1206
1207                 if (argc == 1 && argv[0]->value.string[0] == 0) {
1208                         truth = TRUE;
1209                 } else {
1210                         for (i=0;i<argc && !truth;i++) {
1211                                 if (argv[i]->type == ESEXP_RES_STRING) {
1212                                         words = camel_search_words_split((const unsigned char *) argv[i]->value.string);
1213                                         truth = TRUE;
1214                                         if ((words->type & CAMEL_SEARCH_WORD_COMPLEX) == 0 && search->body_index) {
1215                                                 for (j=0;j<words->len && truth;j++)
1216                                                         truth = match_message_index(search->body_index, camel_message_info_uid(search->current), words->words[j]->word, ex);
1217                                         } else {
1218                                                 /* TODO: cache current message incase of multiple body search terms */
1219                                                 truth = match_words_message(search->folder, camel_message_info_uid(search->current), words, ex);
1220                                         }
1221                                         camel_search_words_free(words);
1222                                 }
1223                         }
1224                 }
1225                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
1226                 r->value.bool = truth;
1227         } else {
1228                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
1229                 r->value.ptrarray = g_ptr_array_new();
1230
1231                 if (argc == 1 && argv[0]->value.string[0] == 0) {
1232                         GPtrArray *v = search->summary_set?search->summary_set:search->summary;
1233
1234                         for (i=0;i<v->len;i++) {
1235                                 CamelMessageInfo *info = g_ptr_array_index(v, i);
1236
1237                                 g_ptr_array_add(r->value.ptrarray, (char *)camel_message_info_uid(info));
1238                         }
1239                 } else {
1240                         GHashTable *ht = g_hash_table_new(g_str_hash, g_str_equal);
1241                         GPtrArray *matches;
1242
1243                         for (i=0;i<argc;i++) {
1244                                 if (argv[i]->type == ESEXP_RES_STRING) {
1245                                         words = camel_search_words_split((const unsigned char *) argv[i]->value.string);
1246                                         if ((words->type & CAMEL_SEARCH_WORD_COMPLEX) == 0 && search->body_index) {
1247                                                 matches = match_words_index(search, words, ex);
1248                                         } else {
1249                                                 matches = match_words_messages(search, words, ex);
1250                                         }
1251                                         for (j=0;j<matches->len;j++)
1252                                                 g_hash_table_insert(ht, matches->pdata[j], matches->pdata[j]);
1253                                         g_ptr_array_free(matches, TRUE);
1254                                         camel_search_words_free(words);
1255                                 }
1256                         }
1257                         lambdafoo.uids = r->value.ptrarray;
1258                         g_hash_table_foreach(ht, (GHFunc)g_lib_sux_htor, &lambdafoo);
1259                         g_hash_table_destroy(ht);
1260                 }
1261         }
1262
1263         return r;
1264 }
1265
1266 static ESExpResult *
1267 search_user_flag(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1268 {
1269         ESExpResult *r;
1270         int i;
1271
1272         r(printf("executing user-flag\n"));
1273
1274         /* are we inside a match-all? */
1275         if (search->current) {
1276                 int truth = FALSE;
1277                 /* performs an OR of all words */
1278                 for (i=0;i<argc && !truth;i++) {
1279                         if (argv[i]->type == ESEXP_RES_STRING
1280                             && camel_message_info_user_flag(search->current, argv[i]->value.string)) {
1281                                 truth = TRUE;
1282                                 break;
1283                         }
1284                 }
1285                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
1286                 r->value.bool = truth;
1287         } else {
1288                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
1289                 r->value.ptrarray = g_ptr_array_new();
1290         }
1291
1292         return r;
1293 }
1294
1295 static ESExpResult *
1296 search_system_flag (struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1297 {
1298         ESExpResult *r;
1299         
1300         r(printf ("executing system-flag\n"));
1301         
1302         if (search->current) {
1303                 gboolean truth = FALSE;
1304                 
1305                 if (argc == 1)
1306                         truth = camel_system_flag_get (camel_message_info_flags(search->current), argv[0]->value.string);
1307                 
1308                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
1309                 r->value.bool = truth;
1310         } else {
1311                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
1312                 r->value.ptrarray = g_ptr_array_new ();
1313         }
1314         
1315         return r;
1316 }
1317
1318 static ESExpResult *
1319 search_user_tag(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1320 {
1321         const char *value = NULL;
1322         ESExpResult *r;
1323         
1324         r(printf("executing user-tag\n"));
1325         
1326         if (argc == 1)
1327                 value = camel_message_info_user_tag(search->current, argv[0]->value.string);
1328         
1329         r = e_sexp_result_new(f, ESEXP_RES_STRING);
1330         r->value.string = g_strdup (value ? value : "");
1331         
1332         return r;
1333 }
1334
1335 static ESExpResult *
1336 search_get_sent_date(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *s)
1337 {
1338         ESExpResult *r;
1339
1340         r(printf("executing get-sent-date\n"));
1341
1342         /* are we inside a match-all? */
1343         if (s->current) {
1344                 r = e_sexp_result_new(f, ESEXP_RES_INT);
1345
1346                 r->value.number = camel_message_info_date_sent(s->current);
1347         } else {
1348                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
1349                 r->value.ptrarray = g_ptr_array_new ();
1350         }
1351
1352         return r;
1353 }
1354
1355 static ESExpResult *
1356 search_get_received_date(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *s)
1357 {
1358         ESExpResult *r;
1359
1360         r(printf("executing get-received-date\n"));
1361
1362         /* are we inside a match-all? */
1363         if (s->current) {
1364                 r = e_sexp_result_new(f, ESEXP_RES_INT);
1365
1366                 r->value.number = camel_message_info_date_received(s->current);
1367         } else {
1368                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
1369                 r->value.ptrarray = g_ptr_array_new ();
1370         }
1371
1372         return r;
1373 }
1374
1375 static ESExpResult *
1376 search_get_current_date(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *s)
1377 {
1378         ESExpResult *r;
1379
1380         r(printf("executing get-current-date\n"));
1381
1382         r = e_sexp_result_new(f, ESEXP_RES_INT);
1383         r->value.number = time (NULL);
1384         return r;
1385 }
1386
1387 static ESExpResult *
1388 search_get_size (struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *s)
1389 {
1390         ESExpResult *r;
1391         
1392         r(printf("executing get-size\n"));
1393         
1394         /* are we inside a match-all? */
1395         if (s->current) {
1396                 r = e_sexp_result_new (f, ESEXP_RES_INT);
1397                 r->value.number = camel_message_info_size(s->current) / 1024;
1398         } else {
1399                 r = e_sexp_result_new (f, ESEXP_RES_ARRAY_PTR);
1400                 r->value.ptrarray = g_ptr_array_new ();
1401         }
1402         
1403         return r;
1404 }
1405
1406 static ESExpResult *
1407 search_uid(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1408 {
1409         ESExpResult *r;
1410         int i;
1411
1412         r(printf("executing uid\n"));
1413
1414         /* are we inside a match-all? */
1415         if (search->current) {
1416                 int truth = FALSE;
1417                 const char *uid = camel_message_info_uid(search->current);
1418
1419                 /* performs an OR of all words */
1420                 for (i=0;i<argc && !truth;i++) {
1421                         if (argv[i]->type == ESEXP_RES_STRING
1422                             && !strcmp(uid, argv[i]->value.string)) {
1423                                 truth = TRUE;
1424                                 break;
1425                         }
1426                 }
1427                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
1428                 r->value.bool = truth;
1429         } else {
1430                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
1431                 r->value.ptrarray = g_ptr_array_new();
1432                 for (i=0;i<argc;i++) {
1433                         if (argv[i]->type == ESEXP_RES_STRING)
1434                                 g_ptr_array_add(r->value.ptrarray, argv[i]->value.string);
1435                 }
1436         }
1437
1438         return r;
1439 }