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