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