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