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