adee900ba3ddbdfce7b74d5e5311e593a62c17e4
[citadel.git] / webcit / subst.c
1 /*
2  * $Id$
3  */
4 /**
5  * \defgroup Subst Variable substitution type stuff
6  * \ingroup CitadelConfig
7  */
8
9 /*@{*/
10
11 #include "sysdep.h"
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <unistd.h>
15 #include <dirent.h>
16 #include <errno.h>
17 #include <stdarg.h>
18 #define SHOW_ME_VAPPEND_PRINTF
19
20 #include "webcit.h"
21 #include "webserver.h"
22
23 extern char *static_dirs[PATH_MAX];  /**< Disk representation */
24
25 HashList *WirelessTemplateCache;
26 HashList *WirelessLocalTemplateCache;
27 HashList *TemplateCache;
28 HashList *LocalTemplateCache;
29
30 HashList *GlobalNS;
31 HashList *Iterators;
32 HashList *Contitionals;
33
34 int LoadTemplates = 0;
35
36 #define SV_GETTEXT 1
37 #define SV_CONDITIONAL 2
38 #define SV_NEG_CONDITIONAL 3
39 #define SV_CUST_STR_CONDITIONAL 4
40 #define SV_SUBTEMPL 5
41 #define SV_PREEVALUATED 6
42
43 typedef struct _WCTemplate {
44         StrBuf *Data;
45         StrBuf *FileName;
46         int nTokensUsed;
47         int TokenSpace;
48         WCTemplateToken **Tokens;
49 } WCTemplate;
50
51 typedef struct _HashHandler {
52         int nMinArgs;
53         int nMaxArgs;
54         WCHandlerFunc HandlerFunc;
55 }HashHandler;
56
57 void *load_template(StrBuf *filename, StrBuf *Key, HashList *PutThere);
58
59 void RegisterNS(const char *NSName, long len, int nMinArgs, int nMaxArgs, WCHandlerFunc HandlerFunc)
60 {
61         HashHandler *NewHandler;
62         
63         NewHandler = (HashHandler*) malloc(sizeof(HashHandler));
64         NewHandler->nMinArgs = nMinArgs;
65         NewHandler->nMaxArgs = nMaxArgs;
66         NewHandler->HandlerFunc = HandlerFunc;  
67         Put(GlobalNS, NSName, len, NewHandler, NULL);
68 }
69
70 void FreeToken(WCTemplateToken **Token)
71 {
72         int i; 
73         FreeStrBuf(&(*Token)->FlatToken);
74         if ((*Token)->HaveParameters) 
75                 for (i = 0; i < (*Token)->nParameters; i++)
76                         free((*Token)->Params[i]);
77         free(*Token);
78         *Token = NULL;
79 }
80
81
82
83 void FreeWCTemplate(void *vFreeMe)
84 {
85         int i;
86         WCTemplate *FreeMe = (WCTemplate*)vFreeMe;
87
88         if (FreeMe->TokenSpace > 0) {
89                 for (i = 0; i < FreeMe->nTokensUsed; i ++) {
90                         FreeToken(&FreeMe->Tokens[i]);
91                 }
92                 free(FreeMe->Tokens);
93         }
94         FreeStrBuf(&FreeMe->FileName);
95         FreeStrBuf(&FreeMe->Data);
96         free(FreeMe);
97 }
98
99
100 /**
101  * \brief debugging function to print array to log
102  */
103 void VarPrintTransition(void *vVar1, void *vVar2, int odd){}
104 /**
105  * \brief debugging function to print array to log
106  */
107 void VarPrintEntry(const char *Key, void *vSubst, int odd)
108 {
109         wcsubst *ptr;
110         lprintf(1,"Subst[%s] : ", Key);
111         ptr = (wcsubst*) vSubst;
112
113         switch(ptr->wcs_type) {
114         case WCS_STRING:
115                 lprintf(1, "  -> %s\n", ChrPtr(ptr->wcs_value));
116                 break;
117         case WCS_SERVCMD:
118                 lprintf(1, "  -> Server [%s]\n", ChrPtr(ptr->wcs_value));
119                 break;
120         case WCS_FUNCTION:
121                 lprintf(1, "  -> function at [%0xd]\n", ptr->wcs_function);
122                 break;
123         default:
124                 lprintf(1,"  WARNING: invalid type: [%ld]!\n", ptr->wcs_type);
125         }
126 }
127
128
129
130 /**
131  * \brief Clear out the list of substitution variables local to this session
132  */
133 void clear_substs(struct wcsession *wc) {
134
135         if (wc->vars != NULL) {
136                 DeleteHash(&wc->vars);
137         }
138 }
139
140 /**
141  * \brief Clear out the list of substitution variables local to this session
142  */
143 void clear_local_substs(void) {
144         clear_substs (WC);
145 }
146
147 int NeedNewBuf(type)
148 {
149         switch(type) {
150         case WCS_STRING:
151         case WCS_SERVCMD:
152         case WCS_STRBUF:
153                 return 1;
154         case WCS_FUNCTION:
155         case WCS_STRBUF_REF:
156         case WCS_LONG:
157         default:
158                 return 0;
159         }
160 }
161
162 void FlushPayload(wcsubst *ptr, int reusestrbuf, int type)
163 {
164         int NeedNew = NeedNewBuf(type);
165         switch(ptr->wcs_type) {
166         case WCS_STRING:
167         case WCS_SERVCMD:
168         case WCS_STRBUF:
169                 if (reusestrbuf && NeedNew) {
170                         FlushStrBuf(ptr->wcs_value);
171                 }
172                 else {
173                         
174                         FreeStrBuf(&ptr->wcs_value);
175                         ptr->wcs_value = NULL;
176                 }
177                 break;
178         case WCS_FUNCTION:
179                 ptr->wcs_function = NULL;
180                 if (reusestrbuf && NeedNew)
181                         ptr->wcs_value = NewStrBuf();
182                 break;
183         case WCS_STRBUF_REF:
184                 ptr->wcs_value = NULL;
185                 if (reusestrbuf && NeedNew)
186                         ptr->wcs_value = NewStrBuf();
187                 break;
188         case WCS_LONG:
189                 ptr->lvalue = 0;
190                 if (reusestrbuf && NeedNew)
191                         ptr->wcs_value = NewStrBuf();
192                 break;
193         default:
194                 if (reusestrbuf && NeedNew)
195                         ptr->wcs_value = NewStrBuf();
196                 break;
197         }
198 }
199
200
201 /**
202  * \brief destructor; kill one entry.
203  */
204 void deletevar(void *data)
205 {
206         wcsubst *ptr = (wcsubst*)data;
207         FlushPayload(ptr, 0, ptr->wcs_type);
208         free(ptr);      
209 }
210
211
212 wcsubst *NewSubstVar(const char *keyname, int keylen, int type)
213 {
214         wcsubst* ptr;
215         struct wcsession *WCC = WC;
216
217         ptr = (wcsubst *) malloc(sizeof(wcsubst));
218         memset(ptr, 0, sizeof(wcsubst));
219
220         ptr->wcs_type = type;
221         safestrncpy(ptr->wcs_key, keyname, sizeof ptr->wcs_key);
222         Put(WCC->vars, keyname, keylen, ptr,  deletevar);
223
224         switch(ptr->wcs_type) {
225         case WCS_STRING:
226         case WCS_SERVCMD:
227                 ptr->wcs_value = NewStrBuf();
228                 break;
229         case WCS_STRBUF:
230         case WCS_FUNCTION:
231         case WCS_STRBUF_REF:
232         case WCS_LONG:
233         default:
234                 break;
235         }
236         return ptr;
237 }
238
239
240 /**
241  * \brief Add a substitution variable (local to this session) (strlen version...)
242  * \param keyname the replacementstring to substitute
243  * \param keytype the kind of the key
244  * \param format the format string ala printf
245  * \param ... the arguments to substitute in the formatstring
246  */
247 void SVPRINTF(char *keyname, int keytype, const char *format,...)
248 {
249         va_list arg_ptr;
250         void *vPtr;
251         wcsubst *ptr = NULL;
252         size_t keylen;
253         struct wcsession *WCC = WC;
254         
255         keylen = strlen(keyname);
256         /**
257          * First look if we're doing a replacement of
258          * an existing key
259          */
260         /*PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
261         if (GetHash(WCC->vars, keyname, keylen, &vPtr)) {
262                 ptr = (wcsubst*)vPtr;
263                 FlushPayload(ptr, keytype, keytype);
264                 ptr->wcs_type = keytype;
265         }
266         else    /** Otherwise allocate a new one */
267         {
268                 ptr = NewSubstVar(keyname, keylen, keytype);
269         }
270
271         /** Format the string */
272         va_start(arg_ptr, format);
273         StrBufVAppendPrintf(ptr->wcs_value, format, arg_ptr);
274         va_end(arg_ptr);
275 }
276
277 /**
278  * \brief Add a substitution variable (local to this session)
279  * \param keyname the replacementstring to substitute
280  * \param keytype the kind of the key
281  * \param format the format string ala printf
282  * \param ... the arguments to substitute in the formatstring
283  */
284 void svprintf(char *keyname, size_t keylen, int keytype, const char *format,...)
285 {
286         va_list arg_ptr;
287         void *vPtr;
288         wcsubst *ptr = NULL;
289         struct wcsession *WCC = WC;
290                 
291         /**
292          * First look if we're doing a replacement of
293          * an existing key
294          */
295         /*PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
296         if (GetHash(WCC->vars, keyname, keylen, &vPtr)) {
297                 ptr = (wcsubst*)vPtr;
298                 FlushPayload(ptr, 1, keytype);
299                 ptr->wcs_type = keytype;
300         }
301         else    /** Otherwise allocate a new one */
302         {
303                 ptr = NewSubstVar(keyname, keylen, keytype);
304         }
305
306         /** Format the string and save it */
307         va_start(arg_ptr, format);
308         StrBufVAppendPrintf(ptr->wcs_value, format, arg_ptr);
309         va_end(arg_ptr);
310 }
311
312 /**
313  * \brief Add a substitution variable (local to this session)
314  * \param keyname the replacementstring to substitute
315  * \param keytype the kind of the key
316  * \param format the format string ala printf
317  * \param ... the arguments to substitute in the formatstring
318  */
319 void SVPut(char *keyname, size_t keylen, int keytype, char *Data)
320 {
321         void *vPtr;
322         wcsubst *ptr = NULL;
323         struct wcsession *WCC = WC;
324
325         
326         /**
327          * First look if we're doing a replacement of
328          * an existing key
329          */
330         /*PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
331         if (GetHash(WCC->vars, keyname, keylen, &vPtr)) {
332                 ptr = (wcsubst*)vPtr;
333                 FlushPayload(ptr, 1, keytype);
334                 ptr->wcs_type = keytype;
335         }
336         else    /** Otherwise allocate a new one */
337         {
338                 ptr = NewSubstVar(keyname, keylen, keytype);
339         }
340         StrBufAppendBufPlain(ptr->wcs_value, Data, -1, 0);
341 }
342
343 /**
344  * \brief Add a substitution variable (local to this session)
345  * \param keyname the replacementstring to substitute
346  * \param keytype the kind of the key
347  * \param format the format string ala printf
348  * \param ... the arguments to substitute in the formatstring
349  */
350 void SVPutLong(char *keyname, size_t keylen, long Data)
351 {
352         void *vPtr;
353         wcsubst *ptr = NULL;
354         struct wcsession *WCC = WC;
355
356         
357         /**
358          * First look if we're doing a replacement of
359          * an existing key
360          */
361         /*PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
362         if (GetHash(WCC->vars, keyname, keylen, &vPtr)) {
363                 ptr = (wcsubst*)vPtr;
364                 FlushPayload(ptr, 1, WCS_LONG);
365                 ptr->wcs_type = WCS_LONG;
366         }
367         else    /** Otherwise allocate a new one */
368         {
369                 ptr = NewSubstVar(keyname, keylen, WCS_LONG);
370         }
371         ptr->lvalue = Data;
372 }
373
374 /**
375  * \brief Add a substitution variable (local to this session) that does a callback
376  * \param keyname the keystring to substitute
377  * \param fcn_ptr the function callback to give the substitution string
378  */
379 void SVCallback(char *keyname, size_t keylen, WCHandlerFunc fcn_ptr)
380 {
381         wcsubst *ptr;
382         void *vPtr;
383         struct wcsession *WCC = WC;
384
385         /**
386          * First look if we're doing a replacement of
387          * an existing key
388          */
389         /*PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
390         if (GetHash(WCC->vars, keyname, keylen, &vPtr)) {
391                 ptr = (wcsubst*)vPtr;
392                 FlushPayload(ptr, 1, WCS_FUNCTION);
393                 ptr->wcs_type = WCS_FUNCTION;
394         }
395         else    /** Otherwise allocate a new one */
396         {
397                 ptr = NewSubstVar(keyname, keylen, WCS_FUNCTION);
398         }
399
400         ptr->wcs_function = fcn_ptr;
401 }
402 inline void SVCALLBACK(char *keyname, WCHandlerFunc fcn_ptr)
403 {
404         SVCallback(keyname, strlen(keyname), fcn_ptr);
405 }
406
407
408
409 void SVPUTBuf(const char *keyname, int keylen, const StrBuf *Buf, int ref)
410 {
411         wcsubst *ptr;
412         void *vPtr;
413         struct wcsession *WCC = WC;
414
415         /**
416          * First look if we're doing a replacement of
417          * an existing key
418          */
419         /*PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
420         if (GetHash(WCC->vars, keyname, keylen, &vPtr)) {
421                 ptr = (wcsubst*)vPtr;
422                 FlushPayload(ptr, 0, (ref)?WCS_STRBUF_REF:WCS_STRBUF);
423                 ptr->wcs_type = (ref)?WCS_STRBUF_REF:WCS_STRBUF;
424         }
425         else    /** Otherwise allocate a new one */
426         {
427                 ptr = NewSubstVar(keyname, keylen, (ref)?WCS_STRBUF_REF:WCS_STRBUF);
428         }
429         ptr->wcs_value = (StrBuf*)Buf;
430 }
431
432 /**
433  * \brief back end for print_value_of() ... does a server command
434  * \param servcmd server command to execute on the citadel server
435  */
436 void pvo_do_cmd(StrBuf *Target, StrBuf *servcmd) {
437         char buf[SIZ];
438         int len;
439
440         serv_puts(ChrPtr(servcmd));
441         len = serv_getln(buf, sizeof buf);
442
443         switch(buf[0]) {
444                 case '2':
445                 case '3':
446                 case '5':
447                         StrBufAppendPrintf(Target, "%s\n", &buf[4]);
448                         break;
449                 case '1':
450                         _fmout(Target, "CENTER");
451                         break;
452                 case '4':
453                         StrBufAppendPrintf(Target, "%s\n", &buf[4]);
454                         serv_puts("000");
455                         break;
456         }
457 }
458
459 /**
460  * \brief Print the value of a variable
461  * \param keyname get a key to print
462  */
463 void print_value_of(StrBuf *Target, WCTemplateToken *Token, void *Context) {
464         struct wcsession *WCC = WC;
465         wcsubst *ptr;
466         void *vVar;
467
468         /*if (WCC->vars != NULL) PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
469         /// TODO: debricated!
470         if (Token->pName[0] == '=') {
471                 DoTemplate(Token->pName+1, Token->NameEnd - 1, NULL, NULL);
472         }
473
474 //////TODO: if param[1] == "U" -> urlescape
475 /// X -> escputs
476         /** Page-local variables */
477         if ((WCC->vars!= NULL) && GetHash(WCC->vars, Token->pName, Token->NameEnd, &vVar)) {
478                 ptr = (wcsubst*) vVar;
479                 switch(ptr->wcs_type) {
480                 case WCS_STRING:
481                         StrBufAppendBuf(Target, ptr->wcs_value, 0);
482                         break;
483                 case WCS_SERVCMD:
484                         pvo_do_cmd(Target, ptr->wcs_value);
485                         break;
486                 case WCS_FUNCTION:
487                         (*ptr->wcs_function) (Target, Token->nParameters, Token, Context);
488                         break;
489                 case WCS_STRBUF:
490                 case WCS_STRBUF_REF:
491                         StrBufAppendBuf(Target, ptr->wcs_value, 0);
492                         break;
493                 case WCS_LONG:
494                         StrBufAppendPrintf(Target, "%ld", ptr->lvalue);
495                         break;
496                 default:
497                         lprintf(1,"WARNING: invalid value in SV-Hash at %s!\n", Token->pName);
498                         StrBufAppendPrintf(Target, "<pre>WARNING: \ninvalid value in SV-Hash at %s!\n</pre>", Token->pName);
499                 }
500         }
501 }
502
503 int CompareSubstToToken(TemplateParam *ParamToCompare, TemplateParam *ParamToLookup)
504 {
505         struct wcsession *WCC = WC;
506         wcsubst *ptr;
507         void *vVar;
508
509         if ((WCC->vars!= NULL) && GetHash(WCC->vars, ParamToLookup->Start, 
510                                           ParamToLookup->len, &vVar)) {
511                 ptr = (wcsubst*) vVar;
512                 switch(ptr->wcs_type) {
513                 case WCS_STRING:
514                 case WCS_STRBUF:
515                 case WCS_STRBUF_REF:
516                         if (ParamToCompare->Type == TYPE_STR)
517                                 return ((ParamToCompare->len == StrLength(ptr->wcs_value)) &&
518                                         (strcmp(ParamToCompare->Start, ChrPtr(ptr->wcs_value)) == 0));
519                         else
520                                 return ParamToCompare->lvalue == StrTol(ptr->wcs_value);
521                         break;
522                 case WCS_SERVCMD:
523                         return 1; 
524                         break;
525                 case WCS_FUNCTION:
526                         return 1;
527                 case WCS_LONG:
528                         if (ParamToCompare->Type == TYPE_STR)
529                                 return 0;
530                         else 
531                                 return ParamToCompare->lvalue == ptr->lvalue;
532                         break;
533                 default:
534                         lprintf(1,"WARNING: invalid value in SV-Hash at %s!\n", 
535                                 ParamToLookup->Start);
536                 }
537         }
538         return 0;
539 }
540
541 int CompareSubstToStrBuf(StrBuf *Compare, TemplateParam *ParamToLookup)
542 {
543         struct wcsession *WCC = WC;
544         wcsubst *ptr;
545         void *vVar;
546
547         if ((WCC->vars!= NULL) && GetHash(WCC->vars, ParamToLookup->Start, 
548                                           ParamToLookup->len, &vVar)) {
549                 ptr = (wcsubst*) vVar;
550                 switch(ptr->wcs_type) {
551                 case WCS_STRING:
552                 case WCS_STRBUF:
553                 case WCS_STRBUF_REF:
554                         return ((StrLength(Compare) == StrLength(ptr->wcs_value)) &&
555                                 (strcmp(ChrPtr(Compare), ChrPtr(ptr->wcs_value)) == 0));
556                 case WCS_SERVCMD:
557                         return 1; 
558                         break;
559                 case WCS_FUNCTION:
560                         return 1;
561                 case WCS_LONG:
562                         return StrTol(Compare) == ptr->lvalue;
563                 default:
564                         lprintf(1,"WARNING: invalid value in SV-Hash at %s!\n", 
565                                 ParamToLookup->Start);
566                 }
567         }
568         return 0;
569 }
570
571
572 void PutNewToken(WCTemplate *Template, WCTemplateToken *NewToken)
573 {
574         if (Template->nTokensUsed + 1 >= Template->TokenSpace) {
575                 if (Template->TokenSpace <= 0) {
576                         Template->Tokens = (WCTemplateToken**)malloc(
577                                 sizeof(WCTemplateToken*) * 10);
578                         Template->TokenSpace = 10;
579                 }
580                 else {
581                         WCTemplateToken **NewTokens;
582                         NewTokens= (WCTemplateToken**)malloc(
583                                 sizeof(WCTemplateToken*) * 
584                                 Template->TokenSpace * 2);
585                         memcpy(NewTokens, Template->Tokens, 
586                                sizeof(WCTemplateToken*) * Template->nTokensUsed);
587                         free(Template->Tokens);
588                         Template->TokenSpace *= 2;
589                         Template->Tokens = NewTokens;
590                 }
591         }
592         Template->Tokens[(Template->nTokensUsed)++] = NewToken;
593 }
594
595 TemplateParam *GetNextParameter(StrBuf *Buf, const char **pCh, const char *pe, WCTemplateToken *Token, WCTemplate *pTmpl)
596 {
597         const char *pch = *pCh;
598         const char *pchs, *pche;
599         TemplateParam *Parm = (TemplateParam *) malloc(sizeof(TemplateParam));
600         char quote = '\0';
601         
602         /* Skip leading whitespaces */
603         while ((*pch == ' ' )||
604                (*pch == '\t')||
605                (*pch == '\r')||
606                (*pch == '\n')) pch ++;
607         if (*pch == '"')
608                 quote = '"';
609         else if (*pch == '\'')
610                 quote = '\'';
611         if (quote != '\0') {
612                 pch ++;
613                 pchs = pch;
614                 Parm->Type = TYPE_STR;
615                 while (pch <= pe &&
616                        ((*pch != quote) ||
617                         ( (pch > pchs) && (*(pch - 1) == '\\'))
618                                )) {
619                         pch ++;
620                 }
621                 pche = pch;
622                 if (*pch != quote) {
623                         lprintf(1, "Error (in '%s' line %ld); "
624                                 "evaluating template param [%s] in Token [%s]\n",
625                                 ChrPtr(pTmpl->FileName),
626                                 Token->Line,
627                                 ChrPtr(Token->FlatToken),
628                                 *pCh);
629                         pch ++;
630                         free(Parm);
631                         return NULL;
632                 }
633                 else {
634                         StrBufPeek(Buf, pch, -1, '\0');         
635                         if (LoadTemplates > 1) {                        
636                                 lprintf(1, "DBG: got param [%s] %ld %ld\n", 
637                                         pchs, pche - pchs, strlen(pchs));
638                         }
639                         Parm->Start = pchs;
640                         Parm->len = pche - pchs;
641                         pch ++; /* move after trailing quote */
642                 }
643         }
644         else {
645                 Parm->Type = TYPE_LONG;
646                 pchs = pch;
647                 while ((pch <= pe) &&
648                        (isdigit(*pch) ||
649                         (*pch == '+') ||
650                         (*pch == '-')))
651                         pch ++;
652                 pch ++;
653                 if (pch - pchs > 1){
654                         StrBufPeek(Buf, pch, -1, '\0');
655                         Parm->lvalue = atol(pchs);
656                         Parm->Start = pchs;
657                         pch++;
658                 }
659                 else {
660                         Parm->lvalue = 0;
661                         lprintf(1, "Error (in '%s' line %ld); "
662                                 "evaluating long template param [%s] in Token [%s]\n",
663                                 ChrPtr(pTmpl->FileName),
664                                 Token->Line,
665                                 ChrPtr(Token->FlatToken),
666                                 *pCh);
667                         free(Parm);
668                         return NULL;
669                 }
670         }
671         while ((*pch == ' ' )||
672                (*pch == '\t')||
673                (*pch == '\r')||
674                (*pch == ',' )||
675                (*pch == '\n')) pch ++;
676
677         *pCh = pch;
678         return Parm;
679 }
680
681 WCTemplateToken *NewTemplateSubstitute(StrBuf *Buf, 
682                                        const char *pStart, 
683                                        const char *pTmplStart, 
684                                        const char *pTmplEnd, 
685                                        long Line,
686                                        WCTemplate *pTmpl)
687 {
688         const char *pch;
689         TemplateParam *Param;
690         WCTemplateToken *NewToken = (WCTemplateToken*)malloc(sizeof(WCTemplateToken));
691
692         NewToken->Flags = 0;
693         NewToken->Line = Line + 1;
694         NewToken->pTokenStart = pTmplStart;
695         NewToken->TokenStart = pTmplStart - pStart;
696         NewToken->TokenEnd =  (pTmplEnd - pStart) - NewToken->TokenStart;
697         NewToken->pTokenEnd = pTmplEnd;
698         NewToken->NameEnd = NewToken->TokenEnd - 2;
699         NewToken->PreEval = NULL;
700         NewToken->FlatToken = NewStrBufPlain(pTmplStart + 2, pTmplEnd - pTmplStart - 2);
701         
702         StrBufPeek(Buf, pTmplStart, + 1, '\0');
703         StrBufPeek(Buf, pTmplEnd, -1, '\0');
704         pch = NewToken->pName = pTmplStart + 2;
705
706         NewToken->HaveParameters = 0;;
707         NewToken->nParameters = 0;
708
709         while (pch < pTmplEnd - 1) {
710                 if (*pch == '(') {
711                         StrBufPeek(Buf, pch, -1, '\0');
712                         NewToken->NameEnd = pch - NewToken->pName;
713                         pch ++;
714                         while (pch < pTmplEnd - 1) {
715                                 Param = GetNextParameter(Buf, &pch, pTmplEnd - 1, NewToken, pTmpl);
716                                 if (Param != NULL) {
717                                         NewToken->HaveParameters = 1;
718                                         if (NewToken->nParameters > MAXPARAM) {
719                                                 lprintf(1, "Error (in '%s' line %ld); "
720                                                         "only [%ld] Params allowed in Tokens [%s]\n",
721                                                         ChrPtr(pTmpl->FileName),
722                                                         NewToken->Line,
723                                                         MAXPARAM,
724                                                         ChrPtr(NewToken->FlatToken));
725                                                 free(Param);
726                                                 FreeToken(&NewToken);
727                                                 return NULL;
728                                         }
729                                         NewToken->Params[NewToken->nParameters++] = Param;
730                                 }
731                                 else break;
732                         }
733                         if((NewToken->NameEnd == 1) &&
734                            (NewToken->HaveParameters == 1))
735                            
736                         {
737                                 if ((NewToken->nParameters == 1) &&
738                                     (*(NewToken->pName) == '_'))
739                                         NewToken->Flags = SV_GETTEXT;
740                                 else if ((NewToken->nParameters == 1) &&
741                                          (*(NewToken->pName) == '='))
742                                         NewToken->Flags = SV_SUBTEMPL;
743                                 else if ((NewToken->nParameters >= 2) &&
744                                          (*(NewToken->pName) == '%'))
745                                         NewToken->Flags = SV_CUST_STR_CONDITIONAL;
746                                 else if ((NewToken->nParameters >= 2) &&
747                                          (*(NewToken->pName) == '?'))
748                                         NewToken->Flags = SV_CONDITIONAL;
749                                 else if ((NewToken->nParameters >=2) &&
750                                          (*(NewToken->pName) == '!'))
751                                         NewToken->Flags = SV_NEG_CONDITIONAL;
752                         }
753                 }
754                 else pch ++;            
755         }
756         
757         if (NewToken->Flags == 0) {
758                 /* If we're able to find out more about the token, do it now while its fresh. */
759                 void *vVar;
760                 if (GetHash(GlobalNS, NewToken->pName, NewToken->NameEnd, &vVar)) {
761                         HashHandler *Handler;
762                         Handler = (HashHandler*) vVar;
763                         if ((NewToken->nParameters < Handler->nMinArgs) || 
764                             (NewToken->nParameters > Handler->nMaxArgs)) {
765                                 lprintf(1, "Handler [%s] (in '%s' line %ld); "
766                                         "doesn't work with %ld params [%s]\n", 
767                                         NewToken->pName,
768                                         ChrPtr(pTmpl->FileName),
769                                         NewToken->Line,
770                                         NewToken->nParameters, 
771                                         ChrPtr(NewToken->FlatToken));
772                         }
773                         else {
774                                 NewToken->PreEval = Handler;
775                                 NewToken->Flags = SV_PREEVALUATED;              
776                         }
777                 }               
778         }
779
780         return NewToken;
781 }
782
783
784
785 int EvaluateConditional(StrBuf *Target, WCTemplateToken *Token, WCTemplate *pTmpl, void *Context, int Neg, int state)
786 {
787         void *vConditional = NULL;
788         ConditionalStruct *Cond;
789
790         if ((Token->Params[0]->len == 1) &&
791             (Token->Params[0]->Start[0] == 'X'))
792                 return (state != 0)?Token->Params[1]->lvalue:0;
793
794         if (!GetHash(Contitionals, 
795                  Token->Params[0]->Start,
796                  Token->Params[0]->len,
797                  &vConditional) || 
798             (vConditional == NULL)) {
799                 lprintf(1, "Conditional [%s] (in '%s' line %ld); Not found![%s]\n", 
800                         Token->Params[0]->Start,
801                         ChrPtr(pTmpl->FileName),
802                         Token->Line,
803                         ChrPtr(Token->FlatToken));
804                 StrBufAppendPrintf(
805                         Target, 
806                         "<pre>\nConditional [%s] (in '%s' line %ld); Not found!\n[%s]\n</pre>\n", 
807                         Token->Params[0]->Start,
808                         ChrPtr(pTmpl->FileName),
809                         Token->Line,
810                         ChrPtr(Token->FlatToken));
811         }
812             
813         Cond = (ConditionalStruct *) vConditional;
814
815         if (Token->nParameters < Cond->nParams) {
816                 lprintf(1, "Conditional [%s] (in '%s' line %ld); needs %ld Params![%s]\n", 
817                         Token->Params[0]->Start,
818                         ChrPtr(pTmpl->FileName),
819                         Token->Line,
820                         Cond->nParams,
821                         ChrPtr(Token->FlatToken));
822                 StrBufAppendPrintf(
823                         Target, 
824                         "<pre>\nConditional [%s] (in '%s' line %ld); needs %ld Params!\n[%s]\n</pre>\n", 
825                         Token->Params[0]->Start,
826                         ChrPtr(pTmpl->FileName),
827                         Token->Line,
828                         Cond->nParams,
829                         ChrPtr(Token->FlatToken));
830                 return 0;
831         }
832         if (Cond->CondF(Token, Context) == Neg)
833                 return Token->Params[1]->lvalue;
834         return 0;
835 }
836
837 int EvaluateToken(StrBuf *Target, WCTemplateToken *Token, WCTemplate *pTmpl, void *Context, int state)
838 {
839         HashHandler *Handler;
840         void *vVar;
841 // much output, since pName is not terminated...
842 //      lprintf(1,"Doing token: %s\n",Token->pName);
843         switch (Token->Flags) {
844         case SV_GETTEXT:
845                 TmplGettext(Target, Token->nParameters, Token);
846                 break;
847         case SV_CONDITIONAL: /** Forward conditional evaluation */
848                 return EvaluateConditional(Target, Token, pTmpl, Context, 1, state);
849                 break;
850         case SV_NEG_CONDITIONAL: /** Reverse conditional evaluation */
851                 return EvaluateConditional(Target, Token, pTmpl, Context, 0, state);
852                 break;
853         case SV_CUST_STR_CONDITIONAL: /** Conditional put custom strings from params */
854                 if (Token->nParameters >= 6) {
855                         if (EvaluateConditional(Target, Token, pTmpl, Context, 0, state))
856                                 StrBufAppendBufPlain(Target, 
857                                                      Token->Params[5]->Start,
858                                                      Token->Params[5]->len,
859                                                      0);
860                         else
861                                 StrBufAppendBufPlain(Target, 
862                                                      Token->Params[4]->Start,
863                                                      Token->Params[4]->len,
864                                                      0);
865                 }
866                 break;
867         case SV_SUBTEMPL:
868                 if (Token->nParameters == 1)
869                         DoTemplate(Token->Params[0]->Start, Token->Params[0]->len, NULL, NULL);
870                 break;
871         case SV_PREEVALUATED:
872                 Handler = (HashHandler*) Token->PreEval;
873                 Handler->HandlerFunc(Target, 
874                                      Token->nParameters,
875                                      Token,
876                                      Context); 
877                 break;          
878         default:
879                 if (GetHash(GlobalNS, Token->pName, Token->NameEnd, &vVar)) {
880                         Handler = (HashHandler*) vVar;
881                         if ((Token->nParameters < Handler->nMinArgs) || 
882                             (Token->nParameters > Handler->nMaxArgs)) {
883                                 lprintf(1, "Handler [%s] (in '%s' line %ld); "
884                                         "doesn't work with %ld params [%s]\n", 
885                                         Token->pName,
886                                         ChrPtr(pTmpl->FileName),
887                                         Token->Line,
888                                         Token->nParameters, 
889                                         ChrPtr(Token->FlatToken));
890                                 StrBufAppendPrintf(
891                                         Target, 
892                                         "<pre>\nHandler [%s] (in '%s' line %ld);"
893                                         " doesn't work with %ld params!\n[%s]\n</pre>\n", 
894                                         Token->pName,
895                                         ChrPtr(pTmpl->FileName),
896                                         Token->Line,
897                                         Token->nParameters,
898                                         ChrPtr(Token->FlatToken));
899                         }
900                         else {
901                                 Handler->HandlerFunc(Target, 
902                                                      Token->nParameters,
903                                                      Token,
904                                                      Context); /*TODO: subset of that */
905                                 
906                         }
907                 }
908                 else {
909                         print_value_of(Target, Token, Context);
910                 }
911         }
912         return 0;
913 }
914
915 void ProcessTemplate(WCTemplate *Tmpl, StrBuf *Target, void *Context)
916 {
917         WCTemplate *pTmpl = Tmpl;
918         int done = 0;
919         int i, state;
920         const char *pData, *pS;
921         long len;
922
923         if (LoadTemplates != 0) {                       
924                 if (LoadTemplates > 1)
925                         lprintf(1, "DBG: ----- loading:  [%s] ------ \n", 
926                                 ChrPtr(Tmpl->FileName));
927                 pTmpl = load_template(Tmpl->FileName, NULL, NULL);
928                 if(pTmpl == NULL) {
929                         StrBufAppendPrintf(
930                                 Target, 
931                                 "<pre>\nError loading Template [%s]\n See Logfile for details\n</pre>\n", 
932                                 ChrPtr(Tmpl->FileName));
933                         return;
934
935
936                 }
937
938         }
939
940         pS = pData = ChrPtr(pTmpl->Data);
941         len = StrLength(pTmpl->Data);
942         i = 0;
943         state = 0;
944         while (!done) {
945                 if (i >= pTmpl->nTokensUsed) {
946                         StrBufAppendBufPlain(Target, 
947                                              pData, 
948                                              len - (pData - pS), 0);
949                         done = 1;
950                 }
951                 else {
952                         StrBufAppendBufPlain(
953                                 Target, pData, 
954                                 pTmpl->Tokens[i]->pTokenStart - pData, 0);
955                         state = EvaluateToken(Target, pTmpl->Tokens[i], pTmpl, Context, state);
956                         while ((state != 0) && (i+1 < pTmpl->nTokensUsed)) {
957                         /* condition told us to skip till its end condition */
958                                 i++;
959                                 if ((pTmpl->Tokens[i]->Flags == SV_CONDITIONAL) ||
960                                     (pTmpl->Tokens[i]->Flags == SV_NEG_CONDITIONAL)) {
961                                         if (state == EvaluateConditional(
962                                                     Target,
963                                                     pTmpl->Tokens[i], 
964                                                     pTmpl,
965                                                     Context, 
966                                                     pTmpl->Tokens[i]->Flags,
967                                                     state))
968                                                 state = 0;
969                                 }
970                         }
971                         pData = pTmpl->Tokens[i++]->pTokenEnd + 1;
972                         if (i > pTmpl->nTokensUsed)
973                                 done = 1;
974                 }
975         }
976         if (LoadTemplates != 0) {
977                 FreeWCTemplate(pTmpl);
978         }
979 }
980
981
982 /**
983  * \brief Display a variable-substituted template
984  * \param templatename template file to load
985  */
986 void *prepare_template(StrBuf *filename, StrBuf *Key, HashList *PutThere)
987 {
988         WCTemplate *NewTemplate;
989         NewTemplate = (WCTemplate *) malloc(sizeof(WCTemplate));
990         NewTemplate->Data = NULL;
991         NewTemplate->FileName = NewStrBufDup(filename);
992         NewTemplate->nTokensUsed = 0;
993         NewTemplate->TokenSpace = 0;
994         NewTemplate->Tokens = NULL;
995
996         Put(PutThere, ChrPtr(Key), StrLength(Key), NewTemplate, FreeWCTemplate);
997         return NewTemplate;
998 }
999
1000 /**
1001  * \brief Display a variable-substituted template
1002  * \param templatename template file to load
1003  */
1004 void *load_template(StrBuf *filename, StrBuf *Key, HashList *PutThere)
1005 {
1006         int fd;
1007         struct stat statbuf;
1008         const char *pS, *pE, *pch, *Err;
1009         long Line;
1010         int pos;
1011         WCTemplate *NewTemplate;
1012
1013         fd = open(ChrPtr(filename), O_RDONLY);
1014         if (fd <= 0) {
1015                 lprintf(1, "ERROR: could not open template '%s' - %s\n",
1016                         ChrPtr(filename), strerror(errno));
1017                 return NULL;
1018         }
1019
1020         if (fstat(fd, &statbuf) == -1) {
1021                 lprintf(1, "ERROR: could not stat template '%s' - %s\n",
1022                         ChrPtr(filename), strerror(errno));
1023                 return NULL;
1024         }
1025
1026         NewTemplate = (WCTemplate *) malloc(sizeof(WCTemplate));
1027         NewTemplate->Data = NewStrBufPlain(NULL, statbuf.st_size);
1028         NewTemplate->FileName = NewStrBufDup(filename);
1029         NewTemplate->nTokensUsed = 0;
1030         NewTemplate->TokenSpace = 0;
1031         NewTemplate->Tokens = NULL;
1032         if (StrBufReadBLOB(NewTemplate->Data, &fd, 1, statbuf.st_size, &Err) < 0) {
1033                 close(fd);
1034                 FreeWCTemplate(NewTemplate);
1035                 lprintf(1, "ERROR: reading template '%s' - %s<br />\n",
1036                         ChrPtr(filename), strerror(errno));
1037                 return NULL;
1038         }
1039         close(fd);
1040
1041         Line = 0;
1042         pS = pch = ChrPtr(NewTemplate->Data);
1043         pE = pS + StrLength(NewTemplate->Data);
1044         while (pch < pE) {
1045                 const char *pts, *pte;
1046                 int InQuotes = 0;
1047                 int InDoubleQuotes = 0;
1048
1049                 /** Find one <? > */
1050                 pos = (-1);
1051                 for (; pch < pE; pch ++) {
1052                         if ((*pch=='<')&&(*(pch + 1)=='?'))
1053                                 break;
1054                         if (*pch=='\n') Line ++;
1055                 }
1056                 if (pch >= pE)
1057                         continue;
1058                 pts = pch;
1059
1060                 /** Found one? parse it. */
1061                 for (; pch < pE - 1; pch ++) {
1062                         if (*pch == '"')
1063                                 InDoubleQuotes = ! InDoubleQuotes;
1064                         else if (*pch == '\'')
1065                                 InQuotes = ! InQuotes;
1066                         else if ((!InQuotes  && !InDoubleQuotes) &&
1067                                  ((*pch!='\\')&&(*(pch + 1)=='>'))) {
1068                                 pch ++;
1069                                 break;
1070                         }
1071                 }
1072                 if (pch + 1 >= pE)
1073                         continue;
1074                 pte = pch;
1075                 PutNewToken(NewTemplate, 
1076                             NewTemplateSubstitute(NewTemplate->Data, pS, pts, pte, Line, NewTemplate));
1077                 pch ++;
1078         }
1079         if (LoadTemplates == 0)
1080                 Put(PutThere, ChrPtr(Key), StrLength(Key), NewTemplate, FreeWCTemplate);
1081         return NewTemplate;
1082 }
1083
1084
1085 ///void PrintTemplate(const char *Key, void *vSubst, int odd)
1086 const char* PrintTemplate(void *vSubst)
1087 {
1088         WCTemplate *Tmpl = vSubst;
1089
1090         return ChrPtr(Tmpl->FileName);
1091
1092 }
1093
1094
1095 /**
1096  * \brief Display a variable-substituted template
1097  * \param templatename template file to load
1098  */
1099 void DoTemplate(const char *templatename, long len, void *Context, StrBuf *Target) 
1100 {
1101         HashList *Static;
1102         HashList *StaticLocal;
1103         void *vTmpl;
1104         
1105         if (Target == NULL)
1106                 Target = WC->WBuf;
1107         if (WC->is_mobile) {
1108                 Static = WirelessTemplateCache;
1109                 StaticLocal = WirelessLocalTemplateCache;
1110         }
1111         else {
1112                 Static = TemplateCache;
1113                 StaticLocal = LocalTemplateCache;
1114         }
1115
1116         if (len == 0)
1117         {
1118                 lprintf (1, "Can't to load a template with empty name!\n");
1119                 StrBufAppendPrintf(Target, "<pre>\nCan't to load a template with empty name!\n</pre>");
1120                 return;
1121         }
1122
1123         if (!GetHash(StaticLocal, templatename, len, &vTmpl) &&
1124             !GetHash(Static, templatename, len, &vTmpl)) {
1125                 lprintf (1, "didn't find Template [%s] %ld %ld\n", templatename, len , (long)strlen(templatename));
1126                 StrBufAppendPrintf(Target, "<pre>\ndidn't find Template [%s] %ld %ld\n</pre>", 
1127                                    templatename, len, 
1128                                    (long)strlen(templatename));
1129 ///             dbg_PrintHash(Static, PrintTemplate, NULL);
1130 //              PrintHash(Static, VarPrintTransition, PrintTemplate);
1131                 return;
1132         }
1133         if (vTmpl == NULL) 
1134                 return;
1135         ProcessTemplate(vTmpl, Target, Context);        
1136 }
1137
1138 int LoadTemplateDir(const char *DirName, HashList *wireless, HashList *big)
1139 {
1140         StrBuf *FileName;
1141         StrBuf *Tag;
1142         StrBuf *Dir;
1143         DIR *filedir = NULL;
1144         struct dirent *filedir_entry;
1145         int d_namelen;
1146         int d_without_ext;
1147         int IsMobile;
1148         
1149         Dir = NewStrBuf();
1150         StrBufPrintf(Dir, "%s/t", DirName);
1151         filedir = opendir (ChrPtr(Dir));
1152         if (filedir == NULL) {
1153                 FreeStrBuf(&Dir);
1154                 return 0;
1155         }
1156
1157         FileName = NewStrBuf();
1158         Tag = NewStrBuf();
1159         while ((filedir_entry = readdir(filedir)))
1160         {
1161                 char *MinorPtr;
1162                 char *PStart;
1163 #ifdef _DIRENT_HAVE_D_NAMELEN
1164                 d_namelen = filedir_entry->d_namelen;
1165 #else
1166                 d_namelen = strlen(filedir_entry->d_name);
1167 #endif
1168                 d_without_ext = d_namelen;
1169                 while ((d_without_ext > 0) && (filedir_entry->d_name[d_without_ext] != '.'))
1170                         d_without_ext --;
1171                 if ((d_without_ext == 0) || (d_namelen < 3))
1172                         continue;
1173                 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
1174                         continue; /* Ignore backup files... */
1175
1176                 IsMobile = (strstr(filedir_entry->d_name, ".m.html")!= NULL);
1177                 PStart = filedir_entry->d_name;
1178                 StrBufPrintf(FileName, "%s/%s", ChrPtr(Dir),  filedir_entry->d_name);
1179                 MinorPtr = strchr(filedir_entry->d_name, '.');
1180                 if (MinorPtr != NULL)
1181                         *MinorPtr = '\0';
1182                 StrBufPlain(Tag, filedir_entry->d_name, MinorPtr - filedir_entry->d_name);
1183
1184
1185                 lprintf(1, "%s %d %s\n",ChrPtr(FileName), IsMobile, ChrPtr(Tag));
1186                 if (LoadTemplates == 0)
1187                         load_template(FileName, Tag, (IsMobile)?wireless:big);
1188                 else
1189                         prepare_template(FileName, Tag, (IsMobile)?wireless:big);
1190         }
1191         closedir(filedir);
1192         FreeStrBuf(&FileName);
1193         FreeStrBuf(&Tag);
1194         FreeStrBuf(&Dir);
1195         return 1;
1196 }
1197
1198 void InitTemplateCache(void)
1199 {
1200         LoadTemplateDir(static_dirs[0],
1201                         WirelessTemplateCache,
1202                         TemplateCache);
1203         LoadTemplateDir(static_dirs[1],
1204                         WirelessLocalTemplateCache,
1205                         LocalTemplateCache);
1206 }
1207
1208 void tmplput_serv_ip(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1209 {
1210         StrBufAppendPrintf(Target, "%d", WC->ctdl_pid);
1211 }
1212
1213 void tmplput_serv_nodename(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1214 {
1215         StrEscAppend(Target, NULL, serv_info.serv_nodename, 0, 0);
1216 }
1217
1218 void tmplput_serv_humannode(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1219 {
1220         StrEscAppend(Target, NULL, serv_info.serv_humannode, 0, 0);
1221 }
1222
1223 void tmplput_serv_fqdn(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1224 {
1225         StrEscAppend(Target, NULL, serv_info.serv_fqdn, 0, 0);
1226 }
1227
1228 void tmmplput_serv_software(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1229 {
1230         StrEscAppend(Target, NULL, serv_info.serv_software, 0, 0);
1231 }
1232
1233 void tmplput_serv_rev_level(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1234 {
1235         StrBufAppendPrintf(Target, "%d.%02d",
1236                             serv_info.serv_rev_level / 100,
1237                             serv_info.serv_rev_level % 100);
1238 }
1239
1240 void tmmplput_serv_bbs_city(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1241 {
1242         StrEscAppend(Target, NULL, serv_info.serv_bbs_city, 0, 0);
1243 }
1244
1245 void tmplput_current_user(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1246 {
1247         StrEscAppend(Target, NULL, WC->wc_fullname, 0, 0);
1248 }
1249
1250 void tmplput_current_room(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1251 {
1252         StrEscAppend(Target, NULL, WC->wc_roomname, 0, 0);
1253 }
1254
1255
1256 typedef struct _HashIterator {
1257         HashList *StaticList;
1258         int AdditionalParams;
1259         RetrieveHashlistFunc GetHash;
1260         HashDestructorFunc Destructor;
1261         SubTemplFunc DoSubTemplate;
1262 } HashIterator;
1263
1264 void tmpl_iterate_subtmpl(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1265 {
1266         void *vIt;
1267         HashIterator *It;
1268         HashList *List;
1269         HashPos  *it;
1270         long len; 
1271         const char *Key;
1272         void *vContext;
1273         StrBuf *SubBuf;
1274         int oddeven = 0;
1275         
1276         if (!GetHash(Iterators, 
1277                      Tokens->Params[0]->Start,
1278                      Tokens->Params[0]->len,
1279                      &vIt)) {
1280                 lprintf(1, "unknown Iterator [%s] (in line %ld); "
1281                         " [%s]\n", 
1282                         Tokens->Params[0]->Start,
1283                         Tokens->Line,
1284                         ChrPtr(Tokens->FlatToken));
1285                 StrBufAppendPrintf(
1286                         Target,
1287                         "<pre>\nunknown Iterator [%s] (in line %ld); \n"
1288                         " [%s]\n</pre>", 
1289                         Tokens->Params[0]->Start,
1290                         Tokens->Line,
1291                         ChrPtr(Tokens->FlatToken));
1292                 return;
1293         }
1294
1295         It = (HashIterator*) vIt;
1296
1297         if (Tokens->nParameters < It->AdditionalParams + 2) {
1298                 lprintf(1, "Iterator [%s] (in line %ld); "
1299                         "doesn't work with %ld params [%s]\n", 
1300                         Tokens->Params[0]->Start,
1301                         Tokens->Line,
1302                         Tokens->nParameters, 
1303                         ChrPtr(Tokens->FlatToken));
1304                 StrBufAppendPrintf(
1305                         Target,
1306                         "<pre>Iterator [%s] \n(in line %ld);\n"
1307                         "doesn't work with %ld params \n[%s]\n</pre>", 
1308                         Tokens->Params[0]->Start,
1309                         Tokens->Line,
1310                         Tokens->nParameters, 
1311                         ChrPtr(Tokens->FlatToken));
1312                 return;
1313         }
1314
1315         if (It->StaticList == NULL)
1316                 List = It->GetHash(Tokens);
1317         else
1318                 List = It->StaticList;
1319
1320         SubBuf = NewStrBuf();
1321         it = GetNewHashPos();
1322         while (GetNextHashPos(List, it, &len, &Key, &vContext)) {
1323                 svprintf(HKEY("ITERATE:ODDEVEN"), WCS_STRING, "%s", (oddeven)?"odd":"even");
1324                 svprintf(HKEY("ITERATE:KEY"), WCS_STRING, "%s",Key);
1325                 It->DoSubTemplate(SubBuf, vContext, Tokens);
1326                 DoTemplate(Tokens->Params[1]->Start,
1327                            Tokens->Params[1]->len,
1328                            vContext, SubBuf);
1329                         
1330                 StrBufAppendBuf(Target, SubBuf, 0);
1331                 FlushStrBuf(SubBuf);
1332                 oddeven = ~ oddeven;
1333         }
1334         FreeStrBuf(&SubBuf);
1335         DeleteHashPos(&it);
1336         if (It->Destructor != NULL)
1337                 It->Destructor(&List);
1338 }
1339
1340 int ConditionalVar(WCTemplateToken *Tokens, void *Context)
1341 {
1342         void *vsubst;
1343         wcsubst *subst;
1344         
1345         if (!GetHash(WC->vars, 
1346                      Tokens->Params[2]->Start,
1347                      Tokens->Params[2]->len,
1348                      &vsubst))
1349                 return 0;
1350         subst = (wcsubst*) vsubst;
1351         switch(subst->wcs_type) {
1352         case WCS_FUNCTION:
1353                 return (subst->wcs_function!=NULL);
1354         case WCS_SERVCMD:
1355                 lprintf(1, "  -> Server [%s]\n", subst->wcs_value);////todo
1356                 return 1;
1357         case WCS_STRING:
1358         case WCS_STRBUF:
1359         case WCS_STRBUF_REF:
1360                 if (Tokens->nParameters < 4)
1361                         return 1;
1362                 return (strcmp(Tokens->Params[3]->Start, ChrPtr(subst->wcs_value)) == 0);
1363         case WCS_LONG:
1364                 if (Tokens->nParameters < 4)
1365                         return (subst->lvalue != 0);
1366                 return (subst->lvalue == Tokens->Params[3]->lvalue);
1367         default:
1368                 lprintf(1,"  WARNING: invalid type: [%ld]!\n", subst->wcs_type);
1369         }
1370         return 0;
1371 }
1372
1373 void RegisterITERATOR(const char *Name, long len, 
1374                       int AdditionalParams, 
1375                       HashList *StaticList, 
1376                       RetrieveHashlistFunc GetHash, 
1377                       SubTemplFunc DoSubTempl,
1378                       HashDestructorFunc Destructor)
1379 {
1380         HashIterator *It = (HashIterator*)malloc(sizeof(HashIterator));
1381         It->StaticList = StaticList;
1382         It->AdditionalParams = AdditionalParams;
1383         It->GetHash = GetHash;
1384         It->DoSubTemplate = DoSubTempl;
1385         It->Destructor = Destructor;
1386         Put(Iterators, Name, len, It, NULL);
1387 }
1388
1389 void RegisterConditional(const char *Name, long len, 
1390                          int nParams,
1391                          WCConditionalFunc CondF)
1392 {
1393         ConditionalStruct *Cond = (ConditionalStruct*)malloc(sizeof(ConditionalStruct));
1394         Cond->nParams = nParams;
1395         Cond->CondF = CondF;
1396         Put(Contitionals, Name, len, Cond, NULL);
1397 }
1398
1399 void tmpl_do_boxed(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1400 {
1401         if (nArgs == 2) {
1402                 StrBuf *Headline = NewStrBuf();
1403                 DoTemplate(Tokens->Params[1]->Start, 
1404                            Tokens->Params[1]->len,
1405                            Context, 
1406                            Headline);
1407                 SVPutBuf("BOXTITLE", Headline, 0);
1408         }
1409
1410         DoTemplate(HKEY("beginbox"), Context, Target);
1411         DoTemplate(Tokens->Params[0]->Start, 
1412                    Tokens->Params[0]->len,
1413                    Context, 
1414                    Target);
1415         DoTemplate(HKEY("endbox"), Context, Target);
1416 }
1417
1418 void tmpl_do_tabbed(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1419 {
1420         StrBuf **TabNames;
1421         int i, ntabs, nTabs;
1422
1423         nTabs = ntabs = Tokens->nParameters / 2;
1424         TabNames = (StrBuf **) malloc(ntabs * sizeof(StrBuf*));
1425
1426         for (i = 0; i < ntabs; i++) {
1427                 TabNames[i] = NewStrBuf();
1428                 if (Tokens->Params[i * 2]->len > 0) {
1429                         DoTemplate(Tokens->Params[i * 2]->Start, 
1430                                    Tokens->Params[i * 2]->len,
1431                                    Context,
1432                                    TabNames[i]);
1433                 }
1434                 else { 
1435                         /** A Tab without subject? we can't count that, add it as silent */
1436                         nTabs --;
1437                 }
1438         }
1439
1440         StrTabbedDialog(Target, nTabs, TabNames);
1441         for (i = 0; i < ntabs; i++) {
1442                 StrBeginTab(Target, i, nTabs);
1443
1444                 DoTemplate(Tokens->Params[i * 2 + 1]->Start, 
1445                            Tokens->Params[i * 2 + 1]->len,
1446                            Context, 
1447                            Target);
1448                 StrEndTab(Target, i, nTabs);
1449         }
1450 }
1451
1452 void 
1453 InitModule_SUBST
1454 (void)
1455 {
1456         RegisterNamespace("SERV:PID", 0, 0, tmplput_serv_ip);
1457         RegisterNamespace("SERV:NODENAME", 0, 0, tmplput_serv_nodename);
1458         RegisterNamespace("SERV:HUMANNODE", 0, 0, tmplput_serv_humannode);
1459         RegisterNamespace("SERV:FQDN", 0, 0, tmplput_serv_fqdn);
1460         RegisterNamespace("SERV:SOFTWARE", 0, 0, tmmplput_serv_software);
1461         RegisterNamespace("SERV:REV_LEVEL", 0, 0, tmplput_serv_rev_level);
1462         RegisterNamespace("SERV:BBS_CITY", 0, 0, tmmplput_serv_bbs_city);
1463 ///     RegisterNamespace("SERV:LDAP_SUPP", 0, 0, tmmplput_serv_ldap_enabled);
1464         RegisterNamespace("CURRENT_USER", 0, 0, tmplput_current_user);
1465         RegisterNamespace("CURRENT_ROOM", 0, 0, tmplput_current_room);
1466         RegisterNamespace("ITERATE", 2, 100, tmpl_iterate_subtmpl);
1467         RegisterNamespace("DOBOXED", 1, 2, tmpl_do_boxed);
1468         RegisterNamespace("DOTABBED", 2, 100, tmpl_do_tabbed);
1469         RegisterConditional(HKEY("COND:SUBST"), 3, ConditionalVar);
1470 }
1471
1472 /*@}*/