125991cc112b1ce7dfd3c4ae2e81bdfedfaeba18
[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 = NULL;  /* 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 = mhbasename(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 = NULL;
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 = getcpy(expandfol(cp));
163                 } else
164                         app_msgarg(&msgs, cp);
165         }
166
167         if (!msgs.size)
168                 app_msgarg(&msgs, seq_all);
169         if (!datesw)
170                 datesw = "date";
171         if (!folder)
172                 folder = getcurfol();
173         maildir = toabsdir(folder);
174
175         if (chdir(maildir) == NOTOK)
176                 adios(maildir, "unable to change directory to");
177
178         /* read folder and create message structure */
179         if (!(mp = folder_read(folder)))
180                 adios(NULL, "unable to read folder %s", folder);
181
182         /* check for empty folder */
183         if (mp->nummsg == 0)
184                 adios(NULL, "no messages in %s", folder);
185
186         /* parse all the message ranges/sequences and set SELECTED */
187         for (msgnum = 0; msgnum < msgs.size; msgnum++)
188                 if (!m_convert(mp, msgs.msgs[msgnum]))
189                         done(1);
190         seq_setprev(mp);  /* set the previous sequence */
191
192         if ((nmsgs = read_hdrs(mp, datesw)) <= 0)
193                 adios(NULL, "no messages to sort");
194
195         /*
196         ** sort a list of pointers to our "messages to be sorted".
197         */
198         dlist = (struct smsg **) mh_xmalloc((nmsgs+1) * sizeof(*dlist));
199         for (i = 0; i < nmsgs; i++)
200                 dlist[i] = &smsgs[i];
201         dlist[nmsgs] = 0;
202
203         if (verbose) {  /* announce what we're doing */
204                 if (subjsort)
205                         printf("sorting by %s-major %s-minor\n",
206                                 submajor ? subjsort : datesw,
207                                 submajor ? datesw : subjsort);
208                 else
209                         printf("sorting by datefield %s\n", datesw);
210         }
211
212         /* first sort by date, or by subject-major, date-minor */
213         qsort((char *) dlist, nmsgs, sizeof(*dlist),
214                         (qsort_comp) (submajor && subjsort ? txtsort : dsort));
215
216         /*
217         ** if we're sorting on subject, we need another list
218         ** in subject order, then a merge pass to collate the
219         ** two sorts.
220         */
221         if (!submajor && subjsort) {  /* already date sorted */
222                 struct smsg **slist, **flist;
223                 register struct smsg ***il, **fp, **dp;
224
225                 slist = (struct smsg **)
226                                 mh_xmalloc((nmsgs+1) * sizeof(*slist));
227                 memcpy((char *)slist, (char *)dlist, (nmsgs+1)*sizeof(*slist));
228                 qsort((char *)slist, nmsgs, sizeof(*slist),
229                                 (qsort_comp) subsort);
230
231                 /*
232                 ** make an inversion list so we can quickly find
233                 ** the collection of messages with the same subj
234                 ** given a message number.
235                 */
236                 il = (struct smsg ***) calloc(mp->hghsel+1, sizeof(*il));
237                 if (! il)
238                         adios(NULL, "couldn't allocate msg list");
239                 for (i = 0; i < nmsgs; i++)
240                         il[slist[i]->s_msg] = &slist[i];
241                 /*
242                 ** make up the final list, chronological but with
243                 ** all the same subjects grouped together.
244                 */
245                 flist = (struct smsg **)
246                                 mh_xmalloc((nmsgs+1) * sizeof(*flist));
247                 fp = flist;
248                 for (dp = dlist; *dp;) {
249                         register struct smsg **s = il[(*dp++)->s_msg];
250
251                         /* see if we already did this guy */
252                         if (! s)
253                                 continue;
254
255                         *fp++ = *s++;
256                         /*
257                         ** take the next message(s) if there is one,
258                         ** its subject isn't null and its subject
259                         ** is the same as this one and it's not too
260                         ** far away in time.
261                         */
262                         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)) {
263                                 il[(*s)->s_msg] = 0;
264                                 *fp++ = *s++;
265                         }
266                 }
267                 *fp = 0;
268                 free(slist);
269                 free(dlist);
270                 dlist = flist;
271         }
272
273         /*
274         ** At this point, dlist is a sorted array of pointers to smsg
275         ** structures, each of which contains a message number.
276         */
277
278         rename_msgs(mp, dlist);
279
280         context_replace(curfolder, folder);  /* update current folder */
281         seq_save(mp);  /* synchronize message sequences */
282         context_save();  /* save the context file */
283         folder_free(mp);  /* free folder/message structure */
284         done(0);
285         return 1;
286 }
287
288 static int
289 read_hdrs(struct msgs *mp, char *datesw)
290 {
291         int msgnum;
292         struct tws tb;
293         register struct smsg *s;
294
295         twscopy(&tb, dlocaltimenow());
296
297         smsgs = (struct smsg *) calloc((size_t) (mp->hghsel - mp->lowsel + 2),
298                         sizeof(*smsgs));
299         if (smsgs == NULL)
300                 adios(NULL, "unable to allocate sort storage");
301
302         s = smsgs;
303         for (msgnum = mp->lowsel; msgnum <= mp->hghsel; msgnum++) {
304                 if (is_selected(mp, msgnum)) {
305                         if (get_fields(datesw, msgnum, s)) {
306                                 s->s_msg = msgnum;
307                                 s++;
308                         }
309                 }
310         }
311         s->s_msg = 0;
312         return(s - smsgs);
313 }
314
315
316 /*
317 ** Parse the message and get the data or subject field,
318 ** if needed.
319 */
320
321 static int
322 get_fields(char *datesw, int msg, struct smsg *smsg)
323 {
324         register int state;
325         int compnum;
326         char *msgnam, buf[BUFSIZ], nam[NAMESZ];
327         register struct tws *tw;
328         register char *datecomp = NULL, *subjcomp = NULL;
329         register FILE *in;
330
331         if ((in = fopen(msgnam = m_name(msg), "r")) == NULL) {
332                 admonish(msgnam, "unable to read message");
333                 return (0);
334         }
335         for (compnum = 1, state = FLD;;) {
336                 switch (state = m_getfld(state, nam, buf, sizeof(buf), in)) {
337                 case FLD:
338                 case FLDEOF:
339                 case FLDPLUS:
340                         compnum++;
341                         if (!mh_strcasecmp(nam, datesw)) {
342                                 datecomp = add(buf, datecomp);
343                                 while (state == FLDPLUS) {
344                                         state = m_getfld(state, nam, buf,
345                                                         sizeof(buf), in);
346                                         datecomp = add(buf, datecomp);
347                                 }
348                                 if (!subjsort || subjcomp)
349                                         break;
350                         } else if (subjsort && !mh_strcasecmp(nam, subjsort)) {
351                                 subjcomp = add(buf, subjcomp);
352                                 while (state == FLDPLUS) {
353                                         state = m_getfld(state, nam, buf,
354                                                         sizeof(buf), in);
355                                         subjcomp = add(buf, subjcomp);
356                                 }
357                                 if (datecomp)
358                                         break;
359                         } else {
360                                 /* just flush this guy */
361                                 while (state == FLDPLUS)
362                                         state = m_getfld(state, nam, buf,
363                                                         sizeof(buf), in);
364                         }
365                         continue;
366
367                 case BODY:
368                 case BODYEOF:
369                 case FILEEOF:
370                         break;
371
372                 case LENERR:
373                 case FMTERR:
374                         if (state == LENERR || state == FMTERR)
375                                 admonish(NULL, "format error in message %d (header #%d)", msg, compnum);
376                         if (datecomp)
377                                 free(datecomp);
378                         if (subjcomp)
379                                 free(subjcomp);
380                         fclose(in);
381                         return (0);
382
383                 default:
384                         adios(NULL, "internal error -- you lose");
385                 }
386                 break;
387         }
388
389         /*
390         ** If no date component, then use the modification
391         ** time of the file as its date
392         */
393         if (!datecomp || (tw = dparsetime(datecomp)) == NULL) {
394                 struct stat st;
395
396                 admonish(NULL, "can't parse %s field in message %d",
397                                 datesw, msg);
398                 fstat(fileno(in), &st);
399                 smsg->s_clock = st.st_mtime;
400         } else {
401                 smsg->s_clock = dmktime(tw);
402         }
403
404         if (subjsort) {
405                 if (subjcomp) {
406                         /*
407                         ** try to make the subject "canonical": delete
408                         ** leading "re:", everything but letters & smash
409                         ** letters to lower case.
410                         */
411                         register char  *cp, *cp2;
412                         register unsigned char c;
413
414                         cp = subjcomp;
415                         cp2 = subjcomp;
416                         if (strcmp(subjsort, "subject") == 0) {
417                                 while ((c = *cp)) {
418                                         if (! isspace(c)) {
419                                                 if(uprf(cp, "re:"))
420                                                         cp += 2;
421                                                 else
422                                                         break;
423                                         }
424                                         cp++;
425                                 }
426                         }
427
428                         while ((c = *cp++)) {
429                                 if (isalnum(c))
430                                         *cp2++ = isupper(c) ? tolower(c) : c;
431                         }
432
433                         *cp2 = '\0';
434                 } else
435                         subjcomp = "";
436
437                 smsg->s_subj = subjcomp;
438         }
439         fclose(in);
440         if (datecomp)
441                 free(datecomp);
442
443         return (1);
444 }
445
446 /*
447 ** sort on dates.
448 */
449 static int
450 dsort(struct smsg **a, struct smsg **b)
451 {
452         if ((*a)->s_clock < (*b)->s_clock)
453                 return (-1);
454         else if ((*a)->s_clock > (*b)->s_clock)
455                 return (1);
456         else if ((*a)->s_msg < (*b)->s_msg)
457                 return (-1);
458         else
459                 return (1);
460 }
461
462 /*
463 ** sort on subjects.
464 */
465 static int
466 subsort(struct smsg **a, struct smsg **b)
467 {
468         register int i;
469
470         if ((i = strcmp((*a)->s_subj, (*b)->s_subj)))
471                 return (i);
472
473         return (dsort(a, b));
474 }
475
476 static int
477 txtsort(struct smsg **a, struct smsg **b)
478 {
479         register int i;
480
481         if ((i = strcmp((*a)->s_subj, (*b)->s_subj)))
482                 return (i);
483         else if ((*a)->s_msg < (*b)->s_msg)
484                 return (-1);
485         else
486                 return (1);
487 }
488
489 static void
490 rename_chain(struct msgs *mp, struct smsg **mlist, int msg, int endmsg)
491 {
492         int nxt, old, new;
493         char *newname, oldname[BUFSIZ];
494         char newbuf[MAXPATHLEN + 1];
495
496         for (;;) {
497                 nxt = mlist[msg] - smsgs;  /* mlist[msg] is a ptr into smsgs */
498                 mlist[msg] = (struct smsg *)0;
499                 old = smsgs[nxt].s_msg;
500                 new = smsgs[msg].s_msg;
501                 strncpy(oldname, m_name(old), sizeof(oldname));
502                 newname = m_name(new);
503                 if (verbose)
504                         printf("message %d becomes message %d\n", old, new);
505
506                 snprintf(oldname, sizeof (oldname), "%s/%d",
507                                 mp->foldpath, old);
508                 snprintf(newbuf, sizeof (newbuf), "%s/%d", mp->foldpath, new);
509                 ext_hook("ref-hook", oldname, newbuf);
510
511                 if (rename(oldname, newname) == NOTOK)
512                         adios(newname, "unable to rename %s to", oldname);
513
514                 copy_msg_flags(mp, new, old);
515                 if (mp->curmsg == old)
516                         seq_setcur(mp, new);
517
518                 if (nxt == endmsg)
519                         break;
520
521                 msg = nxt;
522         }
523 /* if (nxt != endmsg); */
524 /* rename_chain(mp, mlist, nxt, endmsg); */
525 }
526
527 static void
528 rename_msgs(struct msgs *mp, struct smsg **mlist)
529 {
530         int i, j, old, new;
531         seqset_t tmpset;
532         char f1[BUFSIZ], tmpfil[BUFSIZ];
533         char newbuf[MAXPATHLEN + 1];
534         struct smsg *sp;
535
536         strncpy(tmpfil, m_name(mp->hghmsg + 1), sizeof(tmpfil));
537
538         for (i = 0; i < nmsgs; i++) {
539                 if (! (sp = mlist[i]))
540                         continue;   /* did this one */
541
542                 j = sp - smsgs;
543                 if (j == i)
544                         continue;   /* this one doesn't move */
545
546                 /*
547                 ** the guy that was msg j is about to become msg i.
548                 ** rename 'j' to make a hole, then recursively rename
549                 ** guys to fill up the hole.
550                 */
551                 old = smsgs[j].s_msg;
552                 new = smsgs[i].s_msg;
553                 strncpy(f1, m_name(old), sizeof(f1));
554
555                 if (verbose)
556                         printf("renaming message chain from %d to %d\n",
557                                         old, new);
558
559                 /*
560                 ** Run the external hook to refile the old message as the
561                 ** temporary message number that is off of the end of the
562                 ** messages in the folder.
563                 */
564
565                 snprintf(f1, sizeof (f1), "%s/%d", mp->foldpath, old);
566                 snprintf(newbuf, sizeof (newbuf), "%s/%d",
567                                 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                 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 }