** Fix for bug #544114
[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 ("sexp is : [%s]\n", expr);
510         sql_query = camel_sexp_to_sql (expr);
511         tmp1 = camel_db_sqlize_string(search->folder->full_name);
512         tmp = g_strdup_printf ("SELECT uid FROM %s WHERE %s", tmp1,  sql_query);
513         camel_db_free_sqlized_string (tmp1);
514         g_free (sql_query);
515         printf("Equivalent sql %s\n", tmp);
516         
517         matches = g_ptr_array_new();
518         cdb = (CamelDB *) (search->folder->cdb);
519         camel_db_select (cdb, tmp, (CamelDBSelectCB) read_uid_callback, matches, ex);
520         g_free(tmp);
521         //e_sexp_result_free(search->sexp, r);
522
523 fail:
524         /* these might be allocated by match-threads */
525         if (p->threads)
526                 camel_folder_thread_messages_unref(p->threads);
527         if (p->threads_hash)
528                 g_hash_table_destroy(p->threads_hash);
529         if (search->summary_set)
530                 g_ptr_array_free(search->summary_set, TRUE);
531         camel_folder_free_summary(search->folder, search->summary);
532
533         p->threads = NULL;
534         p->threads_hash = NULL;
535         search->folder = NULL;
536         search->summary = NULL;
537         search->summary_set = NULL;
538         search->current = NULL;
539         search->body_index = NULL;
540
541         return matches;
542 }
543
544 void camel_folder_search_free_result(CamelFolderSearch *search, GPtrArray *result)
545 {
546 #if 0
547         int i;
548         struct _CamelFolderSearchPrivate *p = _PRIVATE(search);
549         EMemPool *pool;
550         pool = g_hash_table_lookup(p->mempool_hash, result);
551         if (pool) {
552                 e_mempool_destroy(pool);
553                 g_hash_table_remove(p->mempool_hash, result);
554         } else {
555                 for (i=0;i<result->len;i++)
556                         g_free(g_ptr_array_index(result, i));
557         }
558 #endif
559         g_ptr_array_foreach (result, (GFunc) camel_pstring_free, NULL);
560         g_ptr_array_free(result, TRUE);
561 }
562
563 /* dummy function, returns false always, or an empty match array */
564 static ESExpResult *
565 search_dummy(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
566 {
567         ESExpResult *r;
568
569         if (search->current == NULL) {
570                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
571                 r->value.bool = FALSE;
572         } else {
573                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
574                 r->value.ptrarray = g_ptr_array_new();
575         }
576
577         return r;
578 }
579
580 /* impelemnt an 'array not', i.e. everything in the summary, not in the supplied array */
581 static ESExpResult *
582 search_not(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
583 {
584         ESExpResult *r;
585         int i;
586
587         if (argc>0) {
588                 if (argv[0]->type == ESEXP_RES_ARRAY_PTR) {
589                         GPtrArray *v = argv[0]->value.ptrarray;
590                         const char *uid;
591
592                         r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
593                         r->value.ptrarray = g_ptr_array_new();
594
595                         /* not against a single message?*/
596                         if (search->current) {
597                                 int found = FALSE;
598
599                                 uid = camel_message_info_uid(search->current);
600                                 for (i=0;!found && i<v->len;i++) {
601                                         if (strcmp(uid, v->pdata[i]) == 0)
602                                                 found = TRUE;
603                                 }
604
605                                 if (!found)
606                                         g_ptr_array_add(r->value.ptrarray, (char *)uid);
607                         } else if (search->summary == NULL) {
608                                 g_warning("No summary set, 'not' against an array requires a summary");
609                         } else {
610                                 /* 'not' against the whole summary */
611                                 GHashTable *have = g_hash_table_new(g_str_hash, g_str_equal);
612                                 char **s;
613                                 char **m;
614
615                                 s = (char **)v->pdata;
616                                 for (i=0;i<v->len;i++)
617                                         g_hash_table_insert(have, s[i], s[i]);
618
619                                 v = search->summary_set?search->summary_set:search->summary;
620                                 m = (char **)v->pdata;
621                                 for (i=0;i<v->len;i++) {
622                                         char *uid = m[i];
623
624                                         if (g_hash_table_lookup(have, uid) == NULL)
625                                                 g_ptr_array_add(r->value.ptrarray, uid);
626                                 }
627                                 g_hash_table_destroy(have);
628                         }
629                 } else {
630                         int res = TRUE;
631
632                         if (argv[0]->type == ESEXP_RES_BOOL)
633                                 res = ! argv[0]->value.bool;
634
635                         r = e_sexp_result_new(f, ESEXP_RES_BOOL);
636                         r->value.bool = res;
637                 }
638         } else {
639                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
640                 r->value.bool = TRUE;
641         }
642
643         return r;
644 }
645
646 static ESExpResult *
647 search_match_all(struct _ESExp *f, int argc, struct _ESExpTerm **argv, CamelFolderSearch *search)
648 {
649         ESExpResult *r, *r1;
650         gchar *error_msg;
651
652         if (argc>1) {
653                 g_warning("match-all only takes a single argument, other arguments ignored");
654         }
655
656         /* we are only matching a single message?  or already inside a match-all? */
657         if (search->current) {
658                 d(printf("matching against 1 message: %s\n", camel_message_info_subject(search->current)));
659                 
660                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
661                 r->value.bool = FALSE;
662
663                 if (argc>0) {
664                         r1 = e_sexp_term_eval(f, argv[0]);
665                         if (r1->type == ESEXP_RES_BOOL) {
666                                 r->value.bool = r1->value.bool;
667                         } else {
668                                 g_warning("invalid syntax, matches require a single bool result");
669                                 error_msg = g_strdup_printf(_("(%s) requires a single bool result"), "match-all");
670                                 e_sexp_fatal_error(f, error_msg);
671                                 g_free(error_msg);
672                         }
673                         e_sexp_result_free(f, r1);
674                 } else {
675                         r->value.bool = TRUE;
676                 }
677                 return r;
678         }
679
680         r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
681         r->value.ptrarray = g_ptr_array_new();
682
683         if (search->summary == NULL) {
684                 /* TODO: make it work - e.g. use the folder and so forth for a slower search */
685                 g_warning("No summary supplied, match-all doesn't work with no summary");
686                 g_assert(0);
687                 return r;
688         }
689 #if 0
690         v = search->summary_set?search->summary_set:search->summary;
691         
692         if (v->len - g_hash_table_size (search->folder->summary->loaded_infos) > 50 && !CAMEL_IS_VEE_FOLDER (search->folder)) {
693                 /* Load the DB contents. FIXME this 100 needs to be a better threshold to reload from DB. */
694                 #warning "handle exception"
695                 camel_folder_summary_reload_from_db (search->folder->summary, NULL);
696         } 
697
698 #endif  
699         e_sexp_term_eval (f, argv [0]);
700 #if 0
701         for (i=0;i<v->len;i++) {
702                 const char *uid;
703
704                 search->current = camel_folder_summary_uid (search->folder->summary, v->pdata[i]);
705                 uid = camel_message_info_uid(search->current);
706
707                 if (argc>0) {
708                         r1 = e_sexp_term_eval(f, argv[0]);
709                         if (r1->type == ESEXP_RES_BOOL) {
710                                 if (r1->value.bool)
711                                         g_ptr_array_add(r->value.ptrarray, (char *)uid);
712                         } else {
713                                 g_warning("invalid syntax, matches require a single bool result");
714                                 error_msg = g_strdup_printf(_("(%s) requires a single bool result"), "match-all");
715                                 e_sexp_fatal_error(f, error_msg);
716                                 g_free(error_msg);
717                         }
718                         e_sexp_result_free(f, r1);
719                 } else {
720                         g_ptr_array_add(r->value.ptrarray, (char *)uid);
721                 }
722                 camel_message_info_free (search->current);
723         }
724 #endif  
725         search->current = NULL;
726         return r;
727 }
728
729 //FIXME Check threads mis
730 static void
731 fill_thread_table(struct _CamelFolderThreadNode *root, GHashTable *id_hash)
732 {
733         while (root) {
734                 g_hash_table_insert(id_hash, (char *)camel_message_info_uid(root->message), root);
735                 if (root->child)
736                         fill_thread_table(root->child, id_hash);
737                 root = root->next;
738         }
739 }
740
741 static void
742 add_thread_results(struct _CamelFolderThreadNode *root, GHashTable *result_hash)
743 {
744         while (root) {
745                 g_hash_table_insert(result_hash, (char *)camel_message_info_uid(root->message), GINT_TO_POINTER (1));
746                 if (root->child)
747                         add_thread_results(root->child, result_hash);
748                 root = root->next;
749         }
750 }
751
752 static void
753 add_results(char *uid, void *dummy, GPtrArray *result)
754 {
755         g_ptr_array_add(result, uid);
756 }
757
758 static ESExpResult *
759 search_match_threads(struct _ESExp *f, int argc, struct _ESExpTerm **argv, CamelFolderSearch *search)
760 {
761         ESExpResult *r;
762         struct _CamelFolderSearchPrivate *p = search->priv;
763         int i, type;
764         GHashTable *results;
765         gchar *error_msg;
766
767         /* not supported in match-all */
768         if (search->current) {
769                 error_msg = g_strdup_printf(_("(%s) not allowed inside %s"), "match-threads", "match-all");
770                 e_sexp_fatal_error(f, error_msg);
771                 g_free(error_msg);
772         }
773
774         if (argc == 0) {
775                 error_msg = g_strdup_printf(_("(%s) requires a match type string"), "match-threads");
776                 e_sexp_fatal_error(f, error_msg);
777                 g_free(error_msg);
778         }
779
780         r = e_sexp_term_eval(f, argv[0]);
781         if (r->type != ESEXP_RES_STRING) {
782                 error_msg = g_strdup_printf(_("(%s) requires a match type string"), "match-threads");
783                 e_sexp_fatal_error(f, error_msg);
784                 g_free(error_msg);
785         }
786
787         type = 0;
788         if (!strcmp(r->value.string, "none"))
789                 type = 0;
790         else if (!strcmp(r->value.string, "all"))
791                 type = 1;
792         else if (!strcmp(r->value.string, "replies"))
793                 type = 2;
794         else if (!strcmp(r->value.string, "replies_parents"))
795                 type = 3;
796         else if (!strcmp(r->value.string, "single"))
797                 type = 4;
798         e_sexp_result_free(f, r);
799
800         /* behave as (begin does */
801         r = NULL;
802         for (i=1;i<argc;i++) {
803                 if (r)
804                         e_sexp_result_free(f, r);
805                 r = e_sexp_term_eval(f, argv[i]);
806         }
807
808         if (r == NULL || r->type != ESEXP_RES_ARRAY_PTR) {
809                 error_msg = g_strdup_printf(_("(%s) expects an array result"), "match-threads");
810                 e_sexp_fatal_error(f, error_msg);
811                 g_free(error_msg);
812         }
813
814         if (type == 0)
815                 return r;
816
817         if (search->folder == NULL) {
818                 error_msg = g_strdup_printf(_("(%s) requires the folder set"), "match-threads");
819                 e_sexp_fatal_error(f, error_msg);
820                 g_free(error_msg);
821         }
822
823         /* cache this, so we only have to re-calculate once per search at most */
824         #warning "make search threads work well. Not sure if that works"
825         if (p->threads == NULL) {
826                 p->threads = camel_folder_thread_messages_new(search->folder, NULL, TRUE);
827                 p->threads_hash = g_hash_table_new(g_str_hash, g_str_equal);
828
829                 fill_thread_table(p->threads->tree, p->threads_hash);
830         }
831
832         results = g_hash_table_new(g_str_hash, g_str_equal);
833         for (i=0;i<r->value.ptrarray->len;i++) {
834                 struct _CamelFolderThreadNode *node, *scan;
835
836                 if (type != 4)
837                         g_hash_table_insert(results, g_ptr_array_index(r->value.ptrarray, i), GINT_TO_POINTER(1));
838
839                 node = g_hash_table_lookup(p->threads_hash, (char *)g_ptr_array_index(r->value.ptrarray, i));
840                 if (node == NULL) /* this shouldn't happen but why cry over spilt milk */
841                         continue;
842
843                 /* select messages in thread according to search criteria */
844                 if (type == 4) {
845                         if (node->child == NULL && node->parent == NULL)
846                                 g_hash_table_insert(results, (char *)camel_message_info_uid(node->message), GINT_TO_POINTER(1));
847                 } else {
848                         if (type == 3) {
849                                 scan = node;
850                                 while (scan && scan->parent) {
851                                         scan = scan->parent;
852                                         g_hash_table_insert(results, (char *)camel_message_info_uid(scan->message), GINT_TO_POINTER(1));
853                                 }
854                         } else if (type == 1) {
855                                 while (node && node->parent)
856                                         node = node->parent;
857                         }
858                         g_hash_table_insert(results, (char *)camel_message_info_uid(node->message), GINT_TO_POINTER(1));
859                         if (node->child)
860                                 add_thread_results(node->child, results);
861                 }
862         }
863         e_sexp_result_free(f, r);
864
865         r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
866         r->value.ptrarray = g_ptr_array_new();
867
868         g_hash_table_foreach(results, (GHFunc)add_results, r->value.ptrarray);
869         g_hash_table_destroy(results);
870
871         return r;
872 }
873
874 static ESExpResult *
875 check_header_deprecated (struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search, camel_search_match_t how)
876 {
877         ESExpResult *r;
878         int truth = FALSE;
879
880         r(printf("executing check-header %d\n", how));
881
882         /* are we inside a match-all? */
883         if (search->current && argc>1
884             && argv[0]->type == ESEXP_RES_STRING) {
885                 char *headername;
886                 const char *header = NULL;
887                 char strbuf[32];
888                 int i, j;
889                 camel_search_t type = CAMEL_SEARCH_TYPE_ASIS;
890                 struct _camel_search_words *words;
891
892                 /* only a subset of headers are supported .. */
893                 headername = argv[0]->value.string;
894                 if (!g_ascii_strcasecmp(headername, "subject")) {
895                         header = camel_message_info_subject(search->current);
896                 } else if (!g_ascii_strcasecmp(headername, "date")) {
897                         /* FIXME: not a very useful form of the date */
898                         sprintf(strbuf, "%d", (int)camel_message_info_date_sent(search->current));
899                         header = strbuf;
900                 } else if (!g_ascii_strcasecmp(headername, "from")) {
901                         header = camel_message_info_from(search->current);
902                         type = CAMEL_SEARCH_TYPE_ADDRESS;
903                 } else if (!g_ascii_strcasecmp(headername, "to")) {
904                         header = camel_message_info_to(search->current);
905                         type = CAMEL_SEARCH_TYPE_ADDRESS;
906                 } else if (!g_ascii_strcasecmp(headername, "cc")) {
907                         header = camel_message_info_cc(search->current);
908                         type = CAMEL_SEARCH_TYPE_ADDRESS;
909                 } else if (!g_ascii_strcasecmp(headername, "x-camel-mlist")) {
910                         header = camel_message_info_mlist(search->current);
911                         type = CAMEL_SEARCH_TYPE_MLIST;
912                 } else {
913                         e_sexp_resultv_free(f, argc, argv);
914                         e_sexp_fatal_error(f, _("Performing query on unknown header: %s"), headername);
915                 }
916
917                 if (header == NULL)
918                         header = "";
919
920                 /* performs an OR of all words */
921                 for (i=1;i<argc && !truth;i++) {
922                         if (argv[i]->type == ESEXP_RES_STRING) {
923                                 if (argv[i]->value.string[0] == 0) {
924                                         truth = TRUE;
925                                 } else if (how == CAMEL_SEARCH_MATCH_CONTAINS) {
926                                         /* doesn't make sense to split words on anything but contains i.e. we can't have an ending match different words */
927                                         words = camel_search_words_split((const unsigned char *) argv[i]->value.string);
928                                         truth = TRUE;
929                                         for (j=0;j<words->len && truth;j++) {
930                                                 truth = camel_search_header_match(header, words->words[j]->word, how, type, NULL);
931                                         }
932                                         camel_search_words_free(words);
933                                 } else {
934                                         truth = camel_search_header_match(header, argv[i]->value.string, how, type, NULL);
935                                 }
936                         }
937                 }
938         }
939         /* TODO: else, find all matches */
940
941         r = e_sexp_result_new(f, ESEXP_RES_BOOL);
942         r->value.bool = truth;
943
944         return r;
945 }
946
947 /*
948 static void 
949 l_printf(char *node)
950 {
951 printf("%s\t", node);
952 }
953 */
954
955 static ESExpResult *
956 check_header (struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search, camel_search_match_t how)
957 {
958         /* FIXME: What to do for headers that are not stored in db */
959
960         ESExpResult *r;
961
962         if (strlen (argv [1]->value.string) > 1) {
963
964                 char *value;
965                 char *temp=NULL;
966                 char *column;
967
968                 column = camel_db_get_column_name (argv [0]->value.string);
969
970                 switch (how) {
971                         case CAMEL_SEARCH_MATCH_EXACT:
972                                 temp = g_strdup_printf ("%s", argv [1]->value.string);
973                                 break;
974                         case CAMEL_SEARCH_MATCH_CONTAINS:
975                         case CAMEL_SEARCH_MATCH_SOUNDEX:
976                                 temp = g_strdup_printf ("%%%s%%", argv [1]->value.string);
977                                 break;
978                         case CAMEL_SEARCH_MATCH_STARTS:
979                                 temp = g_strdup_printf ("%s%%", argv [1]->value.string);
980                                 break;
981                         case CAMEL_SEARCH_MATCH_ENDS:
982                                 temp = g_strdup_printf ("%%%s", argv [1]->value.string);
983                                 break;
984                 }
985
986                 value = camel_db_sqlize_string (temp);
987                 g_free (temp);
988
989                 if (g_str_has_suffix (search->query->str, " "))
990                         g_string_append_printf (search->query, "WHERE %s LIKE %s", column, value);
991                 else {
992                         if (f->operators) {
993                                 /*g_slist_foreach (f->operators, l_printf, NULL);
994                                 printf(" \n");*/
995
996                                 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);
997                                 f->operators = g_slist_remove_link (f->operators, (g_slist_nth (f->operators, (g_slist_length (f->operators) - 2))));
998                                 
999                         } else
1000                                 g_string_append_printf (search->query, " OR %s LIKE %s", column, value);
1001                 }
1002
1003                 g_free (column);
1004                 camel_db_free_sqlized_string (value);
1005         }
1006
1007         r = e_sexp_result_new(f, ESEXP_RES_BOOL);
1008         r->value.bool = FALSE;
1009
1010         return r;
1011 }
1012
1013 static ESExpResult *
1014 search_header_contains (struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1015 {
1016         return check_header(f, argc, argv, search, CAMEL_SEARCH_MATCH_CONTAINS);
1017 }
1018
1019 static ESExpResult *
1020 db_search_header_contains (struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1021 {
1022         return check_header (f, argc, argv, search, CAMEL_SEARCH_MATCH_CONTAINS);
1023 }
1024
1025 static ESExpResult *
1026 search_header_matches(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1027 {
1028         return check_header(f, argc, argv, search, CAMEL_SEARCH_MATCH_EXACT);
1029 }
1030
1031 static ESExpResult *
1032 search_header_starts_with (struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1033 {
1034         return check_header(f, argc, argv, search, CAMEL_SEARCH_MATCH_STARTS);
1035 }
1036
1037 static ESExpResult *
1038 search_header_ends_with (struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1039 {
1040         return check_header(f, argc, argv, search, CAMEL_SEARCH_MATCH_ENDS);
1041 }
1042
1043 static ESExpResult *
1044 search_header_exists (struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1045 {
1046         ESExpResult *r;
1047         
1048         r(printf ("executing header-exists\n"));
1049         
1050         if (search->current) {
1051                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
1052                 if (argc == 1 && argv[0]->type == ESEXP_RES_STRING)
1053                         r->value.bool = camel_medium_get_header(CAMEL_MEDIUM(search->current), argv[0]->value.string) != NULL;
1054                 
1055         } else {
1056                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
1057                 r->value.ptrarray = g_ptr_array_new();
1058         }
1059         
1060         return r;
1061 }
1062
1063 /* this is just to OR results together */
1064 struct _glib_sux_donkeys {
1065         int count;
1066         GPtrArray *uids;
1067 };
1068
1069 /* or, store all unique values */
1070 static void
1071 g_lib_sux_htor(char *key, int value, struct _glib_sux_donkeys *fuckup)
1072 {
1073         g_ptr_array_add(fuckup->uids, key);
1074 }
1075
1076 /* and, only store duplicates */
1077 static void
1078 g_lib_sux_htand(char *key, int value, struct _glib_sux_donkeys *fuckup)
1079 {
1080         if (value == fuckup->count)
1081                 g_ptr_array_add(fuckup->uids, key);
1082 }
1083
1084 static int
1085 match_message_index(CamelIndex *idx, const char *uid, const char *match, CamelException *ex)
1086 {
1087         CamelIndexCursor *wc, *nc;
1088         const char *word, *name;
1089         int truth = FALSE;
1090
1091         wc = camel_index_words(idx);
1092         if (wc) {
1093                 while (!truth && (word = camel_index_cursor_next(wc))) {
1094                         if (camel_ustrstrcase(word,match) != NULL) {
1095                                 /* perf: could have the wc cursor return the name cursor */
1096                                 nc = camel_index_find(idx, word);
1097                                 if (nc) {
1098                                         while (!truth && (name = camel_index_cursor_next(nc)))
1099                                                 truth = strcmp(name, uid) == 0;
1100                                         camel_object_unref((CamelObject *)nc);
1101                                 }
1102                         }
1103                 }
1104                 camel_object_unref((CamelObject *)wc);
1105         }
1106
1107         return truth;
1108 }
1109
1110 /*
1111  "one two" "three" "four five"
1112
1113   one and two
1114 or
1115   three
1116 or
1117   four and five
1118 */
1119
1120 /* returns messages which contain all words listed in words */
1121 static GPtrArray *
1122 match_words_index(CamelFolderSearch *search, struct _camel_search_words *words, CamelException *ex)
1123 {
1124         GPtrArray *result = g_ptr_array_new();
1125         GHashTable *ht = g_hash_table_new(g_str_hash, g_str_equal);
1126         struct _glib_sux_donkeys lambdafoo;
1127         CamelIndexCursor *wc, *nc;
1128         const char *word, *name;
1129         int i;
1130
1131         /* we can have a maximum of 32 words, as we use it as the AND mask */
1132                         
1133         wc = camel_index_words(search->body_index);
1134         if (wc) {
1135                 while ((word = camel_index_cursor_next(wc))) {
1136                         for (i=0;i<words->len;i++) {
1137                                 if (camel_ustrstrcase(word, words->words[i]->word) != NULL) {
1138                                         /* perf: could have the wc cursor return the name cursor */
1139                                         nc = camel_index_find(search->body_index, word);
1140                                         if (nc) {
1141                                                 while ((name = camel_index_cursor_next(nc))) {
1142                                                         int mask;
1143
1144                                                         mask = (GPOINTER_TO_INT(g_hash_table_lookup(ht, name))) | (1<<i);
1145                                                         g_hash_table_insert(ht, (char *)name, GINT_TO_POINTER(mask));
1146                                                         
1147                                                 }
1148                                                 camel_object_unref((CamelObject *)nc);
1149                                         }
1150                                 }
1151                         }
1152                 }
1153                 camel_object_unref((CamelObject *)wc);
1154
1155                 lambdafoo.uids = result;
1156                 lambdafoo.count = (1<<words->len) - 1;
1157                 g_hash_table_foreach(ht, (GHFunc)g_lib_sux_htand, &lambdafoo);
1158                 g_hash_table_destroy(ht);
1159         }
1160
1161         return result;
1162 }
1163
1164 static gboolean
1165 match_words_1message (CamelDataWrapper *object, struct _camel_search_words *words, guint32 *mask)
1166 {
1167         CamelDataWrapper *containee;
1168         int truth = FALSE;
1169         int parts, i;
1170         
1171         containee = camel_medium_get_content_object (CAMEL_MEDIUM (object));
1172         
1173         if (containee == NULL)
1174                 return FALSE;
1175         
1176         /* using the object types is more accurate than using the mime/types */
1177         if (CAMEL_IS_MULTIPART (containee)) {
1178                 parts = camel_multipart_get_number (CAMEL_MULTIPART (containee));
1179                 for (i = 0; i < parts && truth == FALSE; i++) {
1180                         CamelDataWrapper *part = (CamelDataWrapper *)camel_multipart_get_part (CAMEL_MULTIPART (containee), i);
1181                         if (part)
1182                                 truth = match_words_1message(part, words, mask);
1183                 }
1184         } else if (CAMEL_IS_MIME_MESSAGE (containee)) {
1185                 /* for messages we only look at its contents */
1186                 truth = match_words_1message((CamelDataWrapper *)containee, words, mask);
1187         } else if (camel_content_type_is(CAMEL_DATA_WRAPPER (containee)->mime_type, "text", "*")) {
1188                 /* for all other text parts, we look inside, otherwise we dont care */
1189                 CamelStreamMem *mem = (CamelStreamMem *)camel_stream_mem_new ();
1190
1191                 /* FIXME: The match should be part of a stream op */
1192                 camel_data_wrapper_decode_to_stream (containee, CAMEL_STREAM (mem));
1193                 camel_stream_write (CAMEL_STREAM (mem), "", 1);
1194                 for (i=0;i<words->len;i++) {
1195                         /* FIXME: This is horridly slow, and should use a real search algorithm */
1196                         if (camel_ustrstrcase((const char *) mem->buffer->data, words->words[i]->word) != NULL) {
1197                                 *mask |= (1<<i);
1198                                 /* shortcut a match */
1199                                 if (*mask == (1<<(words->len))-1)
1200                                         return TRUE;
1201                         }
1202                 }
1203                 
1204                 camel_object_unref (mem);
1205         }
1206         
1207         return truth;
1208 }
1209
1210 static gboolean
1211 match_words_message(CamelFolder *folder, const char *uid, struct _camel_search_words *words, CamelException *ex)
1212 {
1213         guint32 mask;
1214         CamelMimeMessage *msg;
1215         CamelException x = CAMEL_EXCEPTION_INITIALISER;
1216         int truth;
1217
1218         msg = camel_folder_get_message(folder, uid, &x);
1219         if (msg) {
1220                 mask = 0;
1221                 truth = match_words_1message((CamelDataWrapper *)msg, words, &mask);
1222                 camel_object_unref((CamelObject *)msg);
1223         } else {
1224                 camel_exception_clear(&x);
1225                 truth = FALSE;
1226         }
1227
1228         return truth;
1229 }
1230
1231 static GPtrArray *
1232 match_words_messages(CamelFolderSearch *search, struct _camel_search_words *words, CamelException *ex)
1233 {
1234         int i;
1235         GPtrArray *matches = g_ptr_array_new();
1236
1237         if (search->body_index) {
1238                 GPtrArray *indexed;
1239                 struct _camel_search_words *simple;
1240
1241                 simple = camel_search_words_simple(words);
1242                 indexed = match_words_index(search, simple, ex);
1243                 camel_search_words_free(simple);
1244
1245                 for (i=0;i<indexed->len;i++) {
1246                         const char *uid = g_ptr_array_index(indexed, i);
1247                         
1248                         if (match_words_message(search->folder, uid, words, ex))
1249                                 g_ptr_array_add(matches, (char *)uid);
1250                 }
1251                 
1252                 g_ptr_array_free(indexed, TRUE);
1253         } else {
1254                 GPtrArray *v = search->summary_set?search->summary_set:search->summary;
1255
1256                 for (i=0;i<v->len;i++) {
1257                         char *uid  = g_ptr_array_index(v, i);
1258                         
1259                         if (match_words_message(search->folder, uid, words, ex))
1260                                 g_ptr_array_add(matches, (char *)uid);
1261                 }
1262         }
1263
1264         return matches;
1265 }
1266
1267 static ESExpResult *
1268 search_body_contains(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1269 {
1270         int i, j;
1271         CamelException *ex = search->priv->ex;
1272         struct _camel_search_words *words;
1273         ESExpResult *r;
1274         struct _glib_sux_donkeys lambdafoo;
1275
1276         if (search->current) {  
1277                 int truth = FALSE;
1278
1279                 if (argc == 1 && argv[0]->value.string[0] == 0) {
1280                         truth = TRUE;
1281                 } else {
1282                         for (i=0;i<argc && !truth;i++) {
1283                                 if (argv[i]->type == ESEXP_RES_STRING) {
1284                                         words = camel_search_words_split((const unsigned char *) argv[i]->value.string);
1285                                         truth = TRUE;
1286                                         if ((words->type & CAMEL_SEARCH_WORD_COMPLEX) == 0 && search->body_index) {
1287                                                 for (j=0;j<words->len && truth;j++)
1288                                                         truth = match_message_index(search->body_index, camel_message_info_uid(search->current), words->words[j]->word, ex);
1289                                         } else {
1290                                                 /* TODO: cache current message incase of multiple body search terms */
1291                                                 truth = match_words_message(search->folder, camel_message_info_uid(search->current), words, ex);
1292                                         }
1293                                         camel_search_words_free(words);
1294                                 }
1295                         }
1296                 }
1297                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
1298                 r->value.bool = truth;
1299         } else {
1300                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
1301                 r->value.ptrarray = g_ptr_array_new();
1302
1303                 if (argc == 1 && argv[0]->value.string[0] == 0) {
1304                         GPtrArray *v = search->summary_set?search->summary_set:search->summary;
1305
1306                         for (i=0;i<v->len;i++) {
1307                                 char *uid = g_ptr_array_index(v, i);
1308
1309                                 g_ptr_array_add(r->value.ptrarray, uid);
1310                         }
1311                 } else {
1312                         GHashTable *ht = g_hash_table_new(g_str_hash, g_str_equal);
1313                         GPtrArray *matches;
1314
1315                         for (i=0;i<argc;i++) {
1316                                 if (argv[i]->type == ESEXP_RES_STRING) {
1317                                         words = camel_search_words_split((const unsigned char *) argv[i]->value.string);
1318                                         if ((words->type & CAMEL_SEARCH_WORD_COMPLEX) == 0 && search->body_index) {
1319                                                 matches = match_words_index(search, words, ex);
1320                                         } else {
1321                                                 matches = match_words_messages(search, words, ex);
1322                                         }
1323                                         for (j=0;j<matches->len;j++)
1324                                                 g_hash_table_insert(ht, matches->pdata[j], matches->pdata[j]);
1325                                         g_ptr_array_free(matches, TRUE);
1326                                         camel_search_words_free(words);
1327                                 }
1328                         }
1329                         lambdafoo.uids = r->value.ptrarray;
1330                         g_hash_table_foreach(ht, (GHFunc)g_lib_sux_htor, &lambdafoo);
1331                         g_hash_table_destroy(ht);
1332                 }
1333         }
1334
1335         return r;
1336 }
1337
1338 static ESExpResult *
1339 search_user_flag(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1340 {
1341                 char *value = NULL;
1342                 ESExpResult *r;
1343                 char * tmp;
1344
1345                 r(printf("\nexecuting user-flag with init str: [%s]\n", search->query->str));
1346
1347                 if (argc == 1) {
1348
1349                                 if (search->current) {
1350                                                 /* FIXME: I am not sure if this will ever be executed */
1351                                                 abort ();
1352                                 } else {
1353                                                 tmp = g_strdup_printf ("%%%s%%", argv[0]->value.string);
1354                                                 value = camel_db_sqlize_string (tmp);
1355                                                 g_free (tmp);
1356
1357                                                 if (g_str_has_suffix (search->query->str, " ")) {
1358                                                                 g_string_append_printf (search->query, "WHERE labels LIKE %s", value);
1359                                                 } else {
1360                                                                 if (f->operators) {
1361                                                                                 g_string_append_printf (search->query, " %s labels LIKE %s", (char *) (g_slist_nth_data (f->operators, 0)), value);
1362                                                                                 f->operators = g_slist_remove_link (f->operators, g_slist_nth (f->operators, 0));
1363                                                                 } else {
1364                                                                                 g_string_append_printf (search->query, " OR labels LIKE %s", value);
1365                                                                 }
1366                                                 }
1367
1368                                                 r(printf ("user-flag search value is : [%s] Appended str is : [%s]\n\n", value, search->query->str));
1369                                                 camel_db_free_sqlized_string (value);
1370                                 }
1371                 } else
1372                                 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);
1373
1374                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
1375                 r->value.bool = FALSE;
1376
1377                 return r;
1378 }
1379
1380 static ESExpResult *
1381 search_system_flag (struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1382 {
1383         ESExpResult *r;
1384         
1385         r(printf ("executing system-flag\n"));
1386         
1387         if (search->current) {
1388                 gboolean truth = FALSE;
1389                 
1390                 if (argc == 1) 
1391                         truth = camel_system_flag_get (camel_message_info_flags(search->current), argv[0]->value.string);
1392                 
1393                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
1394                 r->value.bool = truth;
1395         } else {
1396                         /* FIXME: You need to complete the camel-db.c:camel_db_get_column_name function and use those return values */
1397                         char * value = camel_db_get_column_name (argv[0]->value.string);
1398                         char *connector = "=";
1399
1400                         if (argc > 1) {
1401                                 if (! strcmp(argv[1]->value.string, "set") )
1402                                         connector = "!=";
1403                         }
1404
1405                         if (g_str_has_suffix (search->query->str, " "))
1406                                         g_string_append_printf (search->query, "WHERE (%s %s 0)", value, connector);
1407                         else {
1408                                         gboolean flag = FALSE;
1409                                         if (search->query->str [search->query->len - 1] == ')') {
1410                                                         search->query->len -= 1;
1411                                                         flag = TRUE;
1412                                         }
1413
1414                                         if (f->operators) {
1415                                                         g_string_append_printf (search->query, " %s %s %s 0", (char *) (g_slist_nth_data (f->operators, 0)), value, connector);
1416                                         }
1417                                         else
1418                                                         g_string_append_printf (search->query, " OR %s %s 0", value, connector);
1419
1420
1421                                         if (flag)
1422                                                 g_string_append (search->query,")");
1423                         }
1424
1425                         g_free (value);
1426
1427                         r = e_sexp_result_new(f, ESEXP_RES_BOOL);
1428                         r->value.bool = FALSE; 
1429         }
1430         
1431         return r;
1432 }
1433
1434 static ESExpResult *
1435 search_user_tag(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1436 {
1437                 char *value = NULL;
1438                 ESExpResult *r;
1439                 char * tmp;
1440
1441                 r(printf("executing user-tag\n"));
1442
1443                 if (argc == 2) {
1444
1445                                 if (search->current) {
1446                                                 /* FIXME: I am not sure if this will ever be executed */
1447                                                 abort ();
1448                                 } else {
1449
1450                                                 tmp = g_strdup_printf ("%s%s", argv[0]->value.string, argv[1]->value.string);
1451                                                 value = camel_db_sqlize_string (tmp);
1452                                                 g_free (tmp);
1453
1454                                                 if (g_str_has_suffix (search->query->str, " "))
1455                                                                 g_string_append_printf (search->query, "WHERE usertags = %s", value);
1456                                                 else {
1457                                                                 if (f->operators)
1458                                                                                 g_string_append_printf (search->query, " %s usertags = %s", (char *) (g_slist_nth_data (f->operators, 0)), value);
1459                                                                 else
1460                                                                                 g_string_append_printf (search->query, " OR usertags = %s", value);
1461                                                 }
1462
1463                                                 camel_db_free_sqlized_string (value);
1464
1465                                 }
1466                 } else
1467                                 g_warning ("Makes no sense to search for multiple things in user tag as it can hold only one string data : [%d] ", argc);
1468
1469                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
1470                 r->value.bool = TRUE;
1471
1472                 return r;
1473 }
1474
1475 static ESExpResult *
1476 search_get_sent_date(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *s)
1477 {
1478         ESExpResult *r;
1479
1480         r(printf("executing get-sent-date\n"));
1481
1482         /* are we inside a match-all? */
1483         if (s->current) {
1484                 r = e_sexp_result_new(f, ESEXP_RES_INT);
1485
1486                 r->value.number = camel_message_info_date_sent(s->current);
1487         } else {
1488                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
1489                 r->value.ptrarray = g_ptr_array_new ();
1490         }
1491
1492         return r;
1493 }
1494
1495 static ESExpResult *
1496 search_get_received_date(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *s)
1497 {
1498         ESExpResult *r;
1499
1500         r(printf("executing get-received-date\n"));
1501
1502         /* are we inside a match-all? */
1503         if (s->current) {
1504                 r = e_sexp_result_new(f, ESEXP_RES_INT);
1505
1506                 r->value.number = camel_message_info_date_received(s->current);
1507         } else {
1508                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
1509                 r->value.ptrarray = g_ptr_array_new ();
1510         }
1511
1512         return r;
1513 }
1514
1515 static ESExpResult *
1516 search_get_current_date(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *s)
1517 {
1518         ESExpResult *r;
1519
1520         r(printf("executing get-current-date\n"));
1521
1522         r = e_sexp_result_new(f, ESEXP_RES_INT);
1523         r->value.number = time (NULL);
1524         return r;
1525 }
1526
1527 static ESExpResult *
1528 search_get_size (struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *s)
1529 {
1530         ESExpResult *r;
1531         
1532         r(printf("executing get-size\n"));
1533         
1534         /* are we inside a match-all? */
1535         if (s->current) {
1536                 r = e_sexp_result_new (f, ESEXP_RES_INT);
1537                 r->value.number = camel_message_info_size(s->current) / 1024;
1538         } else {
1539                 r = e_sexp_result_new (f, ESEXP_RES_ARRAY_PTR);
1540                 r->value.ptrarray = g_ptr_array_new ();
1541         }
1542         
1543         return r;
1544 }
1545
1546 static ESExpResult *
1547 search_uid(struct _ESExp *f, int argc, struct _ESExpResult **argv, CamelFolderSearch *search)
1548 {
1549         ESExpResult *r;
1550         int i;
1551
1552         r(printf("executing uid\n"));
1553
1554         /* are we inside a match-all? */
1555         if (search->current) {
1556                 int truth = FALSE;
1557                 const char *uid = camel_message_info_uid(search->current);
1558
1559                 /* performs an OR of all words */
1560                 for (i=0;i<argc && !truth;i++) {
1561                         if (argv[i]->type == ESEXP_RES_STRING
1562                             && !strcmp(uid, argv[i]->value.string)) {
1563                                 truth = TRUE;
1564                                 break;
1565                         }
1566                 }
1567                 r = e_sexp_result_new(f, ESEXP_RES_BOOL);
1568                 r->value.bool = truth;
1569         } else {
1570                 r = e_sexp_result_new(f, ESEXP_RES_ARRAY_PTR);
1571                 r->value.ptrarray = g_ptr_array_new();
1572                 for (i=0;i<argc;i++) {
1573                         if (argv[i]->type == ESEXP_RES_STRING)
1574                                 g_ptr_array_add(r->value.ptrarray, argv[i]->value.string);
1575                 }
1576         }
1577
1578         return r;
1579 }
1580
1581 static int 
1582 read_uid_callback (void * ref, int ncol, char ** cols, char **name)
1583 {
1584         GPtrArray *matches;
1585
1586         matches = (GPtrArray *) ref;
1587
1588 #if 0
1589
1590         int i;
1591         for (i = 0; i < ncol; ++i) {
1592                 if ( !strcmp (name [i], "uid") ) 
1593                         g_ptr_array_add (matches, g_strdup (cols [i]));
1594         }
1595 #else
1596         g_ptr_array_add (matches, (GFunc) camel_pstring_strdup (cols [0]));
1597 #endif
1598         return 0;
1599 }