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