Rename activate_privacy_system() to compose_activate_privacy_system().
[claws.git] / src / advsearch.c
1 /*
2  * Claws Mail -- a GTK+ based, lightweight, and fast e-mail client
3  * Copyright (C) 2012-2014 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                 { "da", "date_after",                   1,      FALSE,  TRUE  },
161                 { "db", "date_before",                  1,      FALSE,  TRUE  },
162                 { "e",  "header \"Sender\"",            1,      TRUE,   TRUE  },
163                 { "E",  "execute",                      1,      FALSE,  TRUE  },
164                 { "f",  "from",                         1,      TRUE,   TRUE  },
165                 { "F",  "forwarded",                    0,      FALSE,  FALSE },
166                 { "h",  "headers_part",                 1,      TRUE,   TRUE  },
167                 { "H",  "headers_cont",                 1,      TRUE,   TRUE  },
168                 { "ha", "has_attachments",              0,      FALSE,  FALSE },
169                 { "i",  "messageid",                    1,      TRUE,   TRUE  },
170                 { "I",  "inreplyto",                    1,      TRUE,   TRUE  },
171                 { "k",  "colorlabel",                   1,      FALSE,  FALSE },
172                 { "L",  "locked",                       0,      FALSE,  FALSE },
173                 { "n",  "newsgroups",                   1,      TRUE,   TRUE  },
174                 { "N",  "new",                          0,      FALSE,  FALSE },
175                 { "O",  "~new",                         0,      FALSE,  FALSE },
176                 { "r",  "replied",                      0,      FALSE,  FALSE },
177                 { "R",  "~unread",                      0,      FALSE,  FALSE },
178                 { "s",  "subject",                      1,      TRUE,   TRUE  },
179                 { "se", "score_equal",                  1,      FALSE,  FALSE },
180                 { "sg", "score_greater",                1,      FALSE,  FALSE },
181                 { "sl", "score_lower",                  1,      FALSE,  FALSE },
182                 { "Se", "size_equal",                   1,      FALSE,  FALSE },
183                 { "Sg", "size_greater",                 1,      FALSE,  FALSE },
184                 { "Ss", "size_smaller",                 1,      FALSE,  FALSE },
185                 { "t",  "to",                           1,      TRUE,   TRUE  },
186                 { "tg", "tag",                          1,      TRUE,   TRUE  },
187                 { "T",  "marked",                       0,      FALSE,  FALSE },
188                 { "U",  "unread",                       0,      FALSE,  FALSE },
189                 { "x",  "references",                   1,      TRUE,   TRUE  },
190                 { "X",  "test",                         1,      FALSE,  FALSE },
191                 { "y",  "header \"X-Label\"",           1,      TRUE,   TRUE  },
192                 { "&",  "&",                            0,      FALSE,  FALSE },
193                 { "|",  "|",                            0,      FALSE,  FALSE },
194                 { "p",  "partial",                      0,      FALSE,  FALSE },
195                 { NULL, NULL,                           0,      FALSE,  FALSE }
196         };
197
198         if (search_string == NULL)
199                 return NULL;
200
201         copy_str = g_strdup(search_string);
202
203         matcherstr = g_string_sized_new(16);
204         cmd_start = copy_str;
205         while (cmd_start && *cmd_start) {
206                 /* skip all white spaces */
207                 while (*cmd_start && isspace((guchar)*cmd_start))
208                         cmd_start++;
209                 cmd_end = cmd_start;
210
211                 /* extract a command */
212                 while (*cmd_end && !isspace((guchar)*cmd_end))
213                         cmd_end++;
214
215                 /* save character */
216                 save_char = *cmd_end;
217                 *cmd_end = '\0';
218
219                 dontmatch = FALSE;
220                 casesens = FALSE;
221                 regex = FALSE;
222
223                 /* ~ and ! mean logical NOT */
224                 if (*cmd_start == '~' || *cmd_start == '!')
225                 {
226                         dontmatch = TRUE;
227                         cmd_start++;
228                 }
229                 /* % means case sensitive match */
230                 if (*cmd_start == '%')
231                 {
232                         casesens = TRUE;
233                         cmd_start++;
234                 }
235                 /* # means regex match */
236                 if (*cmd_start == '#') {
237                         regex = TRUE;
238                         cmd_start++;
239                 }
240
241                 /* find matching abbreviation */
242                 for (i = 0; cmds[i].command; i++) {
243                         if (!strcmp(cmd_start, cmds[i].abbreviated)) {
244                                 /* restore character */
245                                 *cmd_end = save_char;
246
247                                 /* copy command */
248                                 if (matcherstr->len > 0) {
249                                         g_string_append(matcherstr, " ");
250                                 }
251                                 if (dontmatch)
252                                         g_string_append(matcherstr, "~");
253                                 g_string_append(matcherstr, cmds[i].command);
254                                 g_string_append(matcherstr, " ");
255
256                                 /* stop if no params required */
257                                 if (cmds[i].numparams == 0)
258                                         break;
259
260                                 /* extract a parameter, allow quotes */
261                                 while (*cmd_end && isspace((guchar)*cmd_end))
262                                         cmd_end++;
263
264                                 cmd_start = cmd_end;
265                                 if (*cmd_start == '"') {
266                                         term_char = '"';
267                                         cmd_end++;
268                                 }
269                                 else
270                                         term_char = ' ';
271
272                                 /* extract actual parameter */
273                                 while ((*cmd_end) && (*cmd_end != term_char))
274                                         cmd_end++;
275
276                                 if (*cmd_end == '"')
277                                         cmd_end++;
278
279                                 save_char = *cmd_end;
280                                 *cmd_end = '\0';
281
282                                 if (cmds[i].qualifier) {
283                                         if (casesens)
284                                                 g_string_append(matcherstr, regex ? "regexp " : "match ");
285                                         else
286                                                 g_string_append(matcherstr, regex ? "regexpcase " : "matchcase ");
287                                 }
288
289                                 /* do we need to add quotes ? */
290                                 if (cmds[i].quotes && term_char != '"')
291                                         g_string_append(matcherstr, "\"");
292
293                                 /* copy actual parameter */
294                                 g_string_append(matcherstr, cmd_start);
295
296                                 /* do we need to add quotes ? */
297                                 if (cmds[i].quotes && term_char != '"')
298                                         g_string_append(matcherstr, "\"");
299
300                                 /* restore original character */
301                                 *cmd_end = save_char;
302
303                                 break;
304                         }
305                 }
306
307                 if (*cmd_end)
308                         cmd_end++;
309                 cmd_start = cmd_end;
310         }
311
312         g_free(copy_str);
313
314         /* return search string if no match is found to allow
315            all available filtering expressions in advanced search */
316         if (matcherstr->len > 0) {
317                 returnstr = g_string_free(matcherstr, FALSE);
318         } else {
319                 returnstr = g_strdup(search_string);
320                 g_string_free(matcherstr, TRUE);
321         }
322         return returnstr;
323 }
324
325 static void prepare_matcher_extended(AdvancedSearch *search)
326 {
327         gchar *newstr = advsearch_expand_search_string(search->request.matchstring);
328
329         if (newstr && newstr[0] != '\0') {
330                 search->predicate = matcher_parser_get_cond(newstr, &search->is_fast);
331                 g_free(newstr);
332         }
333 }
334
335 #define debug_matcher_list(prefix, list)                                        \
336 do {                                                                            \
337         gchar *str = list ? matcherlist_to_string(list) : g_strdup("(NULL)");   \
338                                                                                 \
339         debug_print("%s: %s\n", prefix, str);                                   \
340                                                                                 \
341         g_free(str);                                                            \
342 } while(0)
343
344 static void prepare_matcher_tag(AdvancedSearch *search)
345 {
346         gchar **words = search->request.matchstring 
347                         ? g_strsplit(search->request.matchstring, " ", -1)
348                         : NULL;
349         gint i = 0;
350
351         if (search->predicate == NULL) {
352                 search->predicate = g_new0(MatcherList, 1);
353                 search->predicate->bool_and = FALSE;
354                 search->is_fast = TRUE;
355         }
356
357         while (words && words[i] && *words[i]) {
358                 MatcherProp *matcher;
359
360                 g_strstrip(words[i]);
361
362                 matcher = matcherprop_new(MATCHCRITERIA_TAG, NULL,
363                                           MATCHTYPE_MATCHCASE, words[i], 0);
364
365                 search->predicate->matchers = g_slist_prepend(search->predicate->matchers, matcher);
366
367                 i++;
368         }
369         g_strfreev(words);
370 }
371
372 static void prepare_matcher_header(AdvancedSearch *search, gint match_header)
373 {
374         MatcherProp *matcher;
375
376         if (search->predicate == NULL) {
377                 search->predicate = g_new0(MatcherList, 1);
378                 search->predicate->bool_and = FALSE;
379                 search->is_fast = TRUE;
380         }
381
382         matcher = matcherprop_new(match_header, NULL, MATCHTYPE_MATCHCASE,
383                         search->request.matchstring, 0);
384
385         search->predicate->matchers = g_slist_prepend(search->predicate->matchers, matcher);
386 }
387
388 static void prepare_matcher_mixed(AdvancedSearch *search)
389 {
390         prepare_matcher_tag(search);
391         debug_matcher_list("tag matcher list", search->predicate);
392
393         /* we want an OR search */
394         if (search->predicate)
395                 search->predicate->bool_and = FALSE;
396
397         prepare_matcher_header(search, MATCHCRITERIA_SUBJECT);
398         debug_matcher_list("tag + subject matcher list", search->predicate);
399         prepare_matcher_header(search, MATCHCRITERIA_FROM);
400         debug_matcher_list("tag + subject + from matcher list", search->predicate);
401         prepare_matcher_header(search, MATCHCRITERIA_TO);
402         debug_matcher_list("tag + subject + from + to matcher list", search->predicate);
403         prepare_matcher_header(search, MATCHCRITERIA_CC);
404         debug_matcher_list("tag + subject + from + to + cc matcher list", search->predicate);
405 }
406
407 static void prepare_matcher(AdvancedSearch *search)
408 {
409         const gchar *search_string;
410
411         cm_return_if_fail(search != NULL);
412
413         if (search->predicate) {
414                 matcherlist_free(search->predicate);
415                 search->predicate = NULL;
416         }
417
418         search_string = search->request.matchstring;
419
420         if (search_string == NULL || search_string[0] == '\0')
421                 return;
422
423         switch (search->request.type) {
424                 case ADVANCED_SEARCH_SUBJECT:
425                         prepare_matcher_header(search, MATCHCRITERIA_SUBJECT);
426                         debug_matcher_list("subject search", search->predicate);
427                         break;
428
429                 case ADVANCED_SEARCH_FROM:
430                         prepare_matcher_header(search, MATCHCRITERIA_FROM);
431                         debug_matcher_list("from search", search->predicate);
432                         break;
433
434                 case ADVANCED_SEARCH_TO:
435                         prepare_matcher_header(search, MATCHCRITERIA_TO);
436                         debug_matcher_list("to search", search->predicate);
437                         break;
438
439                 case ADVANCED_SEARCH_TAG:
440                         prepare_matcher_tag(search);
441                         debug_matcher_list("tag search", search->predicate);
442                         break;
443
444                 case ADVANCED_SEARCH_MIXED:
445                         prepare_matcher_mixed(search);
446                         debug_matcher_list("mixed search", search->predicate);
447                         break;
448
449                 case ADVANCED_SEARCH_EXTENDED:
450                         prepare_matcher_extended(search);
451                         debug_matcher_list("extended search", search->predicate);
452                         break;
453
454                 default:
455                         debug_print("unknown search type (%d)\n", search->request.type);
456                         break;
457         }
458 }
459
460 static gboolean search_progress_notify_cb(gpointer data, gboolean on_server, guint at,
461                 guint matched, guint total)
462 {
463         AdvancedSearch *search = (AdvancedSearch*) data;
464
465         if (search->search_aborted)
466                 return FALSE;
467
468         if (on_server || search->on_progress_cb.cb == NULL)
469                 return TRUE;
470
471         return search->on_progress_cb.cb(search->on_progress_cb.data, at, matched, total);
472 }
473
474 static gboolean search_filter_folder(MsgNumberList **msgnums, AdvancedSearch *search,
475                                           FolderItem *folderItem, gboolean onServer)
476 {
477         gint matched;
478         gboolean tried_server = onServer;
479
480         matched = folder_item_search_msgs(folderItem->folder,
481                 folderItem,
482                 msgnums,
483                 &onServer,
484                 search->predicate,
485                 search_progress_notify_cb,
486                 search);
487
488         if (matched < 0) {
489                 if (search->on_error_cb.cb != NULL)
490                         search->on_error_cb.cb(search->on_error_cb.data);
491                 return FALSE;
492         }
493
494         if (folderItem->folder->klass->supports_server_search && tried_server && !onServer) {
495                 return search_filter_folder(msgnums, search, folderItem, onServer);
496         } else {
497                 return TRUE;
498         }
499 }
500
501 static gboolean search_impl(MsgInfoList **messages, AdvancedSearch* search,
502                             FolderItem* folderItem, gboolean recursive)
503 {
504         if (recursive) {
505                 if (!search_impl(messages, search, folderItem, FALSE))
506                         return FALSE;
507
508                 if (folderItem->node->children != NULL && !search->search_aborted) {
509                         GNode *node;
510                         for (node = folderItem->node->children; node != NULL; node = node->next) {
511                                 FolderItem *cur = FOLDER_ITEM(node->data);
512                                 debug_print("in: %s\n", cur->path);
513                                 if (!search_impl(messages, search, cur, TRUE))
514                                         return FALSE;
515                         }
516                 }
517         } else if (!folderItem->no_select) {
518                 MsgNumberList *msgnums = NULL;
519                 MsgNumberList *cur;
520                 MsgInfoList *msgs = NULL;
521                 gboolean can_search_on_server = folderItem->folder->klass->supports_server_search;
522
523                 if (!search_filter_folder(&msgnums, search, folderItem,
524                                           can_search_on_server)) {
525                         g_slist_free(msgnums);
526                         return FALSE;
527                 }
528
529                 for (cur = msgnums; cur != NULL; cur = cur->next) {
530                         MsgInfo *msg = folder_item_get_msginfo(folderItem, GPOINTER_TO_UINT(cur->data));
531
532                         msgs = g_slist_prepend(msgs, msg);
533                 }
534
535                 while (msgs != NULL) {
536                         MsgInfoList *front = msgs;
537
538                         msgs = msgs->next;
539
540                         front->next = *messages;
541                         *messages = front;
542                 }
543
544                 g_slist_free(msgnums);
545         }
546
547         return TRUE;
548 }