Multi-language support fixes
[srvx.git] / src / helpfile.c
1 /* helpfile.c - Help file loading and display
2  * Copyright 2000-2004 srvx Development Team
3  *
4  * This file is part of srvx.
5  *
6  * srvx is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with srvx; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA.
19  */
20
21 #include "conf.h"
22 #include "helpfile.h"
23 #include "log.h"
24 #include "modcmd.h"
25 #include "nickserv.h"
26
27 #include <dirent.h>
28
29 static const struct message_entry msgtab[] = {
30     { "HFMSG_MISSING_HELPFILE", "The help file could not be found.  Sorry!" },
31     { "HFMSG_HELP_NOT_STRING", "Help file error (help data was not a string)." },
32     { NULL, NULL }
33 };
34
35 #define DEFAULT_LINE_SIZE       MAX_LINE_SIZE
36 #define DEFAULT_TABLE_SIZE      80
37
38 extern struct userNode *global, *chanserv, *opserv, *nickserv;
39 struct userNode *message_dest;
40 struct userNode *message_source;
41 struct language *lang_C;
42 struct dict *languages;
43
44 static void language_cleanup(void)
45 {
46     dict_delete(languages);
47 }
48
49 static void language_free_helpfile(void *data)
50 {
51     struct helpfile *hf = data;
52     close_helpfile(hf);
53 }
54
55 static void language_free(void *data)
56 {
57     struct language *lang = data;
58     dict_delete(lang->messages);
59     dict_delete(lang->helpfiles);
60     free(lang->name);
61     free(lang);
62 }
63
64 static struct language *language_alloc(const char *name)
65 {
66     struct language *lang = calloc(1, sizeof(*lang));
67     lang->name = strdup(name);
68     lang->parent = lang_C;
69     if (!languages) {
70         languages = dict_new();
71         dict_set_free_data(languages, language_free);
72     }
73     dict_insert(languages, lang->name, lang);
74     return lang;
75 }
76
77 /* Language names should use a lang or lang_COUNTRY type system, where
78  * lang is a two-letter code according to ISO-639-1 (or three-letter
79  * code according to ISO-639-2 for languages not in ISO-639-1), and
80  * COUNTRY is the ISO 3166 country code in all upper case.
81  * 
82  * See also:
83  * http://www.loc.gov/standards/iso639-2/
84  * http://www.loc.gov/standards/iso639-2/langhome.html
85  * http://www.iso.ch/iso/en/prods-services/iso3166ma/index.html
86  */
87 struct language *language_find(const char *name)
88 {
89     struct language *lang;
90     char alt_name[MAXLEN];
91     const char *uscore;
92
93     if ((lang = dict_find(languages, name, NULL)))
94         return lang;
95     if ((uscore = strchr(name, '_'))) {
96         strncpy(alt_name, name, uscore-name);
97         alt_name[uscore-name] = 0;
98         if ((lang = dict_find(languages, alt_name, NULL)))
99             return lang;
100     }
101     if (!lang_C) {
102         lang_C = language_alloc("C");
103         lang_C->messages = dict_new();
104         lang_C->helpfiles = dict_new();
105     }
106     return lang_C;
107 }
108
109 static void language_set_messages(struct language *lang, dict_t dict)
110 {
111     dict_iterator_t it, it2;
112     struct record_data *rd;
113     char *msg;
114     int extra, missing;
115
116     extra = missing = 0;
117     for (it = dict_first(dict), it2 = dict_first(lang_C->messages); it; ) {
118         const char *msgid = iter_key(it);
119         int diff = it2 ? irccasecmp(msgid, iter_key(it2)) : -1;
120         if (diff < 0) {
121             extra++;
122             it = iter_next(it);
123             continue;
124         } else if (diff > 0) {
125             missing++;
126             it2 = iter_next(it2);
127             continue;
128         }
129         rd = iter_data(it);
130         switch (rd->type) {
131         case RECDB_QSTRING:
132             msg = strdup(rd->d.qstring);
133             break;
134         case RECDB_STRING_LIST:
135             /* XXX: maybe do an unlistify_help() type thing */
136         default:
137             log_module(MAIN_LOG, LOG_WARNING, "Unsupported record type for message %s in language %s", msgid, lang->name);
138             continue;
139         }
140         dict_insert(lang->messages, strdup(msgid), msg);
141         it = iter_next(it);
142         it2 = iter_next(it2);
143     }
144     while (it2) {
145         missing++;
146         it2 = iter_next(it2);
147     }
148     if (extra || missing)
149         log_module(MAIN_LOG, LOG_WARNING, "In language %s, %d extra and %d missing messages.", lang->name, extra, missing);
150 }
151
152 static struct language *language_read(const char *name)
153 {
154     DIR *dir;
155     struct dirent *dirent;
156     struct language *lang;
157     struct helpfile *hf;
158     char filename[MAXLEN], *uscore;
159     FILE *file;
160     dict_t dict;
161
162     /* Never try to read the C language from disk. */
163     if (!irccasecmp(name, "C"))
164         return lang_C;
165
166     /* Open the directory stream; if we can't, fail. */
167     snprintf(filename, sizeof(filename), "languages/%s", name);
168     if (!(dir = opendir(filename)))
169         return NULL;
170     if (!(lang = dict_find(languages, name, NULL)))
171         lang = language_alloc(name);
172
173     /* Find the parent language. */
174     snprintf(filename, sizeof(filename), "languages/%s/parent", name);
175     if (!(file = fopen(filename, "r"))
176         || !fgets(filename, sizeof(filename), file)) {
177         strcpy(filename, "C");
178     }
179     if (!(lang->parent = language_find(filename))) {
180         uscore = strchr(filename, '_');
181         if (uscore) {
182             *uscore = 0;
183             lang->parent = language_find(filename);
184         }
185         if (!lang->parent)
186             lang->parent = lang_C;
187     }
188
189     /* (Re-)initialize the language's dicts. */
190     dict_delete(lang->messages);
191     lang->messages = dict_new();
192     dict_set_free_keys(lang->messages, free);
193     dict_set_free_data(lang->messages, free);
194     lang->helpfiles = dict_new();
195     dict_set_free_data(lang->helpfiles, language_free_helpfile);
196
197     /* Read all the translations from the directory. */
198     while ((dirent = readdir(dir))) {
199         snprintf(filename, sizeof(filename), "languages/%s/%s", name, dirent->d_name);
200         if (!strcmp(dirent->d_name,"parent")) {
201             continue;
202         } else if (!strcmp(dirent->d_name, "strings.db")) {
203             dict = parse_database(filename);
204             language_set_messages(lang, dict);
205             free_database(dict);
206         } else if ((hf = dict_find(lang_C->helpfiles, dirent->d_name, NULL))) {
207             hf = open_helpfile(filename, hf->expand);
208             dict_insert(lang->helpfiles, hf->name, hf);
209         }
210     }
211
212     /* All done. */
213     closedir(dir);
214     return lang;
215 }
216
217 static void language_read_list(void)
218 {
219     struct dirent *dirent;
220     DIR *dir;
221
222     if (!(dir = opendir("languages")))
223         return;
224     while ((dirent = readdir(dir))) {
225         if (!strcmp(dirent->d_name, ".") || !strcmp(dirent->d_name, ".."))
226             continue;
227         language_alloc(dirent->d_name);
228     }
229     closedir(dir);
230 }
231
232 static void language_read_all(void)
233 {
234     struct string_list *slist;
235     struct dirent *dirent;
236     DIR *dir;
237     unsigned int ii;
238
239     /* Read into an in-memory list and sort so we are likely to load
240      * parent languages before their children (de_DE sorts after de).
241      */
242     if (!(dir = opendir("languages")))
243         return;
244     slist = alloc_string_list(4);
245     while ((dirent = readdir(dir)))
246         string_list_append(slist, strdup(dirent->d_name));
247     closedir(dir);
248     string_list_sort(slist);
249     for (ii = 0; ii < slist->used; ++ii) {
250         if (!strcmp(slist->list[ii], ".") || !strcmp(slist->list[ii], ".."))
251             continue;
252         language_read(slist->list[ii]);
253     }
254     free_string_list(slist);
255 }
256
257 const char *language_find_message(struct language *lang, const char *msgid) {
258     struct language *curr;
259     const char *msg;
260     if (!lang)
261         lang = lang_C;
262     for (curr = lang; curr; curr = curr->parent)
263         if ((msg = dict_find(curr->messages, msgid, NULL)))
264             return msg;
265     log_module(MAIN_LOG, LOG_ERROR, "Tried to find unregistered message \"%s\" (original language %s)", msgid, lang->name);
266     return NULL;
267 }
268
269 void
270 table_send(struct userNode *from, const char *to, unsigned int size, irc_send_func irc_send, struct helpfile_table table) {
271     unsigned int ii, jj, len, nreps, reps, tot_width, pos, spaces, *max_width;
272     char line[MAX_LINE_SIZE+1];
273     struct handle_info *hi;
274
275     if (IsChannelName(to) || *to == '$') {
276         message_dest = NULL;
277         hi = NULL;
278     } else {
279         message_dest = GetUserH(to);
280         if (!message_dest) {
281             log_module(MAIN_LOG, LOG_ERROR, "Unable to find user with nickname %s (in table_send from %s).", to, from->nick);
282             return;
283         }
284         hi = message_dest->handle_info;
285 #ifdef WITH_PROTOCOL_P10
286         to = message_dest->numeric;
287 #endif
288     }
289     message_source = from;
290
291     /* If size or irc_send are 0, we should try to use a default. */
292     if (size)
293         {} /* keep size */
294     else if (!hi)
295         size = DEFAULT_TABLE_SIZE;
296     else if (hi->table_width)
297         size = hi->table_width;
298     else if (hi->screen_width)
299         size = hi->screen_width;
300     else
301         size = DEFAULT_TABLE_SIZE;
302
303     if (irc_send)
304         {} /* use that function */
305     else if (hi)
306         irc_send = HANDLE_FLAGGED(hi, USE_PRIVMSG) ? irc_privmsg : irc_notice;
307     else
308         irc_send = IsChannelName(to) ? irc_privmsg : irc_notice;
309
310     /* Limit size to how much we can show at once */
311     if (size > sizeof(line))
312         size = sizeof(line);
313
314     /* Figure out how wide columns should be */
315     max_width = alloca(table.width * sizeof(int));
316     for (jj=tot_width=0; jj<table.width; jj++) {
317         /* Find the widest width for this column */
318         max_width[jj] = 0;
319         for (ii=0; ii<table.length; ii++) {
320             len = strlen(table.contents[ii][jj]);
321             if (len > max_width[jj])
322                 max_width[jj] = len;
323         }
324         /* Separate columns with spaces */
325         tot_width += max_width[jj] + 1;
326     }
327     /* How many rows to put in a line? */
328     if ((table.flags & TABLE_REPEAT_ROWS) && (size > tot_width))
329         nreps = size / tot_width;
330     else
331         nreps = 1;
332     /* Send headers line.. */
333     if (table.flags & TABLE_NO_HEADERS) {
334         ii = 0;
335     } else {
336         /* Sending headers needs special treatment: either show them
337          * once, or repeat them as many times as we repeat the columns
338          * in a row. */
339         for (pos=ii=0; ii<((table.flags & TABLE_REPEAT_HEADERS)?nreps:1); ii++) {
340             for (jj=0; 1; ) {
341                 len = strlen(table.contents[0][jj]);
342                 spaces = max_width[jj] - len;
343                 if (table.flags & TABLE_PAD_LEFT)
344                     while (spaces--)
345                         line[pos++] = ' ';
346                 memcpy(line+pos, table.contents[0][jj], len);
347                 pos += len;
348                 if (++jj == table.width)
349                     break;
350                 if (!(table.flags & TABLE_PAD_LEFT))
351                     while (spaces--)
352                         line[pos++] = ' ';
353                 line[pos++] = ' ';
354             }
355         }
356         line[pos] = 0;
357         irc_send(from, to, line);
358         ii = 1;
359     }
360     /* Send the table. */
361     for (jj=0, pos=0, reps=0; ii<table.length; ) {
362         while (1) {
363             len = strlen(table.contents[ii][jj]);
364             spaces = max_width[jj] - len;
365             if (table.flags & TABLE_PAD_LEFT)
366                 while (spaces--) line[pos++] = ' ';
367             memcpy(line+pos, table.contents[ii][jj], len);
368             pos += len;
369             if (++jj == table.width) {
370                 jj = 0, ++ii, ++reps;
371                 if ((reps == nreps) || (ii == table.length)) {
372                     line[pos] = 0;
373                     irc_send(from, to, line);
374                     pos = reps = 0;
375                     break;
376                 }
377             }
378             if (!(table.flags & TABLE_PAD_LEFT))
379                 while (spaces--)
380                     line[pos++] = ' ';
381             line[pos++] = ' ';
382         }
383     }
384     if (!(table.flags & TABLE_NO_FREE)) {
385         /* Deallocate table memory (but not the string memory). */
386         for (ii=0; ii<table.length; ii++)
387             free(table.contents[ii]);
388         free(table.contents);
389     }
390 }
391
392 static int
393 vsend_message(const char *dest, struct userNode *src, struct handle_info *handle, int msg_type, expand_func_t expand_f, const char *format, va_list al)
394 {
395     void (*irc_send)(struct userNode *from, const char *to, const char *msg);
396     static struct string_buffer input;
397     unsigned int size, ipos, pos, length, chars_sent, use_color;
398     unsigned int expand_pos, expand_ipos, newline_ipos;
399     char line[MAX_LINE_SIZE];
400
401     if (IsChannelName(dest) || *dest == '$') {
402         message_dest = NULL;
403     } else if (!(message_dest = GetUserH(dest))) {
404         log_module(MAIN_LOG, LOG_ERROR, "Unable to find user with nickname %s (in vsend_message from %s).", dest, src->nick);
405         return 0;
406     } else if (message_dest->dead) {
407         /* No point in sending to a user who is leaving. */
408         return 0;
409     } else {
410 #ifdef WITH_PROTOCOL_P10
411         dest = message_dest->numeric;
412 #endif
413     }
414     message_source = src;
415     if (!(msg_type & 4) && !(format = handle_find_message(handle, format)))
416         return 0;
417     /* fill in a buffer with the string */
418     input.used = 0;
419     string_buffer_append_vprintf(&input, format, al);
420
421     /* figure out how to send the messages */
422     if (handle) {
423         msg_type |= (HANDLE_FLAGGED(handle, USE_PRIVMSG) ? 1 : 0);
424         use_color = HANDLE_FLAGGED(handle, MIRC_COLOR);
425         size = handle->screen_width;
426         if (size > sizeof(line))
427             size = sizeof(line);
428     } else {
429         size = sizeof(line);
430         use_color = 1;
431     }
432     if (!size)
433         size = DEFAULT_LINE_SIZE;
434     switch (msg_type & 3) {
435         case 0:
436             irc_send = irc_notice;
437             break;
438         case 2:
439             irc_send = irc_wallchops;
440             break;
441         case 1:
442         default:
443             irc_send = irc_privmsg;
444     }
445
446     /* This used to be two passes, but if you do that and allow
447      * arbitrary sizes for ${}-expansions (as with help indexes),
448      * that requires a very big intermediate buffer.
449      */
450     expand_ipos = newline_ipos = ipos = 0;
451     expand_pos = pos = 0;
452     chars_sent = 0;
453     while (input.list[ipos]) {
454         char ch, *value, *free_value;
455
456         while ((ch = input.list[ipos]) && (ch != '$') && (ch != '\n') && (pos < size)) {
457             line[pos++] = ch;
458             ipos++;
459         }
460
461         if (!input.list[ipos])
462             goto send_line;
463         if (input.list[ipos] == '\n') {
464             ipos++;
465             goto send_line;
466         }
467         if (pos == size) {
468             unsigned int new_ipos;
469             /* Scan backwards for a space in the input, until we hit
470              * either the last newline or the last variable expansion.
471              * Print the line up to that point, and start from there.
472              */
473             for (new_ipos = ipos;
474                  (new_ipos > expand_ipos) && (new_ipos > newline_ipos);
475                  --new_ipos)
476                 if (input.list[new_ipos] == ' ')
477                     break;
478             pos -= ipos - new_ipos;
479             if (new_ipos == newline_ipos) {
480                 /* Single word was too big to fit on one line; skip
481                  * forward to its end and print it as a whole.
482                  */
483                 while (input.list[new_ipos]
484                        && (input.list[new_ipos] != ' ')
485                        && (input.list[new_ipos] != '\n')
486                        && (input.list[new_ipos] != '$'))
487                     line[pos++] = input.list[new_ipos++];
488             }
489             ipos = new_ipos;
490             while (input.list[ipos] == ' ')
491                 ipos++;
492             goto send_line;
493         }
494
495         free_value = 0;
496         switch (input.list[++ipos]) {
497         /* Literal '$' or end of string. */
498         case 0:
499             ipos--;
500         case '$':
501             value = "$";
502             break;
503         /* The following two expand to mIRC color codes if enabled
504            by the user. */
505         case 'b':
506             value = use_color ? "\002" : "";
507             break;
508         case 'o':
509             value = use_color ? "\017" : "";
510             break;
511         case 'r':
512             value = use_color ? "\026" : "";
513             break;
514         case 'u':
515             value = use_color ? "\037" : "";
516             break;
517         /* Service nicks. */
518         case 'S':
519             value = src->nick;
520             break;
521         case 'G':
522             value = global ? global->nick : "Global";
523             break;
524         case 'C':
525             value = chanserv ? chanserv->nick : "ChanServ";
526             break;
527         case 'O':
528             value = opserv ? opserv->nick : "OpServ";
529             break;
530         case 'N':
531             value = nickserv ? nickserv->nick : "NickServ";
532             break;
533         case 's':
534             value = self->name;
535             break;
536         case 'H':
537             value = handle ? handle->handle : "Account";
538             break;
539 #define SEND_LINE() do { line[pos] = 0; if (pos > 0) irc_send(src, dest, line); chars_sent += pos; pos = 0; newline_ipos = ipos; } while (0)
540         /* Custom expansion handled by helpfile-specific function. */
541         case '{':
542         case '(': {
543             struct helpfile_expansion exp;
544             char *name_end = input.list + ipos + 1, *colon = NULL;
545
546             while (*name_end != '}' && *name_end != ')' && *name_end) {
547                 if (*name_end == ':') {
548                     colon = name_end;
549                     *colon = '\0';
550                 }
551                 name_end++;
552             }
553             if (!*name_end)
554                 goto fallthrough;
555             *name_end = '\0';
556             if (colon) {
557                 struct module *module = module_find(input.list + ipos + 1);
558                 if (module && module->expand_help)
559                     exp = module->expand_help(colon + 1);
560                 else {
561                     *colon = ':';
562                     goto fallthrough;
563                 }
564             } else if (expand_f)
565                 exp = expand_f(input.list + ipos + 1);
566             else
567                 goto fallthrough;
568             switch (exp.type) {
569             case HF_STRING:
570                 free_value = value = exp.value.str;
571                 if (!value)
572                     value = "";
573                 break;
574             case HF_TABLE:
575                 /* Must send current line, then emit table. */
576                 SEND_LINE();
577                 table_send(src, (message_dest ? message_dest->nick : dest), 0, irc_send, exp.value.table);
578                 value = "";
579                 break;
580             default:
581                 value = "";
582                 log_module(MAIN_LOG, LOG_ERROR, "Invalid exp.type %d from expansion function %p.", exp.type, expand_f);
583                 break;
584             }
585             ipos = name_end - input.list;
586             break;
587         }
588         default:
589         fallthrough:
590             value = alloca(3);
591             value[0] = '$';
592             value[1] = input.list[ipos];
593             value[2] = 0;
594         }
595         ipos++;
596         while ((pos + strlen(value) > size) || strchr(value, '\n')) {
597             unsigned int avail;
598             avail = size - pos - 1;
599             length = strcspn(value, "\n ");
600             if (length <= avail) {
601                 strncpy(line+pos, value, length);
602                 pos += length;
603                 value += length;
604                 /* copy over spaces, until (possible) end of line */
605                 while (*value == ' ') {
606                     if (pos < size-1)
607                         line[pos++] = *value;
608                     value++;
609                 }
610             } else {
611                 /* word to send is too big to send now.. what to do? */
612                 if (pos > 0) {
613                     /* try to put it on a separate line */
614                     SEND_LINE();
615                 } else {
616                     /* already at start of line; only send part of it */
617                     strncpy(line, value, avail);
618                     pos += avail;
619                     value += length;
620                     /* skip any trailing spaces */
621                     while (*value == ' ')
622                         value++;
623                 }
624             }
625             /* if we're looking at a newline, send the accumulated text */
626             if (*value == '\n') {
627                 SEND_LINE();
628                 value++;
629             }
630         }
631         length = strlen(value);
632         memcpy(line + pos, value, length);
633         if (free_value)
634             free(free_value);
635         pos += length;
636         if ((pos < size-1) && input.list[ipos]) {
637             expand_pos = pos;
638             expand_ipos = ipos;
639             continue;
640         }
641       send_line:
642         expand_pos = pos;
643         expand_ipos = ipos;
644         SEND_LINE();
645 #undef SEND_LINE
646     }
647     return chars_sent;
648 }
649
650 int
651 send_message(struct userNode *dest, struct userNode *src, const char *format, ...)
652 {
653     int res;
654     va_list ap;
655
656     if (IsLocal(dest)) return 0;
657     va_start(ap, format);
658     res = vsend_message(dest->nick, src, dest->handle_info, 0, NULL, format, ap);
659     va_end(ap);
660     return res;
661 }
662
663 int
664 send_message_type(int msg_type, struct userNode *dest, struct userNode *src, const char *format, ...) {
665     int res;
666     va_list ap;
667
668     if (IsLocal(dest)) return 0;
669     va_start(ap, format);
670     res = vsend_message(dest->nick, src, dest->handle_info, msg_type, NULL, format, ap);
671     va_end(ap);
672     return res;
673 }
674
675 int
676 send_target_message(int msg_type, const char *dest, struct userNode *src, const char *format, ...)
677 {
678     int res;
679     va_list ap;
680
681     va_start(ap, format);
682     res = vsend_message(dest, src, NULL, msg_type, NULL, format, ap);
683     va_end(ap);
684     return res;
685 }
686
687 int
688 _send_help(struct userNode *dest, struct userNode *src, expand_func_t expand, const char *format, ...)
689 {
690     int res;
691
692     va_list ap;
693     va_start(ap, format);
694     res = vsend_message(dest->nick, src, dest->handle_info, 4, expand, format, ap);
695     va_end(ap);
696     return res;
697 }
698
699 int
700 send_help(struct userNode *dest, struct userNode *src, struct helpfile *hf, const char *topic)
701 {
702     struct helpfile *lang_hf;
703     struct record_data *rec;
704     struct language *curr;
705
706     if (!topic)
707         topic = "<index>";
708     if (!hf) {
709         _send_help(dest, src, NULL, "HFMSG_MISSING_HELPFILE");
710         return 0;
711     }
712     for (curr = (dest->handle_info ? dest->handle_info->language : lang_C);
713          curr;
714          curr = curr->parent) {
715         lang_hf = dict_find(curr->helpfiles, hf->name, NULL);
716         if (!lang_hf)
717             continue;
718         rec = dict_find(lang_hf->db, topic, NULL);
719         if (rec && rec->type == RECDB_QSTRING)
720             return _send_help(dest, src, hf->expand, rec->d.qstring);
721     }
722     rec = dict_find(hf->db, "<missing>", NULL);
723     if (!rec)
724         return send_message(dest, src, "MSG_TOPIC_UNKNOWN");
725     if (rec->type != RECDB_QSTRING)
726         return send_message(dest, src, "HFMSG_HELP_NOT_STRING");
727     return _send_help(dest, src, hf->expand, rec->d.qstring);
728 }
729
730 /* Grammar supported by this parser:
731  * condition = expr | prefix expr
732  * expr = atomicexpr | atomicexpr op atomicexpr
733  * op = '&&' | '||' | 'and' | 'or'
734  * atomicexpr = '(' expr ')' | identifier
735  * identifier = ( '0'-'9' 'A'-'Z' 'a'-'z' '-' '_' '/' )+ | ! identifier
736  *
737  * Whitespace is ignored. The parser is implemented as a recursive
738  * descent parser by functions like:
739  *   static int helpfile_eval_<element>(const char *start, const char **end);
740  */
741
742 enum helpfile_op {
743     OP_INVALID,
744     OP_BOOL_AND,
745     OP_BOOL_OR
746 };
747
748 static const struct {
749     const char *str;
750     enum helpfile_op op;
751 } helpfile_operators[] = {
752     { "&&", OP_BOOL_AND },
753     { "and", OP_BOOL_AND },
754     { "||", OP_BOOL_OR },
755     { "or", OP_BOOL_OR },
756     { NULL, OP_INVALID }
757 };
758
759 static const char *identifier_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_/";
760
761 static int helpfile_eval_expr(const char *start, const char **end);
762 static int helpfile_eval_atomicexpr(const char *start, const char **end);
763 static int helpfile_eval_identifier(const char *start, const char **end);
764
765 static int
766 helpfile_eval_identifier(const char *start, const char **end)
767 {
768     /* Skip leading whitespace. */
769     while (isspace(*start) && (start < *end))
770         start++;
771     if (start == *end) {
772         log_module(MAIN_LOG, LOG_FATAL, "Expected identifier in helpfile condition.");
773         return -1;
774     }
775
776     if (start[0] == '!') {
777         int res = helpfile_eval_identifier(start+1, end);
778         if (res < 0)
779             return res;
780         return !res;
781     } else if (start[0] == '/') {
782         const char *sep;
783         char *id_str, *value;
784
785         for (sep = start;
786              strchr(identifier_chars, sep[0]) && (sep < *end);
787              ++sep) ;
788         memcpy(id_str = alloca(sep+1-start), start, sep-start);
789         id_str[sep-start] = '\0';
790         value = conf_get_data(id_str+1, RECDB_QSTRING);
791         *end = sep;
792         if (!value)
793             return 0;
794         return enabled_string(value) || true_string(value);
795     } else if ((*end - start >= 4) && !ircncasecmp(start, "true", 4)) {
796         *end = start + 4;
797         return 1;
798     } else if ((*end - start >= 5) && !ircncasecmp(start, "false", 5)) {
799         *end = start + 5;
800         return 0;
801     } else {
802         log_module(MAIN_LOG, LOG_FATAL, "Unexpected helpfile identifier '%.*s'.", *end-start, start);
803         return -1;
804     }
805 }
806
807 static int
808 helpfile_eval_atomicexpr(const char *start, const char **end)
809 {
810     const char *sep;
811     int res;
812
813     /* Skip leading whitespace. */
814     while (isspace(*start) && (start < *end))
815         start++;
816     if (start == *end) {
817         log_module(MAIN_LOG, LOG_FATAL, "Expected atomic expression in helpfile condition.");
818         return -1;
819     }
820
821     /* If it's not parenthesized, it better be a valid identifier. */
822     if (*start != '(')
823         return helpfile_eval_identifier(start, end);
824
825     /* Parse the internal expression. */
826     start++;
827     sep = *end;
828     res = helpfile_eval_expr(start, &sep);
829
830     /* Check for the closing parenthesis. */
831     while (isspace(*sep) && (sep < *end))
832         sep++;
833     if ((sep == *end) || (sep[0] != ')')) {
834         log_module(MAIN_LOG, LOG_FATAL, "Expected close parenthesis at '%.*s'.", *end-sep, sep);
835         return -1;
836     }
837
838     /* Report the end location and result. */
839     *end = sep + 1;
840     return res;
841 }
842
843 static int
844 helpfile_eval_expr(const char *start, const char **end)
845 {
846     const char *sep, *sep2;
847     unsigned int ii, len;
848     int res_a, res_b;
849     enum helpfile_op op;
850
851     /* Parse the first atomicexpr. */
852     sep = *end;
853     res_a = helpfile_eval_atomicexpr(start, &sep);
854     if (res_a < 0)
855         return res_a;
856
857     /* Figure out what follows that. */
858     while (isspace(*sep) && (sep < *end))
859         sep++;
860     if (sep == *end)
861         return res_a;
862     op = OP_INVALID;
863     for (ii = 0; helpfile_operators[ii].str; ++ii) {
864         len = strlen(helpfile_operators[ii].str);
865         if (ircncasecmp(sep, helpfile_operators[ii].str, len))
866             continue;
867         op = helpfile_operators[ii].op;
868         sep += len;
869     }
870     if (op == OP_INVALID) {
871         log_module(MAIN_LOG, LOG_FATAL, "Unrecognized helpfile operator at '%.*s'.", *end-sep, sep);
872         return -1;
873     }
874
875     /* Parse the next atomicexpr. */
876     sep2 = *end;
877     res_b = helpfile_eval_atomicexpr(sep, &sep2);
878     if (res_b < 0)
879         return res_b;
880
881     /* Make sure there's no trailing garbage */
882     while (isspace(*sep2) && (sep2 < *end))
883         sep2++;
884     if (sep2 != *end) {
885         log_module(MAIN_LOG, LOG_FATAL, "Trailing garbage in helpfile expression: '%.*s'.", *end-sep2, sep2);
886         return -1;
887     }
888
889     /* Record where we stopped parsing. */
890     *end = sep2;
891
892     /* Do the logic on the subexpressions. */
893     switch (op) {
894     case OP_BOOL_AND:
895         return res_a && res_b;
896     case OP_BOOL_OR:
897         return res_a || res_b;
898     default:
899         return -1;
900     }
901 }
902
903 static int
904 helpfile_eval_condition(const char *start, const char **end)
905 {
906     const char *term;
907
908     /* Skip the prefix if there is one. */
909     for (term = start; isalnum(*term) && (term < *end); ++term) ;
910     if (term != start) {
911         if ((term + 2 >= *end) || (term[0] != ':') || (term[1] != ' ')) {
912             log_module(MAIN_LOG, LOG_FATAL, "In helpfile condition '%.*s' expected prefix to end with ': '.", *end-start, start);
913             return -1;
914         }
915         start = term + 2;
916     }
917
918     /* Evaluate the remaining string as an expression. */
919     return helpfile_eval_expr(start, end);
920 }
921
922 static int
923 unlistify_help(const char *key, void *data, void *extra)
924 {
925     struct record_data *rd = data;
926     dict_t newdb = extra;
927
928     switch (rd->type) {
929     case RECDB_QSTRING:
930         dict_insert(newdb, strdup(key), alloc_record_data_qstring(GET_RECORD_QSTRING(rd)));
931         return 0;
932     case RECDB_STRING_LIST: {
933         struct string_list *slist = GET_RECORD_STRING_LIST(rd);
934         char *dest;
935         unsigned int totlen, len, i;
936
937         for (i=totlen=0; i<slist->used; i++)
938             totlen = totlen + strlen(slist->list[i]) + 1;
939         dest = alloca(totlen+1);
940         for (i=totlen=0; i<slist->used; i++) {
941             len = strlen(slist->list[i]);
942             memcpy(dest+totlen, slist->list[i], len);
943             dest[totlen+len] = '\n';
944             totlen = totlen + len + 1;
945         }
946         dest[totlen] = 0;
947         dict_insert(newdb, strdup(key), alloc_record_data_qstring(dest));
948         return 0;
949     }
950     case RECDB_OBJECT: {
951         dict_iterator_t it;
952
953         for (it = dict_first(GET_RECORD_OBJECT(rd)); it; it = iter_next(it)) {
954             const char *k2, *end;
955             int res;
956
957             /* Evaluate the expression for this subentry. */
958             k2 = iter_key(it);
959             end = k2 + strlen(k2);
960             res = helpfile_eval_condition(k2, &end);
961             /* If the evaluation failed, bail. */
962             if (res < 0) {
963                 log_module(MAIN_LOG, LOG_FATAL, " .. while processing entry '%s' condition '%s'.", key, k2);
964                 return 1;
965             }
966             /* If the condition was false, try another. */
967             if (!res)
968                 continue;
969             /* If we cannot unlistify the contents, bail. */
970             if (unlistify_help(key, iter_data(it), extra))
971                 return 1;
972             return 0;
973         }
974         /* If none of the conditions apply, just omit the entry. */
975         return 0;
976     }
977     default:
978         return 1;
979     }
980 }
981
982 struct helpfile *
983 open_helpfile(const char *fname, expand_func_t expand)
984 {
985     struct helpfile *hf;
986     char *slash;
987     dict_t db = parse_database(fname);
988     hf = calloc(1, sizeof(*hf));
989     hf->expand = expand;
990     hf->db = alloc_database();
991     dict_set_free_keys(hf->db, free);
992     if ((slash = strrchr(fname, '/'))) {
993         hf->name = strdup(slash + 1);
994     } else {
995         hf->name = strdup(fname);
996         dict_insert(language_find("C")->helpfiles, hf->name, hf);
997     }
998     if (db) {
999         dict_foreach(db, unlistify_help, hf->db);
1000         free_database(db);
1001     }
1002     return hf;
1003 }
1004
1005 void close_helpfile(struct helpfile *hf)
1006 {
1007     if (!hf)
1008         return;
1009     free((char*)hf->name);
1010     free_database(hf->db);
1011     free(hf);
1012 }
1013
1014 void message_register_table(const struct message_entry *table)
1015 {
1016     if (!lang_C)
1017         language_find("C");
1018     while (table->msgid) {
1019         dict_insert(lang_C->messages, table->msgid, (char*)table->format);
1020         table++;
1021     }
1022 }
1023
1024 void helpfile_init(void)
1025 {
1026     message_register_table(msgtab);
1027     language_read_list();
1028 }
1029
1030 void helpfile_finalize(void)
1031 {
1032     language_read_all();
1033     reg_exit_func(language_cleanup);
1034 }