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