Fix bug #2875, "SMTP session disconnects before recieving multi-line
[claws.git] / src / advsearch.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 2012 the Claws Mail team
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 3 of the License, or
8  * (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program. If not, see <http://www.gnu.org/licenses/>.
17  * 
18  */
19
20 #ifdef HAVE_CONFIG_H
21 # include "config.h"
22 # include "claws-features.h"
23 #endif
24
25 #include "advsearch.h"
26
27 #include <glib.h>
28 #include <ctype.h>
29
30 #include "matcher.h"
31 #include "matcher_parser.h"
32 #include "utils.h"
33 #include "prefs_common.h"
34
35 struct _AdvancedSearch {
36         struct {
37                 AdvancedSearchType       type;
38                 gchar                   *matchstring;
39         } request;
40
41         MatcherList                     *predicate;
42         gboolean                         is_fast;
43         gboolean                         search_aborted;
44
45         struct {
46                 gboolean (*cb)(gpointer data, guint at, guint matched, guint total);
47                 gpointer data;
48         } on_progress_cb;
49         struct {
50                 void (*cb)(gpointer data);
51                 gpointer data;
52         } on_error_cb;
53 };
54
55 void advsearch_set_on_progress_cb(AdvancedSearch *search, gboolean (*cb)(gpointer, guint, guint, guint), gpointer data)
56 {
57         search->on_progress_cb.cb = cb;
58         search->on_progress_cb.data = data;
59 }
60
61 void advsearch_set_on_error_cb(AdvancedSearch* search, void (*cb)(gpointer data), gpointer data)
62 {
63         search->on_error_cb.cb = cb;
64         search->on_error_cb.data = data;
65 }
66
67 static void prepare_matcher(AdvancedSearch *search);
68 static gboolean search_impl(MsgInfoList **messages, AdvancedSearch* search,
69                             FolderItem* folderItem, gboolean recursive);
70
71 // --------------------------
72
73 AdvancedSearch* advsearch_new()
74 {
75         AdvancedSearch *result;
76
77         result = g_new0(AdvancedSearch, 1);
78
79         return result;
80 }
81
82 void advsearch_free(AdvancedSearch *search)
83 {
84         if (search->predicate != NULL)
85                 matcherlist_free(search->predicate);
86
87         g_free(search->request.matchstring);
88         g_free(search);
89 }
90
91 void advsearch_set(AdvancedSearch *search, AdvancedSearchType type, const gchar *matchstring)
92 {
93         cm_return_if_fail(search != NULL);
94
95         search->request.type = type;
96
97         g_free(search->request.matchstring);
98         search->request.matchstring = g_strdup(matchstring);
99
100         prepare_matcher(search);
101 }
102
103 gboolean advsearch_is_fast(AdvancedSearch *search)
104 {
105         cm_return_val_if_fail(search != NULL, FALSE);
106
107         return search->is_fast;
108 }
109
110 gboolean advsearch_has_proper_predicate(AdvancedSearch *search)
111 {
112         cm_return_val_if_fail(search != NULL, FALSE);
113
114         return search->predicate != NULL;
115 }
116
117 gboolean advsearch_search_msgs_in_folders(AdvancedSearch* search, MsgInfoList **messages,
118                                           FolderItem* folderItem, gboolean recursive)
119 {
120         if (search == NULL || search->predicate == NULL)
121                 return FALSE;
122
123         search->search_aborted = FALSE;
124         return search_impl(messages, search, folderItem, recursive);
125 }
126
127 void advsearch_abort(AdvancedSearch *search)
128 {
129         search->search_aborted = TRUE;
130 }
131
132 gchar *advsearch_expand_search_string(const gchar *search_string)
133 {
134         int i = 0;
135         gchar term_char, save_char;
136         gchar *cmd_start, *cmd_end;
137         GString *matcherstr;
138         gchar *returnstr = NULL;
139         gchar *copy_str;
140         gboolean casesens, dontmatch, regex;
141         /* list of allowed pattern abbreviations */
142         struct {
143                 gchar           *abbreviated;   /* abbreviation */
144                 gchar           *command;       /* actual matcher command */
145                 gint            numparams;      /* number of params for cmd */
146                 gboolean        qualifier;      /* do we append stringmatch operations */
147                 gboolean        quotes;         /* do we need quotes */
148         }
149         cmds[] = {
150                 { "a",  "all",                          0,      FALSE,  FALSE },
151                 { "ag", "age_greater",                  1,      FALSE,  FALSE },
152                 { "al", "age_lower",                    1,      FALSE,  FALSE },
153                 { "agh","age_greater_hours",            1,      FALSE,  FALSE },
154                 { "alh","age_lower_hours",              1,      FALSE,  FALSE },
155                 { "b",  "body_part",                    1,      TRUE,   TRUE  },
156                 { "B",  "message",                      1,      TRUE,   TRUE  },
157                 { "c",  "cc",                           1,      TRUE,   TRUE  },
158                 { "C",  "to_or_cc",                     1,      TRUE,   TRUE  },
159                 { "D",  "deleted",                      0,      FALSE,  FALSE },
160                 { "e",  "header \"Sender\"",            1,      TRUE,   TRUE  },
161                 { "E",  "execute",                      1,      FALSE,  TRUE  },
162                 { "f",  "from",                         1,      TRUE,   TRUE  },
163                 { "F",  "forwarded",                    0,      FALSE,  FALSE },
164                 { "h",  "headers_part",                 1,      TRUE,   TRUE  },
165                 { "ha", "has_attachments",              0,      FALSE,  FALSE },
166                 { "i",  "header \"Message-ID\"",        1,      TRUE,   TRUE  },
167                 { "I",  "inreplyto",                    1,      TRUE,   TRUE  },
168                 { "k",  "colorlabel",                   1,      FALSE,  FALSE },
169                 { "L",  "locked",                       0,      FALSE,  FALSE },
170                 { "n",  "newsgroups",                   1,      TRUE,   TRUE  },
171                 { "N",  "new",                          0,      FALSE,  FALSE },
172                 { "O",  "~new",                         0,      FALSE,  FALSE },
173                 { "r",  "replied",                      0,      FALSE,  FALSE },
174                 { "R",  "~unread",                      0,      FALSE,  FALSE },
175                 { "s",  "subject",                      1,      TRUE,   TRUE  },
176                 { "se", "score_equal",                  1,      FALSE,  FALSE },
177                 { "sg", "score_greater",                1,      FALSE,  FALSE },
178                 { "sl", "score_lower",                  1,      FALSE,  FALSE },
179                 { "Se", "size_equal",                   1,      FALSE,  FALSE },
180                 { "Sg", "size_greater",                 1,      FALSE,  FALSE },
181                 { "Ss", "size_smaller",                 1,      FALSE,  FALSE },
182                 { "t",  "to",                           1,      TRUE,   TRUE  },
183                 { "tg", "tag",                          1,      TRUE,   TRUE  },
184                 { "T",  "marked",                       0,      FALSE,  FALSE },
185                 { "U",  "unread",                       0,      FALSE,  FALSE },
186                 { "x",  "header \"References\"",        1,      TRUE,   TRUE  },
187                 { "X",  "test",                         1,      FALSE,  FALSE },
188                 { "y",  "header \"X-Label\"",           1,      TRUE,   TRUE  },
189                 { "&",  "&",                            0,      FALSE,  FALSE },
190                 { "|",  "|",                            0,      FALSE,  FALSE },
191                 { "p",  "partial",                      0,      FALSE,  FALSE },
192                 { NULL, NULL,                           0,      FALSE,  FALSE }
193         };
194
195         if (search_string == NULL)
196                 return NULL;
197
198         copy_str = g_strdup(search_string);
199
200         matcherstr = g_string_sized_new(16);
201         cmd_start = copy_str;
202         while (cmd_start && *cmd_start) {
203                 /* skip all white spaces */
204                 while (*cmd_start && isspace((guchar)*cmd_start))
205                         cmd_start++;
206                 cmd_end = cmd_start;
207
208                 /* extract a command */
209                 while (*cmd_end && !isspace((guchar)*cmd_end))
210                         cmd_end++;
211
212                 /* save character */
213                 save_char = *cmd_end;
214                 *cmd_end = '\0';
215
216                 dontmatch = FALSE;
217                 casesens = FALSE;
218                 regex = FALSE;
219
220                 /* ~ and ! mean logical NOT */
221                 if (*cmd_start == '~' || *cmd_start == '!')
222                 {
223                         dontmatch = TRUE;
224                         cmd_start++;
225                 }
226                 /* % means case sensitive match */
227                 if (*cmd_start == '%')
228                 {
229                         casesens = TRUE;
230                         cmd_start++;
231                 }
232                 /* # means regex match */
233                 if (*cmd_start == '#') {
234                         regex = TRUE;
235                         cmd_start++;
236                 }
237
238                 /* find matching abbreviation */
239                 for (i = 0; cmds[i].command; i++) {
240                         if (!strcmp(cmd_start, cmds[i].abbreviated)) {
241                                 /* restore character */
242                                 *cmd_end = save_char;
243
244                                 /* copy command */
245                                 if (matcherstr->len > 0) {
246                                         g_string_append(matcherstr, " ");
247                                 }
248                                 if (dontmatch)
249                                         g_string_append(matcherstr, "~");
250                                 g_string_append(matcherstr, cmds[i].command);
251                                 g_string_append(matcherstr, " ");
252
253                                 /* stop if no params required */
254                                 if (cmds[i].numparams == 0)
255                                         break;
256
257                                 /* extract a parameter, allow quotes */
258                                 while (*cmd_end && isspace((guchar)*cmd_end))
259                                         cmd_end++;
260
261                                 cmd_start = cmd_end;
262                                 if (*cmd_start == '"') {
263                                         term_char = '"';
264                                         cmd_end++;
265                                 }
266                                 else
267                                         term_char = ' ';
268
269                                 /* extract actual parameter */
270                                 while ((*cmd_end) && (*cmd_end != term_char))
271                                         cmd_end++;
272
273                                 if (*cmd_end == '"')
274                                         cmd_end++;
275
276                                 save_char = *cmd_end;
277                                 *cmd_end = '\0';
278
279                                 if (cmds[i].qualifier) {
280                                         if (casesens)
281                                                 g_string_append(matcherstr, regex ? "regexp " : "match ");
282                                         else
283                                                 g_string_append(matcherstr, regex ? "regexpcase " : "matchcase ");
284                                 }
285
286                                 /* do we need to add quotes ? */
287                                 if (cmds[i].quotes && term_char != '"')
288                                         g_string_append(matcherstr, "\"");
289
290                                 /* copy actual parameter */
291                                 g_string_append(matcherstr, cmd_start);
292
293                                 /* do we need to add quotes ? */
294                                 if (cmds[i].quotes && term_char != '"')
295                                         g_string_append(matcherstr, "\"");
296
297                                 /* restore original character */
298                                 *cmd_end = save_char;
299
300                                 break;
301                         }
302                 }
303
304                 if (*cmd_end)
305                         cmd_end++;
306                 cmd_start = cmd_end;
307         }
308
309         g_free(copy_str);
310
311         /* return search string if no match is found to allow
312            all available filtering expressions in advanced search */
313         if (matcherstr->len > 0) returnstr = matcherstr->str;
314         else returnstr = g_strdup(search_string);
315         g_string_free(matcherstr, FALSE);
316         return returnstr;
317 }
318
319 static void prepare_matcher_extended(AdvancedSearch *search)
320 {
321         gchar *newstr = advsearch_expand_search_string(search->request.matchstring);
322
323         if (newstr && newstr[0] != '\0') {
324                 search->predicate = matcher_parser_get_cond(newstr, &search->is_fast);
325                 g_free(newstr);
326         }
327 }
328
329 #define debug_matcher_list(prefix, list)                                        \
330 do {                                                                            \
331         gchar *str = list ? matcherlist_to_string(list) : g_strdup("(NULL)");   \
332                                                                                 \
333         debug_print("%s: %s\n", prefix, str);                                   \
334                                                                                 \
335         g_free(str);                                                            \
336 } while(0)
337
338 static void prepare_matcher_tag(AdvancedSearch *search)
339 {
340         gchar **words = search->request.matchstring 
341                         ? g_strsplit(search->request.matchstring, " ", -1)
342                         : NULL;
343         gint i = 0;
344
345         if (search->predicate == NULL) {
346                 search->predicate = g_new0(MatcherList, 1);
347                 search->predicate->bool_and = FALSE;
348                 search->is_fast = TRUE;
349         }
350
351         while (words && words[i] && *words[i]) {
352                 MatcherProp *matcher;
353
354                 g_strstrip(words[i]);
355
356                 matcher = matcherprop_new(MATCHCRITERIA_TAG, NULL,
357                                           MATCHTYPE_MATCHCASE, words[i], 0);
358
359                 search->predicate->matchers = g_slist_prepend(search->predicate->matchers, matcher);
360
361                 i++;
362         }
363         g_strfreev(words);
364 }
365
366 static void prepare_matcher_header(AdvancedSearch *search, gint match_header)
367 {
368         MatcherProp *matcher;
369
370         if (search->predicate == NULL) {
371                 search->predicate = g_new0(MatcherList, 1);
372                 search->predicate->bool_and = FALSE;
373                 search->is_fast = TRUE;
374         }
375
376         matcher = matcherprop_new(match_header, NULL, MATCHTYPE_MATCHCASE,
377                         search->request.matchstring, 0);
378
379         search->predicate->matchers = g_slist_prepend(search->predicate->matchers, matcher);
380 }
381
382 static void prepare_matcher_mixed(AdvancedSearch *search)
383 {
384         prepare_matcher_tag(search);
385         debug_matcher_list("tag matcher list", search->predicate);
386
387         /* we want an OR search */
388         if (search->predicate)
389                 search->predicate->bool_and = FALSE;
390
391         prepare_matcher_header(search, MATCHCRITERIA_SUBJECT);
392         debug_matcher_list("tag + subject matcher list", search->predicate);
393         prepare_matcher_header(search, MATCHCRITERIA_FROM);
394         debug_matcher_list("tag + subject + from matcher list", search->predicate);
395         prepare_matcher_header(search, MATCHCRITERIA_TO);
396         debug_matcher_list("tag + subject + from + to matcher list", search->predicate);
397 }
398
399 static void prepare_matcher(AdvancedSearch *search)
400 {
401         const gchar *search_string;
402
403         cm_return_if_fail(search != NULL);
404
405         if (search->predicate) {
406                 matcherlist_free(search->predicate);
407                 search->predicate = NULL;
408         }
409
410         search_string = search->request.matchstring;
411
412         if (search_string == NULL || search_string[0] == '\0')
413                 return;
414
415         switch (search->request.type) {
416                 case ADVANCED_SEARCH_SUBJECT:
417                         prepare_matcher_header(search, MATCHCRITERIA_SUBJECT);
418                         debug_matcher_list("subject search", search->predicate);
419                         break;
420
421                 case ADVANCED_SEARCH_FROM:
422                         prepare_matcher_header(search, MATCHCRITERIA_FROM);
423                         debug_matcher_list("from search", search->predicate);
424                         break;
425
426                 case ADVANCED_SEARCH_TO:
427                         prepare_matcher_header(search, MATCHCRITERIA_TO);
428                         debug_matcher_list("to search", search->predicate);
429                         break;
430
431                 case ADVANCED_SEARCH_TAG:
432                         prepare_matcher_tag(search);
433                         debug_matcher_list("tag search", search->predicate);
434                         break;
435
436                 case ADVANCED_SEARCH_MIXED:
437                         prepare_matcher_mixed(search);
438                         debug_matcher_list("mixed search", search->predicate);
439                         break;
440
441                 case ADVANCED_SEARCH_EXTENDED:
442                         prepare_matcher_extended(search);
443                         debug_matcher_list("extended search", search->predicate);
444                         break;
445
446                 default:
447                         debug_print("unknown search type (%d)\n", search->request.type);
448                         break;
449         }
450 }
451
452 static gboolean search_progress_notify_cb(gpointer data, gboolean on_server, guint at,
453                 guint matched, guint total)
454 {
455         AdvancedSearch *search = (AdvancedSearch*) data;
456
457         if (search->search_aborted)
458                 return FALSE;
459
460         if (on_server || search->on_progress_cb.cb == NULL)
461                 return TRUE;
462
463         return search->on_progress_cb.cb(search->on_progress_cb.data, at, matched, total);
464 }
465
466 static gboolean search_filter_folder(MsgNumberList **msgnums, AdvancedSearch *search,
467                                           FolderItem *folderItem, gboolean onServer)
468 {
469         gint matched;
470         gboolean tried_server = onServer;
471
472         matched = folder_item_search_msgs(folderItem->folder,
473                 folderItem,
474                 msgnums,
475                 &onServer,
476                 search->predicate,
477                 search_progress_notify_cb,
478                 search);
479
480         if (matched < 0) {
481                 if (search->on_error_cb.cb != NULL)
482                         search->on_error_cb.cb(search->on_error_cb.data);
483                 return FALSE;
484         }
485
486         if (folderItem->folder->klass->supports_server_search && tried_server && !onServer) {
487                 return search_filter_folder(msgnums, search, folderItem, onServer);
488         } else {
489                 return TRUE;
490         }
491 }
492
493 static gboolean search_impl(MsgInfoList **messages, AdvancedSearch* search,
494                             FolderItem* folderItem, gboolean recursive)
495 {
496         if (recursive) {
497                 if (!search_impl(messages, search, folderItem, FALSE))
498                         return FALSE;
499
500                 if (folderItem->node->children != NULL && !search->search_aborted) {
501                         GNode *node;
502                         for (node = folderItem->node->children; node != NULL; node = node->next) {
503                                 FolderItem *cur = FOLDER_ITEM(node->data);
504                                 debug_print("in: %s\n", cur->path);
505                                 if (!search_impl(messages, search, cur, TRUE))
506                                         return FALSE;
507                         }
508                 }
509         } else if (!folderItem->no_select) {
510                 MsgNumberList *msgnums = NULL;
511                 MsgNumberList *cur;
512                 MsgInfoList *msgs = NULL;
513                 gboolean can_search_on_server = folderItem->folder->klass->supports_server_search;
514
515                 if (!search_filter_folder(&msgnums, search, folderItem,
516                                           can_search_on_server)) {
517                         g_slist_free(msgnums);
518                         return FALSE;
519                 }
520
521                 for (cur = msgnums; cur != NULL; cur = cur->next) {
522                         MsgInfo *msg = folder_item_get_msginfo(folderItem, GPOINTER_TO_UINT(cur->data));
523
524                         msgs = g_slist_prepend(msgs, msg);
525                 }
526
527                 while (msgs != NULL) {
528                         MsgInfoList *front = msgs;
529
530                         msgs = msgs->next;
531
532                         front->next = *messages;
533                         *messages = front;
534                 }
535
536                 g_slist_free(msgnums);
537         }
538
539         return TRUE;
540 }