1 /* helpfile.c - Help file loading and display
2 * Copyright 2000-2004 srvx Development Team
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version. Important limitations are
8 * listed in the COPYING file that accompanies this software.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, email srvx-maintainers@srvx.net.
26 static const struct message_entry msgtab[] = {
27 { "HFMSG_MISSING_HELPFILE", "The help file could not be found. Sorry!" },
28 { "HFMSG_HELP_NOT_STRING", "Help file error (help data was not a string)." },
32 #define DEFAULT_LINE_SIZE MAX_LINE_SIZE
33 #define DEFAULT_TABLE_SIZE 80
35 extern struct userNode *global, *chanserv, *opserv, *nickserv;
36 struct userNode *message_dest;
37 struct userNode *message_source;
38 struct language *lang_C;
39 struct dict *languages;
41 static void language_cleanup(void)
43 dict_delete(languages);
46 static void language_free_helpfile(void *data)
48 struct helpfile *hf = data;
52 static void language_free(void *data)
54 struct language *lang = data;
55 dict_delete(lang->messages);
56 dict_delete(lang->helpfiles);
61 static struct language *language_alloc(const char *name)
63 struct language *lang = calloc(1, sizeof(*lang));
64 lang->name = strdup(name);
66 languages = dict_new();
67 dict_set_free_data(languages, language_free);
69 dict_insert(languages, lang->name, lang);
73 /* Language names should use a lang or lang_COUNTRY type system, where
74 * lang is a two-letter code according to ISO-639-1 (or three-letter
75 * code according to ISO-639-2 for languages not in ISO-639-1), and
76 * COUNTRY is the ISO 3166 country code in all upper case.
79 * http://www.loc.gov/standards/iso639-2/
80 * http://www.loc.gov/standards/iso639-2/langhome.html
81 * http://www.iso.ch/iso/en/prods-services/iso3166ma/index.html
83 struct language *language_find(const char *name)
85 struct language *lang;
86 char alt_name[MAXLEN];
89 if ((lang = dict_find(languages, name, NULL)))
91 if ((uscore = strchr(name, '_'))) {
92 strncpy(alt_name, name, uscore-name);
93 alt_name[uscore-name] = 0;
94 if ((lang = dict_find(languages, alt_name, NULL)))
98 lang_C = language_alloc("C");
99 lang_C->messages = dict_new();
100 lang_C->helpfiles = dict_new();
105 static void language_set_messages(struct language *lang, dict_t dict)
107 dict_iterator_t it, it2;
108 struct record_data *rd;
111 int diff, extra, missing;
114 for (it = dict_first(dict), it2 = dict_first(lang_C->messages); it || it2; ) {
115 msgid = iter_key(it);
117 diff = irccasecmp(msgid, iter_key(it2));
126 } else if (diff > 0) {
128 it2 = iter_next(it2);
131 msgid = iter_key(it);
135 msg = strdup(rd->d.qstring);
137 case RECDB_STRING_LIST:
138 /* XXX: maybe do an unlistify_help() type thing */
140 log_module(MAIN_LOG, LOG_WARNING, "Unsupported record type for message %s in language %s", msgid, lang->name);
143 dict_insert(lang->messages, iter_key(it2), msg);
145 it2 = iter_next(it2);
147 log_module(MAIN_LOG, LOG_WARNING, "In language %s, %d extra and %d missing messages", lang->name, extra, missing);
150 static struct language *language_read(const char *name)
153 struct dirent *dirent;
154 struct language *lang;
156 char filename[MAXLEN], *uscore;
160 /* Never try to read the C language from disk. */
161 if (!irccasecmp(name, "C"))
164 /* Open the directory stream; if we can't, fail. */
165 snprintf(filename, sizeof(filename), "languages/%s", name);
166 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_data(lang->messages, free);
193 lang->helpfiles = dict_new();
194 dict_set_free_data(lang->helpfiles, language_free_helpfile);
196 /* Read all the translations from the directory. */
197 while ((dirent = readdir(dir))) {
198 snprintf(filename, sizeof(filename), "languages/%s/%s", name, dirent->d_name);
199 if (!strcmp(dirent->d_name,"parent")) {
201 } else if (!strcmp(dirent->d_name, "strings.db")) {
202 dict = parse_database(filename);
203 language_set_messages(lang, dict);
205 } else if ((hf = dict_find(lang_C->helpfiles, dirent->d_name, NULL))) {
206 hf = open_helpfile(filename, hf->expand);
207 dict_insert(lang->helpfiles, hf->name, hf);
216 static void language_read_all(void)
218 struct string_list *slist;
219 struct dirent *dirent;
223 /* Read into an in-memory list and sort so we are likely to load
224 * parent languages before their children (de_DE sorts after de).
226 if (!(dir = opendir("languages")))
228 slist = alloc_string_list(4);
229 while ((dirent = readdir(dir)))
230 string_list_append(slist, strdup(dirent->d_name));
232 string_list_sort(slist);
233 for (ii = 0; ii < slist->used; ++ii) {
234 if (!strcmp(slist->list[ii], ".") || !strcmp(slist->list[ii], ".."))
236 language_read(slist->list[ii]);
238 free_string_list(slist);
241 const char *language_find_message(struct language *lang, const char *msgid) {
242 struct language *curr;
246 for (curr = lang; curr; curr = curr->parent)
247 if ((msg = dict_find(curr->messages, msgid, NULL)))
249 log_module(MAIN_LOG, LOG_ERROR, "Tried to find unregistered message \"%s\" (original language %s)", msgid, lang->name);
254 table_send(struct userNode *from, const char *to, unsigned int size, irc_send_func irc_send, struct helpfile_table table) {
255 unsigned int ii, jj, len, nreps, reps, tot_width, pos, spaces, *max_width;
256 char line[MAX_LINE_SIZE+1];
257 struct handle_info *hi;
259 if (IsChannelName(to) || *to == '$') {
263 message_dest = GetUserH(to);
265 log_module(MAIN_LOG, LOG_ERROR, "Unable to find user with nickname %s (in table_send from %s).", to, from->nick);
268 hi = message_dest->handle_info;
269 #ifdef WITH_PROTOCOL_P10
270 to = message_dest->numeric;
273 message_source = from;
275 /* If size or irc_send are 0, we should try to use a default. */
279 size = DEFAULT_TABLE_SIZE;
280 else if (hi->table_width)
281 size = hi->table_width;
282 else if (hi->screen_width)
283 size = hi->screen_width;
285 size = DEFAULT_TABLE_SIZE;
288 {} /* use that function */
290 irc_send = HANDLE_FLAGGED(hi, USE_PRIVMSG) ? irc_privmsg : irc_notice;
292 irc_send = IsChannelName(to) ? irc_privmsg : irc_notice;
294 /* Limit size to how much we can show at once */
295 if (size > sizeof(line))
298 /* Figure out how wide columns should be */
299 max_width = alloca(table.width * sizeof(int));
300 for (jj=tot_width=0; jj<table.width; jj++) {
301 /* Find the widest width for this column */
303 for (ii=0; ii<table.length; ii++) {
304 len = strlen(table.contents[ii][jj]);
305 if (len > max_width[jj])
308 /* Separate columns with spaces */
309 tot_width += max_width[jj] + 1;
311 /* How many rows to put in a line? */
312 if ((table.flags & TABLE_REPEAT_ROWS) && (size > tot_width))
313 nreps = size / tot_width;
316 /* Send headers line.. */
317 if (table.flags & TABLE_NO_HEADERS) {
320 /* Sending headers needs special treatment: either show them
321 * once, or repeat them as many times as we repeat the columns
323 for (pos=ii=0; ii<((table.flags & TABLE_REPEAT_HEADERS)?nreps:1); ii++) {
325 len = strlen(table.contents[0][jj]);
326 spaces = max_width[jj] - len;
327 if (table.flags & TABLE_PAD_LEFT)
330 memcpy(line+pos, table.contents[0][jj], len);
332 if (++jj == table.width)
334 if (!(table.flags & TABLE_PAD_LEFT))
341 irc_send(from, to, line);
344 /* Send the table. */
345 for (jj=0, pos=0, reps=0; ii<table.length; ) {
347 len = strlen(table.contents[ii][jj]);
348 spaces = max_width[jj] - len;
349 if (table.flags & TABLE_PAD_LEFT)
350 while (spaces--) line[pos++] = ' ';
351 memcpy(line+pos, table.contents[ii][jj], len);
353 if (++jj == table.width) {
354 jj = 0, ++ii, ++reps;
355 if ((reps == nreps) || (ii == table.length)) {
357 irc_send(from, to, line);
362 if (!(table.flags & TABLE_PAD_LEFT))
368 if (!(table.flags & TABLE_NO_FREE)) {
369 /* Deallocate table memory (but not the string memory). */
370 for (ii=0; ii<table.length; ii++)
371 free(table.contents[ii]);
372 free(table.contents);
377 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)
379 void (*irc_send)(struct userNode *from, const char *to, const char *msg);
380 static struct string_buffer input;
381 unsigned int size, ipos, pos, length, chars_sent, use_color;
382 unsigned int expand_pos, expand_ipos, newline_ipos;
383 char line[MAX_LINE_SIZE];
385 if (IsChannelName(dest) || *dest == '$') {
387 } else if (!(message_dest = GetUserH(dest))) {
388 log_module(MAIN_LOG, LOG_ERROR, "Unable to find user with nickname %s (in vsend_message from %s).", dest, src->nick);
390 } else if (message_dest->dead) {
391 /* No point in sending to a user who is leaving. */
394 #ifdef WITH_PROTOCOL_P10
395 dest = message_dest->numeric;
398 message_source = src;
399 if (!(msg_type & 4) && !(format = handle_find_message(handle, format)))
401 /* fill in a buffer with the string */
403 string_buffer_append_vprintf(&input, format, al);
405 /* figure out how to send the messages */
407 msg_type |= (HANDLE_FLAGGED(handle, USE_PRIVMSG) ? 1 : 0);
408 use_color = HANDLE_FLAGGED(handle, MIRC_COLOR);
409 size = handle->screen_width;
410 if (size > sizeof(line))
417 size = DEFAULT_LINE_SIZE;
418 switch (msg_type & 3) {
420 irc_send = irc_notice;
423 irc_send = irc_wallchops;
427 irc_send = irc_privmsg;
430 /* This used to be two passes, but if you do that and allow
431 * arbitrary sizes for ${}-expansions (as with help indexes),
432 * that requires a very big intermediate buffer.
434 expand_ipos = newline_ipos = ipos = 0;
435 expand_pos = pos = 0;
437 while (input.list[ipos]) {
438 char ch, *value, *free_value;
440 while ((ch = input.list[ipos]) && (ch != '$') && (ch != '\n') && (pos < size)) {
445 if (!input.list[ipos])
447 if (input.list[ipos] == '\n') {
452 unsigned int new_ipos;
453 /* Scan backwards for a space in the input, until we hit
454 * either the last newline or the last variable expansion.
455 * Print the line up to that point, and start from there.
457 for (new_ipos = ipos;
458 (new_ipos > expand_ipos) && (new_ipos > newline_ipos);
460 if (input.list[new_ipos] == ' ')
462 pos -= ipos - new_ipos;
463 if (new_ipos == newline_ipos) {
464 /* Single word was too big to fit on one line; skip
465 * forward to its end and print it as a whole.
467 while (input.list[new_ipos]
468 && (input.list[new_ipos] != ' ')
469 && (input.list[new_ipos] != '\n')
470 && (input.list[new_ipos] != '$'))
471 line[pos++] = input.list[new_ipos++];
474 while (input.list[ipos] == ' ')
480 switch (input.list[++ipos]) {
481 /* Literal '$' or end of string. */
487 /* The following two expand to mIRC color codes if enabled
490 value = use_color ? "\002" : "";
493 value = use_color ? "\017" : "";
496 value = use_color ? "\026" : "";
499 value = use_color ? "\037" : "";
506 value = global ? global->nick : "Global";
509 value = chanserv ? chanserv->nick : "ChanServ";
512 value = opserv ? opserv->nick : "OpServ";
515 value = nickserv ? nickserv->nick : "NickServ";
521 value = handle ? handle->handle : "Account";
523 #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)
524 /* Custom expansion handled by helpfile-specific function. */
528 char *name_end = input.list + ipos + 1;
530 while (*name_end != '}' && *name_end != ')' && *name_end) name_end++;
532 struct helpfile_expansion exp;
534 exp = expand_f(input.list + ipos + 1);
537 free_value = value = exp.value.str;
542 /* Must send current line, then emit table. */
544 table_send(src, (message_dest ? message_dest->nick : dest), 0, irc_send, exp.value.table);
549 log_module(MAIN_LOG, LOG_ERROR, "Invalid exp.type %d from expansion function %p.", exp.type, expand_f);
552 ipos = name_end - input.list;
557 /* Let it fall through when there's no expansion function or
562 value[1] = input.list[ipos];
566 while ((pos + strlen(value) > size) || strchr(value, '\n')) {
568 avail = size - pos - 1;
569 length = strcspn(value, "\n ");
570 if (length <= avail) {
571 strncpy(line+pos, value, length);
574 /* copy over spaces, until (possible) end of line */
575 while (*value == ' ') {
577 line[pos++] = *value;
581 /* word to send is too big to send now.. what to do? */
583 /* try to put it on a separate line */
586 /* already at start of line; only send part of it */
587 strncpy(line, value, avail);
590 /* skip any trailing spaces */
591 while (*value == ' ')
595 /* if we're looking at a newline, send the accumulated text */
596 if (*value == '\n') {
601 length = strlen(value);
602 memcpy(line + pos, value, length);
606 if ((pos < size-1) && input.list[ipos]) {
621 send_message(struct userNode *dest, struct userNode *src, const char *format, ...)
626 if (IsLocal(dest)) return 0;
627 va_start(ap, format);
628 res = vsend_message(dest->nick, src, dest->handle_info, 0, NULL, format, ap);
634 send_message_type(int msg_type, struct userNode *dest, struct userNode *src, const char *format, ...) {
638 if (IsLocal(dest)) return 0;
639 va_start(ap, format);
640 res = vsend_message(dest->nick, src, dest->handle_info, msg_type, NULL, format, ap);
646 send_target_message(int msg_type, const char *dest, struct userNode *src, const char *format, ...)
651 va_start(ap, format);
652 res = vsend_message(dest, src, NULL, msg_type, NULL, format, ap);
658 _send_help(struct userNode *dest, struct userNode *src, expand_func_t expand, const char *format, ...)
663 va_start(ap, format);
664 res = vsend_message(dest->nick, src, dest->handle_info, 4, expand, format, ap);
670 send_help(struct userNode *dest, struct userNode *src, struct helpfile *hf, const char *topic)
672 struct helpfile *lang_hf;
673 struct record_data *rec;
674 struct language *curr;
679 _send_help(dest, src, NULL, "HFMSG_MISSING_HELPFILE");
682 for (curr = (dest->handle_info ? dest->handle_info->language : lang_C);
684 curr = curr->parent) {
685 lang_hf = dict_find(curr->helpfiles, hf->name, NULL);
688 rec = dict_find(lang_hf->db, topic, NULL);
689 if (rec && rec->type == RECDB_QSTRING)
690 return _send_help(dest, src, hf->expand, rec->d.qstring);
692 rec = dict_find(hf->db, "<missing>", NULL);
694 return send_message(dest, src, "MSG_TOPIC_UNKNOWN");
695 if (rec->type != RECDB_QSTRING)
696 return send_message(dest, src, "HFMSG_HELP_NOT_STRING");
697 return _send_help(dest, src, hf->expand, rec->d.qstring);
700 /* Grammar supported by this parser:
701 * condition = expr | prefix expr
702 * expr = atomicexpr | atomicexpr op atomicexpr
703 * op = '&&' | '||' | 'and' | 'or'
704 * atomicexpr = '(' expr ')' | identifier
705 * identifier = ( '0'-'9' 'A'-'Z' 'a'-'z' '-' '_' '/' )+ | ! identifier
707 * Whitespace is ignored. The parser is implemented as a recursive
708 * descent parser by functions like:
709 * static int helpfile_eval_<element>(const char *start, const char **end);
718 static const struct {
721 } helpfile_operators[] = {
722 { "&&", OP_BOOL_AND },
723 { "and", OP_BOOL_AND },
724 { "||", OP_BOOL_OR },
725 { "or", OP_BOOL_OR },
729 static const char *identifier_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_/";
731 static int helpfile_eval_expr(const char *start, const char **end);
732 static int helpfile_eval_atomicexpr(const char *start, const char **end);
733 static int helpfile_eval_identifier(const char *start, const char **end);
736 helpfile_eval_identifier(const char *start, const char **end)
738 /* Skip leading whitespace. */
739 while (isspace(*start) && (start < *end))
742 log_module(MAIN_LOG, LOG_FATAL, "Expected identifier in helpfile condition.");
746 if (start[0] == '!') {
747 int res = helpfile_eval_identifier(start+1, end);
751 } else if (start[0] == '/') {
753 char *id_str, *value;
756 strchr(identifier_chars, sep[0]) && (sep < *end);
758 memcpy(id_str = alloca(sep+1-start), start, sep-start);
759 id_str[sep-start] = '\0';
760 value = conf_get_data(id_str+1, RECDB_QSTRING);
764 return enabled_string(value) || true_string(value);
765 } else if ((*end - start >= 4) && !ircncasecmp(start, "true", 4)) {
768 } else if ((*end - start >= 5) && !ircncasecmp(start, "false", 5)) {
772 log_module(MAIN_LOG, LOG_FATAL, "Unexpected helpfile identifier '%.*s'.", *end-start, start);
778 helpfile_eval_atomicexpr(const char *start, const char **end)
783 /* Skip leading whitespace. */
784 while (isspace(*start) && (start < *end))
787 log_module(MAIN_LOG, LOG_FATAL, "Expected atomic expression in helpfile condition.");
791 /* If it's not parenthesized, it better be a valid identifier. */
793 return helpfile_eval_identifier(start, end);
795 /* Parse the internal expression. */
798 res = helpfile_eval_expr(start, &sep);
800 /* Check for the closing parenthesis. */
801 while (isspace(*sep) && (sep < *end))
803 if ((sep == *end) || (sep[0] != ')')) {
804 log_module(MAIN_LOG, LOG_FATAL, "Expected close parenthesis at '%.*s'.", *end-sep, sep);
808 /* Report the end location and result. */
814 helpfile_eval_expr(const char *start, const char **end)
816 const char *sep, *sep2;
817 unsigned int ii, len;
821 /* Parse the first atomicexpr. */
823 res_a = helpfile_eval_atomicexpr(start, &sep);
827 /* Figure out what follows that. */
828 while (isspace(*sep) && (sep < *end))
833 for (ii = 0; helpfile_operators[ii].str; ++ii) {
834 len = strlen(helpfile_operators[ii].str);
835 if (ircncasecmp(sep, helpfile_operators[ii].str, len))
837 op = helpfile_operators[ii].op;
840 if (op == OP_INVALID) {
841 log_module(MAIN_LOG, LOG_FATAL, "Unrecognized helpfile operator at '%.*s'.", *end-sep, sep);
845 /* Parse the next atomicexpr. */
847 res_b = helpfile_eval_atomicexpr(sep, &sep2);
851 /* Make sure there's no trailing garbage */
852 while (isspace(*sep2) && (sep2 < *end))
855 log_module(MAIN_LOG, LOG_FATAL, "Trailing garbage in helpfile expression: '%.*s'.", *end-sep2, sep2);
859 /* Record where we stopped parsing. */
862 /* Do the logic on the subexpressions. */
865 return res_a && res_b;
867 return res_a || res_b;
874 helpfile_eval_condition(const char *start, const char **end)
878 /* Skip the prefix if there is one. */
879 for (term = start; isalnum(*term) && (term < *end); ++term) ;
881 if ((term + 2 >= *end) || (term[0] != ':') || (term[1] != ' ')) {
882 log_module(MAIN_LOG, LOG_FATAL, "In helpfile condition '%.*s' expected prefix to end with ': '.", *end-start, start);
888 /* Evaluate the remaining string as an expression. */
889 return helpfile_eval_expr(start, end);
893 unlistify_help(const char *key, void *data, void *extra)
895 struct record_data *rd = data;
896 dict_t newdb = extra;
900 dict_insert(newdb, strdup(key), alloc_record_data_qstring(GET_RECORD_QSTRING(rd)));
902 case RECDB_STRING_LIST: {
903 struct string_list *slist = GET_RECORD_STRING_LIST(rd);
905 unsigned int totlen, len, i;
907 for (i=totlen=0; i<slist->used; i++)
908 totlen = totlen + strlen(slist->list[i]) + 1;
909 dest = alloca(totlen+1);
910 for (i=totlen=0; i<slist->used; i++) {
911 len = strlen(slist->list[i]);
912 memcpy(dest+totlen, slist->list[i], len);
913 dest[totlen+len] = '\n';
914 totlen = totlen + len + 1;
917 dict_insert(newdb, strdup(key), alloc_record_data_qstring(dest));
923 for (it = dict_first(GET_RECORD_OBJECT(rd)); it; it = iter_next(it)) {
924 const char *k2, *end;
927 /* Evaluate the expression for this subentry. */
929 end = k2 + strlen(k2);
930 res = helpfile_eval_condition(k2, &end);
931 /* If the evaluation failed, bail. */
933 log_module(MAIN_LOG, LOG_FATAL, " .. while processing entry '%s' condition '%s'.", key, k2);
936 /* If the condition was false, try another. */
939 /* If we cannot unlistify the contents, bail. */
940 if (unlistify_help(key, iter_data(it), extra))
944 /* If none of the conditions apply, just omit the entry. */
953 open_helpfile(const char *fname, expand_func_t expand)
957 dict_t db = parse_database(fname);
958 hf = calloc(1, sizeof(*hf));
960 hf->db = alloc_database();
961 dict_set_free_keys(hf->db, free);
962 if ((slash = strrchr(fname, '/'))) {
963 hf->name = strdup(slash + 1);
965 hf->name = strdup(fname);
966 dict_insert(language_find("C")->helpfiles, hf->name, hf);
969 dict_foreach(db, unlistify_help, hf->db);
975 void close_helpfile(struct helpfile *hf)
979 free((char*)hf->name);
980 free_database(hf->db);
984 void message_register_table(const struct message_entry *table)
988 while (table->msgid) {
989 dict_insert(lang_C->messages, table->msgid, (char*)table->format);
994 void helpfile_finalize(void)
996 message_register_table(msgtab);
998 reg_exit_func(language_cleanup);