212b441659db00d51dfcfdbf63fd119fada04eee
[mmh] / uip / sortm.c
1
2 /*
3  * sortm.c -- sort messages in a folder by date/time
4  *
5  * $Id$
6  *
7  * This code is Copyright (c) 2002, by the authors of nmh.  See the
8  * COPYRIGHT file in the root directory of the nmh distribution for
9  * complete copyright information.
10  */
11
12 #include <h/mh.h>
13 #include <h/tws.h>
14 #include <h/utils.h>
15
16 static struct swit switches[] = {
17 #define DATESW                 0
18      { "datefield field", 0 },
19 #define TEXTSW                 1
20      { "textfield field", 0 },
21 #define NSUBJSW                2
22      { "notextfield", 0 },
23 #define SUBJSW                 3
24      { "subject", -3 },            /* backward-compatibility */
25 #define LIMSW                  4
26      { "limit days", 0 },
27 #define NLIMSW                 5
28      { "nolimit", 0 },
29 #define VERBSW                 6
30      { "verbose", 0 },
31 #define NVERBSW                7
32      { "noverbose", 0 },
33 #define VERSIONSW              8
34      { "version", 0 },
35 #define HELPSW                 9
36      { "help", 0 },
37      { NULL, 0 }
38 };
39
40 struct smsg {
41     int s_msg;
42     time_t s_clock;
43     char *s_subj;
44 };
45
46 static struct smsg *smsgs;
47 int nmsgs;
48
49 char *subjsort = (char *) 0;    /* sort on subject if != 0 */
50 unsigned long datelimit = 0;
51 int submajor = 0;               /* if true, sort on subject-major */
52 int verbose;
53
54 /* This keeps compiler happy on calls to qsort */
55 typedef int (*qsort_comp) (const void *, const void *);
56
57 /*
58  * static prototypes
59  */
60 static int read_hdrs (struct msgs *, char *);
61 static int get_fields (char *, int, struct smsg *);
62 static int dsort (struct smsg **, struct smsg **);
63 static int subsort (struct smsg **, struct smsg **);
64 static int txtsort (struct smsg **, struct smsg **);
65 static void rename_chain (struct msgs *, struct smsg **, int, int);
66 static void rename_msgs (struct msgs *, struct smsg **);
67
68
69 int
70 main (int argc, char **argv)
71 {
72     int i, msgnum;
73     unsigned char *cp;
74     char *maildir, *datesw = NULL;
75     char *folder = NULL, buf[BUFSIZ], **argp;
76     char **arguments;
77     struct msgs_array msgs = { 0, 0, NULL };
78     struct msgs *mp;
79     struct smsg **dlist;
80
81 #ifdef LOCALE
82     setlocale(LC_ALL, "");
83 #endif
84     invo_name = r1bindex (argv[0], '/');
85
86     /* read user profile/context */
87     context_read();
88
89     arguments = getarguments (invo_name, argc, argv, 1);
90     argp = arguments;
91
92     /*
93      * Parse arguments
94      */
95     while ((cp = *argp++)) {
96         if (*cp == '-') {
97             switch (smatch (++cp, switches)) {
98             case AMBIGSW:
99                 ambigsw (cp, switches);
100                 done (1);
101             case UNKWNSW:
102                 adios (NULL, "-%s unknown", cp);
103
104             case HELPSW:
105                 snprintf(buf, sizeof(buf), "%s [+folder] [msgs] [switches]",
106                         invo_name);
107                 print_help (buf, switches, 1);
108                 done (1);
109             case VERSIONSW:
110                 print_version(invo_name);
111                 done (1);
112
113             case DATESW:
114                 if (datesw)
115                     adios (NULL, "only one date field at a time");
116                 if (!(datesw = *argp++) || *datesw == '-')
117                     adios (NULL, "missing argument to %s", argp[-2]);
118                 continue;
119
120             case TEXTSW:
121                 if (subjsort)
122                     adios (NULL, "only one text field at a time");
123                 if (!(subjsort = *argp++) || *subjsort == '-')
124                     adios (NULL, "missing argument to %s", argp[-2]);
125                 continue;
126
127             case SUBJSW:
128                 subjsort = "subject";
129                 continue;
130             case NSUBJSW:
131                 subjsort = (char *)0;
132                 continue;
133
134             case LIMSW:
135                 if (!(cp = *argp++) || *cp == '-')
136                         adios (NULL, "missing argument to %s", argp[-2]);
137                 while (*cp == '0')
138                     cp++;               /* skip any leading zeros */
139                 if (!*cp) {             /* hit end of string */
140                     submajor++;         /* sort subject-major */
141                     continue;
142                 }
143                 if (!isdigit(*cp) || !(datelimit = atoi(cp)))
144                     adios (NULL, "impossible limit %s", cp);
145                 datelimit *= 60*60*24;
146                 continue;
147             case NLIMSW:
148                 submajor = 0;   /* use date-major, but */
149                 datelimit = 0;  /* use no limit */
150                 continue;
151
152             case VERBSW:
153                 verbose++;
154                 continue;
155             case NVERBSW:
156                 verbose = 0;
157                 continue;
158             }
159         }
160         if (*cp == '+' || *cp == '@') {
161             if (folder)
162                 adios (NULL, "only one folder at a time!");
163             else
164                 folder = pluspath (cp);
165         } else
166                 app_msgarg(&msgs, cp);
167     }
168
169     if (!context_find ("path"))
170         free (path ("./", TFOLDER));
171     if (!msgs.size)
172         app_msgarg(&msgs, "all");
173     if (!datesw)
174         datesw = "date";
175     if (!folder)
176         folder = getfolder (1);
177     maildir = m_maildir (folder);
178
179     if (chdir (maildir) == NOTOK)
180         adios (maildir, "unable to change directory to");
181
182     /* read folder and create message structure */
183     if (!(mp = folder_read (folder)))
184         adios (NULL, "unable to read folder %s", folder);
185
186     /* check for empty folder */
187     if (mp->nummsg == 0)
188         adios (NULL, "no messages in %s", folder);
189
190     /* parse all the message ranges/sequences and set SELECTED */
191     for (msgnum = 0; msgnum < msgs.size; msgnum++)
192         if (!m_convert (mp, msgs.msgs[msgnum]))
193             done (1);
194     seq_setprev (mp);   /* set the previous sequence */
195
196     if ((nmsgs = read_hdrs (mp, datesw)) <= 0)
197         adios (NULL, "no messages to sort");
198
199     /*
200      * sort a list of pointers to our "messages to be sorted".
201      */
202     dlist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*dlist));
203     for (i = 0; i < nmsgs; i++)
204         dlist[i] = &smsgs[i];
205     dlist[nmsgs] = 0;
206
207     if (verbose) {      /* announce what we're doing */
208         if (subjsort)
209             printf ("sorting by %s-major %s-minor\n",
210                 submajor ? subjsort : datesw,
211                 submajor ? datesw : subjsort);
212         else
213             printf ("sorting by datefield %s\n", datesw);
214     }
215
216     /* first sort by date, or by subject-major, date-minor */
217     qsort ((char *) dlist, nmsgs, sizeof(*dlist),
218             (qsort_comp) (submajor && subjsort ? txtsort : dsort));
219
220     /*
221      * if we're sorting on subject, we need another list
222      * in subject order, then a merge pass to collate the
223      * two sorts.
224      */
225     if (!submajor && subjsort) {        /* already date sorted */
226         struct smsg **slist, **flist;
227         register struct smsg ***il, **fp, **dp;
228
229         slist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*slist));
230         memcpy((char *)slist, (char *)dlist, (nmsgs+1)*sizeof(*slist));
231         qsort((char *)slist, nmsgs, sizeof(*slist), (qsort_comp) subsort);
232
233         /*
234          * make an inversion list so we can quickly find
235          * the collection of messages with the same subj
236          * given a message number.
237          */
238         il = (struct smsg ***) calloc (mp->hghsel+1, sizeof(*il));
239         if (! il)
240             adios (NULL, "couldn't allocate msg list");
241         for (i = 0; i < nmsgs; i++)
242             il[slist[i]->s_msg] = &slist[i];
243         /*
244          * make up the final list, chronological but with
245          * all the same subjects grouped together.
246          */
247         flist = (struct smsg **) mh_xmalloc ((nmsgs+1) * sizeof(*flist));
248         fp = flist;
249         for (dp = dlist; *dp;) {
250             register struct smsg **s = il[(*dp++)->s_msg];
251
252             /* see if we already did this guy */
253             if (! s)
254                 continue;
255
256             *fp++ = *s++;
257             /*
258              * take the next message(s) if there is one,
259              * its subject isn't null and its subject
260              * is the same as this one and it's not too
261              * far away in time.
262              */
263             while (*s && (*s)->s_subj[0] &&
264                    strcmp((*s)->s_subj, s[-1]->s_subj) == 0 &&
265                    (datelimit == 0 ||
266                    (*s)->s_clock - s[-1]->s_clock <= datelimit)) {
267                 il[(*s)->s_msg] = 0;
268                 *fp++ = *s++;
269             }
270         }
271         *fp = 0;
272         free (slist);
273         free (dlist);
274         dlist = flist;
275     }
276
277     /*
278      * At this point, dlist is a sorted array of pointers to smsg structures,
279      * each of which contains a message number.
280      */
281
282     rename_msgs (mp, dlist);
283
284     context_replace (pfolder, folder);  /* update current folder         */
285     seq_save (mp);                      /* synchronize message sequences */
286     context_save ();                    /* save the context file         */
287     folder_free (mp);                   /* free folder/message structure */
288     done (0);
289     return 1;
290 }
291
292 static int
293 read_hdrs (struct msgs *mp, char *datesw)
294 {
295     int msgnum;
296     struct tws tb;
297     register struct smsg *s;
298
299     twscopy (&tb, dlocaltimenow ());
300
301     smsgs = (struct smsg *)
302         calloc ((size_t) (mp->hghsel - mp->lowsel + 2),
303             sizeof(*smsgs));
304     if (smsgs == NULL)
305         adios (NULL, "unable to allocate sort storage");
306
307     s = smsgs;
308     for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
309         if (is_selected(mp, msgnum)) {
310             if (get_fields (datesw, msgnum, s)) {
311                 s->s_msg = msgnum;
312                 s++;
313             }
314         }
315     }
316     s->s_msg = 0;
317     return(s - smsgs);
318 }
319
320
321 /*
322  * Parse the message and get the data or subject field,
323  * if needed.
324  */
325
326 static int
327 get_fields (char *datesw, int msg, struct smsg *smsg)
328 {
329     register int state;
330     int compnum;
331     char *msgnam, buf[BUFSIZ], nam[NAMESZ];
332     register struct tws *tw;
333     register char *datecomp = NULL, *subjcomp = NULL;
334     register FILE *in;
335
336     if ((in = fopen (msgnam = m_name (msg), "r")) == NULL) {
337         admonish (msgnam, "unable to read message");
338         return (0);
339     }
340     for (compnum = 1, state = FLD;;) {
341         switch (state = m_getfld (state, nam, buf, sizeof(buf), in)) {
342         case FLD:
343         case FLDEOF:
344         case FLDPLUS:
345             compnum++;
346             if (!mh_strcasecmp (nam, datesw)) {
347                 datecomp = add (buf, datecomp);
348                 while (state == FLDPLUS) {
349                     state = m_getfld (state, nam, buf, sizeof(buf), in);
350                     datecomp = add (buf, datecomp);
351                 }
352                 if (!subjsort || subjcomp)
353                     break;
354             } else if (subjsort && !mh_strcasecmp (nam, subjsort)) {
355                 subjcomp = add (buf, subjcomp);
356                 while (state == FLDPLUS) {
357                     state = m_getfld (state, nam, buf, sizeof(buf), in);
358                     subjcomp = add (buf, subjcomp);
359                 }
360                 if (datecomp)
361                     break;
362             } else {
363                 /* just flush this guy */
364                 while (state == FLDPLUS)
365                     state = m_getfld (state, nam, buf, sizeof(buf), in);
366             }
367             continue;
368
369         case BODY:
370         case BODYEOF:
371         case FILEEOF:
372             break;
373
374         case LENERR:
375         case FMTERR:
376             if (state == LENERR || state == FMTERR)
377                 admonish (NULL, "format error in message %d (header #%d)",
378                       msg, compnum);
379             if (datecomp)
380                 free (datecomp);
381             if (subjcomp)
382                 free (subjcomp);
383             fclose (in);
384             return (0);
385
386         default:
387             adios (NULL, "internal error -- you lose");
388         }
389         break;
390     }
391
392     /*
393      * If no date component, then use the modification
394      * time of the file as its date
395      */
396     if (!datecomp || (tw = dparsetime (datecomp)) == NULL) {
397         struct stat st;
398
399         admonish (NULL, "can't parse %s field in message %d", datesw, msg);
400         fstat (fileno (in), &st);
401         smsg->s_clock = st.st_mtime;
402     } else {
403         smsg->s_clock = dmktime (tw);
404     }
405
406     if (subjsort) {
407         if (subjcomp) {
408             /*
409              * try to make the subject "canonical": delete
410              * leading "re:", everything but letters & smash
411              * letters to lower case.
412              */
413             register char  *cp, *cp2;
414             register unsigned char c;
415
416             cp = subjcomp;
417             cp2 = subjcomp;
418             if (strcmp (subjsort, "subject") == 0) {
419                 while ((c = *cp)) {
420                     if (! isspace(c)) {
421                         if(uprf(cp, "re:"))
422                             cp += 2;
423                         else
424                             break;
425                     }
426                     cp++;
427                 }
428             }
429
430             while ((c = *cp++)) {
431                 if (isalnum(c))
432                     *cp2++ = isupper(c) ? tolower(c) : c;
433             }
434
435             *cp2 = '\0';
436         }
437         else
438             subjcomp = "";
439
440         smsg->s_subj = subjcomp;
441     }
442     fclose (in);
443     if (datecomp)
444         free (datecomp);
445
446     return (1);
447 }
448
449 /*
450  * sort on dates.
451  */
452 static int
453 dsort (struct smsg **a, struct smsg **b)
454 {
455     if ((*a)->s_clock < (*b)->s_clock)
456         return (-1);
457     else if ((*a)->s_clock > (*b)->s_clock)
458         return (1);
459     else if ((*a)->s_msg < (*b)->s_msg)
460         return (-1);
461     else
462         return (1);
463 }
464
465 /*
466  * sort on subjects.
467  */
468 static int
469 subsort (struct smsg **a, struct smsg **b)
470 {
471     register int i;
472
473     if ((i = strcmp ((*a)->s_subj, (*b)->s_subj)))
474         return (i);
475
476     return (dsort (a, b));
477 }
478
479 static int
480 txtsort (struct smsg **a, struct smsg **b)
481 {
482     register int i;
483
484     if ((i = strcmp ((*a)->s_subj, (*b)->s_subj)))
485         return (i);
486     else if ((*a)->s_msg < (*b)->s_msg)
487         return (-1);
488     else
489         return (1);
490 }
491
492 static void
493 rename_chain (struct msgs *mp, struct smsg **mlist, int msg, int endmsg)
494 {
495     int nxt, old, new;
496     char *newname, oldname[BUFSIZ];
497     char newbuf[MAXPATHLEN + 1];
498
499     for (;;) {
500         nxt = mlist[msg] - smsgs;       /* mlist[msg] is a ptr into smsgs */
501         mlist[msg] = (struct smsg *)0;
502         old = smsgs[nxt].s_msg;
503         new = smsgs[msg].s_msg;
504         strncpy (oldname, m_name (old), sizeof(oldname));
505         newname = m_name (new);
506         if (verbose)
507             printf ("message %d becomes message %d\n", old, new);
508
509         (void)snprintf(oldname, sizeof (oldname), "%s/%d", mp->foldpath, old);
510         (void)snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, new);
511         ext_hook("ref-hook", oldname, newbuf);
512
513         if (rename (oldname, newname) == NOTOK)
514             adios (newname, "unable to rename %s to", oldname);
515
516         copy_msg_flags (mp, new, old);
517         if (mp->curmsg == old)
518             seq_setcur (mp, new);
519
520         if (nxt == endmsg)
521             break;
522
523         msg = nxt;
524     }
525 /*      if (nxt != endmsg); */
526 /*      rename_chain (mp, mlist, nxt, endmsg); */
527 }
528
529 static void
530 rename_msgs (struct msgs *mp, struct smsg **mlist)
531 {
532     int i, j, old, new;
533     seqset_t tmpset;
534     char f1[BUFSIZ], tmpfil[BUFSIZ];
535     char newbuf[MAXPATHLEN + 1];
536     struct smsg *sp;
537
538     strncpy (tmpfil, m_name (mp->hghmsg + 1), sizeof(tmpfil));
539
540     for (i = 0; i < nmsgs; i++) {
541         if (! (sp = mlist[i]))
542             continue;   /* did this one */
543
544         j = sp - smsgs;
545         if (j == i)
546             continue;   /* this one doesn't move */
547
548         /*
549          * the guy that was msg j is about to become msg i.
550          * rename 'j' to make a hole, then recursively rename
551          * guys to fill up the hole.
552          */
553         old = smsgs[j].s_msg;
554         new = smsgs[i].s_msg;
555         strncpy (f1, m_name (old), sizeof(f1));
556
557         if (verbose)
558             printf ("renaming message chain from %d to %d\n", old, new);
559
560         /*
561          *      Run the external hook to refile the old message as the
562          *      temporary message number that is off of the end of the
563          *      messages in the folder.
564          */
565
566         (void)snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, old);
567         (void)snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, mp->hghmsg + 1);
568         ext_hook("ref-hook", f1, newbuf);
569
570         if (rename (f1, tmpfil) == NOTOK)
571             adios (tmpfil, "unable to rename %s to ", f1);
572
573         get_msg_flags (mp, &tmpset, old);
574
575         rename_chain (mp, mlist, j, i);
576
577         /*
578          *      Run the external hook to refile the temorary message number
579          *      to the real place.
580          */
581
582         (void)snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, new);
583         ext_hook("ref-hook", newbuf, f1);
584
585         if (rename (tmpfil, m_name(new)) == NOTOK)
586             adios (m_name(new), "unable to rename %s to", tmpfil);
587
588         set_msg_flags (mp, &tmpset, new);
589         mp->msgflags |= SEQMOD;
590     }
591 }