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.
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)." },
35 #define DEFAULT_LINE_SIZE MAX_LINE_SIZE
36 #define DEFAULT_TABLE_SIZE 80
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;
44 static void language_cleanup(void)
46 dict_delete(languages);
49 static void language_free_helpfile(void *data)
51 struct helpfile *hf = data;
55 static void language_free(void *data)
57 struct language *lang = data;
58 dict_delete(lang->messages);
59 dict_delete(lang->helpfiles);
64 static struct language *language_alloc(const char *name)
66 struct language *lang = calloc(1, sizeof(*lang));
67 lang->name = strdup(name);
68 lang->parent = lang_C;
70 languages = dict_new();
71 dict_set_free_data(languages, language_free);
73 dict_insert(languages, lang->name, lang);
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.
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
87 struct language *language_find(const char *name)
89 struct language *lang;
90 char alt_name[MAXLEN];
93 if ((lang = dict_find(languages, name, NULL)))
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)))
102 lang_C = language_alloc("C");
103 lang_C->messages = dict_new();
104 lang_C->helpfiles = dict_new();
109 static void language_set_messages(struct language *lang, dict_t dict)
111 dict_iterator_t it, it2;
112 struct record_data *rd;
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;
124 } else if (diff > 0) {
126 it2 = iter_next(it2);
132 msg = strdup(rd->d.qstring);
134 case RECDB_STRING_LIST:
135 /* XXX: maybe do an unlistify_help() type thing */
137 log_module(MAIN_LOG, LOG_WARNING, "Unsupported record type for message %s in language %s", msgid, lang->name);
140 dict_insert(lang->messages, strdup(msgid), msg);
142 it2 = iter_next(it2);
146 it2 = iter_next(it2);
148 if (extra || missing)
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)))
170 if (!(lang = dict_find(languages, name, NULL)))
171 lang = language_alloc(name);
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");
179 if (!(lang->parent = language_find(filename))) {
180 uscore = strchr(filename, '_');
183 lang->parent = language_find(filename);
186 lang->parent = lang_C;
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);
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")) {
202 } else if (!strcmp(dirent->d_name, "strings.db")) {
203 dict = parse_database(filename);
204 language_set_messages(lang, 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);
217 static void language_read_list(void)
219 struct dirent *dirent;
222 if (!(dir = opendir("languages")))
224 while ((dirent = readdir(dir))) {
225 if (dirent->d_name[0] == '.')
227 if (dirent->d_type != DT_DIR)
229 language_alloc(dirent->d_name);
234 const char *language_find_message(struct language *lang, const char *msgid) {
235 struct language *curr;
239 for (curr = lang; curr; curr = curr->parent)
240 if ((msg = dict_find(curr->messages, msgid, NULL)))
242 log_module(MAIN_LOG, LOG_ERROR, "Tried to find unregistered message \"%s\" (original language %s)", msgid, lang->name);
247 table_send(struct userNode *from, const char *to, unsigned int size, irc_send_func irc_send, struct helpfile_table table) {
248 unsigned int ii, jj, len, nreps, reps, tot_width, pos, spaces, *max_width;
249 char line[MAX_LINE_SIZE+1];
250 struct handle_info *hi;
252 if (IsChannelName(to) || *to == '$') {
256 message_dest = GetUserH(to);
258 log_module(MAIN_LOG, LOG_ERROR, "Unable to find user with nickname %s (in table_send from %s).", to, from->nick);
261 hi = message_dest->handle_info;
262 #ifdef WITH_PROTOCOL_P10
263 to = message_dest->numeric;
266 message_source = from;
268 /* If size or irc_send are 0, we should try to use a default. */
272 size = DEFAULT_TABLE_SIZE;
273 else if (hi->table_width)
274 size = hi->table_width;
275 else if (hi->screen_width)
276 size = hi->screen_width;
278 size = DEFAULT_TABLE_SIZE;
281 {} /* use that function */
283 irc_send = HANDLE_FLAGGED(hi, USE_PRIVMSG) ? irc_privmsg : irc_notice;
285 irc_send = IsChannelName(to) ? irc_privmsg : irc_notice;
287 /* Limit size to how much we can show at once */
288 if (size > sizeof(line))
291 /* Figure out how wide columns should be */
292 max_width = alloca(table.width * sizeof(int));
293 for (jj=tot_width=0; jj<table.width; jj++) {
294 /* Find the widest width for this column */
296 for (ii=0; ii<table.length; ii++) {
297 len = strlen(table.contents[ii][jj]);
298 if (len > max_width[jj])
301 /* Separate columns with spaces */
302 tot_width += max_width[jj] + 1;
304 /* How many rows to put in a line? */
305 if ((table.flags & TABLE_REPEAT_ROWS) && (size > tot_width))
306 nreps = size / tot_width;
309 /* Send headers line.. */
310 if (table.flags & TABLE_NO_HEADERS) {
313 /* Sending headers needs special treatment: either show them
314 * once, or repeat them as many times as we repeat the columns
316 for (pos=ii=0; ii<((table.flags & TABLE_REPEAT_HEADERS)?nreps:1); ii++) {
318 len = strlen(table.contents[0][jj]);
319 spaces = max_width[jj] - len;
320 if (table.flags & TABLE_PAD_LEFT)
323 memcpy(line+pos, table.contents[0][jj], len);
325 if (++jj == table.width)
327 if (!(table.flags & TABLE_PAD_LEFT))
334 irc_send(from, to, line);
337 /* Send the table. */
338 for (jj=0, pos=0, reps=0; ii<table.length; ) {
340 len = strlen(table.contents[ii][jj]);
341 spaces = max_width[jj] - len;
342 if (table.flags & TABLE_PAD_LEFT)
343 while (spaces--) line[pos++] = ' ';
344 memcpy(line+pos, table.contents[ii][jj], len);
346 if (++jj == table.width) {
347 jj = 0, ++ii, ++reps;
348 if ((reps == nreps) || (ii == table.length)) {
350 irc_send(from, to, line);
355 if (!(table.flags & TABLE_PAD_LEFT))
361 if (!(table.flags & TABLE_NO_FREE)) {
362 /* Deallocate table memory (but not the string memory). */
363 for (ii=0; ii<table.length; ii++)
364 free(table.contents[ii]);
365 free(table.contents);
370 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)
372 void (*irc_send)(struct userNode *from, const char *to, const char *msg);
373 static struct string_buffer input;
374 unsigned int size, ipos, pos, length, chars_sent, use_color;
375 unsigned int expand_pos, expand_ipos, newline_ipos;
376 char line[MAX_LINE_SIZE];
378 if (IsChannelName(dest) || *dest == '$') {
380 } else if (!(message_dest = GetUserH(dest))) {
381 log_module(MAIN_LOG, LOG_ERROR, "Unable to find user with nickname %s (in vsend_message from %s).", dest, src->nick);
383 } else if (message_dest->dead) {
384 /* No point in sending to a user who is leaving. */
387 #ifdef WITH_PROTOCOL_P10
388 dest = message_dest->numeric;
391 message_source = src;
392 if (!(msg_type & 4) && !(format = handle_find_message(handle, format)))
394 /* fill in a buffer with the string */
396 string_buffer_append_vprintf(&input, format, al);
398 /* figure out how to send the messages */
400 msg_type |= (HANDLE_FLAGGED(handle, USE_PRIVMSG) ? 1 : 0);
401 use_color = HANDLE_FLAGGED(handle, MIRC_COLOR);
402 size = handle->screen_width;
403 if (size > sizeof(line))
410 size = DEFAULT_LINE_SIZE;
411 switch (msg_type & 3) {
413 irc_send = irc_notice;
416 irc_send = irc_wallchops;
420 irc_send = irc_privmsg;
423 /* This used to be two passes, but if you do that and allow
424 * arbitrary sizes for ${}-expansions (as with help indexes),
425 * that requires a very big intermediate buffer.
427 expand_ipos = newline_ipos = ipos = 0;
428 expand_pos = pos = 0;
430 while (input.list[ipos]) {
431 char ch, *value, *free_value;
433 while ((ch = input.list[ipos]) && (ch != '$') && (ch != '\n') && (pos < size)) {
438 if (!input.list[ipos])
440 if (input.list[ipos] == '\n') {
445 unsigned int new_ipos;
446 /* Scan backwards for a space in the input, until we hit
447 * either the last newline or the last variable expansion.
448 * Print the line up to that point, and start from there.
450 for (new_ipos = ipos;
451 (new_ipos > expand_ipos) && (new_ipos > newline_ipos);
453 if (input.list[new_ipos] == ' ')
455 pos -= ipos - new_ipos;
456 if (new_ipos == newline_ipos) {
457 /* Single word was too big to fit on one line; skip
458 * forward to its end and print it as a whole.
460 while (input.list[new_ipos]
461 && (input.list[new_ipos] != ' ')
462 && (input.list[new_ipos] != '\n')
463 && (input.list[new_ipos] != '$'))
464 line[pos++] = input.list[new_ipos++];
467 while (input.list[ipos] == ' ')
473 switch (input.list[++ipos]) {
474 /* Literal '$' or end of string. */
480 /* The following two expand to mIRC color codes if enabled
483 value = use_color ? "\002" : "";
486 value = use_color ? "\017" : "";
489 value = use_color ? "\026" : "";
492 value = use_color ? "\037" : "";
499 value = global ? global->nick : "Global";
502 value = chanserv ? chanserv->nick : "ChanServ";
505 value = opserv ? opserv->nick : "OpServ";
508 value = nickserv ? nickserv->nick : "NickServ";
514 value = handle ? handle->handle : "Account";
516 #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)
517 /* Custom expansion handled by helpfile-specific function. */
520 struct helpfile_expansion exp;
521 char *name_end = input.list + ipos + 1, *colon = NULL;
523 while (*name_end != '}' && *name_end != ')' && *name_end) {
524 if (*name_end == ':') {
534 struct module *module = module_find(input.list + ipos + 1);
535 if (module && module->expand_help)
536 exp = module->expand_help(colon + 1);
542 exp = expand_f(input.list + ipos + 1);
547 free_value = value = exp.value.str;
552 /* Must send current line, then emit table. */
554 table_send(src, (message_dest ? message_dest->nick : dest), 0, irc_send, exp.value.table);
559 log_module(MAIN_LOG, LOG_ERROR, "Invalid exp.type %d from expansion function %p.", exp.type, expand_f);
562 ipos = name_end - input.list;
569 value[1] = input.list[ipos];
573 while ((pos + strlen(value) > size) || strchr(value, '\n')) {
575 avail = size - pos - 1;
576 length = strcspn(value, "\n ");
577 if (length <= avail) {
578 strncpy(line+pos, value, length);
581 /* copy over spaces, until (possible) end of line */
582 while (*value == ' ') {
584 line[pos++] = *value;
588 /* word to send is too big to send now.. what to do? */
590 /* try to put it on a separate line */
593 /* already at start of line; only send part of it */
594 strncpy(line, value, avail);
597 /* skip any trailing spaces */
598 while (*value == ' ')
602 /* if we're looking at a newline, send the accumulated text */
603 if (*value == '\n') {
608 length = strlen(value);
609 memcpy(line + pos, value, length);
613 if ((pos < size-1) && input.list[ipos]) {
628 send_message(struct userNode *dest, struct userNode *src, const char *format, ...)
633 if (IsLocal(dest)) return 0;
634 va_start(ap, format);
635 res = vsend_message(dest->nick, src, dest->handle_info, 0, NULL, format, ap);
641 send_message_type(int msg_type, struct userNode *dest, struct userNode *src, const char *format, ...) {
645 if (IsLocal(dest)) return 0;
646 va_start(ap, format);
647 res = vsend_message(dest->nick, src, dest->handle_info, msg_type, NULL, format, ap);
653 send_target_message(int msg_type, const char *dest, struct userNode *src, const char *format, ...)
658 va_start(ap, format);
659 res = vsend_message(dest, src, NULL, msg_type, NULL, format, ap);
665 _send_help(struct userNode *dest, struct userNode *src, expand_func_t expand, const char *format, ...)
670 va_start(ap, format);
671 res = vsend_message(dest->nick, src, dest->handle_info, 4, expand, format, ap);
677 send_help(struct userNode *dest, struct userNode *src, struct helpfile *hf, const char *topic)
679 struct helpfile *lang_hf;
680 struct record_data *rec;
681 struct language *curr;
686 _send_help(dest, src, NULL, "HFMSG_MISSING_HELPFILE");
689 for (curr = (dest->handle_info ? dest->handle_info->language : lang_C);
691 curr = curr->parent) {
692 lang_hf = dict_find(curr->helpfiles, hf->name, NULL);
695 rec = dict_find(lang_hf->db, topic, NULL);
696 if (rec && rec->type == RECDB_QSTRING)
697 return _send_help(dest, src, hf->expand, rec->d.qstring);
699 rec = dict_find(hf->db, "<missing>", NULL);
701 return send_message(dest, src, "MSG_TOPIC_UNKNOWN");
702 if (rec->type != RECDB_QSTRING)
703 return send_message(dest, src, "HFMSG_HELP_NOT_STRING");
704 return _send_help(dest, src, hf->expand, rec->d.qstring);
707 /* Grammar supported by this parser:
708 * condition = expr | prefix expr
709 * expr = atomicexpr | atomicexpr op atomicexpr
710 * op = '&&' | '||' | 'and' | 'or'
711 * atomicexpr = '(' expr ')' | identifier
712 * identifier = ( '0'-'9' 'A'-'Z' 'a'-'z' '-' '_' '/' )+ | ! identifier
714 * Whitespace is ignored. The parser is implemented as a recursive
715 * descent parser by functions like:
716 * static int helpfile_eval_<element>(const char *start, const char **end);
725 static const struct {
728 } helpfile_operators[] = {
729 { "&&", OP_BOOL_AND },
730 { "and", OP_BOOL_AND },
731 { "||", OP_BOOL_OR },
732 { "or", OP_BOOL_OR },
736 static const char *identifier_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_/";
738 static int helpfile_eval_expr(const char *start, const char **end);
739 static int helpfile_eval_atomicexpr(const char *start, const char **end);
740 static int helpfile_eval_identifier(const char *start, const char **end);
743 helpfile_eval_identifier(const char *start, const char **end)
745 /* Skip leading whitespace. */
746 while (isspace(*start) && (start < *end))
749 log_module(MAIN_LOG, LOG_FATAL, "Expected identifier in helpfile condition.");
753 if (start[0] == '!') {
754 int res = helpfile_eval_identifier(start+1, end);
758 } else if (start[0] == '/') {
760 char *id_str, *value;
763 strchr(identifier_chars, sep[0]) && (sep < *end);
765 memcpy(id_str = alloca(sep+1-start), start, sep-start);
766 id_str[sep-start] = '\0';
767 value = conf_get_data(id_str+1, RECDB_QSTRING);
771 return enabled_string(value) || true_string(value);
772 } else if ((*end - start >= 4) && !ircncasecmp(start, "true", 4)) {
775 } else if ((*end - start >= 5) && !ircncasecmp(start, "false", 5)) {
779 log_module(MAIN_LOG, LOG_FATAL, "Unexpected helpfile identifier '%.*s'.", *end-start, start);
785 helpfile_eval_atomicexpr(const char *start, const char **end)
790 /* Skip leading whitespace. */
791 while (isspace(*start) && (start < *end))
794 log_module(MAIN_LOG, LOG_FATAL, "Expected atomic expression in helpfile condition.");
798 /* If it's not parenthesized, it better be a valid identifier. */
800 return helpfile_eval_identifier(start, end);
802 /* Parse the internal expression. */
805 res = helpfile_eval_expr(start, &sep);
807 /* Check for the closing parenthesis. */
808 while (isspace(*sep) && (sep < *end))
810 if ((sep == *end) || (sep[0] != ')')) {
811 log_module(MAIN_LOG, LOG_FATAL, "Expected close parenthesis at '%.*s'.", *end-sep, sep);
815 /* Report the end location and result. */
821 helpfile_eval_expr(const char *start, const char **end)
823 const char *sep, *sep2;
824 unsigned int ii, len;
828 /* Parse the first atomicexpr. */
830 res_a = helpfile_eval_atomicexpr(start, &sep);
834 /* Figure out what follows that. */
835 while (isspace(*sep) && (sep < *end))
840 for (ii = 0; helpfile_operators[ii].str; ++ii) {
841 len = strlen(helpfile_operators[ii].str);
842 if (ircncasecmp(sep, helpfile_operators[ii].str, len))
844 op = helpfile_operators[ii].op;
847 if (op == OP_INVALID) {
848 log_module(MAIN_LOG, LOG_FATAL, "Unrecognized helpfile operator at '%.*s'.", *end-sep, sep);
852 /* Parse the next atomicexpr. */
854 res_b = helpfile_eval_atomicexpr(sep, &sep2);
858 /* Make sure there's no trailing garbage */
859 while (isspace(*sep2) && (sep2 < *end))
862 log_module(MAIN_LOG, LOG_FATAL, "Trailing garbage in helpfile expression: '%.*s'.", *end-sep2, sep2);
866 /* Record where we stopped parsing. */
869 /* Do the logic on the subexpressions. */
872 return res_a && res_b;
874 return res_a || res_b;
881 helpfile_eval_condition(const char *start, const char **end)
885 /* Skip the prefix if there is one. */
886 for (term = start; isalnum(*term) && (term < *end); ++term) ;
888 if ((term + 2 >= *end) || (term[0] != ':') || (term[1] != ' ')) {
889 log_module(MAIN_LOG, LOG_FATAL, "In helpfile condition '%.*s' expected prefix to end with ': '.", *end-start, start);
895 /* Evaluate the remaining string as an expression. */
896 return helpfile_eval_expr(start, end);
900 unlistify_help(const char *key, void *data, void *extra)
902 struct record_data *rd = data;
903 dict_t newdb = extra;
907 dict_insert(newdb, strdup(key), alloc_record_data_qstring(GET_RECORD_QSTRING(rd)));
909 case RECDB_STRING_LIST: {
910 struct string_list *slist = GET_RECORD_STRING_LIST(rd);
912 unsigned int totlen, len, i;
914 for (i=totlen=0; i<slist->used; i++)
915 totlen = totlen + strlen(slist->list[i]) + 1;
916 dest = alloca(totlen+1);
917 for (i=totlen=0; i<slist->used; i++) {
918 len = strlen(slist->list[i]);
919 memcpy(dest+totlen, slist->list[i], len);
920 dest[totlen+len] = '\n';
921 totlen = totlen + len + 1;
924 dict_insert(newdb, strdup(key), alloc_record_data_qstring(dest));
930 for (it = dict_first(GET_RECORD_OBJECT(rd)); it; it = iter_next(it)) {
931 const char *k2, *end;
934 /* Evaluate the expression for this subentry. */
936 end = k2 + strlen(k2);
937 res = helpfile_eval_condition(k2, &end);
938 /* If the evaluation failed, bail. */
940 log_module(MAIN_LOG, LOG_FATAL, " .. while processing entry '%s' condition '%s'.", key, k2);
943 /* If the condition was false, try another. */
946 /* If we cannot unlistify the contents, bail. */
947 if (unlistify_help(key, iter_data(it), extra))
951 /* If none of the conditions apply, just omit the entry. */
960 open_helpfile(const char *fname, expand_func_t expand)
964 dict_t db = parse_database(fname);
965 hf = calloc(1, sizeof(*hf));
967 hf->db = alloc_database();
968 dict_set_free_keys(hf->db, free);
969 if ((slash = strrchr(fname, '/'))) {
970 hf->name = strdup(slash + 1);
972 hf->name = strdup(fname);
973 dict_insert(language_find("C")->helpfiles, hf->name, hf);
976 dict_foreach(db, unlistify_help, hf->db);
982 void close_helpfile(struct helpfile *hf)
986 free((char*)hf->name);
987 free_database(hf->db);
991 void message_register_table(const struct message_entry *table)
995 while (table->msgid) {
996 dict_insert(lang_C->messages, table->msgid, (char*)table->format);
1001 void helpfile_init(void)
1003 message_register_table(msgtab);
1004 language_read_list();
1007 void helpfile_finalize(void)
1010 for (it = dict_first(languages); it; it = iter_next(it))
1011 language_read(iter_key(it));
1012 reg_exit_func(language_cleanup);