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