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