c764ce6527b6a06b951484a5e94fa3e96a517f72
[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 }
509
510 int CompareSubstToToken(TemplateParam *ParamToCompare, TemplateParam *ParamToLookup)
511 {
512         struct wcsession *WCC = WC;
513         wcsubst *ptr;
514         void *vVar;
515
516         if ((WCC->vars!= NULL) && GetHash(WCC->vars, ParamToLookup->Start, 
517                                           ParamToLookup->len, &vVar)) {
518                 ptr = (wcsubst*) vVar;
519                 switch(ptr->wcs_type) {
520                 case WCS_STRING:
521                 case WCS_STRBUF:
522                 case WCS_STRBUF_REF:
523                         if (ParamToCompare->Type == TYPE_STR)
524                                 return ((ParamToCompare->len == StrLength(ptr->wcs_value)) &&
525                                         (strcmp(ParamToCompare->Start, ChrPtr(ptr->wcs_value)) == 0));
526                         else
527                                 return ParamToCompare->lvalue == StrTol(ptr->wcs_value);
528                         break;
529                 case WCS_SERVCMD:
530                         return 1; 
531                         break;
532                 case WCS_FUNCTION:
533                         return 1;
534                 case WCS_LONG:
535                         if (ParamToCompare->Type == TYPE_STR)
536                                 return 0;
537                         else 
538                                 return ParamToCompare->lvalue == ptr->lvalue;
539                         break;
540                 default:
541                         lprintf(1,"WARNING: invalid value in SV-Hash at %s!\n", 
542                                 ParamToLookup->Start);
543                 }
544         }
545         return 0;
546 }
547
548 int CompareSubstToStrBuf(StrBuf *Compare, TemplateParam *ParamToLookup)
549 {
550         struct wcsession *WCC = WC;
551         wcsubst *ptr;
552         void *vVar;
553
554         if ((WCC->vars!= NULL) && GetHash(WCC->vars, ParamToLookup->Start, 
555                                           ParamToLookup->len, &vVar)) {
556                 ptr = (wcsubst*) vVar;
557                 switch(ptr->wcs_type) {
558                 case WCS_STRING:
559                 case WCS_STRBUF:
560                 case WCS_STRBUF_REF:
561                         return ((StrLength(Compare) == StrLength(ptr->wcs_value)) &&
562                                 (strcmp(ChrPtr(Compare), ChrPtr(ptr->wcs_value)) == 0));
563                 case WCS_SERVCMD:
564                         return 1; 
565                         break;
566                 case WCS_FUNCTION:
567                         return 1;
568                 case WCS_LONG:
569                         return StrTol(Compare) == ptr->lvalue;
570                 default:
571                         lprintf(1,"WARNING: invalid value in SV-Hash at %s!\n", 
572                                 ParamToLookup->Start);
573                 }
574         }
575         return 0;
576 }
577
578
579 void PutNewToken(WCTemplate *Template, WCTemplateToken *NewToken)
580 {
581         if (Template->nTokensUsed + 1 >= Template->TokenSpace) {
582                 if (Template->TokenSpace <= 0) {
583                         Template->Tokens = (WCTemplateToken**)malloc(
584                                 sizeof(WCTemplateToken*) * 10);
585                         Template->TokenSpace = 10;
586                 }
587                 else {
588                         WCTemplateToken **NewTokens;
589                         NewTokens= (WCTemplateToken**)malloc(
590                                 sizeof(WCTemplateToken*) * 
591                                 Template->TokenSpace * 2);
592                         memcpy(NewTokens, Template->Tokens, 
593                                sizeof(WCTemplateToken*) * Template->nTokensUsed);
594                         free(Template->Tokens);
595                         Template->TokenSpace *= 2;
596                         Template->Tokens = NewTokens;
597                 }
598         }
599         Template->Tokens[(Template->nTokensUsed)++] = NewToken;
600 }
601
602 TemplateParam *GetNextParameter(StrBuf *Buf, const char **pCh, const char *pe, WCTemplateToken *Token, WCTemplate *pTmpl)
603 {
604         const char *pch = *pCh;
605         const char *pchs, *pche;
606         TemplateParam *Parm = (TemplateParam *) malloc(sizeof(TemplateParam));
607         char quote = '\0';
608         
609         /* Skip leading whitespaces */
610         while ((*pch == ' ' )||
611                (*pch == '\t')||
612                (*pch == '\r')||
613                (*pch == '\n')) pch ++;
614         if (*pch == '"')
615                 quote = '"';
616         else if (*pch == '\'')
617                 quote = '\'';
618         if (quote != '\0') {
619                 pch ++;
620                 pchs = pch;
621                 Parm->Type = TYPE_STR;
622                 while (pch <= pe &&
623                        ((*pch != quote) ||
624                         ( (pch > pchs) && (*(pch - 1) == '\\'))
625                                )) {
626                         pch ++;
627                 }
628                 pche = pch;
629                 if (*pch != quote) {
630                         lprintf(1, "Error (in '%s' line %ld); "
631                                 "evaluating template param [%s] in Token [%s]\n",
632                                 ChrPtr(pTmpl->FileName),
633                                 Token->Line,
634                                 ChrPtr(Token->FlatToken),
635                                 *pCh);
636                         pch ++;
637                         free(Parm);
638                         return NULL;
639                 }
640                 else {
641                         StrBufPeek(Buf, pch, -1, '\0');         
642                         if (LoadTemplates > 1) {                        
643                                 lprintf(1, "DBG: got param [%s] %ld %ld\n", 
644                                         pchs, pche - pchs, strlen(pchs));
645                         }
646                         Parm->Start = pchs;
647                         Parm->len = pche - pchs;
648                         pch ++; /* move after trailing quote */
649                 }
650         }
651         else {
652                 Parm->Type = TYPE_LONG;
653                 pchs = pch;
654                 while ((pch <= pe) &&
655                        (isdigit(*pch) ||
656                         (*pch == '+') ||
657                         (*pch == '-')))
658                         pch ++;
659                 pch ++;
660                 if (pch - pchs > 1){
661                         StrBufPeek(Buf, pch, -1, '\0');
662                         Parm->lvalue = atol(pchs);
663                         Parm->Start = pchs;
664                         pch++;
665                 }
666                 else {
667                         Parm->lvalue = 0;
668                         lprintf(1, "Error (in '%s' line %ld); "
669                                 "evaluating long template param [%s] in Token [%s]\n",
670                                 ChrPtr(pTmpl->FileName),
671                                 Token->Line,
672                                 ChrPtr(Token->FlatToken),
673                                 *pCh);
674                         free(Parm);
675                         return NULL;
676                 }
677         }
678         while ((*pch == ' ' )||
679                (*pch == '\t')||
680                (*pch == '\r')||
681                (*pch == ',' )||
682                (*pch == '\n')) pch ++;
683
684         *pCh = pch;
685         return Parm;
686 }
687
688 WCTemplateToken *NewTemplateSubstitute(StrBuf *Buf, 
689                                        const char *pStart, 
690                                        const char *pTmplStart, 
691                                        const char *pTmplEnd, 
692                                        long Line,
693                                        WCTemplate *pTmpl)
694 {
695         const char *pch;
696         TemplateParam *Param;
697         WCTemplateToken *NewToken = (WCTemplateToken*)malloc(sizeof(WCTemplateToken));
698
699         NewToken->FileName = pTmpl->FileName; /* to print meaningfull log messages... */
700         NewToken->Flags = 0;
701         NewToken->Line = Line + 1;
702         NewToken->pTokenStart = pTmplStart;
703         NewToken->TokenStart = pTmplStart - pStart;
704         NewToken->TokenEnd =  (pTmplEnd - pStart) - NewToken->TokenStart;
705         NewToken->pTokenEnd = pTmplEnd;
706         NewToken->NameEnd = NewToken->TokenEnd - 2;
707         NewToken->PreEval = NULL;
708         NewToken->FlatToken = NewStrBufPlain(pTmplStart + 2, pTmplEnd - pTmplStart - 2);
709         
710         StrBufPeek(Buf, pTmplStart, + 1, '\0');
711         StrBufPeek(Buf, pTmplEnd, -1, '\0');
712         pch = NewToken->pName = pTmplStart + 2;
713
714         NewToken->HaveParameters = 0;;
715         NewToken->nParameters = 0;
716
717         while (pch < pTmplEnd - 1) {
718                 if (*pch == '(') {
719                         StrBufPeek(Buf, pch, -1, '\0');
720                         NewToken->NameEnd = pch - NewToken->pName;
721                         pch ++;
722                         while (pch < pTmplEnd - 1) {
723                                 Param = GetNextParameter(Buf, &pch, pTmplEnd - 1, NewToken, pTmpl);
724                                 if (Param != NULL) {
725                                         NewToken->HaveParameters = 1;
726                                         if (NewToken->nParameters > MAXPARAM) {
727                                                 lprintf(1, "Error (in '%s' line %ld); "
728                                                         "only [%ld] Params allowed in Tokens [%s]\n",
729                                                         ChrPtr(pTmpl->FileName),
730                                                         NewToken->Line,
731                                                         MAXPARAM,
732                                                         ChrPtr(NewToken->FlatToken));
733                                                 free(Param);
734                                                 FreeToken(&NewToken);
735                                                 return NULL;
736                                         }
737                                         NewToken->Params[NewToken->nParameters++] = Param;
738                                 }
739                                 else break;
740                         }
741                         if((NewToken->NameEnd == 1) &&
742                            (NewToken->HaveParameters == 1))
743                            
744                         {
745                                 if ((NewToken->nParameters == 1) &&
746                                     (*(NewToken->pName) == '_'))
747                                         NewToken->Flags = SV_GETTEXT;
748                                 else if ((NewToken->nParameters == 1) &&
749                                          (*(NewToken->pName) == '='))
750                                         NewToken->Flags = SV_SUBTEMPL;
751                                 else if ((NewToken->nParameters >= 2) &&
752                                          (*(NewToken->pName) == '%'))
753                                         NewToken->Flags = SV_CUST_STR_CONDITIONAL;
754                                 else if ((NewToken->nParameters >= 2) &&
755                                          (*(NewToken->pName) == '?'))
756                                         NewToken->Flags = SV_CONDITIONAL;
757                                 else if ((NewToken->nParameters >=2) &&
758                                          (*(NewToken->pName) == '!'))
759                                         NewToken->Flags = SV_NEG_CONDITIONAL;
760                         }
761                 }
762                 else pch ++;            
763         }
764         
765         if (NewToken->Flags == 0) {
766                 /* If we're able to find out more about the token, do it now while its fresh. */
767                 void *vVar;
768                 if (GetHash(GlobalNS, NewToken->pName, NewToken->NameEnd, &vVar)) {
769                         HashHandler *Handler;
770                         Handler = (HashHandler*) vVar;
771                         if ((NewToken->nParameters < Handler->nMinArgs) || 
772                             (NewToken->nParameters > Handler->nMaxArgs)) {
773                                 lprintf(1, "Handler [%s] (in '%s' line %ld); "
774                                         "doesn't work with %ld params [%s]\n", 
775                                         NewToken->pName,
776                                         ChrPtr(pTmpl->FileName),
777                                         NewToken->Line,
778                                         NewToken->nParameters, 
779                                         ChrPtr(NewToken->FlatToken));
780                         }
781                         else {
782                                 NewToken->PreEval = Handler;
783                                 NewToken->Flags = SV_PREEVALUATED;              
784                         }
785                 }               
786         }
787
788         return NewToken;
789 }
790
791
792
793 int EvaluateConditional(StrBuf *Target, WCTemplateToken *Token, WCTemplate *pTmpl, void *Context, int Neg, int state, int ContextType)
794 {
795         void *vConditional = NULL;
796         ConditionalStruct *Cond;
797
798         if ((Token->Params[0]->len == 1) &&
799             (Token->Params[0]->Start[0] == 'X'))
800                 return (state != 0)?Token->Params[1]->lvalue:0;
801
802         if (!GetHash(Contitionals, 
803                  Token->Params[0]->Start,
804                  Token->Params[0]->len,
805                  &vConditional) || 
806             (vConditional == NULL)) {
807                 lprintf(1, "Conditional [%s] (in '%s' line %ld); Not found![%s]\n", 
808                         Token->Params[0]->Start,
809                         ChrPtr(pTmpl->FileName),
810                         Token->Line,
811                         ChrPtr(Token->FlatToken));
812                 StrBufAppendPrintf(
813                         Target, 
814                         "<pre>\nConditional [%s] (in '%s' line %ld); Not found!\n[%s]\n</pre>\n", 
815                         Token->Params[0]->Start,
816                         ChrPtr(pTmpl->FileName),
817                         Token->Line,
818                         ChrPtr(Token->FlatToken));
819                 return 0;
820         }
821             
822         Cond = (ConditionalStruct *) vConditional;
823
824         if (Token->nParameters < Cond->nParams) {
825                 lprintf(1, "Conditional [%s] (in '%s' line %ld); needs %ld Params![%s]\n", 
826                         Token->Params[0]->Start,
827                         ChrPtr(pTmpl->FileName),
828                         Token->Line,
829                         Cond->nParams,
830                         ChrPtr(Token->FlatToken));
831                 StrBufAppendPrintf(
832                         Target, 
833                         "<pre>\nConditional [%s] (in '%s' line %ld); needs %ld Params!\n[%s]\n</pre>\n", 
834                         Token->Params[0]->Start,
835                         ChrPtr(pTmpl->FileName),
836                         Token->Line,
837                         Cond->nParams,
838                         ChrPtr(Token->FlatToken));
839                 return 0;
840         }
841         if (Cond->CondF(Token, Context, ContextType) == Neg)
842                 return Token->Params[1]->lvalue;
843         return 0;
844 }
845
846 int EvaluateToken(StrBuf *Target, WCTemplateToken *Token, WCTemplate *pTmpl, void *Context, int state, int ContextType)
847 {
848         HashHandler *Handler;
849         void *vVar;
850 // much output, since pName is not terminated...
851 //      lprintf(1,"Doing token: %s\n",Token->pName);
852
853         switch (Token->Flags) {
854         case SV_GETTEXT:
855                 TmplGettext(Target, Token->nParameters, Token);
856                 break;
857         case SV_CONDITIONAL: /** Forward conditional evaluation */
858                 return EvaluateConditional(Target, Token, pTmpl, Context, 1, state, ContextType);
859                 break;
860         case SV_NEG_CONDITIONAL: /** Reverse conditional evaluation */
861                 return EvaluateConditional(Target, Token, pTmpl, Context, 0, state, ContextType);
862                 break;
863         case SV_CUST_STR_CONDITIONAL: /** Conditional put custom strings from params */
864                 if (Token->nParameters >= 6) {
865                         if (EvaluateConditional(Target, Token, pTmpl, Context, 0, state, ContextType))
866                                 StrBufAppendBufPlain(Target, 
867                                                      Token->Params[5]->Start,
868                                                      Token->Params[5]->len,
869                                                      0);
870                         else
871                                 StrBufAppendBufPlain(Target, 
872                                                      Token->Params[4]->Start,
873                                                      Token->Params[4]->len,
874                                                      0);
875                 }
876                 break;
877         case SV_SUBTEMPL:
878                 if (Token->nParameters == 1)
879                         DoTemplate(Token->Params[0]->Start, Token->Params[0]->len, NULL, NULL, ContextType);
880                 break;
881         case SV_PREEVALUATED:
882                 Handler = (HashHandler*) Token->PreEval;
883                 if ((Handler->ContextRequired != CTX_NONE) &&
884                     (Handler->ContextRequired != ContextType)) {
885                         lprintf(1, "Handler [%s] (in '%s' line %ld); "
886                                 "requires context of type %ld, have %ld [%s]\n", 
887                                 Token->pName,
888                                 ChrPtr(pTmpl->FileName),
889                                 Token->Line,
890                                 Handler->ContextRequired, 
891                                 ContextType,
892                                 ChrPtr(Token->FlatToken));
893                         StrBufAppendPrintf(
894                                 Target, 
895                                 "<pre>\nHandler [%s] (in '%s' line %ld);"
896                                 " requires context of type %ld, have %ld!\n[%s]\n</pre>\n", 
897                                 Token->pName,
898                                 ChrPtr(pTmpl->FileName),
899                                 Token->Line,
900                                 Handler->ContextRequired, 
901                                 ContextType,
902                                 ChrPtr(Token->FlatToken));
903                         return -1;
904
905                 }
906                 Handler->HandlerFunc(Target, 
907                                      Token->nParameters,
908                                      Token,
909                                      Context, 
910                                      ContextType); 
911                 break;          
912         default:
913                 if (GetHash(GlobalNS, Token->pName, Token->NameEnd, &vVar)) {
914                         Handler = (HashHandler*) vVar;
915                         if ((Handler->ContextRequired != CTX_NONE) &&
916                             (Handler->ContextRequired != ContextType)) {
917                                 lprintf(1, "Handler [%s] (in '%s' line %ld); "
918                                         "requires context of type %ld, have %ld [%s]\n", 
919                                         Token->pName,
920                                         ChrPtr(pTmpl->FileName),
921                                         Token->Line,
922                                         Handler->ContextRequired, 
923                                         ContextType,
924                                         ChrPtr(Token->FlatToken));
925                                 StrBufAppendPrintf(
926                                         Target, 
927                                         "<pre>\nHandler [%s] (in '%s' line %ld);"
928                                         " requires context of type %ld, have %ld!\n[%s]\n</pre>\n", 
929                                         Token->pName,
930                                         ChrPtr(pTmpl->FileName),
931                                         Token->Line,
932                                         Handler->ContextRequired, 
933                                         ContextType,
934                                         ChrPtr(Token->FlatToken));
935                                 return -1;
936                         }
937                         else if ((Token->nParameters < Handler->nMinArgs) || 
938                                  (Token->nParameters > Handler->nMaxArgs)) {
939                                 lprintf(1, "Handler [%s] (in '%s' line %ld); "
940                                         "doesn't work with %ld params [%s]\n", 
941                                         Token->pName,
942                                         ChrPtr(pTmpl->FileName),
943                                         Token->Line,
944                                         Token->nParameters, 
945                                         ChrPtr(Token->FlatToken));
946                                 StrBufAppendPrintf(
947                                         Target, 
948                                         "<pre>\nHandler [%s] (in '%s' line %ld);"
949                                         " doesn't work with %ld params!\n[%s]\n</pre>\n", 
950                                         Token->pName,
951                                         ChrPtr(pTmpl->FileName),
952                                         Token->Line,
953                                         Token->nParameters,
954                                         ChrPtr(Token->FlatToken));
955                         }
956                         else {
957                                 Handler->HandlerFunc(Target, 
958                                                      Token->nParameters,
959                                                      Token,
960                                                      Context, 
961                                                      ContextType); /*TODO: subset of that */
962                                 
963                         }
964                 }
965                 else {
966                         print_value_of(Target, Token, Context, ContextType);
967                 }
968         }
969         return 0;
970 }
971
972 void ProcessTemplate(WCTemplate *Tmpl, StrBuf *Target, void *Context, int ContextType)
973 {
974         WCTemplate *pTmpl = Tmpl;
975         int done = 0;
976         int i, state;
977         const char *pData, *pS;
978         long len;
979
980         if (LoadTemplates != 0) {                       
981                 if (LoadTemplates > 1)
982                         lprintf(1, "DBG: ----- loading:  [%s] ------ \n", 
983                                 ChrPtr(Tmpl->FileName));
984                 pTmpl = load_template(Tmpl->FileName, NULL, NULL);
985                 if(pTmpl == NULL) {
986                         StrBufAppendPrintf(
987                                 Target, 
988                                 "<pre>\nError loading Template [%s]\n See Logfile for details\n</pre>\n", 
989                                 ChrPtr(Tmpl->FileName));
990                         return;
991                 }
992
993         }
994
995         pS = pData = ChrPtr(pTmpl->Data);
996         len = StrLength(pTmpl->Data);
997         i = 0;
998         state = 0;
999         while (!done) {
1000                 if (i >= pTmpl->nTokensUsed) {
1001                         StrBufAppendBufPlain(Target, 
1002                                              pData, 
1003                                              len - (pData - pS), 0);
1004                         done = 1;
1005                 }
1006                 else {
1007                         StrBufAppendBufPlain(
1008                                 Target, pData, 
1009                                 pTmpl->Tokens[i]->pTokenStart - pData, 0);
1010                         state = EvaluateToken(Target, pTmpl->Tokens[i], pTmpl, Context, state, ContextType);
1011                         while ((state != 0) && (i+1 < pTmpl->nTokensUsed)) {
1012                         /* condition told us to skip till its end condition */
1013                                 i++;
1014                                 if ((pTmpl->Tokens[i]->Flags == SV_CONDITIONAL) ||
1015                                     (pTmpl->Tokens[i]->Flags == SV_NEG_CONDITIONAL)) {
1016                                         if (state == EvaluateConditional(
1017                                                     Target,
1018                                                     pTmpl->Tokens[i], 
1019                                                     pTmpl,
1020                                                     Context, 
1021                                                     pTmpl->Tokens[i]->Flags,
1022                                                     state, 
1023                                                     ContextType))
1024                                                 state = 0;
1025                                 }
1026                         }
1027                         pData = pTmpl->Tokens[i++]->pTokenEnd + 1;
1028                         if (i > pTmpl->nTokensUsed)
1029                                 done = 1;
1030                 }
1031         }
1032         if (LoadTemplates != 0) {
1033                 FreeWCTemplate(pTmpl);
1034         }
1035 }
1036
1037
1038 /**
1039  * \brief Display a variable-substituted template
1040  * \param templatename template file to load
1041  */
1042 void *prepare_template(StrBuf *filename, StrBuf *Key, HashList *PutThere)
1043 {
1044         WCTemplate *NewTemplate;
1045         NewTemplate = (WCTemplate *) malloc(sizeof(WCTemplate));
1046         NewTemplate->Data = NULL;
1047         NewTemplate->FileName = NewStrBufDup(filename);
1048         NewTemplate->nTokensUsed = 0;
1049         NewTemplate->TokenSpace = 0;
1050         NewTemplate->Tokens = NULL;
1051
1052         Put(PutThere, ChrPtr(Key), StrLength(Key), NewTemplate, FreeWCTemplate);
1053         return NewTemplate;
1054 }
1055
1056 /**
1057  * \brief Display a variable-substituted template
1058  * \param templatename template file to load
1059  */
1060 void *load_template(StrBuf *filename, StrBuf *Key, HashList *PutThere)
1061 {
1062         int fd;
1063         struct stat statbuf;
1064         const char *pS, *pE, *pch, *Err;
1065         long Line;
1066         int pos;
1067         WCTemplate *NewTemplate;
1068
1069         fd = open(ChrPtr(filename), O_RDONLY);
1070         if (fd <= 0) {
1071                 lprintf(1, "ERROR: could not open template '%s' - %s\n",
1072                         ChrPtr(filename), strerror(errno));
1073                 return NULL;
1074         }
1075
1076         if (fstat(fd, &statbuf) == -1) {
1077                 lprintf(1, "ERROR: could not stat template '%s' - %s\n",
1078                         ChrPtr(filename), strerror(errno));
1079                 return NULL;
1080         }
1081
1082         NewTemplate = (WCTemplate *) malloc(sizeof(WCTemplate));
1083         NewTemplate->Data = NewStrBufPlain(NULL, statbuf.st_size);
1084         NewTemplate->FileName = NewStrBufDup(filename);
1085         NewTemplate->nTokensUsed = 0;
1086         NewTemplate->TokenSpace = 0;
1087         NewTemplate->Tokens = NULL;
1088         if (StrBufReadBLOB(NewTemplate->Data, &fd, 1, statbuf.st_size, &Err) < 0) {
1089                 close(fd);
1090                 FreeWCTemplate(NewTemplate);
1091                 lprintf(1, "ERROR: reading template '%s' - %s<br />\n",
1092                         ChrPtr(filename), strerror(errno));
1093                 return NULL;
1094         }
1095         close(fd);
1096
1097         Line = 0;
1098         pS = pch = ChrPtr(NewTemplate->Data);
1099         pE = pS + StrLength(NewTemplate->Data);
1100         while (pch < pE) {
1101                 const char *pts, *pte;
1102                 int InQuotes = 0;
1103                 int InDoubleQuotes = 0;
1104
1105                 /** Find one <? > */
1106                 pos = (-1);
1107                 for (; pch < pE; pch ++) {
1108                         if ((*pch=='<')&&(*(pch + 1)=='?'))
1109                                 break;
1110                         if (*pch=='\n') Line ++;
1111                 }
1112                 if (pch >= pE)
1113                         continue;
1114                 pts = pch;
1115
1116                 /** Found one? parse it. */
1117                 for (; pch < pE - 1; pch ++) {
1118                         if (*pch == '"')
1119                                 InDoubleQuotes = ! InDoubleQuotes;
1120                         else if (*pch == '\'')
1121                                 InQuotes = ! InQuotes;
1122                         else if ((!InQuotes  && !InDoubleQuotes) &&
1123                                  ((*pch!='\\')&&(*(pch + 1)=='>'))) {
1124                                 pch ++;
1125                                 break;
1126                         }
1127                 }
1128                 if (pch + 1 >= pE)
1129                         continue;
1130                 pte = pch;
1131                 PutNewToken(NewTemplate, 
1132                             NewTemplateSubstitute(NewTemplate->Data, pS, pts, pte, Line, NewTemplate));
1133                 pch ++;
1134         }
1135         if (LoadTemplates == 0)
1136                 Put(PutThere, ChrPtr(Key), StrLength(Key), NewTemplate, FreeWCTemplate);
1137         return NewTemplate;
1138 }
1139
1140
1141 ///void PrintTemplate(const char *Key, void *vSubst, int odd)
1142 const char* PrintTemplate(void *vSubst)
1143 {
1144         WCTemplate *Tmpl = vSubst;
1145
1146         return ChrPtr(Tmpl->FileName);
1147
1148 }
1149
1150
1151 /**
1152  * \brief Display a variable-substituted template
1153  * \param templatename template file to load
1154  */
1155 void DoTemplate(const char *templatename, long len, StrBuf *Target, void *Context, int ContextType) 
1156 {
1157         HashList *Static;
1158         HashList *StaticLocal;
1159         void *vTmpl;
1160         
1161         if (Target == NULL)
1162                 Target = WC->WBuf;
1163         if (WC->is_mobile) {
1164                 Static = WirelessTemplateCache;
1165                 StaticLocal = WirelessLocalTemplateCache;
1166         }
1167         else {
1168                 Static = TemplateCache;
1169                 StaticLocal = LocalTemplateCache;
1170         }
1171
1172         if (len == 0)
1173         {
1174                 lprintf (1, "Can't to load a template with empty name!\n");
1175                 StrBufAppendPrintf(Target, "<pre>\nCan't to load a template with empty name!\n</pre>");
1176                 return;
1177         }
1178
1179         if (!GetHash(StaticLocal, templatename, len, &vTmpl) &&
1180             !GetHash(Static, templatename, len, &vTmpl)) {
1181                 lprintf (1, "didn't find Template [%s] %ld %ld\n", templatename, len , (long)strlen(templatename));
1182                 StrBufAppendPrintf(Target, "<pre>\ndidn't find Template [%s] %ld %ld\n</pre>", 
1183                                    templatename, len, 
1184                                    (long)strlen(templatename));
1185 ///             dbg_PrintHash(Static, PrintTemplate, NULL);
1186 //              PrintHash(Static, VarPrintTransition, PrintTemplate);
1187                 return;
1188         }
1189         if (vTmpl == NULL) 
1190                 return;
1191         ProcessTemplate(vTmpl, Target, Context, ContextType);
1192 }
1193
1194 int LoadTemplateDir(const char *DirName, HashList *wireless, HashList *big)
1195 {
1196         StrBuf *FileName;
1197         StrBuf *Tag;
1198         StrBuf *Dir;
1199         DIR *filedir = NULL;
1200         struct dirent *filedir_entry;
1201         int d_namelen;
1202         int d_without_ext;
1203         int IsMobile;
1204         
1205         Dir = NewStrBuf();
1206         StrBufPrintf(Dir, "%s/t", DirName);
1207         filedir = opendir (ChrPtr(Dir));
1208         if (filedir == NULL) {
1209                 FreeStrBuf(&Dir);
1210                 return 0;
1211         }
1212
1213         FileName = NewStrBuf();
1214         Tag = NewStrBuf();
1215         while ((filedir_entry = readdir(filedir)))
1216         {
1217                 char *MinorPtr;
1218                 char *PStart;
1219 #ifdef _DIRENT_HAVE_D_NAMELEN
1220                 d_namelen = filedir_entry->d_namelen;
1221 #else
1222                 d_namelen = strlen(filedir_entry->d_name);
1223 #endif
1224                 d_without_ext = d_namelen;
1225                 while ((d_without_ext > 0) && (filedir_entry->d_name[d_without_ext] != '.'))
1226                         d_without_ext --;
1227                 if ((d_without_ext == 0) || (d_namelen < 3))
1228                         continue;
1229                 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
1230                         continue; /* Ignore backup files... */
1231
1232                 IsMobile = (strstr(filedir_entry->d_name, ".m.html")!= NULL);
1233                 PStart = filedir_entry->d_name;
1234                 StrBufPrintf(FileName, "%s/%s", ChrPtr(Dir),  filedir_entry->d_name);
1235                 MinorPtr = strchr(filedir_entry->d_name, '.');
1236                 if (MinorPtr != NULL)
1237                         *MinorPtr = '\0';
1238                 StrBufPlain(Tag, filedir_entry->d_name, MinorPtr - filedir_entry->d_name);
1239
1240
1241                 lprintf(1, "%s %d %s\n",ChrPtr(FileName), IsMobile, ChrPtr(Tag));
1242                 if (LoadTemplates == 0)
1243                         load_template(FileName, Tag, (IsMobile)?wireless:big);
1244                 else
1245                         prepare_template(FileName, Tag, (IsMobile)?wireless:big);
1246         }
1247         closedir(filedir);
1248         FreeStrBuf(&FileName);
1249         FreeStrBuf(&Tag);
1250         FreeStrBuf(&Dir);
1251         return 1;
1252 }
1253
1254 void InitTemplateCache(void)
1255 {
1256         LoadTemplateDir(static_dirs[0],
1257                         WirelessTemplateCache,
1258                         TemplateCache);
1259         LoadTemplateDir(static_dirs[1],
1260                         WirelessLocalTemplateCache,
1261                         LocalTemplateCache);
1262 }
1263
1264 void tmplput_serv_ip(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1265 {
1266         StrBufAppendPrintf(Target, "%d", WC->ctdl_pid);
1267 }
1268
1269 void tmplput_serv_nodename(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1270 {
1271         StrEscAppend(Target, NULL, serv_info.serv_nodename, 0, 0);
1272 }
1273
1274 void tmplput_serv_humannode(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1275 {
1276         StrEscAppend(Target, NULL, serv_info.serv_humannode, 0, 0);
1277 }
1278
1279 void tmplput_serv_fqdn(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1280 {
1281         StrEscAppend(Target, NULL, serv_info.serv_fqdn, 0, 0);
1282 }
1283
1284 void tmmplput_serv_software(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1285 {
1286         StrEscAppend(Target, NULL, serv_info.serv_software, 0, 0);
1287 }
1288
1289 void tmplput_serv_rev_level(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1290 {
1291         StrBufAppendPrintf(Target, "%d.%02d",
1292                             serv_info.serv_rev_level / 100,
1293                             serv_info.serv_rev_level % 100);
1294 }
1295
1296 void tmmplput_serv_bbs_city(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1297 {
1298         StrEscAppend(Target, NULL, serv_info.serv_bbs_city, 0, 0);
1299 }
1300
1301 void tmplput_current_user(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1302 {
1303         StrEscAppend(Target, NULL, WC->wc_fullname, 0, 0);
1304 }
1305
1306 void tmplput_current_room(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1307 {
1308         StrEscAppend(Target, NULL, WC->wc_roomname, 0, 0);
1309 }
1310
1311
1312 typedef struct _HashIterator {
1313         HashList *StaticList;
1314         int AdditionalParams;
1315         int ContextType;
1316         int XPectContextType;
1317         RetrieveHashlistFunc GetHash;
1318         HashDestructorFunc Destructor;
1319         SubTemplFunc DoSubTemplate;
1320 } HashIterator;
1321
1322 void tmpl_iterate_subtmpl(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1323 {
1324         void *vIt;
1325         HashIterator *It;
1326         HashList *List;
1327         HashPos  *it;
1328         long len; 
1329         const char *Key;
1330         void *vContext;
1331         StrBuf *SubBuf;
1332         int oddeven = 0;
1333         
1334         if (!GetHash(Iterators, 
1335                      Tokens->Params[0]->Start,
1336                      Tokens->Params[0]->len,
1337                      &vIt)) {
1338                 lprintf(1, "unknown Iterator [%s] (in '%s' line %ld); "
1339                         " [%s]\n", 
1340                         Tokens->Params[0]->Start,
1341                         ChrPtr(Tokens->FileName),
1342                         Tokens->Line,
1343                         ChrPtr(Tokens->FlatToken));
1344                 StrBufAppendPrintf(
1345                         Target,
1346                         "<pre>\nunknown Iterator [%s] (in '%s' line %ld); \n"
1347                         " [%s]\n</pre>", 
1348                         Tokens->Params[0]->Start,
1349                         ChrPtr(Tokens->FileName),
1350                         Tokens->Line,
1351                         ChrPtr(Tokens->FlatToken));
1352                 return;
1353         }
1354
1355         It = (HashIterator*) vIt;
1356
1357         if (Tokens->nParameters < It->AdditionalParams + 2) {
1358                 lprintf(1, "Iterator [%s] (in '%s' line %ld); "
1359                         "doesn't work with %ld params [%s]\n", 
1360                         Tokens->Params[0]->Start,
1361                         ChrPtr(Tokens->FileName),
1362                         Tokens->Line,
1363                         Tokens->nParameters, 
1364                         ChrPtr(Tokens->FlatToken));
1365                 StrBufAppendPrintf(
1366                         Target,
1367                         "<pre>Iterator [%s] \n(in '%s' line %ld);\n"
1368                         "doesn't work with %ld params \n[%s]\n</pre>", 
1369                         Tokens->Params[0]->Start,
1370                         ChrPtr(Tokens->FileName),
1371                         Tokens->Line,
1372                         Tokens->nParameters, 
1373                         ChrPtr(Tokens->FlatToken));
1374                 return;
1375         }
1376
1377         if ((It->XPectContextType != CTX_NONE) &&
1378             (It->XPectContextType != ContextType)) {
1379                 lprintf(1, "Iterator [%s] (in '%s' line %ld); "
1380                         "requires context of type %ld, have %ld [%s]\n", 
1381                         Tokens->pName,
1382                         ChrPtr(Tokens->FileName),
1383                         Tokens->Line,
1384                         It->XPectContextType, 
1385                         ContextType,
1386                         ChrPtr(Tokens->FlatToken));
1387                 StrBufAppendPrintf(
1388                         Target, 
1389                         "<pre>\nIterator [%s] (in '%s' line %ld);"
1390                         " requires context of type %ld, have %ld!\n[%s]\n</pre>\n", 
1391                         Tokens->pName,
1392                         ChrPtr(Tokens->FileName),
1393                         Tokens->Line,
1394                         It->XPectContextType, 
1395                         ContextType,
1396                         ChrPtr(Tokens->FlatToken));
1397                 return ;
1398                 
1399         }
1400
1401
1402
1403
1404         if (It->StaticList == NULL)
1405                 List = It->GetHash(Target, nArgs, Tokens, Context, ContextType);
1406         else
1407                 List = It->StaticList;
1408
1409         SubBuf = NewStrBuf();
1410         it = GetNewHashPos();
1411         while (GetNextHashPos(List, it, &len, &Key, &vContext)) {
1412                 svprintf(HKEY("ITERATE:ODDEVEN"), WCS_STRING, "%s", 
1413                          (oddeven) ? "odd" : "even");
1414                 svprintf(HKEY("ITERATE:KEY"), WCS_STRING, "%s", Key);
1415
1416                 if (It->DoSubTemplate != NULL)
1417                         It->DoSubTemplate(SubBuf, vContext, Tokens);
1418                 DoTemplate(Tokens->Params[1]->Start,
1419                            Tokens->Params[1]->len,
1420                            SubBuf, vContext,
1421                            It->ContextType);
1422                         
1423                 StrBufAppendBuf(Target, SubBuf, 0);
1424                 FlushStrBuf(SubBuf);
1425                 oddeven = ~ oddeven;
1426         }
1427         FreeStrBuf(&SubBuf);
1428         DeleteHashPos(&it);
1429         if (It->Destructor != NULL)
1430                 It->Destructor(&List);
1431 }
1432
1433 int ConditionalVar(WCTemplateToken *Tokens, void *Context, int ContextType)
1434 {
1435         void *vsubst;
1436         wcsubst *subst;
1437         
1438         if (!GetHash(WC->vars, 
1439                      Tokens->Params[2]->Start,
1440                      Tokens->Params[2]->len,
1441                      &vsubst))
1442                 return 0;
1443         subst = (wcsubst*) vsubst;
1444         if ((subst->ContextRequired != CTX_NONE) &&
1445             (subst->ContextRequired != ContextType)) {
1446                 lprintf(1,"  WARNING: Conditional requires Context: [%ld]!\n", Tokens->Params[2]->Start);
1447                 return -1;
1448         }
1449
1450         switch(subst->wcs_type) {
1451         case WCS_FUNCTION:
1452                 return (subst->wcs_function!=NULL);
1453         case WCS_SERVCMD:
1454                 lprintf(1, "  -> Server [%s]\n", subst->wcs_value);////todo
1455                 return 1;
1456         case WCS_STRING:
1457         case WCS_STRBUF:
1458         case WCS_STRBUF_REF:
1459                 if (Tokens->nParameters < 4)
1460                         return 1;
1461                 return (strcmp(Tokens->Params[3]->Start, ChrPtr(subst->wcs_value)) == 0);
1462         case WCS_LONG:
1463                 if (Tokens->nParameters < 4)
1464                         return (subst->lvalue != 0);
1465                 return (subst->lvalue == Tokens->Params[3]->lvalue);
1466         default:
1467                 lprintf(1,"  WARNING: invalid type: [%ld]!\n", subst->wcs_type);
1468                 return -1;
1469         }
1470         return 0;
1471 }
1472
1473 void RegisterITERATOR(const char *Name, long len, 
1474                       int AdditionalParams, 
1475                       HashList *StaticList, 
1476                       RetrieveHashlistFunc GetHash, 
1477                       SubTemplFunc DoSubTempl,
1478                       HashDestructorFunc Destructor,
1479                       int ContextType, 
1480                       int XPectContextType)
1481 {
1482         HashIterator *It = (HashIterator*)malloc(sizeof(HashIterator));
1483         It->StaticList = StaticList;
1484         It->AdditionalParams = AdditionalParams;
1485         It->GetHash = GetHash;
1486         It->DoSubTemplate = DoSubTempl;
1487         It->Destructor = Destructor;
1488         It->ContextType = ContextType;
1489         It->XPectContextType = XPectContextType;
1490         Put(Iterators, Name, len, It, NULL);
1491 }
1492
1493 void RegisterConditional(const char *Name, long len, 
1494                          int nParams,
1495                          WCConditionalFunc CondF, 
1496                          int ContextRequired)
1497 {
1498         ConditionalStruct *Cond = (ConditionalStruct*)malloc(sizeof(ConditionalStruct));
1499         Cond->nParams = nParams;
1500         Cond->CondF = CondF;
1501         Cond->ContextRequired = ContextRequired;
1502         Put(Contitionals, Name, len, Cond, NULL);
1503 }
1504
1505 void tmpl_do_boxed(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1506 {
1507         if (nArgs == 2) {
1508                 StrBuf *Headline = NewStrBuf();
1509                 DoTemplate(Tokens->Params[1]->Start, 
1510                            Tokens->Params[1]->len,
1511                            Headline, 
1512                            Context, 
1513                            ContextType);
1514                 SVPutBuf("BOXTITLE", Headline, 0);
1515         }
1516         
1517         DoTemplate(HKEY("beginbox"), Target, Context, ContextType);
1518         DoTemplate(Tokens->Params[0]->Start, 
1519                    Tokens->Params[0]->len,
1520                    Target, 
1521                    Context, 
1522                    ContextType);
1523         DoTemplate(HKEY("endbox"), Target, Context, ContextType);
1524 }
1525
1526 void tmpl_do_tabbed(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1527 {
1528         StrBuf **TabNames;
1529         int i, ntabs, nTabs;
1530
1531         nTabs = ntabs = Tokens->nParameters / 2;
1532         TabNames = (StrBuf **) malloc(ntabs * sizeof(StrBuf*));
1533
1534         for (i = 0; i < ntabs; i++) {
1535                 TabNames[i] = NewStrBuf();
1536                 if (Tokens->Params[i * 2]->len > 0) {
1537                         DoTemplate(Tokens->Params[i * 2]->Start, 
1538                                    Tokens->Params[i * 2]->len,
1539                                    TabNames[i],
1540                                    Context,
1541                                    ContextType);
1542                 }
1543                 else { 
1544                         /** A Tab without subject? we can't count that, add it as silent */
1545                         nTabs --;
1546                 }
1547         }
1548
1549         StrTabbedDialog(Target, nTabs, TabNames);
1550         for (i = 0; i < ntabs; i++) {
1551                 StrBeginTab(Target, i, nTabs);
1552
1553                 DoTemplate(Tokens->Params[i * 2 + 1]->Start, 
1554                            Tokens->Params[i * 2 + 1]->len,
1555                            Target,
1556                            Context, 
1557                            ContextType);
1558                 StrEndTab(Target, i, nTabs);
1559         }
1560 }
1561
1562 void 
1563 InitModule_SUBST
1564 (void)
1565 {
1566         RegisterNamespace("SERV:PID", 0, 0, tmplput_serv_ip, CTX_NONE);
1567         RegisterNamespace("SERV:NODENAME", 0, 0, tmplput_serv_nodename, CTX_NONE);
1568         RegisterNamespace("SERV:HUMANNODE", 0, 0, tmplput_serv_humannode, CTX_NONE);
1569         RegisterNamespace("SERV:FQDN", 0, 0, tmplput_serv_fqdn, CTX_NONE);
1570         RegisterNamespace("SERV:SOFTWARE", 0, 0, tmmplput_serv_software, CTX_NONE);
1571         RegisterNamespace("SERV:REV_LEVEL", 0, 0, tmplput_serv_rev_level, CTX_NONE);
1572         RegisterNamespace("SERV:BBS_CITY", 0, 0, tmmplput_serv_bbs_city, CTX_NONE);
1573 ///     RegisterNamespace("SERV:LDAP_SUPP", 0, 0, tmmplput_serv_ldap_enabled, 0);
1574         RegisterNamespace("CURRENT_USER", 0, 0, tmplput_current_user, CTX_NONE);
1575         RegisterNamespace("CURRENT_ROOM", 0, 0, tmplput_current_room, CTX_NONE);
1576         RegisterNamespace("ITERATE", 2, 100, tmpl_iterate_subtmpl, CTX_NONE);
1577         RegisterNamespace("DOBOXED", 1, 2, tmpl_do_boxed, CTX_NONE);
1578         RegisterNamespace("DOTABBED", 2, 100, tmpl_do_tabbed, CTX_NONE);
1579         RegisterConditional(HKEY("COND:SUBST"), 3, ConditionalVar, CTX_NONE);
1580 }
1581
1582 /*@}*/