1 /* helpfile.c - Help file loading and display
2 * Copyright 2000-2004 srvx Development Team
4 * This file is part of srvx.
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.
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.
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.
28 static const struct message_entry msgtab[] = {
29 { "HFMSG_MISSING_HELPFILE", "The help file could not be found. Sorry!" },
30 { "HFMSG_HELP_NOT_STRING", "Help file error (help data was not a string)." },
34 #define DEFAULT_LINE_SIZE MAX_LINE_SIZE
35 #define DEFAULT_TABLE_SIZE 80
37 extern struct userNode *global, *chanserv, *opserv, *nickserv;
38 struct userNode *message_dest;
39 struct userNode *message_source;
40 struct language *lang_C;
41 struct dict *languages;
43 static void language_cleanup(void)
45 dict_delete(languages);
48 static void language_free_helpfile(void *data)
50 struct helpfile *hf = data;
54 static void language_free(void *data)
56 struct language *lang = data;
57 dict_delete(lang->messages);
58 dict_delete(lang->helpfiles);
63 static struct language *language_alloc(const char *name)
65 struct language *lang = calloc(1, sizeof(*lang));
66 lang->name = strdup(name);
68 languages = dict_new();
69 dict_set_free_data(languages, language_free);
71 dict_insert(languages, lang->name, lang);
75 /* Language names should use a lang or lang_COUNTRY type system, where
76 * lang is a two-letter code according to ISO-639-1 (or three-letter
77 * code according to ISO-639-2 for languages not in ISO-639-1), and
78 * COUNTRY is the ISO 3166 country code in all upper case.
81 * http://www.loc.gov/standards/iso639-2/
82 * http://www.loc.gov/standards/iso639-2/langhome.html
83 * http://www.iso.ch/iso/en/prods-services/iso3166ma/index.html
85 struct language *language_find(const char *name)
87 struct language *lang;
88 char alt_name[MAXLEN];
91 if ((lang = dict_find(languages, name, NULL)))
93 if ((uscore = strchr(name, '_'))) {
94 strncpy(alt_name, name, uscore-name);
95 alt_name[uscore-name] = 0;
96 if ((lang = dict_find(languages, alt_name, NULL)))
100 lang_C = language_alloc("C");
101 lang_C->messages = dict_new();
102 lang_C->helpfiles = dict_new();
107 static void language_set_messages(struct language *lang, dict_t dict)
109 dict_iterator_t it, it2;
110 struct record_data *rd;
113 int diff, extra, missing;
116 for (it = dict_first(dict), it2 = dict_first(lang_C->messages); it || it2; ) {
117 msgid = iter_key(it);
119 diff = irccasecmp(msgid, iter_key(it2));
128 } else if (diff > 0) {
130 it2 = iter_next(it2);
133 msgid = iter_key(it);
137 msg = strdup(rd->d.qstring);
139 case RECDB_STRING_LIST:
140 /* XXX: maybe do an unlistify_help() type thing */
142 log_module(MAIN_LOG, LOG_WARNING, "Unsupported record type for message %s in language %s", msgid, lang->name);
145 dict_insert(lang->messages, iter_key(it2), msg);
147 it2 = iter_next(it2);
149 log_module(MAIN_LOG, LOG_WARNING, "In language %s, %d extra and %d missing messages", lang->name, extra, missing);
152 static struct language *language_read(const char *name)
155 struct dirent *dirent;
156 struct language *lang;
158 char filename[MAXLEN], *uscore;
162 /* Never try to read the C language from disk. */
163 if (!irccasecmp(name, "C"))
166 /* Open the directory stream; if we can't, fail. */
167 snprintf(filename, sizeof(filename), "languages/%s", name);
168 if (!(dir = opendir(filename))) {
172 if (!(lang = dict_find(languages, name, NULL)))
173 lang = language_alloc(name);
175 /* Find the parent language. */
176 snprintf(filename, sizeof(filename), "languages/%s/parent", name);
177 if (!(file = fopen(filename, "r"))
178 || !fgets(filename, sizeof(filename), file)) {
179 strcpy(filename, "C");
181 if (!(lang->parent = language_find(filename))) {
182 uscore = strchr(filename, '_');
185 lang->parent = language_find(filename);
188 lang->parent = lang_C;
191 /* (Re-)initialize the language's dicts. */
192 dict_delete(lang->messages);
193 lang->messages = dict_new();
194 dict_set_free_data(lang->messages, free);
195 lang->helpfiles = dict_new();
196 dict_set_free_data(lang->helpfiles, language_free_helpfile);
198 /* Read all the translations from the directory. */
199 while ((dirent = readdir(dir))) {
200 snprintf(filename, sizeof(filename), "languages/%s/%s", name, dirent->d_name);
201 if (!strcmp(dirent->d_name,"parent")) {
203 } else if (!strcmp(dirent->d_name, "strings.db")) {
204 dict = parse_database(filename);
205 language_set_messages(lang, dict);
207 } else if ((hf = dict_find(lang_C->helpfiles, dirent->d_name, NULL))) {
208 hf = open_helpfile(filename, hf->expand);
209 dict_insert(lang->helpfiles, hf->name, hf);
218 static void language_read_all(void)
220 struct string_list *slist;
221 struct dirent *dirent;
225 /* Read into an in-memory list and sort so we are likely to load
226 * parent languages before their children (de_DE sorts after de).
228 if (!(dir = opendir("languages")))
230 slist = alloc_string_list(4);
231 while ((dirent = readdir(dir)))
232 string_list_append(slist, strdup(dirent->d_name));
234 string_list_sort(slist);
235 for (ii = 0; ii < slist->used; ++ii) {
236 if (!strcmp(slist->list[ii], ".") || !strcmp(slist->list[ii], ".."))
238 language_read(slist->list[ii]);
240 free_string_list(slist);
243 const char *language_find_message(struct language *lang, const char *msgid) {
244 struct language *curr;
248 for (curr = lang; curr; curr = curr->parent)
249 if ((msg = dict_find(curr->messages, msgid, NULL)))
251 log_module(MAIN_LOG, LOG_ERROR, "Tried to find unregistered message \"%s\" (original language %s)", msgid, lang->name);
256 table_send(struct userNode *from, const char *to, unsigned int size, irc_send_func irc_send, struct helpfile_table table) {
257 unsigned int ii, jj, len, nreps, reps, tot_width, pos, spaces, *max_width;
258 char line[MAX_LINE_SIZE+1];
259 struct handle_info *hi;
261 if (IsChannelName(to) || *to == '$') {
265 message_dest = GetUserH(to);
267 log_module(MAIN_LOG, LOG_ERROR, "Unable to find user with nickname %s (in table_send from %s).", to, from->nick);
270 hi = message_dest->handle_info;
271 #ifdef WITH_PROTOCOL_P10
272 to = message_dest->numeric;
275 message_source = from;
277 /* If size or irc_send are 0, we should try to use a default. */
281 size = DEFAULT_TABLE_SIZE;
282 else if (hi->table_width)
283 size = hi->table_width;
284 else if (hi->screen_width)
285 size = hi->screen_width;
287 size = DEFAULT_TABLE_SIZE;
290 {} /* use that function */
292 irc_send = HANDLE_FLAGGED(hi, USE_PRIVMSG) ? irc_privmsg : irc_notice;
294 irc_send = IsChannelName(to) ? irc_privmsg : irc_notice;
296 /* Limit size to how much we can show at once */
297 if (size > sizeof(line))
300 /* Figure out how wide columns should be */
301 max_width = alloca(table.width * sizeof(int));
302 for (jj=tot_width=0; jj<table.width; jj++) {
303 /* Find the widest width for this column */
305 for (ii=0; ii<table.length; ii++) {
306 len = strlen(table.contents[ii][jj]);
307 if (len > max_width[jj])
310 /* Separate columns with spaces */
311 tot_width += max_width[jj] + 1;
313 /* How many rows to put in a line? */
314 if ((table.flags & TABLE_REPEAT_ROWS) && (size > tot_width))
315 nreps = size / tot_width;
318 /* Send headers line.. */
319 if (table.flags & TABLE_NO_HEADERS) {
322 /* Sending headers needs special treatment: either show them
323 * once, or repeat them as many times as we repeat the columns
325 for (pos=ii=0; ii<((table.flags & TABLE_REPEAT_HEADERS)?nreps:1); ii++) {
327 len = strlen(table.contents[0][jj]);
328 spaces = max_width[jj] - len;
329 if (table.flags & TABLE_PAD_LEFT)
332 memcpy(line+pos, table.contents[0][jj], len);
334 if (++jj == table.width)
336 if (!(table.flags & TABLE_PAD_LEFT))
343 irc_send(from, to, line);
346 /* Send the table. */
347 for (jj=0, pos=0, reps=0; ii<table.length; ) {
349 len = strlen(table.contents[ii][jj]);
350 spaces = max_width[jj] - len;
351 if (table.flags & TABLE_PAD_LEFT)
352 while (spaces--) line[pos++] = ' ';
353 memcpy(line+pos, table.contents[ii][jj], len);
355 if (++jj == table.width) {
356 jj = 0, ++ii, ++reps;
357 if ((reps == nreps) || (ii == table.length)) {
359 irc_send(from, to, line);
364 if (!(table.flags & TABLE_PAD_LEFT))
370 if (!(table.flags & TABLE_NO_FREE)) {
371 /* Deallocate table memory (but not the string memory). */
372 for (ii=0; ii<table.length; ii++)
373 free(table.contents[ii]);
374 free(table.contents);
379 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)
381 void (*irc_send)(struct userNode *from, const char *to, const char *msg);
382 static struct string_buffer input;
383 unsigned int size, ipos, pos, length, chars_sent, use_color;
384 unsigned int expand_pos, expand_ipos, newline_ipos;
385 char line[MAX_LINE_SIZE];
387 if (IsChannelName(dest) || *dest == '$') {
389 } else if (!(message_dest = GetUserH(dest))) {
390 log_module(MAIN_LOG, LOG_ERROR, "Unable to find user with nickname %s (in vsend_message from %s).", dest, src->nick);
392 } else if (message_dest->dead) {
393 /* No point in sending to a user who is leaving. */
396 #ifdef WITH_PROTOCOL_P10
397 dest = message_dest->numeric;
400 message_source = src;
401 if (!(msg_type & 4) && !(format = handle_find_message(handle, format)))
403 /* fill in a buffer with the string */
405 string_buffer_append_vprintf(&input, format, al);
407 /* figure out how to send the messages */
409 msg_type |= (HANDLE_FLAGGED(handle, USE_PRIVMSG) ? 1 : 0);
410 use_color = HANDLE_FLAGGED(handle, MIRC_COLOR);
411 size = handle->screen_width;
412 if (size > sizeof(line))
419 size = DEFAULT_LINE_SIZE;
420 switch (msg_type & 3) {
422 irc_send = irc_notice;
425 irc_send = irc_wallchops;
429 irc_send = irc_privmsg;
432 /* This used to be two passes, but if you do that and allow
433 * arbitrary sizes for ${}-expansions (as with help indexes),
434 * that requires a very big intermediate buffer.
436 expand_ipos = newline_ipos = ipos = 0;
437 expand_pos = pos = 0;
439 while (input.list[ipos]) {
440 char ch, *value, *free_value;
442 while ((ch = input.list[ipos]) && (ch != '$') && (ch != '\n') && (pos < size)) {
447 if (!input.list[ipos])
449 if (input.list[ipos] == '\n') {
454 unsigned int new_ipos;
455 /* Scan backwards for a space in the input, until we hit
456 * either the last newline or the last variable expansion.
457 * Print the line up to that point, and start from there.
459 for (new_ipos = ipos;
460 (new_ipos > expand_ipos) && (new_ipos > newline_ipos);
462 if (input.list[new_ipos] == ' ')
464 pos -= ipos - new_ipos;
465 if (new_ipos == newline_ipos) {
466 /* Single word was too big to fit on one line; skip
467 * forward to its end and print it as a whole.
469 while (input.list[new_ipos]
470 && (input.list[new_ipos] != ' ')
471 && (input.list[new_ipos] != '\n')
472 && (input.list[new_ipos] != '$'))
473 line[pos++] = input.list[new_ipos++];
476 while (input.list[ipos] == ' ')
482 switch (input.list[++ipos]) {
483 /* Literal '$' or end of string. */
489 /* The following two expand to mIRC color codes if enabled
492 value = use_color ? "\002" : "";
495 value = use_color ? "\017" : "";
498 value = use_color ? "\026" : "";
501 value = use_color ? "\037" : "";
508 value = global ? global->nick : "Global";
511 value = chanserv ? chanserv->nick : "ChanServ";
514 value = opserv ? opserv->nick : "OpServ";
517 value = nickserv ? nickserv->nick : "NickServ";
523 value = handle ? handle->handle : "Account";
525 #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)
526 /* Custom expansion handled by helpfile-specific function. */
530 char *name_end = input.list + ipos + 1;
532 while (*name_end != '}' && *name_end != ')' && *name_end) name_end++;
534 struct helpfile_expansion exp;
536 exp = expand_f(input.list + ipos + 1);
539 free_value = value = exp.value.str;
544 /* Must send current line, then emit table. */
546 table_send(src, (message_dest ? message_dest->nick : dest), 0, irc_send, exp.value.table);
551 log_module(MAIN_LOG, LOG_ERROR, "Invalid exp.type %d from expansion function %p.", exp.type, expand_f);
554 ipos = name_end - input.list;
559 /* Let it fall through when there's no expansion function or
564 value[1] = input.list[ipos];
568 while ((pos + strlen(value) > size) || strchr(value, '\n')) {
570 avail = size - pos - 1;
571 length = strcspn(value, "\n ");
572 if (length <= avail) {
573 strncpy(line+pos, value, length);
576 /* copy over spaces, until (possible) end of line */
577 while (*value == ' ') {
579 line[pos++] = *value;
583 /* word to send is too big to send now.. what to do? */
585 /* try to put it on a separate line */
588 /* already at start of line; only send part of it */
589 strncpy(line, value, avail);
592 /* skip any trailing spaces */
593 while (*value == ' ')
597 /* if we're looking at a newline, send the accumulated text */
598 if (*value == '\n') {
603 length = strlen(value);
604 memcpy(line + pos, value, length);
608 if ((pos < size-1) && input.list[ipos]) {
623 send_message(struct userNode *dest, struct userNode *src, const char *format, ...)
628 if (IsLocal(dest)) return 0;
629 va_start(ap, format);
630 res = vsend_message(dest->nick, src, dest->handle_info, 0, NULL, format, ap);
636 send_message_type(int msg_type, struct userNode *dest, struct userNode *src, const char *format, ...) {
640 if (IsLocal(dest)) return 0;
641 va_start(ap, format);
642 res = vsend_message(dest->nick, src, dest->handle_info, msg_type, NULL, format, ap);
648 send_target_message(int msg_type, const char *dest, struct userNode *src, const char *format, ...)
653 va_start(ap, format);
654 res = vsend_message(dest, src, NULL, msg_type, NULL, format, ap);
660 _send_help(struct userNode *dest, struct userNode *src, expand_func_t expand, const char *format, ...)
665 va_start(ap, format);
666 res = vsend_message(dest->nick, src, dest->handle_info, 4, expand, format, ap);
672 send_help(struct userNode *dest, struct userNode *src, struct helpfile *hf, const char *topic)
674 struct helpfile *lang_hf;
675 struct record_data *rec;
676 struct language *curr;
681 _send_help(dest, src, NULL, "HFMSG_MISSING_HELPFILE");
684 for (curr = (dest->handle_info ? dest->handle_info->language : lang_C);
686 curr = curr->parent) {
687 lang_hf = dict_find(curr->helpfiles, hf->name, NULL);
690 rec = dict_find(lang_hf->db, topic, NULL);
691 if (rec && rec->type == RECDB_QSTRING)
692 return _send_help(dest, src, hf->expand, rec->d.qstring);
694 rec = dict_find(hf->db, "<missing>", NULL);
696 return send_message(dest, src, "MSG_TOPIC_UNKNOWN");
697 if (rec->type != RECDB_QSTRING)
698 return send_message(dest, src, "HFMSG_HELP_NOT_STRING");
699 return _send_help(dest, src, hf->expand, rec->d.qstring);
702 /* Grammar supported by this parser:
703 * condition = expr | prefix expr
704 * expr = atomicexpr | atomicexpr op atomicexpr
705 * op = '&&' | '||' | 'and' | 'or'
706 * atomicexpr = '(' expr ')' | identifier
707 * identifier = ( '0'-'9' 'A'-'Z' 'a'-'z' '-' '_' '/' )+ | ! identifier
709 * Whitespace is ignored. The parser is implemented as a recursive
710 * descent parser by functions like:
711 * static int helpfile_eval_<element>(const char *start, const char **end);
720 static const struct {
723 } helpfile_operators[] = {
724 { "&&", OP_BOOL_AND },
725 { "and", OP_BOOL_AND },
726 { "||", OP_BOOL_OR },
727 { "or", OP_BOOL_OR },
731 static const char *identifier_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_/";
733 static int helpfile_eval_expr(const char *start, const char **end);
734 static int helpfile_eval_atomicexpr(const char *start, const char **end);
735 static int helpfile_eval_identifier(const char *start, const char **end);
738 helpfile_eval_identifier(const char *start, const char **end)
740 /* Skip leading whitespace. */
741 while (isspace(*start) && (start < *end))
744 log_module(MAIN_LOG, LOG_FATAL, "Expected identifier in helpfile condition.");
748 if (start[0] == '!') {
749 int res = helpfile_eval_identifier(start+1, end);
753 } else if (start[0] == '/') {
755 char *id_str, *value;
758 strchr(identifier_chars, sep[0]) && (sep < *end);
760 memcpy(id_str = alloca(sep+1-start), start, sep-start);
761 id_str[sep-start] = '\0';
762 value = conf_get_data(id_str+1, RECDB_QSTRING);
766 return enabled_string(value) || true_string(value);
767 } else if ((*end - start >= 4) && !ircncasecmp(start, "true", 4)) {
770 } else if ((*end - start >= 5) && !ircncasecmp(start, "false", 5)) {
774 log_module(MAIN_LOG, LOG_FATAL, "Unexpected helpfile identifier '%.*s'.", *end-start, start);
780 helpfile_eval_atomicexpr(const char *start, const char **end)
785 /* Skip leading whitespace. */
786 while (isspace(*start) && (start < *end))
789 log_module(MAIN_LOG, LOG_FATAL, "Expected atomic expression in helpfile condition.");
793 /* If it's not parenthesized, it better be a valid identifier. */
795 return helpfile_eval_identifier(start, end);
797 /* Parse the internal expression. */
800 res = helpfile_eval_expr(start, &sep);
802 /* Check for the closing parenthesis. */
803 while (isspace(*sep) && (sep < *end))
805 if ((sep == *end) || (sep[0] != ')')) {
806 log_module(MAIN_LOG, LOG_FATAL, "Expected close parenthesis at '%.*s'.", *end-sep, sep);
810 /* Report the end location and result. */
816 helpfile_eval_expr(const char *start, const char **end)
818 const char *sep, *sep2;
819 unsigned int ii, len;
823 /* Parse the first atomicexpr. */
825 res_a = helpfile_eval_atomicexpr(start, &sep);
829 /* Figure out what follows that. */
830 while (isspace(*sep) && (sep < *end))
835 for (ii = 0; helpfile_operators[ii].str; ++ii) {
836 len = strlen(helpfile_operators[ii].str);
837 if (ircncasecmp(sep, helpfile_operators[ii].str, len))
839 op = helpfile_operators[ii].op;
842 if (op == OP_INVALID) {
843 log_module(MAIN_LOG, LOG_FATAL, "Unrecognized helpfile operator at '%.*s'.", *end-sep, sep);
847 /* Parse the next atomicexpr. */
849 res_b = helpfile_eval_atomicexpr(sep, &sep2);
853 /* Make sure there's no trailing garbage */
854 while (isspace(*sep2) && (sep2 < *end))
857 log_module(MAIN_LOG, LOG_FATAL, "Trailing garbage in helpfile expression: '%.*s'.", *end-sep2, sep2);
861 /* Record where we stopped parsing. */
864 /* Do the logic on the subexpressions. */
867 return res_a && res_b;
869 return res_a || res_b;
876 helpfile_eval_condition(const char *start, const char **end)
880 /* Skip the prefix if there is one. */
881 for (term = start; isalnum(*term) && (term < *end); ++term) ;
883 if ((term + 2 >= *end) || (term[0] != ':') || (term[1] != ' ')) {
884 log_module(MAIN_LOG, LOG_FATAL, "In helpfile condition '%.*s' expected prefix to end with ': '.", *end-start, start);
890 /* Evaluate the remaining string as an expression. */
891 return helpfile_eval_expr(start, end);
895 unlistify_help(const char *key, void *data, void *extra)
897 struct record_data *rd = data;
898 dict_t newdb = extra;
902 dict_insert(newdb, strdup(key), alloc_record_data_qstring(GET_RECORD_QSTRING(rd)));
904 case RECDB_STRING_LIST: {
905 struct string_list *slist = GET_RECORD_STRING_LIST(rd);
907 unsigned int totlen, len, i;
909 for (i=totlen=0; i<slist->used; i++)
910 totlen = totlen + strlen(slist->list[i]) + 1;
911 dest = alloca(totlen+1);
912 for (i=totlen=0; i<slist->used; i++) {
913 len = strlen(slist->list[i]);
914 memcpy(dest+totlen, slist->list[i], len);
915 dest[totlen+len] = '\n';
916 totlen = totlen + len + 1;
919 dict_insert(newdb, strdup(key), alloc_record_data_qstring(dest));
925 for (it = dict_first(GET_RECORD_OBJECT(rd)); it; it = iter_next(it)) {
926 const char *k2, *end;
929 /* Evaluate the expression for this subentry. */
931 end = k2 + strlen(k2);
932 res = helpfile_eval_condition(k2, &end);
933 /* If the evaluation failed, bail. */
935 log_module(MAIN_LOG, LOG_FATAL, " .. while processing entry '%s' condition '%s'.", key, k2);
938 /* If the condition was false, try another. */
941 /* If we cannot unlistify the contents, bail. */
942 if (unlistify_help(key, iter_data(it), extra))
946 /* If none of the conditions apply, just omit the entry. */
955 open_helpfile(const char *fname, expand_func_t expand)
959 dict_t db = parse_database(fname);
960 hf = calloc(1, sizeof(*hf));
962 hf->db = alloc_database();
963 dict_set_free_keys(hf->db, free);
964 if ((slash = strrchr(fname, '/'))) {
965 hf->name = strdup(slash + 1);
967 hf->name = strdup(fname);
968 dict_insert(language_find("C")->helpfiles, hf->name, hf);
971 dict_foreach(db, unlistify_help, hf->db);
977 void close_helpfile(struct helpfile *hf)
981 free((char*)hf->name);
982 free_database(hf->db);
986 void message_register_table(const struct message_entry *table)
990 while (table->msgid) {
991 dict_insert(lang_C->messages, table->msgid, (char*)table->format);
996 void helpfile_finalize(void)
998 message_register_table(msgtab);
1000 reg_exit_func(language_cleanup);